// Shared chrome: Header, Footer, AuditModal (consultation flow), Toast, useReveal, Counter
const { useState, useEffect, useRef, useCallback } = React;

function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal");
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add("in");
            io.unobserve(e.target);
          }
        });
      },
      { threshold: 0.12, rootMargin: "0px 0px -60px 0px" },
    );
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);
}

function Counter({ to, suffix = "", prefix = "", duration = 1400 }) {
  const [val, setVal] = useState(0);
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    let started = false;
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting && !started) {
            started = true;
            const start = performance.now();
            const tick = (t) => {
              const p = Math.min(1, (t - start) / duration);
              const eased = 1 - Math.pow(1 - p, 3);
              setVal(Math.round(to * eased));
              if (p < 1) requestAnimationFrame(tick);
            };
            requestAnimationFrame(tick);
            io.disconnect();
          }
        });
      },
      { threshold: 0.5 },
    );
    io.observe(el);
    return () => io.disconnect();
  }, [to, duration]);
  return (
    <span ref={ref} className="counter">
      {prefix}
      {val.toLocaleString("en-IN")}
      {suffix}
    </span>
  );
}

function Header({ onOpenAudit, currentPage = "home" }) {
  const [mobileOpen, setMobileOpen] = useState(false);

  // Lock body scroll when mobile menu is open
  useEffect(() => {
    document.body.style.overflow = mobileOpen ? "hidden" : "";
    return () => {
      document.body.style.overflow = "";
    };
  }, [mobileOpen]);

  const isActive = (page) => (currentPage === page ? "active" : "");

  return (
    <>
      <header className="site-header">
        <div className="wrap nav">
          <div className="nav-left">
            <a href="index.html" className="brand" aria-label="iAngels Wealth">
              <img
                src="assets/iangels-logo.png"
                alt="iAngels Wealth"
                className="brand-logo"
              />
            </a>
            <nav className="nav-links">
              <a
                href="products-and-solutions.html"
                className={isActive("products")}
              >
                Products &amp; Solutions
              </a>
              <a href="about.html" className={isActive("about")}>
                About
              </a>
              <a href="contact.html" className={isActive("contact")}>
                Contact
              </a>
            </nav>
          </div>
          <div className="nav-right">
            <button className="btn primary sm" onClick={onOpenAudit}>
              Schedule Introductory Call <IconArrow size={12} />
            </button>
            <button
              className="nav-hamburger"
              onClick={() => setMobileOpen(true)}
              aria-label="Open menu"
            >
              <span />
              <span />
              <span />
            </button>
          </div>
        </div>
      </header>

      {/* Mobile slide-in drawer */}
      <div
        className={`mobile-drawer-backdrop ${mobileOpen ? "open" : ""}`}
        onClick={() => setMobileOpen(false)}
      />
      <nav
        className={`mobile-drawer ${mobileOpen ? "open" : ""}`}
        aria-label="Mobile navigation"
      >
        <div className="mobile-drawer-head">
          <a href="index.html" className="brand" aria-label="iAngels Wealth">
            <img
              src="assets/iangels-logo.png"
              alt="iAngels Wealth"
              className="brand-logo"
            />
          </a>
          <button
            className="mobile-drawer-close"
            onClick={() => setMobileOpen(false)}
            aria-label="Close menu"
          >
            <IconClose />
          </button>
        </div>
        <div className="mobile-drawer-body">
          <a href="products-and-solutions.html" className="mobile-drawer-link">
            Products &amp; Solutions
          </a>
          <a href="about.html" className="mobile-drawer-link">
            About
          </a>
          <a href="contact.html" className="mobile-drawer-link">
            Contact
          </a>
        </div>
        <div className="mobile-drawer-foot">
          <button
            className="btn primary lg"
            style={{ width: "100%" }}
            onClick={() => {
              setMobileOpen(false);
              onOpenAudit();
            }}
          >
            Schedule Introductory Call <IconArrow size={12} />
          </button>
          <div
            style={{
              marginTop: 16,
              display: "flex",
              gap: 16,
              fontSize: 13,
              color: "var(--ink-3)",
            }}
          >
            <a
              href="mailto:info@iangelswealth.com"
              style={{ color: "var(--ink-3)" }}
            >
              info@iangelswealth.com
            </a>
          </div>
        </div>
      </nav>

      {/* Mobile sticky CTA */}
      <div className="mobile-sticky-cta">
        <button
          className="btn primary"
          style={{ width: "100%" }}
          onClick={onOpenAudit}
        >
          Schedule Introductory Call <IconArrow size={12} />
        </button>
      </div>
    </>
  );
}

function Footer() {
  return (
    <footer className="site-footer">
      <div className="wrap">
        <div className="footer-grid">
          <div>
            <a href="index.html" className="brand">
              <img
                src="assets/iangels-logo.png"
                alt="iAngels Wealth"
                className="brand-logo brand-logo-lg"
              />
            </a>
            <p
              className="small"
              style={{ maxWidth: 320, marginTop: 16, color: "var(--ink-3)" }}
            >
              Where Capital Meets Clarity
            </p>
          </div>
          <div>
            <h5>Products &amp; Solutions</h5>
            <ul>
              <li>
                <a href="products-and-solutions.html#alternatives">
                  Startups &amp; Alternatives
                </a>
              </li>
              <li>
                <a href="products-and-solutions.html#public-markets">
                  Public Market &amp; Core
                </a>
              </li>
              <li>
                <a href="products-and-solutions.html#global">
                  Global &amp; Cross Border Investing
                </a>
              </li>
              <li>
                <a href="products-and-solutions.html#treasury">
                  Treasury Management Services
                </a>
              </li>
              <li>
                <a href="products-and-solutions.html#legacy-estate">
                  Legacy &amp; Estate Planning
                </a>
              </li>
              <li>
                <a href="products-and-solutions.html#capital-liquidity">
                  Capital &amp; Liquidity Solutions
                </a>
              </li>
            </ul>
          </div>
          <div>
            <h5>About</h5>
            <ul>
              <li>
                <a href="about.html">About</a>
              </li>
            </ul>
          </div>
          <div>
            <h5>Connect</h5>
            <ul>
              <li>
                Email —{" "}
                <a href="mailto:info@iangelswealth.com">
                  info@iangelswealth.com
                </a>
              </li>
              <li>
                Number — <a href="tel:+919717688499">+91 9717688499</a>
              </li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <div>© 2026 iAngels Wealth. All rights reserved.</div>
          <div className="compl">
            <span>SEBI AIFs</span>
            <span>AMFI: ARN - 345264</span>
            <span>APMI: APRN07972</span>
          </div>
        </div>
        <p
          className="small"
          style={{
            marginTop: 24,
            color: "var(--ink-4)",
            fontSize: 12,
            lineHeight: 1.5,
            maxWidth: 880,
          }}
        >
          The information provided herein is for informational purposes only and
          does not constitute investment advice, research, recommendation, or
          solicitation to buy or sell any securities or financial products.
          Investments in securities markets are subject to market risks, and
          past performance is not indicative of future returns. iAngels Wealth
          acts solely as a distributor/facilitator for products and services
          offered through respective SEBI-registered entities, intermediaries,
          or issuers, and does not act as a SEBI-registered investment advisor
          unless explicitly stated. Investors should independently evaluate all
          risks and consult licensed financial, legal, and tax professionals
          before making investment decisions.
        </p>
      </div>
    </footer>
  );
}

// ----------- Lead capture → n8n webhook -----------

const N8N_LEAD_WEBHOOK =
  "https://automate.indiaaccelerator.live/webhook/4638fff7-c057-463f-944b-885e14abcf42";

const AUM_LABELS = {
  "<1": "Under ₹1 Cr",
  "1-5": "₹1-5 Cr",
  "5-25": "₹5-25 Cr",
  "25+": "₹25 Cr+",
};

function defaultModalLeadSource() {
  const file =
    (window.location.pathname || "").split("/").pop() || "index.html";
  const page = file.replace(/\.html$/i, "") || "home";
  return `consultation-modal:${page}`;
}

/** @param {object} form - { name, email, phone, aum, interests, message } */
function buildLeadPayload(form, source) {
  const aum = form.aum || "";
  return {
    source,
    submittedAt: new Date().toISOString(),
    name: (form.name || "").trim(),
    email: (form.email || "").trim(),
    phone: (form.phone || "").trim(),
    aum,
    aumLabel: AUM_LABELS[aum] || aum,
    interests: Array.isArray(form.interests) ? form.interests : [],
    message: (form.message || "").trim(),
    pageUrl: window.location.href,
    pagePath: window.location.pathname,
  };
}

async function submitLeadToN8n(form, source) {
  const payload = buildLeadPayload(form, source);
  const res = await fetch(N8N_LEAD_WEBHOOK, {
    method: "POST",
    headers: { "Content-Type": "application/json", Accept: "application/json" },
    body: JSON.stringify(payload),
  });
  if (!res.ok) {
    const detail = await res.text().catch(() => "");
    throw new Error(detail || `Request failed (${res.status})`);
  }
  return payload;
}

// ----------- Private consultation modal -----------

function AuditModal({ open, onClose, onSubmit, leadSource }) {
  const [step, setStep] = useState(0);
  const [form, setForm] = useState({
    name: "",
    email: "",
    phone: "",
    aum: "",
    interests: [],
    message: "",
  });
  const [errors, setErrors] = useState({});
  const [submitting, setSubmitting] = useState(false);

  useEffect(() => {
    if (open) {
      setStep(0);
      setErrors({});
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "";
    }
  }, [open]);

  const update = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  const toggleInterest = (i) => {
    setForm((f) => ({
      ...f,
      interests: f.interests.includes(i)
        ? f.interests.filter((x) => x !== i)
        : [...f.interests, i],
    }));
  };

  const validate = (s) => {
    const e = {};
    if (s === 0) {
      if (!form.aum) e.aum = "Please choose a wealth stage";
    }
    if (s === 1) {
      if (form.interests.length === 0)
        e.interests = "Select at least one area to explore";
    }
    if (s === 2) {
      if (!form.name.trim()) e.name = "Required";
      if (!form.email.match(/^[^@\s]+@[^@\s]+\.[^@\s]+$/))
        e.email = "Valid email required";
      if (!form.phone.trim() || form.phone.replace(/\D/g, "").length < 8)
        e.phone = "Valid phone required";
    }
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const next = () => {
    if (!validate(step)) return;
    if (step < 2) setStep((s) => s + 1);
    else handleSubmit();
  };
  const back = () => setStep((s) => Math.max(0, s - 1));

  const handleSubmit = async () => {
    setSubmitting(true);
    setErrors((e) => {
      const next = { ...e };
      delete next.submit;
      return next;
    });
    try {
      await submitLeadToN8n(form, leadSource || defaultModalLeadSource());
      onSubmit(form);
      onClose();
    } catch {
      setErrors((e) => ({
        ...e,
        submit:
          "Unable to send your request. Please try again or email info@iangelswealth.com.",
      }));
    } finally {
      setSubmitting(false);
    }
  };

  const aumOptions = [
    {
      v: "<1",
      label: "Under ₹1 Cr",
      sub: "Building towards long-term wealth creation",
    },
    { v: "1-5", label: "₹1–5 Cr", sub: "Scaling and diversifying investments" },
    {
      v: "5-25",
      label: "₹5–25 Cr",
      sub: "Structured wealth management & alternatives",
    },
    { v: "25+", label: "₹25 Cr+", sub: "UHNI / Family Office requirements" },
  ];

  const interestOptions = [
    "Public Markets & Core Allocation",
    "Alternative Investments & AIFs",
    "Curated Startup Opportunities",
    "Global Investing & GIFT City",
    "Estate & Legacy Planning",
    "Liquidity & Capital Solutions",
  ];

  return (
    <div className={`modal-backdrop ${open ? "open" : ""}`} onClick={onClose}>
      <div
        className="modal"
        onClick={(e) => e.stopPropagation()}
        role="dialog"
        aria-modal="true"
        aria-labelledby="consultation-modal-title"
      >
        <div className="modal-head">
          <div className="modal-head__titles">
            <h1 className="modal-cta-title" id="consultation-modal-title">
              Schedule a Private Consultation
            </h1>
            <div className="modal-step-indicator">Step {step + 1} of 3</div>
          </div>
          <button className="modal-close" onClick={onClose} aria-label="Close">
            <IconClose />
          </button>
        </div>
        <div className="modal-progress">
          <div
            className="bar"
            style={{ transform: `scaleX(${(step + 1) / 3})` }}
          />
        </div>

        <div className="modal-body">
          {step === 0 && (
            <>
              <h2>What stage of wealth are we planning for?</h2>
              <p className="lead">
                This helps us understand your current investment landscape and
                structure the right introductory conversation.
              </p>
              <div className="choice-grid">
                {aumOptions.map((o) => (
                  <div
                    key={o.v}
                    className={`choice ${form.aum === o.v ? "selected" : ""}`}
                    onClick={() => update("aum", o.v)}
                  >
                    <div className="label">{o.label}</div>
                    <div className="sub">{o.sub}</div>
                  </div>
                ))}
              </div>
              {errors.aum && (
                <div
                  style={{
                    color: "var(--accent-red)",
                    fontSize: 13,
                    marginTop: 12,
                  }}
                >
                  {errors.aum}
                </div>
              )}
            </>
          )}

          {step === 1 && (
            <>
              <h2>What would you like to explore?</h2>
              <p className="lead">
                Select all that apply. We'll connect you with the relevant
                specialists from our team.
              </p>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
                {interestOptions.map((i) => (
                  <button
                    key={i}
                    type="button"
                    onClick={() => toggleInterest(i)}
                    className={`choice ${form.interests.includes(i) ? "selected" : ""}`}
                    style={{ padding: "12px 18px", flex: "0 0 auto" }}
                  >
                    <div className="label" style={{ fontSize: 15 }}>
                      {i}
                    </div>
                  </button>
                ))}
              </div>
              {errors.interests && (
                <div
                  style={{
                    color: "var(--accent-red)",
                    fontSize: 13,
                    marginTop: 12,
                  }}
                >
                  {errors.interests}
                </div>
              )}
            </>
          )}

          {step === 2 && (
            <>
              <h2>How can we reach you?</h2>
              <p className="lead">
                We'll get in touch within one business day to schedule your
                introductory consultation.
              </p>
              <div className={`field ${errors.name ? "error" : ""}`}>
                <label>Full Name</label>
                <input
                  value={form.name}
                  onChange={(e) => update("name", e.target.value)}
                  placeholder="Your name"
                />
                {errors.name && <div className="err">{errors.name}</div>}
              </div>
              <div className={`field ${errors.email ? "error" : ""}`}>
                <label>Email Address</label>
                <input
                  type="email"
                  value={form.email}
                  onChange={(e) => update("email", e.target.value)}
                  placeholder="you@company.com"
                />
                {errors.email && <div className="err">{errors.email}</div>}
              </div>
              <div className={`field ${errors.phone ? "error" : ""}`}>
                <label>Phone Number (with country code)</label>
                <input
                  value={form.phone}
                  onChange={(e) => update("phone", e.target.value)}
                  placeholder="+91 98XXX XXXXX"
                />
                {errors.phone && <div className="err">{errors.phone}</div>}
              </div>
              <div className="field">
                <label>Anything else we should know? (Optional)</label>
                <textarea
                  rows={4}
                  value={form.message}
                  onChange={(e) => update("message", e.target.value)}
                  placeholder="Current portfolio structure, investment interests, liquidity events, or anything you'd like us to prepare for before the call."
                />
              </div>
            </>
          )}

          {errors.submit ? (
            <p
              role="alert"
              style={{
                marginTop: 16,
                color: "var(--accent-red)",
                fontSize: 14,
                lineHeight: 1.5,
              }}
            >
              {errors.submit}
            </p>
          ) : null}
          <div className="modal-actions">
            {step > 0 ? (
              <button
                className="btn ghost"
                onClick={back}
                disabled={submitting}
              >
                <IconChevL /> Back
              </button>
            ) : (
              <span style={{ fontSize: 12, color: "var(--ink-4)" }}>
                Confidential. We'll never share your details.
              </span>
            )}
            <button
              className="btn primary"
              onClick={next}
              disabled={submitting}
            >
              {submitting
                ? "Sending…"
                : step === 2
                  ? "Schedule Consultation"
                  : "Continue"}{" "}
              <IconArrow size={12} />
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

// Toast
function Toast({ open, message }) {
  return (
    <div className={`toast ${open ? "show" : ""}`}>
      <span className="dot" />
      {message}
    </div>
  );
}

Object.assign(window, {
  Header,
  Footer,
  AuditModal,
  Toast,
  useReveal,
  Counter,
  buildLeadPayload,
  submitLeadToN8n,
});
