// Review screen + build modal

function Review({ form, selected, names, deploy, setDeploy, onBack, onBuild }) {
  const { USE_CASES, LANGS } = window.TB_DATA;
  const selectedCases = selected.map(id => USE_CASES.find(u => u.id === id)).filter(Boolean);
  const totalComponents = selectedCases.reduce((n, uc) => n + uc.components.length, 0);
  const totalNames = selectedCases.reduce((n, uc) => n + uc.nameFields.length, 0);
  const langLabel = (LANGS.find(l => l.k === form.language) || {}).label || form.language;

  return (
    <div className="fade-enter">
      <div className="step-header green">
        <div>
          <div className="eyebrow green">Step 04 — Review & Build</div>
          <h1 className="h-display">Ready to spin up the tenant.</h1>
          <p className="h-sub">Last look before we scaffold the demo for <b>{form.company || "this prospect"}</b>. You can still hop back to tweak anything.</p>
        </div>
        <div className="step-header-badge">
          <div className="v">{totalComponents}</div>
          <div className="k">components</div>
        </div>
      </div>

      <div className="review-grid" style={{ marginBottom: 20 }}>
        <div className="review-card">
          <div className="col-label" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.08em", color: "var(--ink-4)", fontWeight: 600, marginBottom: 4 }}>Prospect</div>
          {form.logoDataUrl && (
            <div style={{ margin: "6px 0 12px" }}>
              <img src={form.logoDataUrl} alt="logo" style={{ maxHeight: 40, maxWidth: 160, objectFit: "contain" }} />
            </div>
          )}
          <div className="kv-row"><div className="k">Company</div><div className="v">{form.company || <em style={{color:"var(--ink-4)",fontStyle:"normal"}}>—</em>}</div></div>
          <div className="kv-row"><div className="k">Industry</div><div className="v">{form.industry || "—"}</div></div>
          <div className="kv-row"><div className="k">Headcount</div><div className="v">{form.headcount || "—"}</div></div>
          <div className="kv-row"><div className="k">Country</div><div className="v">{form.country || "—"}</div></div>
          <div className="kv-row"><div className="k">Language</div><div className="v">{form.language} — {langLabel}</div></div>
          <div className="kv-row"><div className="k">ATS in use</div><div className="v">{form.ats || "—"}</div></div>
          <div className="kv-row"><div className="k">Website</div><div className="v" style={{ fontFamily: "var(--font-mono)", fontSize: 12.5 }}>{form.websiteUrl || "—"}</div></div>
          <div className="kv-row"><div className="k">Career page</div><div className="v" style={{ fontFamily: "var(--font-mono)", fontSize: 12.5 }}>{form.careerUrl || "—"}</div></div>
          <div className="kv-row"><div className="k">Demo date</div><div className="v">{form.demoDate || "—"}</div></div>
          <div className="kv-row"><div className="k">AE / owner</div><div className="v">{form.aeName || "—"}</div></div>
          <div className="kv-row"><div className="k">Brand color</div><div className="v" style={{ display: "flex", alignItems: "center", gap: 8 }}>
            {form.brandColor ? <><span style={{ width: 14, height: 14, borderRadius: 4, background: form.brandColor, display: "inline-block" }} /><span style={{ fontFamily: "var(--font-mono)", fontSize: 12.5 }}>{form.brandColor}</span></> : "—"}
          </div></div>
          <div className="kv-row"><div className="k">Primary contact</div><div className="v">{form.contactName ? `${form.contactName}${form.contactEmail ? ` · ${form.contactEmail}` : ""}` : "—"}</div></div>
        </div>

        <div className="build-summary">
          <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.08em", color: "var(--ink-3)", fontWeight: 600, marginBottom: 8 }}>Build scope</div>
          <div className="num">
            {selectedCases.length}<span className="slash">/</span>
            <span style={{ fontSize: 32, color: "var(--ink)" }}>use cases</span>
          </div>
          <div style={{ marginTop: 18, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, fontSize: 13 }}>
            <div><div style={{ color: "var(--ink-4)", fontSize: 12 }}>Components</div><div style={{ fontSize: 22, fontWeight: 600, letterSpacing: "-0.02em" }}>{totalComponents}</div></div>
            <div><div style={{ color: "var(--ink-4)", fontSize: 12 }}>Named assets</div><div style={{ fontSize: 22, fontWeight: 600, letterSpacing: "-0.02em" }}>{totalNames}</div></div>
          </div>
        </div>
      </div>

      {selectedCases.map(uc => (
        <div key={uc.id} className="review-card" style={{ marginBottom: 12 }}>
          <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", gap: 16, marginBottom: 12 }}>
            <div>
              <div style={{ fontWeight: 600, fontSize: 15, letterSpacing: "-0.01em" }}>{uc.name}</div>
              <div style={{ color: "var(--ink-4)", fontSize: 12.5 }}>{uc.desc}</div>
            </div>
            <span className="count-pill">{uc.components.length} built</span>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20 }}>
            <div>
              <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.08em", color: "var(--ink-4)", fontWeight: 600, marginBottom: 8 }}>Names</div>
              {uc.nameFields.map(f => (
                <div className="kv-row" key={f.key}>
                  <div className="k">{f.label}</div>
                  <div className="v" style={{ fontFamily: "var(--font-mono)", fontSize: 12.5 }}>
                    {(names[uc.id] && names[uc.id][f.key]) || <em>not set</em>}
                  </div>
                </div>
              ))}
            </div>
            <div>
              <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.08em", color: "var(--ink-4)", fontWeight: 600, marginBottom: 8 }}>Components</div>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
                {uc.components.map(c => (
                  <span key={c.k} style={{ background: "var(--surface-2)", padding: "5px 9px", borderRadius: 7, fontSize: 12 }}>
                    {c.k}
                  </span>
                ))}
              </div>
            </div>
          </div>
        </div>
      ))}

      <FooterActions
        left={<>
          <span className="count-pill">{totalComponents} components · {selectedCases.length} use cases</span>
          <button className="btn btn-ghost" style={{ padding: "8px 12px", fontSize: 13 }} onClick={() => {
            const brief = buildHandoffBrief(form, selectedCases, names, langLabel);
            navigator.clipboard.writeText(brief).then(() => {
              const el = document.getElementById("brief-toast");
              if (el) { el.classList.add("show"); setTimeout(() => el.classList.remove("show"), 2000); }
            });
          }}>📋 Copy handoff brief</button>
        </>}
        primaryLabel={<>Start Build <Ic.sparkle /></>}
        onPrimary={onBuild}
        onBack={onBack}
      />
      <div id="brief-toast" className="toast">Handoff brief copied to clipboard</div>
    </div>
  );
}

function BuildingModal({ onClose, onStart, form, selected, names, deploy }) {
  const { USE_CASES } = window.TB_DATA;
  const selectedCases = selected.map(id => USE_CASES.find(u => u.id === id)).filter(Boolean);
  const [lines, setLines] = React.useState([]);
  const [done, setDone] = React.useState(false);
  const [progress, setProgress] = React.useState(0);

  React.useEffect(() => {
    if (onStart) onStart();
    const slug = (s) => (s || "demo").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 24);
    const tenantSlug = `${slug(form.company)}-demo`;
    const totalComponents = selectedCases.reduce((n, uc) => n + uc.components.length, 0);

    const steps = [
      { t: "pulse", txt: `› Connecting to talentry.io…`, d: 200 },
      { t: "ok",    txt: `✓ Authenticated as ${form.aeName || "AE"}`, d: 240 },
      { t: "pulse", txt: `› Spinning up tenant ${tenantSlug}.talentry.io`, d: 420 },
      { t: "muted", txt: `  locale: ${form.language || "EN"} · region: ${form.country || "—"}`, d: 180 },
      form.logoDataUrl && { t: "muted", txt: `  logo: applied to 12 surfaces`, d: 200 },
      form.brandColor && { t: "muted", txt: `  brand color ${form.brandColor} → buttons, links, accents`, d: 200 },
      { t: "dim", txt: ``, d: 120 },
      ...selectedCases.flatMap((uc) => {
        const nameEntries = Object.values((names && names[uc.id]) || {});
        const primary = nameEntries[0];
        return [
          { t: "pulse", txt: `› Forging "${primary || uc.name}" → ${uc.components.length} components`, d: 360 },
          ...uc.components.map(c => ({ t: "muted", txt: `  · ${c.k}  ${c.t.toUpperCase()}`, d: 110 })),
          { t: "dim", txt: ``, d: 120 },
        ];
      }),
      form.careerUrl && { t: "pulse", txt: `› Scraping ${form.careerUrl.replace(/^https?:\/\//, "")}…`, d: 380 },
      form.careerUrl && { t: "muted", txt: `  seeded 6 mock jobs into the demo tenant`, d: 220 },
      { t: "pulse", txt: `› Finalizing ${totalComponents} components`, d: 300 },
      { t: "ok",    txt: `✓ Ready in ${(Math.random() * 2 + 5.5).toFixed(1)}s`, d: 260 },
      { t: "ok",    txt: `✓ Tenant: https://${tenantSlug}.talentry.io`, d: 200 },
    ].filter(Boolean);

    let i = 0;
    let timer;
    const tick = () => {
      const s = steps[i];
      setLines(l => [...l, s]);
      setProgress(Math.round(((i + 1) / steps.length) * 100));
      i++;
      if (i < steps.length) timer = setTimeout(tick, s.d);
      else setDone(true);
    };
    timer = setTimeout(tick, 120);
    return () => clearTimeout(timer);
  }, []);

  const slug = (s) => (s || "demo").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 24);
  const tenantUrl = `https://${slug(form.company)}-demo.talentry.io`;

  return (
    <div className="modal-shade">
      <div className="modal">
        <div className="modal-head">
          <div>
            <div className="eyebrow green" style={{ marginBottom: 4 }}>{done ? "Build complete" : "Building tenant"}</div>
            <h3>{done ? `${form.company || "Your"} demo is live.` : `Scaffolding ${form.company || "the"} demo…`}</h3>
          </div>
          <div className="build-progress-ring" aria-hidden>
            <svg viewBox="0 0 36 36" width="48" height="48">
              <circle cx="18" cy="18" r="15.5" fill="none" stroke="rgba(13,27,26,0.08)" strokeWidth="2.5"/>
              <circle cx="18" cy="18" r="15.5" fill="none" stroke="url(#bp)" strokeWidth="2.5" strokeLinecap="round"
                strokeDasharray={`${(progress/100)*97.4} 97.4`} transform="rotate(-90 18 18)" />
              <defs><linearGradient id="bp" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stopColor="#158158"/><stop offset="1" stopColor="#6B4FEA"/></linearGradient></defs>
            </svg>
            <div className="build-progress-num">{progress}%</div>
          </div>
        </div>
        <div className="build-log">
          {lines.map((s, i) => (
            <div key={i} className={s.t}>{s.txt || "\u00A0"}</div>
          ))}
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 10, marginTop: 18 }}>
          <div style={{ fontSize: 12, color: "var(--ink-4)", fontFamily: "var(--font-mono)" }}>
            {done ? tenantUrl : `${selectedCases.length} use cases · ${selectedCases.reduce((n,uc)=>n+uc.components.length,0)} components`}
          </div>
          <div style={{ display: "flex", gap: 10 }}>
            <button className="btn btn-sec" onClick={onClose}>{done ? "Close" : "Run in background"}</button>
            {done && <button className="btn btn-primary" onClick={onClose}>Open tenant <Ic.arrow /></button>}
          </div>
        </div>
      </div>
    </div>
  );
}

// -------- Recent Builds dropdown --------
function RecentBuilds({ history, onLoad, onDuplicate, onClear, onClose }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const onDoc = (e) => { if (ref.current && !ref.current.contains(e.target)) onClose(); };
    setTimeout(() => document.addEventListener("mousedown", onDoc), 0);
    return () => document.removeEventListener("mousedown", onDoc);
  }, []);
  const fmtDate = (ts) => {
    const d = new Date(ts), now = new Date();
    const mins = Math.round((now - d) / 60000);
    if (mins < 2) return "just now";
    if (mins < 60) return `${mins}m ago`;
    if (mins < 60 * 24) return `${Math.round(mins/60)}h ago`;
    return d.toLocaleDateString(undefined, { month: "short", day: "numeric" });
  };
  return (
    <div ref={ref} className="recent-panel">
      <div className="recent-head">
        <div className="recent-title">Recent builds</div>
        {history.length > 0 && <button className="recent-clear" onClick={onClear}>Clear</button>}
      </div>
      {history.length === 0 ? (
        <div className="recent-empty">
          <div className="recent-empty-mark">
            <svg viewBox="0 0 24 24" width="28" height="28" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><polyline points="12 7 12 12 15 14"/></svg>
          </div>
          <div className="recent-empty-t">No builds yet</div>
          <div className="recent-empty-s">Once you click Start Build, the tenant will land here so you can revisit or duplicate it.</div>
        </div>
      ) : (
        <div className="recent-list">
          {history.map(h => (
            <div key={h.id} className="recent-row">
              <button className="recent-row-main" onClick={() => onLoad(h)}>
                <div className="recent-company">{h.company}</div>
                <div className="recent-meta">
                  {h.useCaseCount} use case{h.useCaseCount === 1 ? "" : "s"}
                  {h.ae && <> · {h.ae}</>}
                  {h.country && <> · {h.country}</>}
                </div>
              </button>
              <div className="recent-side">
                <div className="recent-when">{fmtDate(h.at)}</div>
                <button className="recent-dup" title="Duplicate for a new prospect" onClick={() => onDuplicate(h)}>
                  <svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h10"/></svg>
                  Duplicate
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
window.RecentBuilds = RecentBuilds;

Object.assign(window, { Review, BuildingModal, RecentBuilds });

// -------- Handoff brief builder --------
function buildHandoffBrief(form, selectedCases, names, langLabel) {
  const L = [];
  L.push(`# Tenant handoff — ${form.company || "Prospect"}`);
  const meta = [
    form.aeName && `**AE:** ${form.aeName}`,
    form.demoDate && `**Demo:** ${form.demoDate}`,
    form.country && `**Country:** ${form.country}`,
  ].filter(Boolean).join(" · ");
  if (meta) L.push(meta);
  L.push("");
  L.push(`## Prospect`);
  if (form.websiteUrl) L.push(`- Website: ${form.websiteUrl}`);
  if (form.careerUrl)  L.push(`- Careers: ${form.careerUrl}`);
  const line2 = [form.industry, form.headcount].filter(Boolean).join(" · ");
  if (line2) L.push(`- ${line2}`);
  const line3 = [form.language && `Language: ${form.language} (${langLabel})`, form.ats && `ATS: ${form.ats}`].filter(Boolean).join(" · ");
  if (line3) L.push(`- ${line3}`);
  if (form.contactName || form.contactEmail) L.push(`- Contact: ${[form.contactName, form.contactEmail].filter(Boolean).join(" · ")}`);
  if (form.brandColor) L.push(`- Brand color: ${form.brandColor}`);
  L.push("");
  L.push(`## Use cases built (${selectedCases.length})`);
  for (const uc of selectedCases) {
    L.push(`- **${uc.name}** — ${uc.components.length} components`);
    for (const f of uc.nameFields) {
      const v = (names[uc.id] && names[uc.id][f.key]) || "—";
      L.push(`    - ${f.label}: \`${v}\``);
    }
  }
  L.push("");
  L.push(`## Next steps`);
  L.push(`- Tenant URL from Delivery team`);
  L.push(`- Demo walkthrough with ${form.aeName || "AE"}${form.demoDate ? ` on ${form.demoDate}` : ""}`);
  L.push("");
  L.push(`_Generated by Tenant Builder · ${new Date().toISOString().slice(0,10)}_`);
  return L.join("\n");
}
window.buildHandoffBrief = buildHandoffBrief;
