/* global React */
/* ============================================================
   Vesta marketing — shared components
   Used by ui_kits/marketing/, ui_kits/partners/, ui_kits/clients/
   ============================================================ */

const VM_LOGO_HORIZONTAL = "/assets/logo-horizontal-original.svg?v=2";
const VM_LOGO_MARK = "/assets/logo-mark.svg?v=2";

/* ---------- Brand mark (img-based, never recoloured per bible) ---------- */
function VmBrand({ href = "/", inverted = false }) {
  return (
    <a href={href} className="vm-brand" aria-label="Vesta home">
      <img
        src={VM_LOGO_HORIZONTAL}
        alt="Vesta"
        style={inverted ? { filter: "brightness(0) invert(1)" } : null}
      />
    </a>
  );
}

/* ---------- Nav ----------
   surface: 'partners' | 'clients' | 'marketing'
   Audience toggle is the trust-and-clarity move:
   visitors see exactly which side of the B2B2C they're on.
*/
function VmNav({ surface = "marketing", links = [], brandHref = "/marketing", root = "" }) {
  const [menuOpen, setMenuOpen] = React.useState(false);
  const ctaHref = surface === "clients"
    ? "https://calendly.com/growwithvesta/30min"
    : "https://calendly.com/growwithvesta/team";
  const ctaLabel = surface === "clients" ? "Schedule a call" : "Talk to our team";
  const ctaClass = surface === "clients"
    ? "vm-btn vm-btn-green vm-btn-sm"
    : "vm-btn vm-btn-primary vm-btn-sm";
  const signInHref = surface === "partners"
    ? "https://portal.growwithvesta.com/login"
    : "#signin";

  const closeMenu = () => setMenuOpen(false);

  return (
    <nav className={`vm-nav${menuOpen ? " is-open" : ""}`}>
      <div className="vm-nav-inner">
        <VmBrand href={brandHref} />

        {/* Audience toggle — always visible across all surfaces */}
        <div className="vm-nav-toggle" role="tablist" aria-label="Choose audience">
          <a
            href={`${root}/partners/index.html`}
            className={surface === "partners" ? "is-active" : ""}
            role="tab"
            aria-selected={surface === "partners"}
          >
            Partners
          </a>
          <a
            href={`${root}/clients/index.html`}
            className={surface === "clients" ? "is-active" : ""}
            role="tab"
            aria-selected={surface === "clients"}
          >
            Clients
          </a>
        </div>

        <div className="vm-nav-links">
          {links.map((l) => (
            <a key={l.href} href={l.href} className={l.active ? "is-active" : ""}>
              {l.label}
            </a>
          ))}
        </div>

        <div className="vm-nav-ctas">
          <a href={signInHref} className="vm-link">Sign in</a>
          <a href={ctaHref} className={ctaClass}>{ctaLabel}</a>
          <button
            type="button"
            className="vm-nav-burger"
            aria-label={menuOpen ? "Close menu" : "Open menu"}
            aria-expanded={menuOpen}
            onClick={() => setMenuOpen((o) => !o)}
          >
            <span /><span /><span />
          </button>
        </div>
      </div>

      <div className="vm-nav-panel" aria-hidden={!menuOpen}>
        {links.map((l) => (
          <a
            key={l.href}
            href={l.href}
            className={l.active ? "is-active" : ""}
            onClick={closeMenu}
          >
            {l.label}
          </a>
        ))}
        <a href={signInHref} onClick={closeMenu}>Sign in</a>
      </div>
    </nav>
  );
}

/* ---------- Footer ---------- */
function VmFooter({ surface = "marketing" }) {
  return (
    <>
      <footer className="vm-footer">
        <div className="vm-footer-inner">
          <div className="vm-footer-brand">
            <img src={VM_LOGO_HORIZONTAL} alt="Vesta" />
            <p>Building a more inclusive financial future, from ITINs to long-term savings.</p>
          </div>
          <div className="vm-footer-cols">
            <div>
              <h5>For partners</h5>
              <a href="/partners">Overview</a>
              <a href="/partners#assessment">Assessment</a>
              <a href="/partners/resources.html">Resources</a>
              <a href="https://calendly.com/growwithvesta/team">Talk to our team</a>
            </div>
            <div>
              <h5>For clients</h5>
              <a href="/clients">Overview</a>
              <a href="/clients#services">Services</a>
              <a href="/clients/resources.html#faq">FAQ</a>
              <a href="https://www.growwithvesta.com/itin-intake">Get started</a>
            </div>
            <div>
              <h5>Company</h5>
              <a href="/about.html">About</a>
              <a href="/press.html">Press</a>
              <a href="/careers.html">Careers</a>
              <a href="/contact.html">Contact</a>
            </div>
            <div>
              <h5>Legal</h5>
              <a href="/privacy.html">Privacy</a>
              <a href="/terms.html">Terms</a>
              <a href="/accessibility.html">Accessibility</a>
            </div>
          </div>
        </div>
        <div className="vm-footer-fine">
          <span>© 2026 Vesta Prosperity PBC · Brooklyn, NY</span>
          <span>hello@growwithvesta.com</span>
        </div>
      </footer>
    </>
  );
}

/* ---------- Photo placeholder with art direction ---------- */
function VmPhoto({ aspect = "wide", caption, subject, dir = "tl", orange = false }) {
  const aspectClass = {
    wide: "is-wide",
    square: "is-square",
    tall: "is-tall",
    portrait: "",
  }[aspect] || "";
  const petalDir = {
    tl: "vm-petal-tl",
    tr: "vm-petal-tr",
    bl: "vm-petal-bl",
    br: "vm-petal-br",
  }[dir] || "vm-petal-tr";

  return (
    <figure className={`vm-photo ${aspectClass} ${orange ? "is-orange" : ""}`}>
      <div className="vm-photo-frame"></div>
      <div className={`vm-photo-petal`}>
        <svg
          viewBox="0 0 264.7 264.7"
          fill={orange ? "#ffffff" : "#ff543f"}
          className={petalDir}
          style={{
            position: "absolute",
            width: "30%",
            height: "30%",
            ...(dir === "tl" ? { top: 18, left: 18 } : {}),
            ...(dir === "tr" ? { top: 18, right: 18 } : {}),
            ...(dir === "bl" ? { bottom: 64, left: 18 } : {}),
            ...(dir === "br" ? { bottom: 64, right: 18 } : {}),
            opacity: 0.85,
          }}
        >
          <path d="M263.6,1.1c3.2,35.5.8,71.2-25.8,97.7-24.5,24.5-63,25.8-97.7,25.8h0c0-34.7,1.3-73.2,25.8-97.7C192.5.3,228.2-2.1,263.6,1.1Z" />
        </svg>
      </div>
      <figcaption className="vm-photo-meta">
        <strong>{subject || "Photo placeholder"}</strong>
        {caption || "Real human · warm tones · natural light"}
      </figcaption>
    </figure>
  );
}

/* ---------- Named quote / testimonial ---------- */
function VmQuote({ quote, name, role, lang }) {
  return (
    <figure className="vm-quote" lang={lang || "en"}>
      <div className="vm-quote-photo" aria-hidden="true"></div>
      <div className="vm-quote-body">
        <blockquote>
          <p>"{quote}"</p>
        </blockquote>
        <figcaption className="vm-quote-attr">
          <span className="nm">{name}</span>
          <span className="role">{role}</span>
        </figcaption>
      </div>
    </figure>
  );
}

/* ---------- Partner logos band ---------- */
function VmPartnerLogos() {
  const partners = ["Robin Hood Foundation", "Camelback Ventures", "John Jay College", "Grow Brooklyn", "Hartwick VITA/TCE"];
  return (
    <section className="vm-partners">
      <div className="vm-partners-inner">
        <span className="vm-eyebrow is-mute">Trusted by</span>
        <ul className="vm-partners-list">
          {partners.map((p) => (
            <li key={p}>{p}</li>
          ))}
        </ul>
      </div>
    </section>
  );
}

/* ---------- Stat (number + label) ---------- */
function VmStat({ num, lbl }) {
  return (
    <div className="vm-stat">
      <span className="num">{num}</span>
      <span className="lbl">{lbl}</span>
    </div>
  );
}

/* ---------- Icon set — outlined, 2px stroke, matches bible ---------- */
function VmIcon({ name, size = 24 }) {
  const props = {
    width: size,
    height: size,
    viewBox: "0 0 24 24",
    fill: "none",
    stroke: "currentColor",
    strokeWidth: 2,
    strokeLinecap: "round",
    strokeLinejoin: "round",
  };
  switch (name) {
    case "document":
      return (
        <svg {...props}>
          <path d="M5 4h10l4 4v12a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1Z" />
          <path d="M14 4v5h5" />
          <path d="M8 14h8M8 17h5" />
        </svg>
      );
    case "wallet":
      return (
        <svg {...props}>
          <path d="M4 7c0-1.1.9-2 2-2h12a2 2 0 0 1 2 2v3" />
          <path d="M4 7v10c0 1.1.9 2 2 2h13a1 1 0 0 0 1-1v-3" />
          <path d="M21 13h-4a2 2 0 1 0 0 4h4a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1Z" />
        </svg>
      );
    case "card":
      return (
        <svg {...props}>
          <rect x="3" y="6" width="18" height="13" rx="2" />
          <path d="M3 10h18" />
          <path d="M7 15h3" />
        </svg>
      );
    case "growth":
      return (
        <svg {...props}>
          <path d="M3 17 9 11l4 4 8-8" />
          <path d="M14 7h7v7" />
        </svg>
      );
    case "shield":
      return (
        <svg {...props}>
          <path d="M12 3 3 7v6c0 5 3.5 7.5 9 9 5.5-1.5 9-4 9-9V7l-9-4Z" />
          <path d="m9 12 2 2 4-4" />
        </svg>
      );
    case "community":
      return (
        <svg {...props}>
          <circle cx="9" cy="8" r="3" />
          <path d="M3 20a6 6 0 0 1 12 0" />
          <circle cx="17" cy="9" r="2.5" />
          <path d="M14.5 20a4.5 4.5 0 0 1 7 0" />
        </svg>
      );
    case "education":
      return (
        <svg {...props}>
          <path d="M2 9l10-5 10 5-10 5L2 9Z" />
          <path d="M6 11v5c0 2 3 3 6 3s6-1 6-3v-5" />
          <path d="M22 9v5" />
        </svg>
      );
    case "report":
      return (
        <svg {...props}>
          <path d="M3 3v18h18" />
          <path d="M7 14v4M11 11v7M15 8v10M19 5v13" />
        </svg>
      );
    case "calendar":
      return (
        <svg {...props}>
          <rect x="3" y="5" width="18" height="16" rx="2" />
          <path d="M3 9h18M8 3v4M16 3v4" />
        </svg>
      );
    case "lock":
      return (
        <svg {...props}>
          <rect x="6" y="10" width="12" height="10" rx="2" />
          <path d="M9 10V7a3 3 0 0 1 6 0v3" />
        </svg>
      );
    case "globe":
      return (
        <svg {...props}>
          <circle cx="12" cy="12" r="9" />
          <path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18" />
        </svg>
      );
    case "chat":
      return (
        <svg {...props}>
          <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v10Z" />
        </svg>
      );
    case "video":
      return (
        <svg {...props}>
          <rect x="3" y="6" width="14" height="12" rx="2" />
          <path d="m17 10 4-2v8l-4-2" />
        </svg>
      );
    case "checklist":
      return (
        <svg {...props}>
          <path d="M9 6h11M9 12h11M9 18h11" />
          <path d="m3 6 1.5 1.5L7 5M3 12l1.5 1.5L7 11M3 18l1.5 1.5L7 17" />
        </svg>
      );
    case "arrow-right":
      return (
        <svg {...props}>
          <path d="M5 12h14" />
          <path d="m13 6 6 6-6 6" />
        </svg>
      );
    case "check":
      return (
        <svg {...props}>
          <circle cx="12" cy="12" r="9" />
          <path d="m8 12 3 3 5-6" />
        </svg>
      );
    default:
      return <svg {...props}><circle cx="12" cy="12" r="8" /></svg>;
  }
}

/* ---------- Card (feature / resource) ---------- */
function VmCard({ icon, tag, title, body, cta = "Learn more", href = "#", resource = false }) {
  return (
    <a className={`vm-card ${resource ? "is-resource" : ""}`} href={href}>
      {icon ? <span className="vm-card-icon"><VmIcon name={icon} size={28} /></span> : null}
      {tag ? <span className="vm-card-tag">{tag}</span> : null}
      <h3 className="vm-h3">{title}</h3>
      <p className="vm-body">{body}</p>
      <span className="vm-card-arrow">{cta} <VmIcon name="arrow-right" size={16} /></span>
    </a>
  );
}

/* ---------- ITIN Event Banner — dismissible green strip ---------- */
function ItinEventBanner() {
  const [visible, setVisible] = React.useState(true);
  if (!visible) return null;
  return (
    <div style={{
      background: "var(--vesta-green)", color: "#fff",
      padding: "11px 24px",
      display: "flex", alignItems: "center", justifyContent: "center",
      gap: 20, flexWrap: "wrap", fontSize: 14, position: "relative",
    }}>
      <span>
        <strong>Next ITIN Community Call:</strong> Free live session with our IRS Acceptance Agent team.
      </span>
      <a
        href="https://codeforamerica.zoom.us/meeting/register/XYAj2jn9Qoi_M-iZBHtQmw#/registration"
        target="_blank"
        rel="noopener noreferrer"
        style={{
          background: "#fff", color: "var(--vesta-green)",
          padding: "6px 18px", borderRadius: 999,
          fontSize: 13, fontWeight: 700, whiteSpace: "nowrap",
          textDecoration: "none",
        }}
      >
        Register free
      </a>
      <button
        type="button"
        onClick={() => setVisible(false)}
        aria-label="Dismiss"
        style={{
          position: "absolute", right: 20, top: "50%", transform: "translateY(-50%)",
          background: "none", border: "none", color: "rgba(255,255,255,0.75)",
          cursor: "pointer", fontSize: 22, padding: 4, lineHeight: 1, fontWeight: 300,
        }}
      >×</button>
    </div>
  );
}

/* ---------- Newsletter / intake form ---------- */
function NewsletterIntake({ id = "newsletter", surface = "partners" }) {
  const [form, setForm] = React.useState({ name: "", email: "", type: "" });
  const [submitted, setSubmitted] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [sendError, setSendError] = React.useState(null);
  const isGreen = surface === "clients";
  const accent = isGreen ? "var(--vesta-green)" : "var(--vesta-orange)";
  const btnClass = isGreen ? "vm-btn vm-btn-green vm-btn-lg" : "vm-btn vm-btn-primary vm-btn-lg";

  const types = [
    { value: "partner", label: "Nonprofit or employer", sub: "Add Vesta to your program" },
    { value: "investor", label: "Investor or funder", sub: "Mission-aligned capital" },
    { value: "individual", label: "Individual or family", sub: "Get my ITIN and more" },
    { value: "other", label: "Press or researcher", sub: "Learning about Vesta" },
  ];

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

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!form.email || !form.type || sending) return;
    setSendError(null);
    setSending(true);
    try {
      const res = await fetch("/api/newsletter-welcome", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: form.email, name: form.name, type: form.type, surface }),
      });
      if (!res.ok) throw new Error("HTTP " + res.status);
      setSubmitted(true);
    } catch (err) {
      setSendError("Couldn't sign you up right now. Try again, or email us at hello@growwithvesta.com.");
    } finally {
      setSending(false);
    }
  };

  return (
    <section id={id} style={{ background: "var(--vesta-gray-1)", paddingBlock: "clamp(72px, 8vw, 112px)" }}>
      <div className="vm-container">
        {submitted ? (
          <div style={{ maxWidth: 520, margin: "0 auto", textAlign: "center" }}>
            <div style={{
              width: 64, height: 64, borderRadius: 999,
              background: accent, color: "#fff",
              display: "flex", alignItems: "center", justifyContent: "center",
              margin: "0 auto 24px", fontSize: 28,
            }}>✓</div>
            <h2 className="vm-h1">You're on the list.</h2>
            <p className="vm-lede" style={{ marginTop: 16, maxWidth: "44ch", marginLeft: "auto", marginRight: "auto" }}>
              We'll be in touch soon with updates, resources, and next steps tailored to you.
            </p>
          </div>
        ) : (
          <div className="vm-grid" style={{ alignItems: "start", gap: "0 clamp(32px, 5vw, 80px)" }}>
            <div className="vm-col-4">
              <span className="vm-eyebrow" style={{ color: accent }}>Stay connected</span>
              <h2 className="vm-h1" style={{ marginTop: 14 }}>Join the Vesta community.</h2>
              <p className="vm-lede" style={{ marginTop: 18 }}>
                Updates, resources, and upcoming events tailored to where you fit in. Tell us who you are so we only send what's actually useful.
              </p>
            </div>
            <div className="vm-col-8">
              <form onSubmit={handleSubmit}>
                <div style={{ marginBottom: 28 }}>
                  <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: "0.05em", textTransform: "uppercase", color: "var(--vesta-gray-4)", marginBottom: 12 }}>I am a...</div>
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
                    {types.map((t) => (
                      <button
                        key={t.value}
                        type="button"
                        onClick={() => set("type", t.value)}
                        style={{
                          textAlign: "left", padding: "16px 20px", borderRadius: 12, border: "none",
                          background: form.type === t.value ? "var(--vesta-black)" : "#fff",
                          color: form.type === t.value ? "#fff" : "var(--vesta-black)",
                          cursor: "pointer", transition: "background 150ms, color 150ms",
                          boxShadow: "0 1px 3px rgba(0,0,0,0.07)",
                        }}
                      >
                        <div style={{ fontWeight: 700, fontSize: 14 }}>{t.label}</div>
                        <div style={{ fontSize: 12, opacity: 0.6, marginTop: 2 }}>{t.sub}</div>
                      </button>
                    ))}
                  </div>
                </div>

                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20, marginBottom: 28 }}>
                  {[
                    { key: "name", label: "Name", type: "text", placeholder: "Your name" },
                    { key: "email", label: "Email", type: "email", placeholder: "you@example.com" },
                  ].map((f) => (
                    <div key={f.key}>
                      <label style={{ fontSize: 12, fontWeight: 700, letterSpacing: "0.05em", textTransform: "uppercase", color: "var(--vesta-gray-4)", display: "block", marginBottom: 8 }}>
                        {f.label}
                      </label>
                      <input
                        type={f.type}
                        placeholder={f.placeholder}
                        required={f.key === "email"}
                        value={form[f.key]}
                        onChange={(e) => set(f.key, e.target.value)}
                        style={{
                          width: "100%", padding: "12px 0",
                          fontFamily: "var(--font-sans)", fontSize: 15,
                          border: "none", borderBottom: "1.5px solid var(--vesta-gray-2)",
                          background: "transparent", outline: "none",
                          color: "var(--vesta-black)",
                        }}
                      />
                    </div>
                  ))}
                </div>

                <button
                  type="submit"
                  disabled={sending}
                  className={btnClass}
                  style={{
                    opacity: (!form.email || !form.type || sending) ? 0.38 : 1,
                    pointerEvents: (!form.email || !form.type || sending) ? "none" : "auto",
                    cursor: sending ? "wait" : "pointer",
                  }}
                >
                  {sending ? "Sending…" : "Join our list"}
                </button>
                {sendError && (
                  <p style={{ marginTop: 12, fontSize: 13, color: "var(--vesta-orange)" }}>{sendError}</p>
                )}
              </form>
            </div>
          </div>
        )}
      </div>
    </section>
  );
}

/* expose to other Babel scripts */
Object.assign(window, {
  VmBrand,
  VmNav,
  VmFooter,
  VmPhoto,
  VmQuote,
  VmPartnerLogos,
  VmStat,
  VmIcon,
  VmCard,
  ItinEventBanner,
  NewsletterIntake,
});

/* ============================================================
   Mobile collapsible sections for guide pages.
   On mobile (<=900px), wraps each <h2> inside <article> together
   with its following content into a native <details> element.
   Sections collapsed by default (first one open). Resizing to
   desktop unwraps everything back to flat structure.
   ============================================================ */
(function setupGuideCollapsibles() {
  if (typeof document === "undefined") return;

  function getContentColumns() {
    /* React serializes inline gridColumn:1 + gridRow:"1 / 20" as grid-area shorthand */
    return Array.from(
      document.querySelectorAll('article [style*="grid-area: 1 / 1 / 20"]')
    );
  }

  function isMobile() {
    return window.matchMedia("(max-width: 900px)").matches;
  }

  function unwrap(col) {
    Array.from(col.querySelectorAll(":scope > details.vm-c-section")).forEach((d) => {
      const summary = d.querySelector(":scope > summary");
      if (summary) {
        const h2 = summary.querySelector("h2");
        if (h2) d.parentNode.insertBefore(h2, d);
        summary.remove();
      }
      while (d.firstChild) d.parentNode.insertBefore(d.firstChild, d);
      d.remove();
    });
  }

  function wrap(col) {
    const children = Array.from(col.children);
    const sections = [];
    let current = null;

    children.forEach((child) => {
      const isAnchorSpan =
        child.tagName === "SPAN" &&
        child.id &&
        child.nextElementSibling &&
        child.nextElementSibling.tagName === "H2";
      const isH2 = child.tagName === "H2";

      if (isAnchorSpan) {
        current = { anchor: child, h2: null, body: [] };
        sections.push(current);
      } else if (isH2) {
        if (current && !current.h2) {
          current.h2 = child;
        } else {
          current = { anchor: null, h2: child, body: [] };
          sections.push(current);
        }
      } else if (current) {
        current.body.push(child);
      }
    });

    sections.forEach((section, idx) => {
      if (!section.h2) return;
      const details = document.createElement("details");
      details.className = "vm-c-section";
      if (idx === 0) details.setAttribute("open", "");

      const summary = document.createElement("summary");
      summary.appendChild(section.h2.cloneNode(true));
      details.appendChild(summary);

      section.body.forEach((node) => details.appendChild(node));

      const placeBefore = section.anchor || section.h2;
      placeBefore.parentNode.insertBefore(details, section.h2);
      if (section.h2.parentNode) section.h2.parentNode.removeChild(section.h2);
    });
  }

  function apply() {
    const cols = getContentColumns();
    if (!cols.length) return;
    cols.forEach((col) => {
      unwrap(col);
      if (isMobile()) wrap(col);
    });
  }

  function expandFromHash() {
    const hash = window.location.hash;
    if (!hash || hash.length < 2) return;
    const target = document.getElementById(hash.slice(1));
    if (!target) return;
    let details = target.closest && target.closest("details.vm-c-section");
    if (!details) {
      let n = target.nextElementSibling;
      while (n && n.tagName !== "DETAILS") n = n.nextElementSibling;
      details = n;
    }
    if (details) details.open = true;
  }

  let initDone = false;
  function init() {
    if (initDone) return;
    initDone = true;
    apply();
    expandFromHash();

    let t;
    window.addEventListener("resize", () => {
      clearTimeout(t);
      t = setTimeout(apply, 200);
    });

    document.addEventListener("click", (e) => {
      const a = e.target.closest && e.target.closest('a[href^="#"]');
      if (!a) return;
      const id = a.getAttribute("href").slice(1);
      if (!id) return;
      setTimeout(expandFromHash, 30);
    });

    window.addEventListener("hashchange", expandFromHash);
  }

  if (getContentColumns().length && document.querySelector("article h2")) {
    init();
  } else {
    const obs = new MutationObserver(() => {
      if (getContentColumns().length && document.querySelector("article h2")) {
        obs.disconnect();
        init();
      }
    });
    obs.observe(document.body, { childList: true, subtree: true });
    setTimeout(() => obs.disconnect(), 8000);
  }
})();
