const { useState, useEffect, useMemo } = React;

const DONORS = JSON.parse(document.getElementById('donors-data').textContent);

/* ============ LOGO MARK ============ */
function Mark() {
  return (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
      <path d="M12 2 C 7 6 4 10 4 14 a8 8 0 0 0 16 0 c0-4-3-8-8-12z" stroke="currentColor" strokeWidth="1.4" fill="none" />
      <circle cx="12" cy="14" r="2.2" fill="currentColor" />
    </svg>);

}

/* ============ NAV ============ */
function IconBag() {
  return <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
    <path d="M3 5h10l-1 9H4z" stroke="currentColor" strokeWidth="1.3" />
    <path d="M6 5V4a2 2 0 0 1 4 0v1" stroke="currentColor" strokeWidth="1.3" />
  </svg>;
}

function Nav({ route, setRoute, cartCount }) {
  const tabs = [
  { id: "donors", label: "Find a Donor" },
  { id: "science", label: "Our Science" },
  { id: "fund", label: "Fund" }];

  return (
    <div className="nav-wrap">
      <nav className="nav">
        <div className="nav-left">
          {tabs.map((t) =>
          <button
            key={t.id}
            className={`nav-tab ${route === t.id ? "active" : ""}`}
            onClick={() => setRoute(t.id)}>
            {t.label}</button>
          )}
        </div>
        <div className="nav-brand" onClick={() => setRoute("home")} style={{ cursor: "pointer" }}>
          <span>D1</span>
        </div>
        <div className="nav-right">
          <button className="btn btn-ghost" onClick={() => setRoute("cart")} title="Cart" style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
            <IconBag />
            Cart {cartCount > 0 && <span className="cart-badge">{cartCount}</span>}
          </button>
          <button className="btn btn-primary" onClick={() => setRoute("donors")}>Browse donors</button>
        </div>
      </nav>
    </div>);

}

/* ============ LANDING ============ */
function StatusPill({ status }) {
  const map = {
    available: { label: "Available", cls: "available" },
    limited: { label: "🔥 Limited", cls: "limited" },
    waitlist: { label: "Waitlist", cls: "waitlist" }
  };
  const m = map[status] || map.available;
  return <span className={`pill-status ${m.cls}`}><span className="dot" />{m.label}</span>;
}

function FeaturedDonorCard({ donor, avatarStyle, onClick }) {
  return (
    <div className="donor-card fade-in" onClick={onClick}>
      <div className="donor-portrait">
        <div className="canvas"><DonorAvatar donor={donor} style={avatarStyle} /></div>
        <div className="meta-tl">{donor.id}</div>
        <div className={`meta-tr ${donor.status === 'limited' ? 'limited' : ''}`}>
          {donor.status === "available" ? "Available" : donor.status === "limited" ? "Limited" : "Waitlist"}
        </div>
      </div>
      <div className="donor-name">{donor.alias}</div>
      <div className="donor-traits">{donor.height} · {donor.eyes} · {donor.hair}</div>
      <div className="donor-trait-row">
        <span className="chip">{donor.ethnicity}</span>
        <span className="chip">{donor.education}</span>
      </div>
    </div>);

}

function Landing({ setRoute, tweaks, openDonor }) {
  const featured = DONORS.slice(0, 4);
  return (
    <>
      <section className="hero" style={{ lineHeight: "1" }}>
        <div className="eyebrow">A private donor matching platform</div>
        <h1 className="hero-title" style={{ lineHeight: "1" }}>
          Have a {tweaks.heroVariant === "italic" ? <em>D1</em> : "D1"} Baby
        </h1>
        <p className="hero-sub" style={{ opacity: "0.7", lineHeight: "1.5" }}>Donors are selected from accomplished men among athletes, researchers and entrepreneurs. Transparent genetics. A modern way for women to choose the father of their child — on their own terms.

        </p>
        <div className="hero-cta">
          <button className="btn btn-primary btn-lg" onClick={() => setRoute("donors")}>Browse donors</button>
        </div>
      </section>

      <section className="section" style={{ paddingTop: 0 }}>
        <div className="donor-grid">
          {featured.map((d) =>
          <FeaturedDonorCard
            key={d.id}
            donor={d}
            avatarStyle={tweaks.avatarStyle}
            onClick={() => openDonor(d.id)} />

          )}
        </div>

        <section className="manifesto">
          <h2 style={{ fontSize: "40px" }}>Genes matter. <em style={{ fontSize: "45px" }}>Don't settle</em>.</h2>
          <p>
            Nature shapes more than we admit. D1 was built on the belief that women deserve transparency about who their donor is — and that exceptional intellect, character, and accomplishment are worth celebrating, not anonymizing.
          </p>
          <div className="hero-cta">
            <button className="btn btn-primary btn-lg" onClick={() => setRoute("donors")}>Browse available donors</button>
            <button className="btn btn-outline btn-lg" onClick={() => setRoute("science")}>Our Standards</button>
          </div>
        </section>

        <ResearchSection />

        <div className="trust" style={{ display: "none" }}>
          <div className="trust-stat">
            <div className="trust-num"><em>0.03</em>%</div>
            <div className="trust-lbl">Donor acceptance rate</div>
          </div>
          <div className="trust-stat">
            <div className="trust-num">514</div>
            <div className="trust-lbl">Genetic conditions screened</div>
          </div>
          <div className="trust-stat">
            <div className="trust-num">3<em>yr</em></div>
            <div className="trust-lbl">Health follow-up window</div>
          </div>
          <div className="trust-stat">
            <div className="trust-num">12<em>k</em>+</div>
            <div className="trust-lbl">Children born</div>
          </div>
        </div>
      </section>
    </>);

}

/* ============ DONOR SELECTION ============ */
function IconList() {
  return <svg width="13" height="13" viewBox="0 0 16 16" fill="none">
    <path d="M2 4h12M2 8h12M2 12h12" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" />
  </svg>;
}
function IconGrid() {
  return <svg width="13" height="13" viewBox="0 0 16 16" fill="none">
    <rect x="2" y="2" width="5" height="5" stroke="currentColor" strokeWidth="1.4" />
    <rect x="9" y="2" width="5" height="5" stroke="currentColor" strokeWidth="1.4" />
    <rect x="2" y="9" width="5" height="5" stroke="currentColor" strokeWidth="1.4" />
    <rect x="9" y="9" width="5" height="5" stroke="currentColor" strokeWidth="1.4" />
  </svg>;
}
function IconSearch() {
  return <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
    <circle cx="7" cy="7" r="5" stroke="currentColor" strokeWidth="1.4" />
    <path d="M11 11l3 3" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" />
  </svg>;
}

function ProcessSteps() {
  const steps = [
  { n: 1, label: "Browse",     cat: "Discover", fill: 100, active: true },
  { n: 2, label: "Shortlist",  cat: "Discover", fill: 0,  active: false },
  { n: 3, label: "Reserve",    cat: "Discover", fill: 0,   active: false },
  { n: 4, label: "Counseling", cat: "Prepare",  fill: 0,   active: false },
  { n: 5, label: "Schedule",   cat: "Prepare",  fill: 0,   active: false },
  { n: 6, label: "Conceive",   cat: "Outcome",  fill: 0,   active: false }];

  return (
    <div className="process-steps">
      {steps.map((s) =>
      <div key={s.n} className={`pstep ${s.active ? "" : "dim"} cat-${s.cat.toLowerCase()}`}>
          <div className="pstep-head">
            <span className="pstep-num">{s.n}</span>
            <span>{s.label}</span>
          </div>
          <div className="pstep-bar">
            <div className="pstep-bar-fill" style={{ "--fill": `${s.fill}%` }} />
          </div>
          <div className="pstep-cat">{s.cat}</div>
        </div>
      )}
    </div>);

}

function DonorSelection({ tweaks, openDonor }) {
  const [view, setView] = useState("table"); // table | grid
  const [occ, setOcc] = useState("all");
  const [heightBucket, setHeightBucket] = useState("all");
  const [eyes, setEyes] = useState("all");
  const [q, setQ] = useState("");

  const parseHeight = (h) => {
    const m = h.match(/(\d+)'(\d+)/);
    return m ? parseInt(m[1]) * 12 + parseInt(m[2]) : 0;
  };

  const filtered = useMemo(() => {
    return DONORS.filter((d) => {
      if (occ !== "all" && d.occType !== occ) return false;
      if (heightBucket !== "all") {
        const inches = parseHeight(d.height);
        if (heightBucket === "short" && inches >= 70) return false;
        if (heightBucket === "med" && (inches < 70 || inches >= 74)) return false;
        if (heightBucket === "tall" && inches < 74) return false;
      }
      if (eyes !== "all" && d.eyes !== eyes) return false;
      if (q && !`${d.id} ${d.alias} ${d.ethnicity} ${d.occupation}`.toLowerCase().includes(q.toLowerCase())) return false;
      return true;
    });
  }, [occ, heightBucket, eyes, q]);

  return (
    <>
      <div className="page-head">
        <div className="eyebrow">Donor Catalog</div>
        <h1 className="page-title" style={{ fontFamily: "\"Season Serif\"" }}>Best Genes. Hand-picked. <em></em></h1>
        <p className="page-desc">
          {DONORS.length} active donors. Filter by traits, education, and availability. Every donor has cleared a 28-step medical, genetic, and psychological screening.
        </p>
      </div>

      <ProcessSteps />

      <div className="toolbar">
        <div className="filter-group">
          <span className="filter-label">Occupation</span>
          {[["all", "All"], ["researcher", "Researcher"], ["athlete", "Athlete"], ["entrepreneur", "Entrepreneur"], ["creative", "Creative"]].map(([v, l]) =>
          <button key={v} className={`filter-pill ${occ === v ? "active" : ""}`} onClick={() => setOcc(v)}>{l}</button>
          )}
        </div>
        <div className="filter-group">
          <span className="filter-label">Height</span>
          {[["all", "Any"], ["short", "≤ 5'11\""], ["med", "6'0\"–6'1\""], ["tall", "≥ 6'2\""]].map(([v, l]) =>
          <button key={v} className={`filter-pill ${heightBucket === v ? "active" : ""}`} onClick={() => setHeightBucket(v)}>{l}</button>
          )}
        </div>
        <div className="filter-group">
          <span className="filter-label">Eyes</span>
          {[["all", "Any"], ["Brown", "Brown"], ["Blue", "Blue"], ["Green", "Green"], ["Hazel", "Hazel"], ["Gray", "Gray"]].map(([v, l]) =>
          <button key={v} className={`filter-pill ${eyes === v ? "active" : ""}`} onClick={() => setEyes(v)}>{l}</button>
          )}
        </div>

        <div className="toolbar-spacer" />

        <div className="search">
          <span style={{ color: "var(--fg-3)" }}><IconSearch /></span>
          <input placeholder="Search ID, alias, traits…" value={q} onChange={(e) => setQ(e.target.value)} />
        </div>
        <div className="view-toggle">
          <button className={view === "table" ? "active" : ""} onClick={() => setView("table")}><IconList /> Table</button>
          <button className={view === "grid" ? "active" : ""} onClick={() => setView("grid")}><IconGrid /> Grid</button>
        </div>
      </div>

      <div className="table-wrap">
        {view === "table" ?
        <table className="donor-table">
            <thead>
              <tr>
                <th>Donor</th>
                <th>Status</th>
                <th>IQ</th>
                <th>Superpower</th>
                <th>DNA</th>
                <th>Height</th>
                <th>Eyes / Hair</th>
                <th>Ethnicity</th>
                <th>Education</th>
                <th>Occupation</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((d) =>
            <tr key={d.id} className="row" onClick={() => openDonor(d.id)}>
                  <td>
                    <div className="row-id">
                      <div className="avatar"><DonorAvatar donor={d} style={tweaks.avatarStyle} /></div>
                      <div>
                        <div className="alias">{d.alias}</div>
                        <div className="code" style={{ color: "var(--fg-3)" }}>{d.id}</div>
                      </div>
                    </div>
                  </td>
                  <td><StatusPill status={d.status} /></td>
                  <td><span className="chip-iq">{d.iq}</span></td>
                  <td><span className={`chip-super super-${d.superpower.toLowerCase()}`}>{d.superpower}</span></td>
                  <td><span className="chip-dna">{d.dna}</span></td>
                  <td>{d.height}</td>
                  <td><span style={{ color: "var(--fg-2)" }}>{d.eyes} · {d.hair}</span></td>
                  <td><span className="chip-eth">{d.ethnicity}</span></td>
                  <td><span className="chip-edu">{d.education}</span></td>
                  <td><span style={{ color: "var(--fg-2)" }}>{d.occupation}</span></td>
                  <td onClick={(e) => e.stopPropagation()} style={{ textAlign: "right" }}>
                    <button className="reserve-btn" onClick={() => openDonor(d.id)}>
                      {d.status === "waitlist" ? "Join waitlist" : "Reserve"}
                    </button>
                  </td>
                </tr>
            )}
            </tbody>
          </table> :

        <div className="selection-grid">
            {filtered.map((d) =>
          <FeaturedDonorCard key={d.id} donor={d} avatarStyle={tweaks.avatarStyle} onClick={() => openDonor(d.id)} />
          )}
          </div>
        }

        {filtered.length === 0 &&
        <div style={{ textAlign: "center", padding: "80px 20px", color: "var(--fg-3)" }}>
            No donors match your filters.
          </div>
        }
      </div>
    </>);

}

/* ============ STUB PAGES ============ */
function Stub({ title, kicker }) {
  return (
    <section className="hero" style={{ paddingTop: 130, paddingBottom: 200 }}>
      <div className="eyebrow">{kicker}</div>
      <h1 className="hero-title" style={{ fontSize: "clamp(48px, 7vw, 96px)" }}>{title}</h1>
      <p className="hero-sub">This page is part of the prototype scaffold. The Find a Donor flow is fully built — try that tab.</p>
    </section>);

}

/* ============ TWEAKS ============ */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#E8B57A",
  "avatarStyle": "abstract",
  "heroVariant": "italic"
} /*EDITMODE-END*/;

function Tweaks({ tweaks, setTweak }) {
  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Brand">
        <TweakColor
          label="Accent"
          value={tweaks.accent}
          onChange={(v) => setTweak('accent', v)}
          options={['#E8B57A', '#C9A977', '#9BAAD6', '#8FB89C', '#D6A097']} />
        
      </TweakSection>
      <TweakSection label="Donor portraits">
        <TweakRadio
          label="Avatar style"
          value={tweaks.avatarStyle}
          onChange={(v) => setTweak('avatarStyle', v)}
          options={[
          { value: 'abstract', label: 'Abstract' },
          { value: 'halftone', label: 'Halftone' },
          { value: 'monogram', label: 'Monogram' }]
          } />
        
      </TweakSection>
      <TweakSection label="Hero">
        <TweakRadio
          label="Headline emphasis"
          value={tweaks.heroVariant}
          onChange={(v) => setTweak('heroVariant', v)}
          options={[
          { value: 'italic', label: 'Italic D1' },
          { value: 'solid', label: 'Solid' }]
          } />
        
      </TweakSection>
    </TweaksPanel>);

}

/* ============ APP ============ */
function App() {
  const [route, setRoute] = useState("home");
  const [selectedDonorId, setSelectedDonorId] = useState(null);
  const [cart, setCart] = useState([]);
  const [toast, setToast] = useState("");
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);

  useEffect(() => {
    document.documentElement.style.setProperty('--accent', tweaks.accent);
  }, [tweaks.accent]);

  useEffect(() => {
    window.scrollTo({ top: 0, behavior: "instant" });
  }, [route]);

  const openDonor = (id) => {
    setSelectedDonorId(id);
    setRoute("profile");
  };

  const addToCart = (item) => {
    setCart((c) => {
      // merge by donor+vialKey
      const existing = c.findIndex((x) => x.donorId === item.donorId && x.vialKey === item.vialKey);
      if (existing >= 0) {
        const next = [...c];
        next[existing] = { ...next[existing], qty: next[existing].qty + item.qty };
        return next;
      }
      return [...c, item];
    });
    setToast(`Added ${item.qty} × ${item.alias} (${item.vialName})`);
    setTimeout(() => setToast(""), 2200);
  };

  const cartCount = cart.reduce((s, i) => s + i.qty, 0);
  const selectedDonor = DONORS.find((d) => d.id === selectedDonorId);

  return (
    <div data-screen-label={
    route === "home" ? "01 Landing" :
    route === "donors" ? "02 Donor Selection" :
    route === "science" ? "03 Science" :
    route === "profile" ? "04 Donor Profile" :
    route === "cart" ? "05 Cart" :
    route === "international" ? "06 International" :
    `07 ${route}`
    }>
      <Nav route={route} setRoute={setRoute} cartCount={cartCount} />
      {route === "home" && <Landing setRoute={setRoute} tweaks={tweaks} openDonor={openDonor} />}
      {route === "donors" && <DonorSelection tweaks={tweaks} openDonor={openDonor} />}
      {route === "science" && <Science />}
      {route === "profile" && selectedDonor && <DonorProfile donor={selectedDonor} setRoute={setRoute} addToCart={addToCart} />}
      {route === "cart" && <Cart cart={cart} setCart={setCart} setRoute={setRoute} />}
      {route === "fund" && <Fund />}

      <footer className="footer">
        <div className="footer-brand">D1</div>
        <div>© 2026 D1 · Donor Platform · Privacy first</div>
        <div style={{ display: "flex", gap: 18 }}>
          <a>Privacy</a><a>Terms</a><a>Contact</a>
        </div>
      </footer>

      {toast && <div className="cart-toast">{toast}</div>}

      <Tweaks tweaks={tweaks} setTweak={setTweak} />
    </div>);

}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);