// Setup wizard for Perdura Capital
// 6 steps: welcome → business type → company profile → connect → AI mapping → done

const { useState: useStateW, useEffect: useEffectW, useRef: useRefW } = React;

const wizSteps = [
  { key: "welcome",  label: "Welcome" },
  { key: "type",     label: "Business type" },
  { key: "profile",  label: "Company profile" },
  { key: "connect",  label: "Connect data" },
  { key: "mapping",  label: "Map your chart of accounts" },
  { key: "done",     label: "Ready" },
];

function Wizard({ onComplete, onExit, initialBizType = "service" }) {
  const [step, setStep] = useStateW(0);
  const [bizType, setBizType] = useStateW(initialBizType);
  const [profile, setProfile] = useStateW({
    company: "",
    fyEnd: "December",
    fiscalYearStart: "January",
    employees: "",
    products: 0,
    services: 0,
    revenue: "",
    multiEntity: false,
  });
  const [accountingSystem, setAccountingSystem] = useStateW(null);
  const [connecting, setConnecting] = useStateW(false);
  const [connected, setConnected] = useStateW(false);
  const [aiPhase, setAIPhase] = useStateW(0); // 0 scanning, 1 mapping, 2 done
  const [mappings, setMappings] = useStateW([]);

  const next = () => setStep(s => Math.min(s + 1, wizSteps.length - 1));
  const back = () => setStep(s => Math.max(s - 1, 0));

  // Mock GL accounts for AI mapping step
  const mockGL = [
    { acct: "4000", name: "Product Sales – Online",         pclass: "Revenue", suggested: "Revenue / Net Sales / DTC",                conf: 98 },
    { acct: "4010", name: "Wholesale Revenue",              pclass: "Revenue", suggested: "Revenue / Net Sales / Wholesale",          conf: 96 },
    { acct: "4090", name: "Returns & Allowances",           pclass: "Revenue", suggested: "Revenue / Contra-revenue / Returns",       conf: 99 },
    { acct: "4900", name: "Other Income",                   pclass: "Revenue", suggested: "Other / Non-operating Income",             conf: 87 },
    { acct: "5000", name: "Cost of Goods Sold",             pclass: "COGS",    suggested: "COGS / Direct Material",                   conf: 95 },
    { acct: "5010", name: "Inbound Freight",                pclass: "COGS",    suggested: "COGS / Freight-in",                        conf: 93 },
    { acct: "5020", name: "Packaging Materials",            pclass: "COGS",    suggested: "COGS / Packaging",                         conf: 91 },
    { acct: "5100", name: "Direct Labor – Production",      pclass: "COGS",    suggested: "COGS / Direct Labor",                      conf: 90 },
    { acct: "5200", name: "Manufacturing Overhead Applied", pclass: "COGS",    suggested: "COGS / Overhead Allocation",               conf: 84 },
    { acct: "6010", name: "Salaries – G&A",                 pclass: "Opex",    suggested: "Opex / Personnel / G&A salaries",          conf: 97 },
    { acct: "6020", name: "Payroll Tax",                    pclass: "Opex",    suggested: "Opex / Personnel / Payroll burden",        conf: 96 },
    { acct: "6100", name: "Rent",                           pclass: "Opex",    suggested: "Opex / Facilities / Rent",                 conf: 99 },
    { acct: "6200", name: "Marketing – Paid Media",         pclass: "Opex",    suggested: "Opex / S&M / Performance marketing",       conf: 92 },
    { acct: "6210", name: "Marketing – Events",             pclass: "Opex",    suggested: "Opex / S&M / Brand",                       conf: 78, alts: ["Opex / S&M / Events", "Opex / S&M / Brand"] },
    { acct: "6840", name: "Travel – Air",                   pclass: "Opex",    suggested: "Opex / Travel / Air",                      conf: 73, flag: "2 transactions appear to be hotel charges" },
    { acct: "6900", name: "Software & Subscriptions",       pclass: "Opex",    suggested: "Opex / Software",                          conf: 94 },
    { acct: "7100", name: "Depreciation",                   pclass: "Opex",    suggested: "Opex / D&A / Depreciation",                conf: 99 },
    { acct: "7200", name: "Interest Expense",               pclass: "Opex",    suggested: "Non-operating / Interest",                 conf: 95 },
  ];

  // Start AI scanning when entering mapping step
  useEffectW(() => {
    if (step !== 4) return;
    setAIPhase(0);
    setMappings([]);
    const t1 = setTimeout(() => setAIPhase(1), 1400);
    const t2 = setTimeout(() => {
      setMappings(mockGL.map(g => ({ ...g, status: "suggested" })));
      setAIPhase(2);
    }, 2800);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, [step]);

  return (
    <div className="pc-wiz-root">
      <div className="pc-wiz-bg" />
      <div className="pc-wiz-shell">
        {onExit && (
          <button className="pc-wiz-close" onClick={onExit} title="Exit setup">
            <Icon d={icons.x} size={14} />
            <span>Exit setup</span>
          </button>
        )}
        <div className="pc-wiz-side">
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 36 }}>
            <PerduraMark size={26} />
            <div>
              <div style={{ fontSize: 15, fontWeight: 600 }}>Perdura Capital</div>
              <div style={{ fontSize: 10.5, color: "var(--text-3)", letterSpacing: 0.4, textTransform: "uppercase" }}>Operating intelligence</div>
            </div>
          </div>

          <div style={{ fontSize: 11, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: 0.5, marginBottom: 16 }}>Setup · 6 steps</div>
          <div className="pc-wiz-steps">
            {wizSteps.map((s, i) => (
              <div key={s.key} className={"pc-wiz-step " + (i === step ? "active " : "") + (i < step ? "done " : "")}>
                <div className="pc-wiz-step-dot">
                  {i < step ? <Icon d={icons.check} size={11} strokeWidth={2.4} /> : <span>{i + 1}</span>}
                </div>
                <div className="pc-wiz-step-label">{s.label}</div>
              </div>
            ))}
          </div>

          <div className="pc-wiz-aside-foot">
            <div style={{ fontSize: 11, color: "var(--text-3)", lineHeight: 1.5 }}>
              Setup typically takes <b style={{ color: "var(--accent)" }}>3–4 minutes</b>. Perdura's AI will read your trial balance and propose a chart of accounts mapping — you stay in control.
            </div>
          </div>
        </div>

        <div className="pc-wiz-main">
          {step === 0 && <WizWelcome onNext={next} />}
          {step === 1 && <WizType bizType={bizType} setBizType={setBizType} onNext={next} onBack={back} />}
          {step === 2 && <WizProfile profile={profile} setProfile={setProfile} bizType={bizType} onNext={next} onBack={back} />}
          {step === 3 && <WizConnect
            accountingSystem={accountingSystem} setAccountingSystem={setAccountingSystem}
            connecting={connecting} setConnecting={setConnecting}
            connected={connected} setConnected={setConnected}
            onNext={next} onBack={back} />}
          {step === 4 && <WizMapping aiPhase={aiPhase} mappings={mappings} setMappings={setMappings} onNext={next} onBack={back} />}
          {step === 5 && <WizDone bizType={bizType} profile={profile} onLaunch={() => onComplete({ bizType, profile })} />}
        </div>
      </div>
    </div>
  );
}

// ─── Step 0: Welcome ──────────────────────────────────────────────────────
function WizWelcome({ onNext }) {
  return (
    <div className="pc-wiz-pane">
      <div className="pc-wiz-eyebrow">Welcome</div>
      <h1 className="pc-wiz-title">Let's give you the CFO's view of your business.</h1>
      <p className="pc-wiz-lead">
        In a few minutes, Perdura will connect to your accounting system, study your chart of accounts and transaction history, and produce a live operating dashboard tailored to how your business actually works — not a generic template.
      </p>

      <div className="pc-wiz-cards">
        {[
          { t: "Connect once", d: "Direct read of GL, invoices, bills, items, and customers from QuickBooks, Xero, or NetSuite." },
          { t: "AI does the mapping", d: "We classify every account and transaction into a standard operating P&L — you accept or override." },
          { t: "Dashboards on day one", d: "Financial overview, sales, cash, inventory or utilization, and an exceptions inbox — populated with your real numbers." },
          { t: "Insights that compound", d: "Trends, anomalies, forecasts, and a copilot you can ask anything." },
        ].map((c, i) => (
          <div key={i} className="pc-wiz-card">
            <div style={{ width: 28, height: 28, borderRadius: 6, background: "rgba(110,231,183,0.12)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--accent)", marginBottom: 10 }}>
              {i === 0 && <Icon d="M9 12h6 M12 9v6" size={14} />}
              {i === 1 && <Icon d={icons.ai} size={14} />}
              {i === 2 && <Icon d={icons.overview} size={14} />}
              {i === 3 && <Icon d={icons.forecast} size={14} />}
            </div>
            <div style={{ fontSize: 13.5, fontWeight: 600, marginBottom: 4 }}>{c.t}</div>
            <div style={{ fontSize: 12, color: "var(--text-3)", lineHeight: 1.55 }}>{c.d}</div>
          </div>
        ))}
      </div>

      <div className="pc-wiz-actions">
        <button className="pc-btn primary" onClick={onNext}>Get started <Icon d={icons.chevron} size={13} /></button>
        <button className="pc-btn ghost">I have a question first</button>
      </div>
    </div>
  );
}

// ─── Step 1: Business type ────────────────────────────────────────────────
function WizType({ bizType, setBizType, onNext, onBack }) {
  const types = [
    {
      key: "service", label: "Service business", tag: "Agency · Consulting · Professional services",
      desc: "Revenue comes from billable time, projects, or retainers. You sell people and expertise.",
      kpis: ["Utilization", "Realization", "Project margin", "Bench"],
    },
    {
      key: "product", label: "Product / e-commerce", tag: "DTC · Wholesale · Subscription",
      desc: "You sell physical or digital goods. Inventory, fulfillment, and unit economics drive the P&L.",
      kpis: ["GMROI", "Sell-through", "AOV", "Channel mix"],
    },
    {
      key: "retail", label: "Retail with stores", tag: "Brick-and-mortar · Restaurants · Multi-location",
      desc: "You operate physical locations. Per-store productivity, foot traffic, comp sales, and rent matter.",
      kpis: ["Revenue / sqft", "Comp sales", "Conversion", "Labor %"],
    },
    {
      key: "manufacturing", label: "Manufacturing", tag: "Make to stock · Make to order",
      desc: "You transform inputs into finished goods. Throughput, yield, and BOM accuracy matter.",
      kpis: ["OEE", "Material yield", "Throughput", "WIP days"],
    },
    {
      key: "subscription", label: "Subscription / SaaS", tag: "Recurring revenue · MRR · Annual contracts",
      desc: "Customers pay recurring fees. Retention, expansion, and cohort dynamics drive enterprise value.",
      kpis: ["MRR / ARR", "Net retention", "Gross churn", "Cohort survival"],
    },
  ];
  return (
    <div className="pc-wiz-pane">
      <div className="pc-wiz-eyebrow">Step 1 · Business type</div>
      <h1 className="pc-wiz-title">What kind of business are you running?</h1>
      <p className="pc-wiz-lead">This shapes which operational dashboards we build — inventory, utilization, throughput. You can change this later, or run multiple entities.</p>

      <div className="pc-wiz-types">
        {types.map(t => (
          <div key={t.key} className={"pc-wiz-typecard " + (bizType === t.key ? "selected" : "")}
            onClick={() => setBizType(t.key)}>
            <div className="pc-wiz-typecard-radio">
              {bizType === t.key && <div className="pc-wiz-typecard-dot" />}
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14.5, fontWeight: 600 }}>{t.label}</div>
              <div style={{ fontSize: 11, color: "var(--text-3)", marginBottom: 8, letterSpacing: 0.2 }}>{t.tag}</div>
              <div style={{ fontSize: 12.5, color: "var(--text-2)", lineHeight: 1.55, marginBottom: 12 }}>{t.desc}</div>
              <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                {t.kpis.map(k => <span key={k} className="pc-chip">{k}</span>)}
              </div>
            </div>
          </div>
        ))}
      </div>

      <div className="pc-wiz-actions">
        <button className="pc-btn ghost" onClick={onBack}>Back</button>
        <button className="pc-btn primary" onClick={onNext}>Continue <Icon d={icons.chevron} size={13} /></button>
      </div>
    </div>
  );
}

// ─── Step 2: Profile ──────────────────────────────────────────────────────
function WizProfile({ profile, setProfile, bizType, onNext, onBack }) {
  const u = (k, v) => setProfile(p => ({ ...p, [k]: v }));
  return (
    <div className="pc-wiz-pane">
      <div className="pc-wiz-eyebrow">Step 2 · Company profile</div>
      <h1 className="pc-wiz-title">Tell us about your operation.</h1>
      <p className="pc-wiz-lead">These shape the defaults; we'll refine using your data.</p>

      <div className="pc-wiz-form">
        <Field label="Legal company name">
          <input value={profile.company} onChange={(e) => u("company", e.target.value)} />
        </Field>
        <Field label="Annual revenue band">
          <select value={profile.revenue} onChange={(e) => u("revenue", e.target.value)}>
            {["< $1M", "$1M – $3M", "$3M – $8M", "$8M – $15M", "$15M – $40M", "$40M – $100M", "> $100M"].map(o => <option key={o}>{o}</option>)}
          </select>
        </Field>
        <Field label="Employees (FTE)">
          <input type="number" value={profile.employees} onChange={(e) => u("employees", +e.target.value)} />
        </Field>
        <Field label={bizType === "service" ? "Service lines" : "SKUs / product lines"}>
          <input type="number" value={bizType === "service" ? profile.services : profile.products}
            onChange={(e) => u(bizType === "service" ? "services" : "products", +e.target.value)} />
        </Field>
        <Field label="Fiscal year ends">
          <select value={profile.fyEnd} onChange={(e) => u("fyEnd", e.target.value)}>
            {["December","November","October","September","June","March"].map(o => <option key={o}>{o}</option>)}
          </select>
        </Field>
        <Field label="Multi-entity / consolidation?">
          <div className="pc-wiz-radio-row">
            {["No, single entity", "Yes, 2–5 entities", "Yes, 6+ entities"].map((o, i) => (
              <button key={o}
                className={"pc-wiz-radio " + ((profile.multiEntity === (i > 0)) === (i > 0) && ((i === 0 && !profile.multiEntity) || (i > 0 && profile.multiEntity)) ? "selected" : "")}
                onClick={() => u("multiEntity", i > 0)}>{o}</button>
            ))}
          </div>
        </Field>
      </div>

      <div className="pc-wiz-actions">
        <button className="pc-btn ghost" onClick={onBack}>Back</button>
        <button className="pc-btn primary" onClick={onNext}>Continue <Icon d={icons.chevron} size={13} /></button>
      </div>
    </div>
  );
}

function Field({ label, children }) {
  return (
    <label className="pc-wiz-field">
      <span>{label}</span>
      {children}
    </label>
  );
}

// ─── Step 3: Connect ──────────────────────────────────────────────────────
function WizConnect({ accountingSystem, setAccountingSystem, connecting, setConnecting, connected, setConnected, onNext, onBack }) {
  const systems = [
    { key: "qbo",      name: "QuickBooks Online",     popularity: "Most common",  desc: "Direct API · GL, invoices, bills, items, customers" },
    { key: "xero",     name: "Xero",                  popularity: "Very common",  desc: "Direct API · GL, invoices, bills, contacts, tracking" },
    { key: "netsuite", name: "NetSuite",              popularity: "Enterprise",   desc: "SuiteTalk REST · GL, AR, AP, items, custom segments" },
    { key: "sage",     name: "Sage Intacct",          popularity: "Coming soon",  desc: "Beta — request access", disabled: true },
    { key: "dynamics", name: "Microsoft Dynamics",    popularity: "Coming soon",  desc: "Beta — request access", disabled: true },
    { key: "csv",      name: "Upload CSV / trial balance", popularity: "Manual",  desc: "For systems we don't integrate with yet" },
  ];

  const connect = () => {
    setConnecting(true);
    setTimeout(() => { setConnecting(false); setConnected(true); }, 1800);
  };

  return (
    <div className="pc-wiz-pane">
      <div className="pc-wiz-eyebrow">Step 3 · Connect</div>
      <h1 className="pc-wiz-title">Where does your data live?</h1>
      <p className="pc-wiz-lead">We start with the most popular systems. Connection is read-only by default — Perdura never writes to your books.</p>

      <div className="pc-wiz-systems">
        {systems.map(s => (
          <button key={s.key}
            className={"pc-wiz-system " + (accountingSystem === s.key ? "selected " : "") + (s.disabled ? "disabled" : "")}
            onClick={() => !s.disabled && setAccountingSystem(s.key)}>
            <div className="pc-wiz-system-logo">
              <SystemLogo k={s.key} />
            </div>
            <div style={{ flex: 1, textAlign: "left" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <div style={{ fontSize: 13.5, fontWeight: 600 }}>{s.name}</div>
                <span className="pc-chip" style={{ fontSize: 10 }}>{s.popularity}</span>
              </div>
              <div style={{ fontSize: 11.5, color: "var(--text-3)", marginTop: 2 }}>{s.desc}</div>
            </div>
            {accountingSystem === s.key && !s.disabled && <Icon d={icons.check} size={16} strokeWidth={2.4} stroke="var(--accent)" />}
          </button>
        ))}
      </div>

      {accountingSystem && !connected && (
        <div className="pc-wiz-connect-cta">
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <div style={{ width: 8, height: 8, borderRadius: "50%", background: "var(--warning)", boxShadow: "0 0 12px var(--warning)" }} />
            <div>
              <div style={{ fontSize: 13, fontWeight: 500 }}>Ready to connect to {systems.find(s => s.key === accountingSystem)?.name}</div>
              <div style={{ fontSize: 11, color: "var(--text-3)" }}>Opens a secure OAuth window. We pull last 24 months of transactions.</div>
            </div>
          </div>
          <button className="pc-btn primary" onClick={connect} disabled={connecting}>
            {connecting ? <><Spinner /> Connecting…</> : <>Connect securely</>}
          </button>
        </div>
      )}

      {connected && (
        <div className="pc-wiz-connect-success">
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <div style={{ width: 32, height: 32, borderRadius: "50%", background: "rgba(110,231,183,0.15)", color: "var(--accent)", display: "flex", alignItems: "center", justifyContent: "center" }}>
              <Icon d={icons.check} size={16} strokeWidth={2.4} />
            </div>
            <div>
              <div style={{ fontSize: 13.5, fontWeight: 600 }}>Connected to {systems.find(s => s.key === accountingSystem)?.name}</div>
              <div style={{ fontSize: 11.5, color: "var(--text-3)" }}>
                Pulled <b style={{ color: "var(--text)" }}>248 accounts</b> · <b style={{ color: "var(--text)" }}>14,392 transactions</b> · <b style={{ color: "var(--text)" }}>24 months</b> of history
              </div>
            </div>
          </div>
        </div>
      )}

      <div className="pc-wiz-actions">
        <button className="pc-btn ghost" onClick={onBack}>Back</button>
        <button className="pc-btn primary" onClick={onNext} disabled={!connected}>
          Continue <Icon d={icons.chevron} size={13} />
        </button>
      </div>
    </div>
  );
}

function SystemLogo({ k }) {
  const styles = {
    qbo:      { bg: "#2ca01c", t: "qb" },
    xero:     { bg: "#13b5ea", t: "X" },
    netsuite: { bg: "#125ca0", t: "NS" },
    sage:     { bg: "#00d639", t: "S" },
    dynamics: { bg: "#0067b8", t: "D" },
    csv:      { bg: "var(--border-strong)", t: "csv" },
  };
  const s = styles[k] || styles.csv;
  return (
    <div style={{
      width: 32, height: 32, borderRadius: 6, background: s.bg,
      display: "flex", alignItems: "center", justifyContent: "center",
      fontSize: 11, fontWeight: 700, color: "var(--text)", letterSpacing: -0.2,
    }}>
      {s.t}
    </div>
  );
}

function Spinner() {
  return <div className="pc-spinner" />;
}

// ─── Step 4: AI Mapping ───────────────────────────────────────────────────
function WizMapping({ aiPhase, mappings, setMappings, onNext, onBack }) {
  const [editing, setEditing] = useStateW(null);
  const updateRow = (acct, status, override) => {
    setMappings(rows => rows.map(r => r.acct === acct ? { ...r, status, suggested: override || r.suggested } : r));
    setEditing(null);
  };

  const stats = {
    total: mappings.length,
    accepted: mappings.filter(m => m.status === "accepted").length,
    suggested: mappings.filter(m => m.status === "suggested").length,
    overridden: mappings.filter(m => m.status === "overridden").length,
  };

  if (aiPhase < 2) {
    return (
      <div className="pc-wiz-pane">
        <div className="pc-wiz-eyebrow">Step 4 · AI mapping</div>
        <h1 className="pc-wiz-title">Perdura is reading your chart of accounts.</h1>
        <p className="pc-wiz-lead">Every business posts a little differently. The AI studies your account names, transaction patterns, and vendor history to map them into a standard operating P&L.</p>

        <div className="pc-wiz-ai-scan">
          <div className="pc-wiz-ai-orb">
            <div className="pc-wiz-ai-orb-inner" />
          </div>
          <div className="pc-wiz-ai-log">
            <ScanLine done={true} text="Connected to QuickBooks · pulled 248 accounts" />
            <ScanLine done={aiPhase >= 0} text="Reading account names and hierarchies…" />
            <ScanLine done={aiPhase >= 1} text="Sampling 14,392 transactions across 24 months…" />
            <ScanLine done={aiPhase >= 1} active={aiPhase < 2} text="Classifying accounts → standard operating P&L…" />
            <ScanLine done={aiPhase >= 2} active={false} text="Building mapping with confidence scores…" pending={aiPhase < 2} />
          </div>
        </div>

        <div className="pc-wiz-actions">
          <button className="pc-btn ghost" onClick={onBack} disabled>Back</button>
          <button className="pc-btn primary" disabled>Working…</button>
        </div>
      </div>
    );
  }

  return (
    <div className="pc-wiz-pane">
      <div className="pc-wiz-eyebrow">Step 4 · AI mapping</div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: 16, marginBottom: 4 }}>
        <h1 className="pc-wiz-title" style={{ marginBottom: 0 }}>Review the proposed mapping.</h1>
        <div style={{ fontSize: 11, color: "var(--text-3)" }}>
          {stats.accepted + stats.overridden}/{stats.total} confirmed
        </div>
      </div>
      <p className="pc-wiz-lead">High-confidence mappings (≥90%) are accepted by default. Review the lower-confidence ones — accept, change, or split.</p>

      <div className="pc-wiz-map-summary">
        <div><span style={{ color: "var(--positive)" }}>●</span> {mappings.filter(m => m.conf >= 90).length} high confidence</div>
        <div><span style={{ color: "var(--warning)" }}>●</span> {mappings.filter(m => m.conf >= 80 && m.conf < 90).length} review suggested</div>
        <div><span style={{ color: "var(--danger)" }}>●</span> {mappings.filter(m => m.conf < 80 || m.flag).length} needs your eye</div>
      </div>

      <div className="pc-wiz-map">
        <div className="pc-wiz-map-head">
          <div>Account</div>
          <div>Detected class</div>
          <div>AI suggested mapping</div>
          <div style={{ textAlign: "right" }}>Confidence</div>
          <div></div>
        </div>
        <div className="pc-wiz-map-body">
          {mappings.map(m => (
            <div key={m.acct} className={"pc-wiz-map-row " + (m.status || "")}>
              <div>
                <div style={{ fontFamily: "ui-monospace, monospace", fontSize: 11, color: "var(--text-3)" }}>{m.acct}</div>
                <div style={{ fontSize: 12.5, fontWeight: 500 }}>{m.name}</div>
                {m.flag && (
                  <div className="pc-wiz-map-flag">⚑ {m.flag}</div>
                )}
              </div>
              <div><span className="pc-chip">{m.pclass}</span></div>
              <div>
                {editing === m.acct ? (
                  <select autoFocus
                    onChange={(e) => updateRow(m.acct, "overridden", e.target.value)}
                    onBlur={() => setEditing(null)}>
                    <option>{m.suggested}</option>
                    {(m.alts || ["Opex / Other", "Revenue / Other"]).map(a => <option key={a}>{a}</option>)}
                  </select>
                ) : (
                  <div style={{ fontSize: 12.5, fontFamily: "ui-monospace, monospace" }}>{m.suggested}</div>
                )}
              </div>
              <div style={{ textAlign: "right" }}>
                <ConfPill conf={m.conf} />
              </div>
              <div className="pc-wiz-map-actions">
                {m.status === "accepted" || m.status === "overridden" ? (
                  <span style={{ color: m.status === "overridden" ? "var(--warning)" : "var(--positive)", fontSize: 11 }}>
                    {m.status === "overridden" ? "Overridden" : "Accepted"}
                  </span>
                ) : (
                  <>
                    <button className="pc-btn-mini" onClick={() => updateRow(m.acct, "accepted")}>Accept</button>
                    <button className="pc-btn-mini ghost" onClick={() => setEditing(m.acct)}>Change</button>
                  </>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>

      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 16, padding: "12px 14px", background: "rgba(110,231,183,0.04)", border: "1px solid rgba(110,231,183,0.12)", borderRadius: 6 }}>
        <div style={{ fontSize: 12, color: "var(--text-2)", display: "flex", alignItems: "center", gap: 8 }}>
          <Icon d={icons.ai} size={14} stroke="var(--accent)" />
          <span>Perdura saves these mappings as <b>rules</b> — new accounts will be classified automatically going forward.</span>
        </div>
        <button className="pc-btn ghost" onClick={() => setMappings(rows => rows.map(r => ({ ...r, status: "accepted" })))}>
          Accept all
        </button>
      </div>

      <div className="pc-wiz-actions">
        <button className="pc-btn ghost" onClick={onBack}>Back</button>
        <button className="pc-btn primary" onClick={onNext}>Continue <Icon d={icons.chevron} size={13} /></button>
      </div>
    </div>
  );
}

function ScanLine({ done, active, pending, text }) {
  return (
    <div className={"pc-scan-line " + (done ? "done " : "") + (active ? "active " : "") + (pending ? "pending" : "")}>
      <div className="pc-scan-dot">
        {done ? <Icon d={icons.check} size={10} strokeWidth={2.6} stroke="var(--accent)" /> :
         active ? <Spinner /> :
         <span style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--text-4)", display: "inline-block" }} />}
      </div>
      <span>{text}</span>
    </div>
  );
}

function ConfPill({ conf }) {
  const color = conf >= 90 ? "var(--positive)" : conf >= 80 ? "var(--warning)" : "var(--danger)";
  return (
    <div style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
      <div style={{ width: 36, height: 4, borderRadius: 1, background: "var(--border-strong)", overflow: "hidden" }}>
        <div style={{ width: conf + "%", height: "100%", background: color }} />
      </div>
      <span style={{ fontSize: 11, fontFamily: "ui-monospace, monospace", color, minWidth: 30, textAlign: "right" }}>{conf}%</span>
    </div>
  );
}

// ─── Step 5: Done ─────────────────────────────────────────────────────────
function WizDone({ bizType, profile, onLaunch }) {
  return (
    <div className="pc-wiz-pane">
      <div className="pc-wiz-eyebrow">Step 5 · Ready</div>
      <div style={{ width: 60, height: 60, borderRadius: 16, background: "radial-gradient(circle at 30% 30%, var(--accent), var(--accent-2))", display: "flex", alignItems: "center", justifyContent: "center", marginBottom: 24, boxShadow: "0 12px 40px rgba(110,231,183,0.25)" }}>
        <Icon d={icons.check} size={26} strokeWidth={2.4} stroke="var(--on-accent)" />
      </div>
      <h1 className="pc-wiz-title">Your operating intelligence is live.</h1>
      <p className="pc-wiz-lead">{profile.company} is set up as a {bizType === "service" ? "service business" : bizType === "product" ? "product business" : "manufacturing operation"}. We've already detected <b style={{ color: "var(--warning)" }}>3 exceptions</b> worth your attention.</p>

      <div className="pc-wiz-summary">
        <SummRow l="Company" v={profile.company} />
        <SummRow l="Business type" v={bizType === "service" ? "Services" : bizType === "product" ? "Product / E-commerce" : "Manufacturing"} />
        <SummRow l="Revenue band" v={profile.revenue} />
        <SummRow l="Accounts integrated" v="248 GL accounts · 14,392 transactions" />
        <SummRow l="Mapping confidence" v={<span><b style={{ color: "var(--positive)" }}>94%</b> auto-classified · 6% reviewed</span>} />
        <SummRow l="Dashboards prepared" v="11 modules · AI copilot enabled" />
      </div>

      <div className="pc-wiz-actions">
        <button className="pc-btn primary big" onClick={onLaunch}>
          Launch Perdura
          <Icon d={icons.chevron} size={14} />
        </button>
      </div>
    </div>
  );
}

function SummRow({ l, v }) {
  return (
    <div className="pc-wiz-summ-row">
      <span>{l}</span>
      <span>{v}</span>
    </div>
  );
}

Object.assign(window, { Wizard });
