const fmt = n => n.toLocaleString("en-US");
const CD_DIMS = {
  type: ["All investor types", "Angel Investors", "Venture Capital", "Private Equity", "Family Offices", "Limited Partners", "Institutional Investors", "Hedge Funds", "Crypto Investors", "Real Estate Investors", "Fund of Funds"],
  region: ["Any region", "North America", "Europe", "Asia-Pacific", "Middle East", "Latin America & Caribbean", "Africa"],
  stage: ["Any stage", "Pre-seed", "Seed", "Series A", "Series B+", "Growth", "Buyout / PE", "Early stage (general)"],
  sector: ["Any sector", "Software & IT", "AI, Data & Deep Tech", "Fintech & Financial Services", "Healthcare & Life Sciences", "Consumer & Retail", "Energy, Climate & Cleantech", "Real Estate & PropTech", "Media, Gaming & Entertainment", "Crypto & Web3", "Industrials, Hardware & Manufacturing", "Mobility, Transport & Logistics", "Education", "Agriculture & FoodTech", "Business & Professional Services", "Telecom & Communications", "Sector-agnostic / Diversified"]
};
const CD_FILTERS = [["type", "Investor type"], ["region", "Region"], ["stage", "Stage"], ["sector", "Sector"]];
const CD_TOP10 = [["United States", 114668], ["United Kingdom", 12763], ["Canada", 6389], ["Germany", 6251], ["Switzerland", 4961], ["France", 4124], ["China", 2903], ["Netherlands", 2780], ["Sweden", 2733], ["India", 2561]].map(([name, n]) => ({ name, n }));
const CD_NAMES = { "Palestine, State of": "Palestine", "Virgin Islands, British": "British Virgin Islands", "Virgin Islands, U.S.": "US Virgin Islands", "Congo, The Democratic Republic of the": "DR Congo" };
const dn = n => CD_NAMES[n] || n;
const p3 = s => String(s).padStart(3, "0");
const CD_BANDS = [["10,000+", "#1E3A8A"], ["1,000 to 9,999", "#3B82F6"], ["100 to 999", "#93BAFA"], ["10 to 99", "#C4DAFC"], ["1 to 9", "#E7F0FE"]];
const fillOf = c => !c ? "#EDEDF0" : c.lt ? CD_BANDS[4][1] : CD_BANDS[c.n >= 10000 ? 0 : c.n >= 1000 ? 1 : c.n >= 100 ? 2 : 3][1];
const ATLAS = "https://cdn.jsdelivr.net/npm/world-atlas@2.0.2/countries-110m.json";

function Cta({ size = "lg", light }) {
  return <div className="cd-cta"><Button variant="primary" size={size} arrow href={CH.APP} target="_blank" rel="noopener noreferrer" style={light ? { background: "#fff", color: "var(--accent-primary)" } : undefined}>Get Early Access</Button></div>;
}

function usePageData() {
  const [st, setSt] = React.useState({ d: null, err: false });
  React.useEffect(() => { fetch("data/page-data.json").then(r => { if (!r.ok) throw 0; return r.json(); }).then(d => setSt({ d, err: false })).catch(() => setSt({ d: null, err: true })); }, []);
  return st;
}

function useTween(target) {
  const [v, setV] = React.useState(target);
  const cur = React.useRef(target);
  React.useEffect(() => {
    if (target == null) return;
    const from = cur.current == null ? target : cur.current;
    if (from === target || matchMedia("(prefers-reduced-motion: reduce)").matches) { cur.current = target; setV(target); return; }
    let raf, t0;
    const tick = t => { t0 = t0 || t; const p = Math.min(1, (t - t0) / 300); const x = Math.round(from + (target - from) * p); cur.current = x; setV(x); if (p < 1) raf = requestAnimationFrame(tick); };
    raf = requestAnimationFrame(tick);
    const done = setTimeout(() => { cancelAnimationFrame(raf); cur.current = target; setV(target); }, 350);
    return () => { cancelAnimationFrame(raf); clearTimeout(done); };
  }, [target]);
  return v;
}

function CountryInfo({ c }) {
  if (c.lt) return <div className="cd-info"><b>{dn(c.name)}</b><span>Investor profiles on file</span></div>;
  return <div className="cd-info"><b>{dn(c.name)}</b><span className="mono">{fmt(c.n)} investor profiles</span>{c.top && c.top.length > 0 && <span>Largest types: {c.top.map(([t, x]) => t + " " + fmt(x)).join(" · ")}</span>}</div>;
}

function WorldMap({ data }) {
  const [geo, setGeo] = React.useState(null);
  const [hov, setHov] = React.useState(null);
  const [sel, setSel] = React.useState(null);
  const [open, setOpen] = React.useState(false);
  const box = React.useRef(null);
  React.useEffect(() => {
    fetch(ATLAS).then(r => r.json()).then(t => {
      const fs = topojson.feature(t, t.objects.countries).features.filter(f => f.id !== "010");
      const fc = { type: "FeatureCollection", features: fs };
      const path = d3.geoPath(d3.geoEqualEarth().fitWidth(960, fc));
      const b = path.bounds(fc);
      setGeo({ vb: "0 " + b[0][1] + " 960 " + (b[1][1] - b[0][1]), shapes: fs.map((f, i) => ({ id: f.id != null ? p3(f.id) : "x" + i, d: path(f) })) });
    }).catch(() => setGeo(false));
  }, []);
  const idx = React.useMemo(() => { const m = {}; if (data) { Object.values(data.countries).forEach(c => (m[p3(c.num)] = c)); (data.lt10 || []).forEach(c => (m[p3(c.num)] = { ...c, lt: true })); } return m; }, [data]);
  const all = React.useMemo(() => data ? Object.values(data.countries).sort((a, b) => b.n - a.n) : null, [data]);
  const idOf = e => e.target.getAttribute && e.target.getAttribute("data-id");
  const move = e => {
    const id = idOf(e);
    if (!id || !idx[id] || !matchMedia("(hover: hover)").matches) return setHov(null);
    const r = box.current.getBoundingClientRect();
    setHov({ id, x: Math.max(0, Math.min(e.clientX - r.left + 16, r.width - 266)), y: e.clientY - r.top + 16 });
  };
  const tap = e => { if (window.innerWidth > 900) return; const id = idOf(e); setSel(id && idx[id] && id !== sel ? id : null); };
  const act = (hov && hov.id) || sel;
  const actShape = act && geo && geo.shapes.find(x => x.id === act);
  const rows = open && all ? all : all && all.length >= 10 ? all.slice(0, 10) : CD_TOP10;
  return (
    <section id="coverage" className="cd-sec" data-screen-label="World map"><div className="wrap">
      <SecHead eyebrow="Global Coverage" title="Where the Investors Are" lead="Investor profiles in 170+ countries. Hover or tap a country to see how many investors it holds and its largest investor types." />
      <div className="cd-mapg rv">
        <div>
          <div className="cd-map" ref={box}>
            {geo ? (
              <svg viewBox={geo.vb} role="img" aria-label="World map shaded by the number of investor profiles in each country. The United States and the United Kingdom are the darkest. A ranked list of countries follows the map." onMouseMove={move} onMouseLeave={() => setHov(null)} onClick={tap}>
                {geo.shapes.map(x => <path key={x.id} data-id={x.id} d={x.d} fill={fillOf(idx[x.id])} stroke="#fff" strokeWidth=".5" vectorEffect="non-scaling-stroke" />)}
                {actShape && <path d={actShape.d} fill="none" stroke="#1E3A8A" strokeWidth="1.5" vectorEffect="non-scaling-stroke" pointerEvents="none" />}
              </svg>
            ) : <div className="ph"></div>}
            {hov && idx[hov.id] && <div className="cd-tip" style={{ left: hov.x, top: hov.y }}><CountryInfo c={idx[hov.id]} /></div>}
          </div>
          <div className="cd-panel" aria-live="polite">{sel && idx[sel] ? <CountryInfo c={idx[sel]} /> : "Tap a country to see its count."}</div>
          <div className="cd-legend"><b>Investor profiles per country</b>{CD_BANDS.map(([l, c]) => <span key={l}><i style={{ background: c }}></i>{l}</span>)}</div>
        </div>
        <div className="cd-list">
          <h3>Top 10 Countries</h3>
          <div id="cd-countries" className={"cd-tw" + (open ? " open" : "")}>
            <table>
              <thead><tr><th scope="col">#</th><th scope="col">Country</th>{open && <th scope="col">Region</th>}<th scope="col">Profiles</th></tr></thead>
              <tbody>{rows.map((c, i) => <tr key={c.name}><td>{i + 1}</td><td>{dn(c.name)}</td>{open && <td className="rg">{c.region}</td>}<td>{fmt(c.n)}</td></tr>)}</tbody>
            </table>
          </div>
          <button type="button" className="cd-link" style={{ marginTop: 8 }} aria-expanded={open} aria-controls="cd-countries" disabled={!all} onClick={() => setOpen(o => !o)}>{open ? "Show top 10 countries" : "Show all countries"}</button>
        </div>
      </div>
    </div></section>
  );
}

function CDPricing() {
  return (
    <section id="pricing" className="cd-sec" data-screen-label="Pricing"><div className="wrap">
      <div className="cd-price rv">
        <SecHead align="l" eyebrow="Pricing" title="Half Price Until We Launch" lead="Early access members pay 50% less. Capital Lite is $149 a quarter (standard price $297), Capital Plus is $374 (standard $747) and Capital Exec is $746 (standard $1,491). Early access closes on 28 December 2026." />
        <div className="acts"><Cta /><a className="cd-link" href="/#pricing">See Plans and Pricing</a></div>
      </div>
    </div></section>
  );
}

const CD_FAQ = [
  { q: "How many investors are in Capital Data?", a: "More than 200,000: 150,000+ people and 60,000+ firms across ten investor types." },
  { q: "Which investor types do you cover?", a: "Angel investors, venture capital, family offices, institutional investors, limited partners, private equity, hedge funds, crypto investors, fund of funds and real estate investors." },
  { q: "What do I get in a profile?", a: "One layout of 62 structured fields in four groups: the person, their firm, how they invest and their investor type." },
  { q: "How many profiles have contact details?", a: "85% carry an email, phone number or LinkedIn link. 150,000+ profiles have an email, 125,000+ have a phone number and 110,000+ have a LinkedIn link." },
  { q: "Can I filter by stage, sector and geography?", a: "Yes. Shortlist by investor type, region, stage, sector and cheque size, then export the list." },
  { q: "Can I export the data?", a: "Yes. Export your shortlist to CSV or XLS, or send it to your CRM." },
  { q: "How is the database built?", a: "Every source is mapped to the same 62 fields. People and firms are matched across sources and merged, and each release passes a set of automated quality checks before it goes live." }
];
function CDFinal() {
  return (
    <section id="early-access" className="cd-final navy dk" data-screen-label="Final call to action">
      <div className="wrap cd-final-in">
        <span className="eb rv"><i></i>Early Access</span>
        <h2 className="h2 rv">Get Early Access to Capital Data</h2>
        <p className="lead rv">Join before we launch on 28 December 2026 and get 50% off your plan.</p>
        <ul className="cd-points rv">{["200,000+ investor profiles", "10 investor types across 170+ countries", "50% early access discount"].map(p => <li key={p}><Icon name="Check" size={16} />{p}</li>)}</ul>
        <div className="rv" style={{ alignSelf: "stretch" }}><Cta size="xl" light /></div>
      </div>
    </section>
  );
}

Object.assign(window, { fmt, CD_DIMS, CD_FILTERS, Cta, usePageData, useTween, CountryInfo, WorldMap, CDPricing, CD_FAQ, CDFinal });
