const DS = window.CapitalHuntDesignSystem_5cb134;
const { Icon, Button, IconBox, Avatar, MatchScore, InvestorTypeTag, VerifiedBadge, QueryFilter, AskBar, SegmentedToggle, FAQAccordion } = DS;

const initialsOf = n => n.split(" ").map(s => s[0]).slice(0, 2).join("").toUpperCase();

function Photo({ src, name = "", size = 32, style }) {
  const [bad, setBad] = React.useState(false);
  if (!src || bad) return <Avatar initials={initialsOf(name)} size={size} style={style} />;
  return <img className="ph" loading="lazy" decoding="async" src={src} alt="" width={size} height={size} onError={() => setBad(true)} style={{ width: size, height: size, ...style }} />;
}

function FirmLogo({ dom, size = 16, name = "", style }) {
  const [ok, setOk] = React.useState(false);
  const letter = ((name || dom || "?").trim()[0] || "?").toUpperCase();
  return (
    <span style={{ position: "relative", width: size, height: size, borderRadius: Math.round(size * .28), display: "inline-flex", alignItems: "center", justifyContent: "center", overflow: "hidden", flexShrink: 0, background: ok ? "#fff" : "var(--accent-primary)", color: "#fff", fontFamily: "var(--font-display)", fontWeight: 800, fontSize: Math.max(9, Math.round(size * .46)), lineHeight: 1, ...style }}>
      {!ok && letter}
      {dom ? <img src={CH.L(dom)} alt="" loading="lazy" decoding="async" onLoad={() => setOk(true)} style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "contain", padding: Math.max(1, Math.round(size * .1)) }} /> : null}
    </span>
  );
}

function LogoAvatar({ dom, name = "", size = 36, style }) {
  return <FirmLogo dom={dom} name={name} size={size} style={{ border: "1px solid var(--border-subtle)", ...style }} />;
}

function useInView(opts = { threshold: .3 }) {
  const ref = React.useRef(null);
  const [v, setV] = React.useState(false);
  React.useEffect(() => {
    const el = ref.current; if (!el) return;
    const io = new IntersectionObserver(([e]) => { if (e.isIntersecting) { setV(true); io.disconnect(); } }, opts);
    io.observe(el); return () => io.disconnect();
  }, []);
  return [ref, v];
}

function CountUp({ to, dur = 1800, suffix = "+", format = true }) {
  const [ref, v] = useInView({ threshold: .4 });
  const [n, setN] = React.useState(0);
  React.useEffect(() => {
    if (!v) return; let raf, t0;
    const tick = t => { t0 = t0 || t; const p = Math.min(1, (t - t0) / dur); setN(Math.round(to * (1 - Math.pow(1 - p, 4)))); if (p < 1) raf = requestAnimationFrame(tick); };
    raf = requestAnimationFrame(tick); return () => cancelAnimationFrame(raf);
  }, [v]);
  return <span ref={ref}>{format ? n.toLocaleString("en-US") : n}{suffix}</span>;
}

function Marquee({ children, dur = 40, reverse = false, gap = 16, style }) {
  return <div className="mq" style={style}><div className={"mq-t" + (reverse ? " r" : "")} style={{ "--dur": dur + "s", gap }}>{children}<React.Fragment>{React.Children.map(children, (c, i) => React.cloneElement(c, { key: "d" + i, "aria-hidden": true }))}</React.Fragment></div></div>;
}

const spot = e => { const r = e.currentTarget.getBoundingClientRect(); e.currentTarget.style.setProperty("--mx", (e.clientX - r.left) + "px"); e.currentTarget.style.setProperty("--my", (e.clientY - r.top) + "px"); };

function SecHead({ eyebrow, title, lead, align = "c", children }) {
  return (
    <div className={"sh" + (align === "l" ? " l" : "")}>
      {eyebrow && <span className="eb rv"><i></i>{eyebrow}</span>}
      <h2 className="h2 rv" style={{ "--d": "80ms" }}>{title}</h2>
      {lead && <p className="lead rv" style={{ "--d": "160ms" }}>{lead}</p>}
      {children}
    </div>
  );
}

function useActive(count, rootMargin) {
  const refs = React.useRef([]);
  const [a, setA] = React.useState(0);
  React.useEffect(() => {
    const onScroll = () => {
      const mid = window.innerHeight / 2;
      let best = 0, bestD = Infinity;
      refs.current.forEach((el, i) => { if (!el) return; const r = el.getBoundingClientRect(); const c = r.top + r.height / 2; const d = Math.abs(c - mid); if (d < bestD) { bestD = d; best = i; } });
      setA(best);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => { window.removeEventListener("scroll", onScroll); window.removeEventListener("resize", onScroll); };
  }, [count]);
  const bind = i => ({ ref: el => (refs.current[i] = el), "data-i": i });
  const go = i => { const el = refs.current[i]; if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - window.innerHeight / 2 + el.offsetHeight / 2, behavior: "smooth" }); };
  return [a, bind, go];
}

function useTyping(text, { speed = 45, hold = 2600, start = true } = {}) {
  const [i, setI] = React.useState(0);
  React.useEffect(() => {
    if (!start) return;
    const t = setTimeout(() => setI(i >= text.length + Math.round(hold / speed) ? 0 : i + 1), i === 0 ? 600 : speed);
    return () => clearTimeout(t);
  }, [i, start]);
  return [text.slice(0, i), i >= text.length];
}

function Header({ base = "", current }) {
  const [sc, setSc] = React.useState(false);
  const [open, setOpen] = React.useState(false);
  React.useEffect(() => { const f = () => setSc(window.scrollY > 40); f(); window.addEventListener("scroll", f, { passive: true }); return () => window.removeEventListener("scroll", f); }, []);
  const nav = [["Features", base + "#features"], ["Capital Data", "capital-data.html"], ["Capital Connect", "capital-connect.html"], ["Pricing", base + "#pricing"], ["Blog", "blog.html"], ["Free Calculators", "calculators.html"], ["Free Templates", "templates.html"]];
  const close = () => setOpen(false);
  const menuRef = React.useRef(null), burgerRef = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const root = document.documentElement, prev = root.style.overflow;
    root.style.overflow = "hidden";
    const onKey = e => { if (e.key === "Escape") { setOpen(false); burgerRef.current && burgerRef.current.focus(); } };
    const onDown = e => { if (menuRef.current && !menuRef.current.contains(e.target) && burgerRef.current && !burgerRef.current.contains(e.target)) setOpen(false); };
    const mq = window.matchMedia("(min-width:1241px)"), onMq = () => { if (mq.matches) setOpen(false); };
    document.addEventListener("keydown", onKey);
    document.addEventListener("pointerdown", onDown);
    mq.addEventListener("change", onMq);
    return () => { root.style.overflow = prev; document.removeEventListener("keydown", onKey); document.removeEventListener("pointerdown", onDown); mq.removeEventListener("change", onMq); };
  }, [open]);
  return (
    <div className={"shell" + (sc ? " sc" : "")}>
      <div className="tb"><span className="dot"></span><span><b>Launching 28th December 2026, 08:00 UTC</b><span className="tb-x"> — 500 Spots open for Pre-registration.</span> <a href={CH.APP} target="_blank" rel="noopener noreferrer">Join now to unlock 50% off&nbsp;→</a></span></div>
      <div style={{ padding: "0 12px" }}>
        <header className="hdr">
          <a href={base || "#top"} aria-label="Capital Hunt home"><img src="assets/logos/logo-dark.png" alt="Capital Hunt" /></a>
          <nav className="nav">{nav.map(([l, h]) => <a key={l} href={h} className={l === current ? "on" : undefined} aria-current={l === current ? "page" : undefined}>{l}</a>)}</nav>
          <div className="hdr-cta">
            <a className="login" href={CH.APP} target="_blank" rel="noopener noreferrer">Log In</a>
            <Button className="hdr-go" variant="primary" size="sm" arrow href={CH.APP} target="_blank" style={{ height: 44, padding: "0 20px", fontSize: 13 }}>Get Early Access</Button>
            <button ref={burgerRef} className="burger" aria-label="Menu" aria-expanded={open} aria-controls="mmenu" onClick={() => setOpen(o => !o)} style={{ width: 44, height: 44, borderRadius: 12, border: "1px solid var(--border-subtle)", background: "#fff", alignItems: "center", justifyContent: "center", cursor: "pointer" }}><Icon name={open ? "X" : "Menu"} size={18} /></button>
          </div>
        </header>
      </div>
      <div ref={menuRef} id="mmenu" className={"mmenu" + (open ? " on" : "")}>
        {nav.map(([l, h]) => <a key={l} href={h} onClick={close} className={l === current ? "on" : undefined} aria-current={l === current ? "page" : undefined}>{l}</a>)}
        
        <div className="mm-cta">
          <a className="login" href={CH.APP} target="_blank" rel="noopener noreferrer" onClick={close}>Log In</a>
          <Button variant="primary" arrow fullWidth href={CH.APP} target="_blank">Get Early Access</Button>
        </div>
      </div>
    </div>
  );
}

function SiteFooterBody({ base = "" }) {
  const cols = [
    ["Product", [["Features", base + "#features"], ["Capital Data", "capital-data.html"], ["Capital Connect", "capital-connect.html"], ["Pricing", base + "#pricing"]]],
    ["Resources", [["Blog", "blog.html"], ["Free Calculators", "calculators.html"], ["Free Templates", "templates.html"]]],
    ["Company", [["About", "about.html"], ["Contact", "contact.html"]]],
    ["Legal", [["Privacy", "privacy.html"], ["Terms", "terms.html"]]]
  ];
  return (
    <>
      <div className="fcols">
        <div style={{ display: "flex", flexDirection: "column", gap: 18, alignItems: "flex-start" }}>
          <a href={base || "#top"} style={{ padding: 0, minHeight: 44, display: "flex", alignItems: "center" }}><img src="assets/logos/logo-white.png" alt="Capital Hunt" style={{ height: 30 }} /></a>
          <p style={{ fontSize: 15, color: "#B8C1D9", maxWidth: 320 }}>Your unfair advantage for fundraising.</p>
        </div>
        {cols.map(([h, l]) => <div key={h}><h4>{h}</h4>{l.map(([x, href]) => <a key={x} href={href}>{x}</a>)}</div>)}
      </div>
      <div style={{ display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 12, padding: "24px 0", borderTop: "1px solid rgba(255,255,255,.1)", fontSize: 13, color: "#8D97B5" }}><span>© 2026 VSP Partners Ltd · Company No. 17485578</span><span>45 Albemarle Street, London W1S 4JL</span></div>
      <div className="wordmark" aria-hidden="true">CAPITAL HUNT</div>
    </>
  );
}

function useRevealAll() {
  React.useEffect(() => {
    const reveal = el => el.classList.add("in");
    const io = "IntersectionObserver" in window ? new IntersectionObserver(es => es.forEach(e => { if (e.isIntersecting) { reveal(e.target); io.unobserve(e.target); } }), { threshold: 0, rootMargin: "0px 0px -8% 0px" }) : null;
    const check = () => document.querySelectorAll(".rv:not(.in),.comp:not(.in)").forEach(el => {
      const r = el.getBoundingClientRect();
      if (r.top < (window.innerHeight || document.documentElement.clientHeight) * 0.92 && r.bottom > 0) reveal(el);
      else if (io) io.observe(el);
    });
    check();
    requestAnimationFrame(check);
    const timers = [100, 300, 600].map(ms => setTimeout(check, ms));
    window.addEventListener("load", check);
    window.addEventListener("scroll", check, { passive: true });
    window.addEventListener("resize", check);
    const mo = new MutationObserver(check); mo.observe(document.body, { childList: true, subtree: true });
    return () => { if (io) io.disconnect(); mo.disconnect(); window.removeEventListener("load", check); window.removeEventListener("scroll", check); window.removeEventListener("resize", check); timers.forEach(clearTimeout); };
  }, []);
}

Object.assign(window, { DS, Icon, Button, IconBox, Avatar, MatchScore, InvestorTypeTag, VerifiedBadge, QueryFilter, AskBar, SegmentedToggle, FAQAccordion, Photo, FirmLogo, LogoAvatar, useInView, CountUp, Marquee, spot, SecHead, useActive, useTyping, Header, SiteFooterBody, useRevealAll, initialsOf });
