/* ============ DONOR PROFILE + CART ============ */

const PREVIEW_CARDS = [
  { name: "Boy", detail: "Age 6", empty: "BOY · AGE 6" },
  { name: "Girl", detail: "Age 6", empty: "GIRL · AGE 6" },
  { name: "Older", detail: "Age 15", empty: "OLDER · AGE 15" },
];

function BabiesSection({ donor }) {
  const [userPhoto, setUserPhoto] = React.useState(null);
  const [results, setResults] = React.useState([null, null, null]);
  const [generating, setGenerating] = React.useState(false);
  const [error, setError] = React.useState("");
  const fileRef = React.useRef(null);

  const resizePhoto = (file) => new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onerror = () => reject(new Error("Could not read that photo."));
    reader.onload = () => {
      const img = new Image();
      img.onerror = () => reject(new Error("Could not load that photo."));
      img.onload = () => {
        const maxSide = 1280;
        const scale = Math.min(1, maxSide / Math.max(img.width, img.height));
        const w = Math.round(img.width * scale);
        const h = Math.round(img.height * scale);
        const canvas = document.createElement("canvas");
        canvas.width = w;
        canvas.height = h;
        canvas.getContext("2d").drawImage(img, 0, 0, w, h);
        resolve(canvas.toDataURL("image/jpeg", 0.9));
      };
      img.src = reader.result;
    };
    reader.readAsDataURL(file);
  });

  const readFile = async (file) => {
    if (!file || !file.type.startsWith("image/")) return;
    try {
      setError("");
      const photo = await resizePhoto(file);
      setUserPhoto(photo);
      setResults([null, null, null]);
    } catch (err) {
      setError(err.message || "Could not use that photo.");
    }
  };

  const onDrop = (e) => {
    e.preventDefault();
    e.currentTarget.classList.remove("dragover");
    readFile(e.dataTransfer.files?.[0]);
  };
  const onDragOver = (e) => {
    e.preventDefault();
    e.currentTarget.classList.add("dragover");
  };
  const onDragLeave = (e) => {
    e.currentTarget.classList.remove("dragover");
  };

  const generate = async () => {
    if (!userPhoto) return;
    setGenerating(true);
    setError("");
    setResults([null, null, null]);
    try {
      const response = await fetch("/api/generate-child-previews", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          userPhoto,
          donor: {
            id: donor.id,
            alias: donor.alias,
            photo: donor.photo,
            age: donor.age,
            height: donor.height,
            eyes: donor.eyes,
            hair: donor.hair,
            ethnicity: donor.ethnicity,
            education: donor.education,
            occupation: donor.occupation,
          },
        }),
      });
      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || "Could not generate previews.");
      }

      const generated = data.previews?.map((preview) => preview.image) || data.images || [];
      setResults(PREVIEW_CARDS.map((_, i) => generated[i] || null));
    } catch (err) {
      setError(err.message || "Could not generate previews.");
    } finally {
      setGenerating(false);
    }
  };

  return (
    <div className="babies-section">
      <div className="babies-head">
        <div>
          <h3>Preview your future child</h3>
          <div className="babies-tag">For preview only — not predictive</div>
        </div>
        <div className="babies-sub">AI · Beta</div>
      </div>

      <div className="preview-composer">
        <div
          className={`photo-drop ${userPhoto ? "filled" : ""}`}
          onDrop={onDrop}
          onDragOver={onDragOver}
          onDragLeave={onDragLeave}
          onClick={() => fileRef.current?.click()}
        >
          {userPhoto ? (
            <img src={userPhoto} alt="Your photo" />
          ) : (
            <>
              <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" style={{ marginBottom: 10 }}>
                <rect x="3" y="5" width="18" height="14" rx="2"/>
                <circle cx="9" cy="11" r="2"/>
                <path d="M3 17 L9 12 L14 16 L17 14 L21 17"/>
              </svg>
              <div style={{ fontWeight: 500, fontSize: 14 }}>Drop your photo</div>
              <div style={{ fontSize: 12, opacity: 0.55, marginTop: 4 }}>or click to browse</div>
            </>
          )}
          <input
            ref={fileRef}
            type="file"
            accept="image/*"
            style={{ display: "none" }}
            onChange={(e) => readFile(e.target.files?.[0])}
          />
        </div>

        <div className="composer-mid">
          <div className="op-sign">+</div>
        </div>

        <div className="donor-mini">
          {donor.photo ? <img src={donor.photo} alt={donor.alias} /> : <DonorAvatar donor={donor} style="abstract" />}
          <div className="donor-mini-label">
            <div className="alias">{donor.alias}</div>
            <div className="code">{donor.id}</div>
          </div>
        </div>

        <div className="composer-mid">
          <div className="op-sign">=</div>
        </div>

        <button
          className="generate-btn"
          onClick={generate}
          disabled={!userPhoto || generating}
        >
          {generating ? "Generating…" : userPhoto ? "Generate previews" : "Drop a photo first"}
        </button>
      </div>
      {error && <div className="preview-error">{error}</div>}

      <div className="babies-grid">
        {results.map((r, i) => (
          <div className="baby-card" key={i}>
            <div className={`baby-slot ${generating ? "shimmer" : ""}`}>
              {r ? (
                <img src={r} alt={`${PREVIEW_CARDS[i].name} preview, ${PREVIEW_CARDS[i].detail.toLowerCase()}`} />
              ) : (
                <div className="baby-empty">
                  <div style={{ fontFamily: "var(--mono)", fontSize: 11, opacity: 0.45, letterSpacing: "0.05em" }}>
                    {generating ? "RENDERING…" : PREVIEW_CARDS[i].empty}
                  </div>
                </div>
              )}
            </div>
            <div className="baby-meta">
              <span className="name">{PREVIEW_CARDS[i].name}</span>
              <span className="born">{PREVIEW_CARDS[i].detail}</span>
            </div>
          </div>
        ))}
      </div>

      <p className="baby-disclaimer">
        Generated previews are fictional age and gender variations inspired by both parent references. Real outcomes depend on thousands of genetic factors and are not predictable from photos. Use this as inspiration, not expectation.
      </p>
    </div>
  );
}

const VIAL_TYPES = [
  { key: "ici", name: "ICI · Unwashed", desc: "Intracervical · for at-home / clinic ICI", price: 5400, stock: 4 },
  { key: "iui", name: "IUI · Washed",   desc: "Lab-washed, ready for IUI cycles",         price: 6200, stock: 3 },
  { key: "ivf", name: "IVF / ICSI",     desc: "Highest-grade prep for IVF / ICSI",        price: 7800, stock: 2 },
];

function DonorProfile({ donor, setRoute, addToCart }) {
  const [tab, setTab] = React.useState("bio");
  const [qty, setQty] = React.useState({ ici: 0, iui: 1, ivf: 0 });

  const total = VIAL_TYPES.reduce((s, v) => s + v.price * (qty[v.key] || 0), 0);
  const vialCount = Object.values(qty).reduce((a, b) => a + b, 0);
  const totalStock = VIAL_TYPES.reduce((s, v) => s + v.stock, 0);
  const stockValue = VIAL_TYPES.reduce((s, v) => s + v.stock * v.price, 0);

  const reserveAll = () => {
    const next = {};
    VIAL_TYPES.forEach((v) => { next[v.key] = v.stock; });
    setQty(next);
  };

  const setQ = (key, delta) => {
    setQty((q) => ({ ...q, [key]: Math.max(0, (q[key] || 0) + delta) }));
  };

  const handleAdd = () => {
    if (vialCount === 0) return;
    VIAL_TYPES.forEach((v) => {
      if (qty[v.key] > 0) {
        addToCart({
          donorId: donor.id,
          alias: donor.alias,
          photo: donor.photo,
          vialKey: v.key,
          vialName: v.name,
          price: v.price,
          qty: qty[v.key],
        });
      }
    });
    setRoute("cart");
  };

  const cognitive = [
    ["WAIS-IV Composite",   "131"],
    ["Verbal Comprehension","134"],
    ["Perceptual Reasoning","129"],
    ["Working Memory",      "128"],
    ["Processing Speed",    "126"],
    ["SAT (1600 scale)",    "1540"],
  ];

  const genetic = [
    ["Carrier panel (514)", "Clear"],
    ["BRCA1 / BRCA2",       "Clear"],
    ["CFTR",                "Clear"],
    ["HEXA (Tay-Sachs)",    "Clear"],
    ["Karyotype",           "46,XY"],
    ["Hemoglobin variants", "Normal"],
  ];

  const character = [
    ["Background check",       "Cleared"],
    ["Psychological eval",     "Stable"],
    ["Identity verification",  "Confirmed"],
    ["Family history",         "Provided (4 gen)"],
    ["Open ID at 18",          "Yes"],
    ["Communication style",    "Warm, responsive"],
  ];

  const bio = `${donor.alias} is a ${donor.age}-year-old ${donor.occupation.toLowerCase()} from a multigenerational ${donor.ethnicity} family. Drawn to ${donor.occupation === "Composer" ? "music from age six" : donor.occupation === "Aerospace Engineer" ? "the night sky" : donor.occupation === "Surgical Resident" ? "medicine and martial arts" : "endurance sports and quiet study"}, ${donor.alias} describes himself as patient, methodical, and unusually persistent. His extended-family medical history is unremarkable across four generations.`;

  return (
    <div className="profile-page" data-screen-label="04 Donor Profile">
      <button className="profile-back" onClick={() => setRoute("donors")}>← Back to catalog</button>

      <div className="profile-layout">
        <div className="profile-left">
          <div className="profile-portrait">
            {donor.photo ? (
              <img src={donor.photo} alt={`Donor ${donor.id}`} />
            ) : (
            <DonorAvatar donor={donor} style="abstract" />
            )}
            <div className="ovl-tl">{donor.id}</div>
            <div className="ovl-tr">
              {donor.status === "available" ? "Available" : donor.status === "limited" ? "Limited" : "Waitlist"}
            </div>
          </div>

          <div className="sponsorship-card">
            <div className="sponsorship-eyebrow">✓ D1 FUND ELIGIBLE</div>
            <h3 className="sponsorship-title">Sponsorship <em>available</em>.</h3>
            <p className="sponsorship-text">
              Get sponsorship for up to 18 years of parenthood. The D1 Fund covers part or all of your introduction package and ongoing support.
            </p>
            <div className="sponsorship-stats">
              <div>
                <div className="sponsorship-num">$2.4<span style={{ fontSize: "0.55em" }}>M</span></div>
                <div className="sponsorship-lbl">Awarded in 2025</div>
              </div>
              <div>
                <div className="sponsorship-num">1 in 4</div>
                <div className="sponsorship-lbl">Members supported</div>
              </div>
              <div>
                <div className="sponsorship-num">7d</div>
                <div className="sponsorship-lbl">Decision</div>
              </div>
            </div>
            <div className="sponsorship-actions">
              <button className="btn btn-primary" onClick={() => setRoute("fund")}>Apply for sponsorship</button>
              <button className="btn-link" onClick={() => setRoute("fund")}>How it works ↗</button>
            </div>
          </div>
        </div>

        <div className="profile-info">
          <div className="alias-eyebrow">DONOR {donor.id}</div>
          <h1>{donor.alias}</h1>
          <p className="lede">
            {donor.age} · {donor.height} · {donor.ethnicity} · {donor.education}
          </p>

          <div className="stat-grid">
            <div className="stat-cell"><div className="lbl">IQ</div><div className="val">{donor.iq}</div></div>
            <div className="stat-cell"><div className="lbl">Eyes</div><div className="val">{donor.eyes}</div></div>
            <div className="stat-cell"><div className="lbl">Hair</div><div className="val">{donor.hair}</div></div>
            <div className="stat-cell"><div className="lbl">Height</div><div className="val">{donor.height}</div></div>
            <div className="stat-cell"><div className="lbl">Education</div><div className="val">{donor.education}</div></div>
            <div className="stat-cell"><div className="lbl">Occupation</div><div className="val">{donor.occupation}</div></div>
          </div>

          <div className="profile-tabs">
            {[
              ["bio",       "Bio"],
              ["genetic",   "Genetic Panel"],
              ["cognitive", "Cognitive"],
              ["character", "Character"],
            ].map(([k, l]) => (
              <button key={k} className={`profile-tab ${tab === k ? "active" : ""}`} onClick={() => setTab(k)}>{l}</button>
            ))}
          </div>

          {tab === "bio" && (
            <div className="report-block">
              <h3>About {donor.alias}</h3>
              <p style={{ color: "#FFFFFF", opacity: 0.75, fontSize: 14, lineHeight: 1.7, margin: 0, maxWidth: 620 }}>{bio}</p>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 20, marginTop: 28 }}>
                <div>
                  <div style={{ fontSize: 11, opacity: 0.5, textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: 6 }}>Personality</div>
                  <div style={{ fontSize: 14, opacity: 0.85 }}>Introvert · Methodical</div>
                </div>
                <div>
                  <div style={{ fontSize: 11, opacity: 0.5, textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: 6 }}>Interests</div>
                  <div style={{ fontSize: 14, opacity: 0.85 }}>Cycling · Reading · Cooking</div>
                </div>
                <div>
                  <div style={{ fontSize: 11, opacity: 0.5, textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: 6 }}>Open ID</div>
                  <div style={{ fontSize: 14, opacity: 0.85 }}>Yes, at child 18</div>
                </div>
              </div>
            </div>
          )}

          {tab === "genetic" && (
            <div className="report-block">
              <h3>Genetic Panel</h3>
              <p style={{ fontSize: 13, opacity: 0.6, margin: "0 0 16px", maxWidth: 620 }}>
                Whole-exome sequencing plus a 514-condition expanded carrier panel. Full report attached to your account on reservation.
              </p>
              <table className="donor-table genetic-table">
                <thead>
                  <tr>
                    <th>Category</th>
                    <th>Marker</th>
                    <th>Status</th>
                    <th>Method</th>
                    <th>Notes</th>
                  </tr>
                </thead>
                <tbody>
                  {[
                    ["Cancer",      "BRCA1",          "Clear",      "Full sequencing", "No pathogenic variants"],
                    ["Cancer",      "BRCA2",          "Clear",      "Full sequencing", "No pathogenic variants"],
                    ["Cancer",      "TP53",           "Clear",      "Full sequencing", "Wild-type"],
                    ["Carrier",     "CFTR",           "Clear",      "Targeted panel",  "Cystic fibrosis"],
                    ["Carrier",     "HEXA",           "Clear",      "Targeted panel",  "Tay-Sachs"],
                    ["Carrier",     "SMN1",           "Clear",      "MLPA",            "Spinal muscular atrophy"],
                    ["Carrier",     "FMR1",           "Clear",      "PCR",             "Fragile X (29 CGG repeats)"],
                    ["Carrier",     "GBA",            "Clear",      "Targeted panel",  "Gaucher disease"],
                    ["Carrier",     "ASPA",           "Clear",      "Targeted panel",  "Canavan disease"],
                    ["Cardiac",     "MYH7 / MYBPC3",  "Clear",      "Full sequencing", "Hypertrophic cardiomyopathy"],
                    ["Metabolic",   "G6PD",           "Normal",     "Enzyme assay",    "Within reference range"],
                    ["Chromosomal", "Karyotype",      "46,XY",      "G-band",          "No structural anomalies"],
                    ["Chromosomal", "Microarray CGH", "Clear",      "Array CGH",       "No microdeletions"],
                    ["Hemoglobin",  "HbS / HbC / β-thal","Normal",  "HPLC",            "No variants"],
                    ["Highlight",   "Longevity SNPs", "Favorable",  "Polygenic",       "+1.4σ vs population"],
                  ].map((row, i) => (
                    <tr key={i} className="row">
                      <td><span className={`chip-cat cat-${row[0].toLowerCase()}`}>{row[0]}</span></td>
                      <td style={{ fontFamily: "var(--mono)", fontSize: 13 }}>{row[1]}</td>
                      <td>
                        <span className={`yn ${(row[2] === "Clear" || row[2] === "Normal" || row[2] === "46,XY" || row[2] === "Favorable") ? "yn-yes" : "yn-no"}`}>{row[2]}</span>
                      </td>
                      <td style={{ color: "var(--fg-2)", opacity: 0.75 }}>{row[3]}</td>
                      <td style={{ color: "var(--fg-2)", opacity: 0.75, fontSize: 13 }}>{row[4]}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}

          {tab === "cognitive" && (
            <div className="report-block">
              <h3>Cognitive Profile</h3>
              <p style={{ fontSize: 13, opacity: 0.6, margin: "0 0 16px", maxWidth: 620 }}>
                Proctored WAIS-IV administered by a licensed psychometrist. Subtest breakdowns and supplementary measures below.
              </p>
              <table className="donor-table genetic-table">
                <thead>
                  <tr>
                    <th>Measure</th>
                    <th>Score</th>
                    <th>Percentile</th>
                    <th>Norm</th>
                    <th>Notes</th>
                  </tr>
                </thead>
                <tbody>
                  {[
                    ["WAIS-IV Composite",     "131", "98th", "US adult", "Very Superior"],
                    ["Verbal Comprehension",  "134", "99th", "US adult", "Strength"],
                    ["Perceptual Reasoning",  "129", "97th", "US adult", "Very Superior"],
                    ["Working Memory",        "128", "97th", "US adult", "Very Superior"],
                    ["Processing Speed",      "126", "96th", "US adult", "Superior"],
                    ["SAT (1600 scale)",      "1540","99th", "Self-reported", "Verified"],
                    ["Raven's Progressive",   "62/72","98th","US adult", "Supplementary"],
                  ].map((row, i) => (
                    <tr key={i} className="row">
                      <td>{row[0]}</td>
                      <td style={{ fontFamily: "var(--mono)", fontWeight: 500 }}>{row[1]}</td>
                      <td style={{ fontFamily: "var(--mono)", color: "#4ADE80" }}>{row[2]}</td>
                      <td style={{ color: "var(--fg-2)", opacity: 0.75 }}>{row[3]}</td>
                      <td style={{ color: "var(--fg-2)", opacity: 0.75, fontSize: 13 }}>{row[4]}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}

          {tab === "character" && (
            <div className="report-block">
              <h3>Character & Identity</h3>
              <p style={{ fontSize: 13, opacity: 0.6, margin: "0 0 16px", maxWidth: 620 }}>
                Background, psychological, and identity verification. Completed at intake and refreshed annually.
              </p>
              <table className="donor-table genetic-table">
                <thead>
                  <tr>
                    <th>Verification</th>
                    <th>Status</th>
                    <th>Method</th>
                    <th>Last reviewed</th>
                  </tr>
                </thead>
                <tbody>
                  {[
                    ["Background check",       "Cleared",     "County + federal",          "Q1 2026"],
                    ["Identity verification",  "Confirmed",   "Government ID + biometric", "Q1 2026"],
                    ["Psychological eval",     "Stable",      "MMPI-3 + clinician",        "Q1 2026"],
                    ["Family medical history", "Provided",    "4-generation pedigree",     "Q1 2026"],
                    ["Open ID at 18",          "Yes",         "Notarized agreement",       "On file"],
                    ["Communication style",    "Warm, responsive", "Coordinator interview", "Q1 2026"],
                  ].map((row, i) => (
                    <tr key={i} className="row">
                      <td>{row[0]}</td>
                      <td>
                        <span className={`yn ${(row[1] === "Cleared" || row[1] === "Confirmed" || row[1] === "Stable" || row[1] === "Yes" || row[1] === "Provided" || row[1] === "Warm, responsive") ? "yn-yes" : "yn-no"}`}>{row[1]}</span>
                      </td>
                      <td style={{ color: "var(--fg-2)", opacity: 0.75 }}>{row[2]}</td>
                      <td style={{ color: "var(--fg-2)", opacity: 0.75, fontFamily: "var(--mono)", fontSize: 12 }}>{row[3]}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}

          <BabiesSection donor={donor} />

          <div className="purchase">
            <div className="purchase-head">
              <div>
                <h3 style={{ fontFamily: "var(--serif)", fontWeight: 400, fontSize: 22, margin: "0 0 4px" }}>Reserve vials</h3>
                <p style={{ fontSize: 13, opacity: 0.55, margin: 0 }}>{totalStock} vials available across 3 grades. Ships to your fertility clinic on confirmation.</p>
              </div>
              <button className="reserve-all-btn" onClick={reserveAll}>
                Reserve all {totalStock} · ${stockValue.toLocaleString()}
              </button>
            </div>
            {VIAL_TYPES.map((v) => (
              <div className="purchase-row" key={v.key}>
                <div className="vial-type">
                  <span className="name">{v.name}</span>
                  <span className="desc">{v.desc}</span>
                  <span className="stock-tag">{v.stock} in stock</span>
                </div>
                <div className="vial-price">${v.price.toLocaleString()}<span className="per"> / vial</span></div>
                <div className="qty">
                  <button onClick={() => setQ(v.key, -1)}>−</button>
                  <span className="val">{qty[v.key] || 0}</span>
                  <button onClick={() => setQ(v.key, +1)} disabled={(qty[v.key] || 0) >= v.stock}>+</button>
                </div>
              </div>
            ))}
            <div className="purchase-foot">
              <div className="total">
                ${total.toLocaleString()}
                <span className="small">{vialCount} vial{vialCount === 1 ? "" : "s"}</span>
              </div>
              <button className="add-cart-btn" onClick={handleAdd} disabled={vialCount === 0} style={{ opacity: vialCount === 0 ? 0.4 : 1, cursor: vialCount === 0 ? "not-allowed" : "pointer", flex: "none", padding: "13px 28px" }}>
                Add to cart
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ============ CART ============ */
function Cart({ cart, setCart, setRoute }) {
  const subtotal = cart.reduce((s, i) => s + i.price * i.qty, 0);
  const coordinator = cart.length > 0 ? 285 : 0;
  const screening  = cart.length > 0 ? 120 : 0;
  const tax = Math.round(subtotal * 0.0875);
  const total = subtotal + coordinator + screening + tax;

  const removeItem = (idx) => {
    setCart((c) => c.filter((_, i) => i !== idx));
  };
  const updateQty = (idx, delta) => {
    setCart((c) => c.map((it, i) => i === idx ? { ...it, qty: Math.max(0, it.qty + delta) } : it).filter((it) => it.qty > 0));
  };

  return (
    <div className="cart-page" data-screen-label="05 Cart">
      <div className="cart-head">
        <div className="eyebrow">Reservation</div>
        <h1>Your <em>reservation</em>.</h1>
        <span className="count">{cart.length} item{cart.length === 1 ? "" : "s"}</span>
      </div>

      {cart.length === 0 ? (
        <div className="empty-cart">
          <p className="empty-title">Your cart is empty.</p>
          <p className="empty-sub">Reserve an introduction from a donor profile to begin.</p>
          <button className="btn btn-primary btn-lg" onClick={() => setRoute("donors")}>Browse donors</button>
        </div>
      ) : (
        <div className="cart-layout">
          <div>
            {cart.map((item, idx) => (
              <div className="cart-item" key={idx}>
                <div className="cart-thumb">
                  {item.photo ? <img src={item.photo} alt="" /> : <div style={{ width: "100%", height: "100%", background: "#1f1f1f" }} />}
                </div>
                <div className="cart-info">
                  <div className="alias">{item.alias}</div>
                  <div className="code">{item.donorId} · {item.vialName}</div>
                  <div className="vial-meta">${item.price.toLocaleString()} per vial · Shipped to your fertility clinic</div>
                </div>
                <div className="cart-right">
                  <div className="qty">
                    <button onClick={() => updateQty(idx, -1)}>−</button>
                    <span className="val">{item.qty}</span>
                    <button onClick={() => updateQty(idx, +1)}>+</button>
                  </div>
                  <div className="line-total">${(item.price * item.qty).toLocaleString()}</div>
                  <button className="cart-remove" onClick={() => removeItem(idx)}>Remove</button>
                </div>
              </div>
            ))}
          </div>

          <aside className="checkout">
            <h3>Order summary</h3>
            <div className="checkout-row"><span>Subtotal</span><span>${subtotal.toLocaleString()}</span></div>
            <div className="checkout-row subtle"><span>Coordinator onboarding</span><span>${coordinator}</span></div>
            <div className="checkout-row subtle"><span>Match concierge</span><span>${screening}</span></div>
            <div className="checkout-row subtle"><span>Estimated tax</span><span>${tax.toLocaleString()}</span></div>
            <div className="checkout-divider" />
            <div className="checkout-total">
              <span>Total</span>
              <span>${total.toLocaleString()}<span className="small"> USD</span></span>
            </div>

            <div style={{ marginTop: 16 }}>
              <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.05em", opacity: 0.5, marginBottom: 10 }}>Your details</div>
              <input className="shipping-input" placeholder="Full name" defaultValue="" />
              <input className="shipping-input" placeholder="Email" defaultValue="" />
              <input className="shipping-input" placeholder="Phone (for coordinator outreach)" defaultValue="" />
            </div>

            <button className="checkout-btn" onClick={() => alert("Reservation placed. A coordinator will contact you within 24h.")}>
              Reserve & checkout
            </button>
            <p style={{ fontSize: 11, opacity: 0.5, textAlign: "center", margin: "12px 0 0", lineHeight: 1.5 }}>
              Payment held; not charged until your coordinator confirms the first introduction.
            </p>
          </aside>
        </div>
      )}
    </div>
  );
}

window.DonorProfile = DonorProfile;
window.Cart = Cart;
