const cdPh = n => "assets/investors/" + n.toLowerCase().replace(/[^a-z]+/g, "-") + ".jpg";
const cdInv = n => CH.investors.find(v => v.name === n);
const CD_WALL = [["Marc Andreessen", "Naval Ravikant", "Bill Gurley", "Josh Kopelman"], ["Reid Hoffman", "Peter Thiel", "Ron Conway", "Alfred Lin"], ["Paul Graham", "Vinod Khosla", "Fred Wilson", "Keith Rabois"]];
const CD_PORT = [["Airbnb", "airbnb.com"], ["Coinbase", "coinbase.com"], ["GitHub", "github.com"], ["Slack", "slack.com"], ["Figma", "figma.com"], ["Instacart", "instacart.com"]];

function Faces({ names, size = 30 }) {
  return <span className="cd-faces">{names.map((n, i) => <img key={n} src={cdPh(n)} alt="" loading="lazy" decoding="async" style={{ width: size, height: size, marginLeft: i ? -Math.round(size * .3) : 0 }} />)}</span>;
}

function CIcon({ k, size = 16 }) {
  if (k === "linkedin") return <img src="assets/logos/brands/linkedin.svg" alt="" width={size} height={size} style={{ display: "block" }} />;
  return <Icon name={k === "email" ? "Mail" : k === "phone" ? "Phone" : "Check"} size={size} strokeWidth={k === "ok" ? 3 : 2} />;
}

function PersonCard({ v }) {
  return (
    <div className="cd-pc">
      <img className="pic" src={cdPh(v.name)} alt="" decoding="async" />
      <div className="cd-pc-b">
        <div className="cd-pc-n"><span className="trunc">{v.name}</span><VerifiedBadge compact /></div>
        <div className="cd-pc-f"><span className="trunc">{v.title}</span></div>
        <div className="cd-pc-f firm"><FirmLogo dom={v.dom} name={v.firm} size={14} /><span className="trunc">{v.firm}</span></div>
        <div className="cd-pc-m"><InvestorTypeTag type={v.type} size="sm" /><span className="trunc">{v.stages.join(", ")}</span></div>
      </div>
    </div>
  );
}

function CDHero() {
  return (
    <section id="hero" className="cd-hero" data-screen-label="Hero">
      <div className="hero-lines"></div>
      <div className="wrap cd-hero-g">
        <div className="cd-hero-c">
          <span className="eb rv"><i></i>Capital Data</span>
          <h1 className="rv" style={{ "--d": "60ms" }}>Build Your Investor List From <span className="hl">200,000+ Profiles</span></h1>
          <p className="lead rv" style={{ "--d": "120ms" }}>Capital Data is the investor database inside Capital Hunt. Angels, venture capital firms, family offices and seven more investor types, across 170+ countries. Search it, shortlist it and export it in minutes.</p>
          <div className="rv" style={{ "--d": "180ms", alignSelf: "stretch" }}><Cta size="xl" /></div>
        </div>
        <div className="cd-wall rv" style={{ "--d": "200ms" }} role="img" aria-label="Investor profile cards from Capital Data, each with a photo, job title, firm, investor type and stages. The cards include Marc Andreessen, Reid Hoffman, Paul Graham, Naval Ravikant, Peter Thiel and Vinod Khosla.">
          <div className="cd-cols fade-y" aria-hidden="true">
            {CD_WALL.map((col, i) => {
              const cards = col.map(cdInv).filter(Boolean);
              return <div key={i}><div className={"vcol" + (i === 1 ? " dn" : "")} style={{ "--dur": [46, 54, 50][i] + "s" }}>{[0, 1].map(k => cards.map(v => <PersonCard key={k + v.name} v={v} />))}</div></div>;
            })}
          </div>
        </div>
      </div>
    </section>
  );
}

function Tiles({ items, four }) {
  return (
    <div className={"cd-tiles rv" + (four ? " four" : "")}>
      {items.map(([ic, to, suf, l]) => (
        <div key={l} className="cd-tile">
          <span className={"cd-ic" + (typeof ic === "string" ? "" : " brand")} aria-hidden="true">{typeof ic === "string" ? <Icon name={ic} size={18} strokeWidth={ic === "Check" ? 3 : 2} /> : ic}</span>
          <div className="n"><CountUp to={to} suffix={suf} /></div>
          <div className="l">{l}</div>
        </div>
      ))}
    </div>
  );
}

function Numbers() {
  return (
    <section id="numbers" className="cd-sec" data-screen-label="Proof strip"><div className="wrap">
      <SecHead eyebrow="The Database" title="Capital Data in Numbers" />
      <Tiles items={[["Database", 200000, "+", "Investor profiles"], ["Users", 150000, "+", "People"], ["Building2", 60000, "+", "Firms"], ["Shapes", 10, "", "Investor types"], ["Globe", 170, "+", "Countries"]]} />
    </div></section>
  );
}

function Counter({ data, err }) {
  const dims = data ? data.dims : CD_DIMS;
  const [s, setS] = React.useState([0, 0, 0, 0]);
  const look = React.useMemo(() => data ? new Map(data.cells.map(c => [c.slice(0, 4).join("|"), c])) : null, [data]);
  const all = look && look.get("0|0|0|0");
  const total = (all && all[4]) || 238435;
  const any = s.every(x => x === 0);
  // Always resolves to a count: the exact combination if the data has it, otherwise the closest broader selection.
  const hit = React.useMemo(() => {
    let best = null;
    if (look) for (let m = 15; m >= 0; m--) {
      const k = s.map((x, i) => (m >> i) & 1 ? x : 0);
      const c = look.get(k.join("|"));
      if (!c) continue;
      const score = k.reduce((a, x, i) => a + (x ? 16 + (8 >> i) : 0), 0);
      if (!best || score > best.score) best = { score, k, n: c[4], plus: !!c[5] };
    }
    return best || { k: [0, 0, 0, 0], n: total, plus: false };
  }, [look, s, total]);
  const shown = useTween(hit.n);
  const label = i => dims[CD_FILTERS[i][0]][s[i]];
  const pick = f => s.map((x, i) => x && f(i) ? label(i) : null).filter(Boolean);
  const chosen = pick(() => true), kept = pick(i => hit.k[i]), dropped = pick(i => !hit.k[i]);
  const num = fmt(shown == null ? hit.n : shown) + (hit.plus && (shown == null || shown === hit.n) ? "+" : "");
  const sentence = any ? "investor profiles across all ten investor types" : dropped.length ? "investor profiles in " + (kept.join(", ") || "the full database") : "investor profiles match";
  const note = dropped.length ? "Showing " + (kept.length ? "all " + kept.join(", ") + " profiles" : "the full database") + ". A breakdown by " + dropped.join(", ") + " is coming soon." : "";
  const pct = hit.n / total * 100;
  const share = any ? "The full database" : (pct < .1 ? "Under 0.1%" : (pct >= 10 ? Math.round(pct) : pct.toFixed(1)) + "%") + " of all profiles";
  return (
    <section id="counter" className="cd-sec" data-screen-label="Investor counter"><div className="wrap">
      <SecHead eyebrow="Investor Counter" title="How Many Investors Match Your Raise?" lead="Pick an investor type, region, stage and sector. The count updates with every choice." />
      <div className="cd-counter rv">
        <div className="cd-filters">
          <div className="cd-fgrid">
            {CD_FILTERS.map(([k, lb], i) => (
              <div key={k} className="cd-f">
                <label htmlFor={"cd-" + k}>{lb}</label>
                <select id={"cd-" + k} className="cd-sel" disabled={!data} value={s[i]} onChange={e => setS(s.map((x, j) => j === i ? +e.target.value : x))}>
                  {dims[k].map((o, j) => <option key={o} value={j}>{o}</option>)}
                </select>
              </div>
            ))}
          </div>
          <div><button type="button" className="cd-link" style={{ visibility: any ? "hidden" : "visible" }} onClick={() => setS([0, 0, 0, 0])}>Reset filters</button></div>
        </div>
        <div className="cd-result">
          <p className="sr" aria-live="polite" aria-atomic="true">{fmt(hit.n) + (hit.plus ? "+" : "") + " " + sentence + ". " + note}</p>
          <div aria-hidden="true" style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            <div className="cd-count">{num}</div>
            <p className="cd-sent">{sentence}</p>
            <p className="cd-chosen">{chosen.join(" · ")}</p>
            <div className="cd-share"><div className="bar"><i style={{ width: Math.min(100, pct) + "%" }}></i></div><span>{share}</span></div>
            {note && <p className="cd-fall">{note}</p>}
          </div>
          {err && <p className="cd-note" style={{ margin: 0 }}>The counter is unavailable right now.</p>}
        </div>
      </div>
    </div></section>
  );
}

const CD_TYPES = [
  ["Rocket", "Venture Capital", 62000, "Venture firms and the people who work at them. For founders raising from seed through growth."],
  ["HandCoins", "Angel Investors", 54000, "Individual angels, angel groups and syndicates. For founders raising pre-seed and seed rounds."],
  ["Gem", "Family Offices", 47000, "Contacts at 18,000+ single and multi-family offices. For founders and fund managers raising from private wealth."],
  ["Landmark", "Institutional Investors", 34000, "Pension funds, banks, foundations, endowments, insurers and sovereign wealth funds. For fund managers and late-stage raises."],
  ["Handshake", "Limited Partners", 21000, "The people who allocate capital to funds. For fund managers and fundraising agents raising a fund."],
  ["Briefcase", "Private Equity", 7700, "Buyout and growth investors. For later-stage companies and the advisers running their raise."],
  ["Activity", "Hedge Funds", 4800, "Hedge fund managers and their investment teams. For broker-dealers and IR consultants."],
  ["Bitcoin", "Crypto Investors", 2600, "Funds and investors backing crypto and Web3. For Web3 founders."],
  ["Layers", "Fund of Funds", 2100, "Funds that invest in other funds. For emerging fund managers."],
  ["Building2", "Real Estate Investors", 1100, "Real estate investors and their principals. For sponsors, developers and PropTech founders."]
];
function Types() {
  return (
    <section id="investor-types" className="cd-sec" data-screen-label="Investor types"><div className="wrap">
      <SecHead eyebrow="Investor Types" title="Ten Investor Types, One Database" lead="Start with the investors who fund companies at your stage." />
      <div className="cd-types">{CD_TYPES.map(([ic, t, n, d], i) => (
        <div key={t} className="rv" style={{ "--d": (i % 5) * 70 + "ms" }}>
          <article className="cd-card" onMouseMove={spot}>
            <span className="cd-ic" aria-hidden="true"><Icon name={ic} size={18} /></span>
            <h3>{t}</h3>
            <div className="n"><CountUp to={n} /><small>profiles</small></div>
            <p>{d}</p>
            <div className="cd-tbar" aria-hidden="true"><i style={{ "--w": Math.max(3, n / 620) + "%" }}></i></div>
          </article>
        </div>
      ))}</div>
    </div></section>
  );
}

function Profile() {
  const groups = [
    ["The person", "Name, job title, location, a short bio, LinkedIn and X, email and phone.", <><img className="pic" src={cdPh("Marc Andreessen")} alt="Marc Andreessen" loading="lazy" /><span className="cd-gcap">Marc Andreessen</span></>],
    ["The firm", "Firm name, website, description, address, founding year, LinkedIn, firm email and phone.", <><FirmLogo dom="a16z.com" name="Andreessen Horowitz" size={84} style={{ borderRadius: 22, border: "1px solid var(--border-subtle)", boxShadow: "0 10px 30px rgba(15,23,42,.08)" }} /><span className="cd-gcap">Andreessen Horowitz</span></>],
    ["How they invest", "Sectors, stages, rounds, target regions, cheque size, assets under management, portfolio and recent investments.", <><div className="cd-logos">{CD_PORT.map(([n, d]) => <LogoAvatar key={d} dom={d} name={n} size={46} style={{ borderRadius: 13 }} />)}</div><span className="cd-gcap">Portfolio</span></>],
    ["Investor type", "Investor type, person or firm, and sub-type.", <div className="cd-gtags"><InvestorTypeTag type="vc" /><span className="cd-chip sm">Person</span><span className="cd-chip sm">Multi-stage</span></div>]
  ];
  const facts = [["Investor type", <InvestorTypeTag type="vc" size="sm" />], ["Sectors", "Software & IT, AI, Data & Deep Tech, Crypto & Web3"], ["Stages", "Seed, Series A, Growth"]];
  const contacts = [["email", "Email", "••••••••@a16z.com"], ["phone", "Phone", "+1 (•••) •••-••••"], ["linkedin", "LinkedIn", "linkedin.com/in/••••••••"]];
  return (
    <section id="profile" className="cd-sec" data-screen-label="Inside a profile"><div className="wrap">
      <SecHead eyebrow="Profile Fields" title="What Is Inside a Profile" lead="Every profile follows one layout of 62 structured fields, so you always know where to look." />
      <div className="cd-profg">
        <div className="cd-left">
          <div className="cd-groups">{groups.map(([t, d, art], i) => <div key={t} className="rv" style={{ "--d": i * 70 + "ms" }}><div className="cd-group"><div className="cd-gimg">{art}</div><div className="tx"><h3>{t}</h3><p>{d}</p></div></div></div>)}</div>
          <Tiles four items={[["Mail", 150000, "+", "profiles with an email"], ["Phone", 125000, "+", "profiles with a phone number"], [<CIcon k="linkedin" size={18} />, 110000, "+", "profiles with a LinkedIn link"], ["Check", 85, "%", "of profiles carry an email, phone number or LinkedIn link"]]} />
        </div>
        <div className="cd-prof rv" style={{ "--d": "100ms" }} role="img" aria-label="Investor profile for Marc Andreessen, Co-Founder and General Partner at Andreessen Horowitz in Menlo Park, California. It lists investor type, sectors and stages. The email, phone number and LinkedIn link are masked.">
          <div className="cd-prof-h">
            <img src={cdPh("Marc Andreessen")} alt="" loading="lazy" />
            <div><b>Marc Andreessen<VerifiedBadge compact /></b><span className="firm"><FirmLogo dom="a16z.com" name="Andreessen Horowitz" size={15} />Co-Founder &amp; General Partner</span><span>Andreessen Horowitz · Menlo Park, California</span></div>
          </div>
          <dl>{facts.map(([k, v]) => <React.Fragment key={k}><dt>{k}</dt><dd>{v}</dd></React.Fragment>)}</dl>
          <div>{contacts.map(([k, l, v]) => <div key={k} className="cd-crow"><span className="ci"><CIcon k={k} size={16} /></span><div><small>{l}</small><b>{v}</b></div><Icon name="Lock" size={14} /></div>)}</div>
        </div>
      </div>
    </div></section>
  );
}

function CDFeatures() {
  const feats = [
    ["AI-Based Automated Matchmaking", "Connect your data room and our AI suggests the best investors for your specific startup.",
      <><span className="cd-ic"><Icon name="FolderOpen" size={18} /></span><Icon className="arr" name="ArrowRight" size={15} /><span className="cd-ic on"><Icon name="Sparkles" size={18} /></span><Icon className="arr" name="ArrowRight" size={15} /><Faces names={["Reid Hoffman", "Bill Gurley", "Alfred Lin"]} size={34} /></>],
    ["200,000+ Curated Profiles", "People and firms across ten investor types in 170+ countries, in one place. Angels, venture capital firms, family offices, limited partners, institutional investors and more, all held in the same profile layout.",
      <><Faces names={["Marc Andreessen", "Peter Thiel", "Paul Graham", "Vinod Khosla", "Naval Ravikant"]} size={36} /><span className="cd-more">+200K</span></>],
    ["Export Anywhere", "Take your shortlist out in the format you work in: CSV, XLS or straight into your CRM. You can also pull the data through the API.",
      <><span className="cd-fmt"><Icon name="FileText" size={15} />CSV</span><span className="cd-fmt"><img src="assets/logos/brands/microsoftexcel.svg" alt="" width="15" height="15" />XLS</span><span className="cd-fmt"><Icon name="Users" size={15} />CRM</span><span className="cd-fmt"><Icon name="Braces" size={15} />API</span></>],
    ["62 Data Points", "On average, every profile tracks 62 fields covering the person, the firm, how they invest and the investor type.",
      <div className="cd-dots">{Array.from({ length: 62 }, (_, i) => <i key={i} style={{ "--i": i }}></i>)}</div>]
  ];
  return (
    <section id="features" className="cd-sec" data-screen-label="Features"><div className="wrap">
      <SecHead eyebrow="Features" title="Search, Shortlist and Export" lead="Everything you need to go from a blank page to a targeted investor list." />
      <div className="cd-feats">{feats.map(([t, d, art], i) => <div key={t} className="rv" style={{ "--d": i * 70 + "ms" }}><article className="cd-card" onMouseMove={spot}><div className="cd-art" aria-hidden="true">{art}</div><h3>{t}</h3><p>{d}</p></article></div>)}</div>
      <div className="cd-after rv"><p>Want to pitch on-platform too? That is Capital Connect.</p><a className="cd-link" href="capital-connect.html">See Capital Connect</a><div style={{ marginTop: 14, alignSelf: "stretch", display: "flex", justifyContent: "center" }}><Cta /></div></div>
    </div></section>
  );
}

function CDFaq() {
  const h = Math.ceil(CD_FAQ.length / 2);
  return (
    <section id="faq" className="cd-sec" data-screen-label="FAQ"><div className="wrap">
      <SecHead eyebrow="FAQ" title="Questions About the Data" />
      <div className="faq2">
        <div className="rv"><FAQAccordion items={CD_FAQ.slice(0, h)} defaultOpen={0} /></div>
        <div className="rv" style={{ "--d": "100ms" }}><FAQAccordion items={CD_FAQ.slice(h)} defaultOpen={-1} /></div>
      </div>
    </div></section>
  );
}

function CapitalData() {
  const { d, err } = usePageData();
  return <div className="cd"><CDHero /><Numbers /><Counter data={d} err={err} /><WorldMap data={d} /><Types /><Profile /><CDFeatures /><CDPricing /><CDFaq /><CDFinal /></div>;
}

mountPage(<CapitalData />, { current: "Capital Data" });
