// Setup / onboarding screen
// Shown to new companies that haven't connected any data yet.
// Guides them through: business profile → connect accounting → go live

const { useState: useStateSetup, useEffect: useEffectSetup } = React;

const MONTHS = ["January","February","March","April","May","June","July","August","September","October","November","December"];

const BIZ_TYPES = [
  { k: "service",      label: "Professional Services",   icon: "M12 4.5v15m7.5-7.5h-15", desc: "Consulting, agencies, law, accounting" },
  { k: "product",      label: "Product / E-commerce",    icon: "M20 7H4a2 2 0 00-2 2v10a2 2 0 002 2h16a2 2 0 002-2V9a2 2 0 00-2-2zM16 3H8l-1 4h10l-1-4z", desc: "Physical goods, DTC, wholesale" },
  { k: "retail",       label: "Retail",                  icon: "M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2 5h14l-2-5M10 20a1 1 0 100-2 1 1 0 000 2zm7 0a1 1 0 100-2 1 1 0 000 2z", desc: "Brick & mortar, multi-location" },
  { k: "manufacturing",label: "Manufacturing",            icon: "M19.428 15.428a2 2 0 00-1.022-.547l-2.387-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z", desc: "Production, assembly, fabrication" },
  { k: "subscription", label: "Subscription / SaaS",     icon: "M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15", desc: "Recurring revenue, MRR tracking" },
];

const REVENUE_BANDS = [
  "Under $500K", "$500K–$1M", "$1M–$3M", "$3M–$10M", "$10M–$25M", "$25M–$50M", "Over $50M"
];

const INTEGRATIONS = [
  { k: "qbo",       n: "QuickBooks Online", cat: "Accounting", primary: true,  logo: "https://images.pexels.com/photos/3943716/pexels-photo-3943716.jpeg" },
  { k: "xero",      n: "Xero",              cat: "Accounting", primary: true },
  { k: "netsuite",  n: "NetSuite",          cat: "Accounting", primary: true },
  { k: "sage",      n: "Sage Intacct",      cat: "Accounting", primary: true,  beta: true },
  { k: "csv",       n: "CSV / Excel",       cat: "Manual",     primary: false },
  { k: "stripe",    n: "Stripe",            cat: "Payments",   primary: false },
  { k: "shopify",   n: "Shopify",           cat: "Commerce",   primary: false },
  { k: "bank",      n: "Bank feed",         cat: "Banking",    primary: false },
];

// ── Logo marks (inline SVG) ──────────────────────────────────────────────────

function IntegLogo({ k, size = 36 }) {
  const colors = {
    qbo: "#2CA01C", xero: "#13B5EA", netsuite: "#2B5FA5", sage: "#00DC84",
    csv: "#059669", stripe: "#635BFF", shopify: "#96BF48", bank: "#0EA5E9",
  };
  const initials = { qbo: "QB", xero: "X", netsuite: "NS", sage: "SI", csv: "CSV", stripe: "S", shopify: "SH", bank: "B" };
  return (
    <div style={{
      width: size, height: size, borderRadius: 8,
      background: (colors[k] || "#64748b") + "22",
      border: `1px solid ${colors[k] || "#64748b"}33`,
      display: "flex", alignItems: "center", justifyContent: "center",
      fontSize: size * 0.28, fontWeight: 700, color: colors[k] || "#64748b",
      flexShrink: 0, letterSpacing: -0.5,
    }}>
      {initials[k] || "?"}
    </div>
  );
}

// ── Step indicator ──────────────────────────────────────────────────────────

function StepDots({ step, total }) {
  return (
    <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
      {Array.from({ length: total }).map((_, i) => (
        <div key={i} style={{
          width: i === step ? 20 : 6,
          height: 6,
          borderRadius: 3,
          background: i === step ? "var(--accent)" : i < step ? "rgba(110,231,183,0.4)" : "var(--border-strong)",
          transition: "width 0.25s, background 0.25s",
        }} />
      ))}
    </div>
  );
}

// ── Step 0: Welcome ──────────────────────────────────────────────────────────

function StepWelcome({ companyName, ownerName, onNext }) {
  return (
    <div className="pc-setup-card pc-setup-welcome">
      <div className="pc-setup-welcome-badge">Welcome to Perdura Capital</div>
      <h1 className="pc-setup-h1">
        {ownerName ? `Hi ${ownerName.split(" ")[0]},` : "Let's get you set up."}
      </h1>
      <p className="pc-setup-lead">
        {companyName ? (
          <><strong>{companyName}</strong>'s financial intelligence platform is ready to configure.</>
        ) : (
          "Your financial intelligence platform is ready to configure."
        )}
        {" "}It takes about 5 minutes to connect your accounting system and unlock real-time dashboards.
      </p>

      <div className="pc-setup-steps-preview">
        {[
          { n: "1", t: "Business profile", d: "Tell us your business type and fiscal year" },
          { n: "2", t: "Connect accounting", d: "Link QuickBooks, Xero, NetSuite, or CSV" },
          { n: "3", t: "Map your accounts", d: "AI classifies your chart of accounts in seconds" },
        ].map(s => (
          <div key={s.n} className="pc-setup-preview-step">
            <div className="pc-setup-preview-num">{s.n}</div>
            <div>
              <div className="pc-setup-preview-title">{s.t}</div>
              <div className="pc-setup-preview-desc">{s.d}</div>
            </div>
          </div>
        ))}
      </div>

      <button className="pc-setup-cta" onClick={onNext}>
        Get started
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" style={{ marginLeft: 8 }}>
          <path d="M5 12h14M12 5l7 7-7 7" />
        </svg>
      </button>
    </div>
  );
}

// ── Step 1: Business type ────────────────────────────────────────────────────

function StepBizType({ value, onChange, onNext, onBack }) {
  return (
    <div className="pc-setup-card">
      <div className="pc-setup-card-inner">
        <div className="pc-setup-card-header">
          <div>
            <div className="pc-setup-step-label">Step 1 of 3</div>
            <h2 className="pc-setup-h2">What best describes your business?</h2>
            <p className="pc-setup-sublead">This shapes which dashboards and KPIs are most relevant.</p>
          </div>
        </div>

        <div className="pc-setup-biz-grid">
          {BIZ_TYPES.map(b => (
            <button
              key={b.k}
              className={"pc-setup-biz-card" + (value === b.k ? " selected" : "")}
              onClick={() => onChange(b.k)}
            >
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" style={{ marginBottom: 8, opacity: 0.8 }}>
                <path d={b.icon} />
              </svg>
              <div className="pc-setup-biz-label">{b.label}</div>
              <div className="pc-setup-biz-desc">{b.desc}</div>
            </button>
          ))}
        </div>

        <div className="pc-setup-nav">
          <button className="pc-setup-back" onClick={onBack}>Back</button>
          <button className="pc-setup-cta" onClick={onNext} disabled={!value}>
            Continue
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ marginLeft: 8 }}>
              <path d="M5 12h14M12 5l7 7-7 7" />
            </svg>
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Step 2: Company profile ──────────────────────────────────────────────────

function StepProfile({ profile, onChange, onNext, onBack }) {
  const set = (k, v) => onChange({ ...profile, [k]: v });
  return (
    <div className="pc-setup-card">
      <div className="pc-setup-card-inner">
        <div className="pc-setup-card-header">
          <div>
            <div className="pc-setup-step-label">Step 1 of 3 — continued</div>
            <h2 className="pc-setup-h2">A bit more about your company</h2>
            <p className="pc-setup-sublead">This information shapes your benchmarks and forecasting models.</p>
          </div>
        </div>

        <div className="pc-setup-form-grid">
          <div className="pc-setup-field">
            <label className="pc-setup-label">Annual revenue</label>
            <select className="pc-setup-select" value={profile.revenue || ""} onChange={e => set("revenue", e.target.value)}>
              <option value="" disabled>Select a range</option>
              {REVENUE_BANDS.map(r => <option key={r} value={r}>{r}</option>)}
            </select>
          </div>

          <div className="pc-setup-field">
            <label className="pc-setup-label">Employees (FTE)</label>
            <input className="pc-setup-input" type="number" min="1" placeholder="e.g. 12"
              value={profile.employees || ""} onChange={e => set("employees", e.target.value)} />
          </div>

          <div className="pc-setup-field">
            <label className="pc-setup-label">Fiscal year end</label>
            <select className="pc-setup-select" value={profile.fyEnd || "December"} onChange={e => set("fyEnd", e.target.value)}>
              {MONTHS.map(m => <option key={m} value={m}>{m}</option>)}
            </select>
          </div>

          <div className="pc-setup-field">
            <label className="pc-setup-label">Multi-entity / consolidation</label>
            <div className="pc-setup-toggle-row">
              {["No", "Yes"].map(opt => (
                <button
                  key={opt}
                  className={"pc-setup-toggle-btn" + ((profile.multiEntity ? "Yes" : "No") === opt ? " active" : "")}
                  onClick={() => set("multiEntity", opt === "Yes")}
                  type="button"
                >
                  {opt}
                </button>
              ))}
            </div>
          </div>
        </div>

        <div className="pc-setup-nav">
          <button className="pc-setup-back" onClick={onBack}>Back</button>
          <button className="pc-setup-cta" onClick={onNext}>
            Continue
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ marginLeft: 8 }}>
              <path d="M5 12h14M12 5l7 7-7 7" />
            </svg>
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Per-provider credential forms ───────────────────────────────────────────

const PROVIDER_FIELDS = {
  qbo: {
    title: "QuickBooks Online",
    intro: "Sign in to QuickBooks Online with your Intuit account. Perdura requests read-only access — we never write data or see your password.",
    authType: "oauth",
    oauthLabel: "Sign in with Intuit",
    fields: [],
    helpUrl: "https://quickbooks.intuit.com",
    helpText: "You'll be redirected to Intuit's secure login page. After authorising, you'll return here automatically.",
  },
  xero: {
    title: "Xero",
    intro: "Connect your Xero organisation. You'll be taken to Xero's login page to grant read-only access.",
    authType: "oauth",
    oauthLabel: "Sign in with Xero",
    fields: [],
    helpUrl: "https://xero.com",
    helpText: "Perdura requests accounting read scope only. No write access is requested.",
  },
  netsuite: {
    title: "NetSuite",
    intro: "Enter your NetSuite credentials to create a read-only token-based connection. We never store your password.",
    authType: "token",
    fields: [
      { k: "account_id",      label: "Account ID",        placeholder: "1234567",         hint: "Found under Setup → Company → Company Information" },
      { k: "consumer_key",    label: "Consumer Key",      placeholder: "Paste key…",      hint: "From your TBA integration record in NetSuite" },
      { k: "consumer_secret", label: "Consumer Secret",   placeholder: "Paste secret…",   hint: "", secret: true },
      { k: "token_id",        label: "Token ID",          placeholder: "Paste token…",    hint: "From your Access Token in NetSuite" },
      { k: "token_secret",    label: "Token Secret",      placeholder: "Paste secret…",   hint: "", secret: true },
    ],
    helpText: "Use Token-Based Authentication (TBA). Create a dedicated read-only role and integration record in NetSuite before connecting.",
  },
  sage: {
    title: "Sage Intacct",
    intro: "Enter your Sage Intacct Web Services credentials. Create a dedicated web-services-only user with read-only permissions.",
    authType: "token",
    fields: [
      { k: "company_id",  label: "Company ID",   placeholder: "Your Intacct company ID", hint: "Case-sensitive. Found in the URL when logged in." },
      { k: "user_id",     label: "User ID",      placeholder: "api_readonly",             hint: "Dedicated web-services user — not your personal login" },
      { k: "password",    label: "Password",     placeholder: "••••••••",                 hint: "", secret: true },
      { k: "sender_id",   label: "Sender ID",    placeholder: "Your Web Services sender", hint: "Assigned by Sage when you enable Web Services" },
      { k: "sender_pass", label: "Sender Password", placeholder: "••••••••",              hint: "", secret: true },
    ],
    helpText: "Create a dedicated Intacct user with the 'Accounting Read Only' role. Enable Web Services under Company → Subscriptions.",
  },
  csv: {
    title: "CSV / Excel Upload",
    intro: "No credentials needed. You'll upload your exported GL file after setup. Perdura accepts standard QuickBooks, Xero, or custom CSV exports.",
    authType: "manual",
    fields: [],
    helpText: "Supported formats: QuickBooks GL export (.xlsx/.csv), Xero GL export, or any CSV with columns: Date, Account, Description, Debit, Credit.",
  },
};

function ConnectModal({ integ, companyId, onClose, onConnected }) {
  const cfg = PROVIDER_FIELDS[integ.k] || PROVIDER_FIELDS.csv;
  const [creds, setCreds] = useStateSetup({});
  const [saving, setSaving] = useStateSetup(false);
  const [error, setError] = useStateSetup("");
  const [showSecrets, setShowSecrets] = useStateSetup({});

  const setField = (k, v) => setCreds(c => ({ ...c, [k]: v }));
  const toggleSecret = (k) => setShowSecrets(s => ({ ...s, [k]: !s[k] }));

  const allFilled = cfg.fields.every(f => creds[f.k] && creds[f.k].trim());

  async function handleSave() {
    setSaving(true);
    setError("");
    try {
      const db = window.supabaseClient;
      // Store integration record with status "pending_setup"
      // Sensitive fields are stored server-side only; we send them via the edge function
      // For now we record the non-secret metadata and flag it for the Perdura team
      const safeCreds = {};
      cfg.fields.forEach(f => {
        if (!f.secret) safeCreds[f.k] = creds[f.k] || "";
      });

      const { error: dbErr } = await db.from("integrations").upsert({
        company_id: companyId,
        provider: integ.k,
        status: "pending_setup",
        credentials: safeCreds,
        provider_meta: { requested_at: new Date().toISOString(), auth_type: cfg.authType },
        connected_at: new Date().toISOString(),
      }, { onConflict: "company_id,provider" });

      if (dbErr) throw dbErr;
      onConnected(integ.k);
    } catch (err) {
      setError(err.message || "Failed to save. Please try again.");
      setSaving(false);
    }
  }

  async function handleOAuth() {
    // Record intent in DB then show pending state
    setSaving(true);
    setError("");
    try {
      const db = window.supabaseClient;
      const { error: dbErr } = await db.from("integrations").upsert({
        company_id: companyId,
        provider: integ.k,
        status: "pending_setup",
        credentials: {},
        provider_meta: { requested_at: new Date().toISOString(), auth_type: "oauth" },
        connected_at: new Date().toISOString(),
      }, { onConflict: "company_id,provider" });
      if (dbErr) throw dbErr;
      onConnected(integ.k);
    } catch (err) {
      setError(err.message || "Failed to save. Please try again.");
      setSaving(false);
    }
  }

  async function handleManual() {
    setSaving(true);
    try {
      const db = window.supabaseClient;
      await db.from("integrations").upsert({
        company_id: companyId,
        provider: integ.k,
        status: "pending_setup",
        credentials: {},
        provider_meta: { requested_at: new Date().toISOString(), auth_type: "manual" },
        connected_at: new Date().toISOString(),
      }, { onConflict: "company_id,provider" });
      onConnected(integ.k);
    } catch (err) {
      setError(err.message || "Failed to save.");
      setSaving(false);
    }
  }

  return (
    <div className="pc-modal-backdrop" onClick={saving ? undefined : onClose}>
      <div className="pc-setup-connect-modal" onClick={e => e.stopPropagation()}
        style={{ maxWidth: cfg.fields.length > 2 ? 520 : 440 }}>

        {/* Header */}
        <div className="pc-setup-connect-modal-hd">
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <IntegLogo k={integ.k} size={40} />
            <div>
              <div style={{ fontSize: 11, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: 0.5 }}>Connect</div>
              <div style={{ fontSize: 17, fontWeight: 600 }}>{cfg.title}</div>
            </div>
          </div>
          <button className="pc-icon-btn" onClick={onClose} disabled={saving}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M18 6L6 18M6 6l12 12" /></svg>
          </button>
        </div>

        <div className="pc-setup-connect-modal-body">
          <p style={{ fontSize: 13, color: "var(--text-2)", lineHeight: 1.6, marginBottom: 18 }}>{cfg.intro}</p>

          {error && (
            <div className="pc-auth-error-banner" style={{ marginBottom: 14, fontSize: 12.5 }}>{error}</div>
          )}

          {/* OAuth flow */}
          {cfg.authType === "oauth" && (
            <div>
              <div className="pc-setup-oauth-perms">
                <div style={{ fontSize: 11.5, fontWeight: 600, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: 10 }}>
                  Perdura will request read-only access to:
                </div>
                {["Chart of accounts", "General ledger — last 24 months", "Vendor & customer names", "Bank account balances"].map(p => (
                  <div key={p} className="pc-setup-connect-perm-row">
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="var(--positive)" strokeWidth="3" strokeLinecap="round"><polyline points="20 6 9 17 4 12" /></svg>
                    <span>{p}</span>
                  </div>
                ))}
                <div className="pc-setup-connect-perm-row" style={{ color: "var(--text-3)", marginTop: 6 }}>
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="var(--danger)" strokeWidth="3" strokeLinecap="round"><path d="M18 6L6 18M6 6l12 12" /></svg>
                  No write access · passwords never seen or stored
                </div>
              </div>
              <div className="pc-setup-connect-help">{cfg.helpText}</div>
              <div style={{ display: "flex", gap: 8, justifyContent: "flex-end", marginTop: 20 }}>
                <button className="pc-btn ghost" onClick={onClose}>Cancel</button>
                <button className="pc-btn primary" onClick={handleOAuth} disabled={saving}>
                  {saving ? "Saving…" : cfg.oauthLabel + " →"}
                </button>
              </div>
            </div>
          )}

          {/* Token / credential flow */}
          {cfg.authType === "token" && (
            <div>
              <div className="pc-setup-cred-grid">
                {cfg.fields.map(f => (
                  <div key={f.k} className="pc-setup-cred-field">
                    <label className="pc-setup-cred-label">{f.label}</label>
                    <div style={{ position: "relative" }}>
                      <input
                        className="pc-setup-cred-input"
                        type={f.secret && !showSecrets[f.k] ? "password" : "text"}
                        placeholder={f.placeholder}
                        value={creds[f.k] || ""}
                        onChange={e => setField(f.k, e.target.value)}
                        autoComplete="off"
                        spellCheck="false"
                      />
                      {f.secret && (
                        <button
                          type="button"
                          onClick={() => toggleSecret(f.k)}
                          style={{ position: "absolute", right: 10, top: "50%", transform: "translateY(-50%)", background: "none", border: "none", color: "var(--text-3)", cursor: "pointer", padding: 2, fontSize: 11 }}>
                          {showSecrets[f.k] ? "Hide" : "Show"}
                        </button>
                      )}
                    </div>
                    {f.hint && <div className="pc-setup-cred-hint">{f.hint}</div>}
                  </div>
                ))}
              </div>
              {cfg.helpText && (
                <div className="pc-setup-connect-help">{cfg.helpText}</div>
              )}
              <div style={{ display: "flex", gap: 8, justifyContent: "flex-end", marginTop: 20 }}>
                <button className="pc-btn ghost" onClick={onClose}>Cancel</button>
                <button className="pc-btn primary" onClick={handleSave}
                  disabled={saving || !allFilled}>
                  {saving ? "Saving…" : "Save & connect →"}
                </button>
              </div>
            </div>
          )}

          {/* Manual / CSV flow */}
          {cfg.authType === "manual" && (
            <div>
              <div className="pc-setup-oauth-perms">
                <div style={{ fontSize: 11.5, fontWeight: 600, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: 10 }}>Accepted formats</div>
                {["QuickBooks GL export (.xlsx or .csv)", "Xero GL export (.csv)", "Custom CSV: Date · Account · Description · Debit · Credit"].map(p => (
                  <div key={p} className="pc-setup-connect-perm-row">
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="var(--positive)" strokeWidth="3" strokeLinecap="round"><polyline points="20 6 9 17 4 12" /></svg>
                    {p}
                  </div>
                ))}
              </div>
              <div className="pc-setup-connect-help">{cfg.helpText}</div>
              <div style={{ display: "flex", gap: 8, justifyContent: "flex-end", marginTop: 20 }}>
                <button className="pc-btn ghost" onClick={onClose}>Cancel</button>
                <button className="pc-btn primary" onClick={handleManual} disabled={saving}>
                  {saving ? "Saving…" : "I'll upload after setup →"}
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ── Step 3: Connect accounting ───────────────────────────────────────────────

function StepConnect({ companyId, onNext, onBack, onSkip }) {
  const [connecting, setConnecting] = useStateSetup(null);
  const [connected, setConnected] = useStateSetup({});

  const primary = INTEGRATIONS.filter(i => i.primary);
  const secondary = INTEGRATIONS.filter(i => !i.primary);
  const hasConnected = Object.keys(connected).length > 0;

  const handleConnect = (integ) => {
    if (integ.beta) {
      alert("Sage Intacct is in beta. We'll reach out within 24 hours to complete your setup.");
      return;
    }
    setConnecting(integ);
  };

  return (
    <div className="pc-setup-card">
      <div className="pc-setup-card-inner">
        <div className="pc-setup-card-header">
          <div>
            <div className="pc-setup-step-label">Step 2 of 3</div>
            <h2 className="pc-setup-h2">Connect your accounting system</h2>
            <p className="pc-setup-sublead">Perdura reads your GL in read-only mode. We never write back or store your login password.</p>
          </div>
        </div>

        <div className="pc-setup-section-label">Primary accounting</div>
        <div className="pc-setup-integ-list">
          {primary.map(i => (
            <div key={i.k} className={"pc-setup-integ-row" + (connected[i.k] ? " connected" : "")}>
              <IntegLogo k={i.k} size={40} />
              <div style={{ flex: 1 }}>
                <div className="pc-setup-integ-name">{i.n}</div>
                <div className="pc-setup-integ-cat">{i.cat}{i.beta ? " · Beta" : ""}</div>
              </div>
              {connected[i.k] ? (
                <div className="pc-setup-integ-badge connected">
                  <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
                    <polyline points="20 6 9 17 4 12" />
                  </svg>
                  Saved
                </div>
              ) : (
                <button className="pc-setup-integ-btn" onClick={() => handleConnect(i)}>
                  {i.beta ? "Request access" : "Connect"}
                </button>
              )}
            </div>
          ))}
        </div>

        <div className="pc-setup-section-label" style={{ marginTop: 20 }}>
          Other integrations{" "}
          <span className="pc-setup-optional-tag">optional · add later in Settings</span>
        </div>
        <div className="pc-setup-integ-grid-sm">
          {secondary.map(i => (
            <div key={i.k} className="pc-setup-integ-sm">
              <IntegLogo k={i.k} size={28} />
              <span>{i.n}</span>
            </div>
          ))}
        </div>

        <div className="pc-setup-nav">
          <button className="pc-setup-back" onClick={onBack}>Back</button>
          <div style={{ display: "flex", gap: 10 }}>
            {!hasConnected && (
              <button className="pc-setup-skip" onClick={onSkip}>Skip for now</button>
            )}
            {hasConnected && (
              <button className="pc-setup-cta" onClick={onNext}>
                Continue
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ marginLeft: 8 }}>
                  <path d="M5 12h14M12 5l7 7-7 7" />
                </svg>
              </button>
            )}
          </div>
        </div>
      </div>

      {connecting && (
        <ConnectModal
          integ={connecting}
          companyId={companyId}
          onClose={() => setConnecting(null)}
          onConnected={(k) => {
            setConnected(c => ({ ...c, [k]: true }));
            setConnecting(null);
          }}
        />
      )}
    </div>
  );
}

// ── Step 4: Done / Launch ────────────────────────────────────────────────────

function StepDone({ bizType, profile, companyName, onComplete }) {
  const biz = BIZ_TYPES.find(b => b.k === bizType) || BIZ_TYPES[0];
  return (
    <div className="pc-setup-card pc-setup-done">
      <div className="pc-setup-done-icon">
        <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <polyline points="20 6 9 17 4 12" />
        </svg>
      </div>
      <h2 className="pc-setup-h2" style={{ marginTop: 20 }}>You're all set{companyName ? ` — ${companyName}` : ""}.</h2>
      <p className="pc-setup-sublead">Here's a summary of your configuration. You can update any of these in Settings.</p>

      <div className="pc-setup-summary-grid">
        <div className="pc-setup-summary-item">
          <div className="pc-setup-summary-label">Business type</div>
          <div className="pc-setup-summary-value">{biz.label}</div>
        </div>
        {profile.revenue && (
          <div className="pc-setup-summary-item">
            <div className="pc-setup-summary-label">Annual revenue</div>
            <div className="pc-setup-summary-value">{profile.revenue}</div>
          </div>
        )}
        {profile.employees && (
          <div className="pc-setup-summary-item">
            <div className="pc-setup-summary-label">Employees</div>
            <div className="pc-setup-summary-value">{profile.employees} FTE</div>
          </div>
        )}
        <div className="pc-setup-summary-item">
          <div className="pc-setup-summary-label">Fiscal year end</div>
          <div className="pc-setup-summary-value">{profile.fyEnd || "December"}</div>
        </div>
        <div className="pc-setup-summary-item">
          <div className="pc-setup-summary-label">Multi-entity</div>
          <div className="pc-setup-summary-value">{profile.multiEntity ? "Yes" : "No"}</div>
        </div>
      </div>

      <div className="pc-setup-what-next">
        <div className="pc-setup-what-next-title">What happens next</div>
        <div className="pc-setup-what-next-item">
          <div className="pc-setup-what-next-dot"></div>
          <div>Your accounting data is syncing — dashboards populate within the hour</div>
        </div>
        <div className="pc-setup-what-next-item">
          <div className="pc-setup-what-next-dot"></div>
          <div>AI is mapping your chart of accounts to canonical categories</div>
        </div>
        <div className="pc-setup-what-next-item">
          <div className="pc-setup-what-next-dot"></div>
          <div>Connect additional integrations anytime from <strong>Settings → Data sources</strong></div>
        </div>
      </div>

      <button className="pc-setup-cta" style={{ marginTop: 32 }} onClick={onComplete}>
        Open my dashboard
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ marginLeft: 8 }}>
          <path d="M5 12h14M12 5l7 7-7 7" />
        </svg>
      </button>
    </div>
  );
}

// ── Main SetupPage ────────────────────────────────────────────────────────────

function SetupPage({ companyProfile, onComplete }) {
  const [step, setStep] = useStateSetup(0); // 0 welcome, 1 biztype, 2 profile, 3 connect, 4 done
  const [bizType, setBizType] = useStateSetup(companyProfile?.business_type || null);
  const [profile, setProfile] = useStateSetup({
    revenue: companyProfile?.revenue_band || "",
    employees: companyProfile?.employee_count || "",
    fyEnd: companyProfile?.fiscal_year_end || "December",
    multiEntity: companyProfile?.multi_entity || false,
  });
  const [skippedConnect, setSkippedConnect] = useStateSetup(false);

  const companyName = companyProfile?.name || "";
  const ownerName = companyProfile?.owner_name || "";
  const totalSteps = 5;

  const handleComplete = () => {
    onComplete({ bizType: bizType || "product", profile });
  };

  return (
    <div className="pc-setup-root">
      {/* Minimal top bar */}
      <div className="pc-setup-topbar">
        <div className="pc-setup-topbar-brand">
          <div className="pc-setup-topbar-logo">CFO</div>
          <span className="pc-setup-topbar-name">Perdura Capital</span>
        </div>
        {step > 0 && (
          <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 6 }}>
            <StepDots step={step - 1} total={4} />
            <div style={{ fontSize: 11, color: "var(--text-3)" }}>
              {["Business type", "Company profile", "Connect data", "Ready"][step - 1]}
            </div>
          </div>
        )}
      </div>

      <div className="pc-setup-body">
        {step === 0 && (
          <StepWelcome
            companyName={companyName}
            ownerName={ownerName}
            onNext={() => setStep(1)}
          />
        )}
        {step === 1 && (
          <StepBizType
            value={bizType}
            onChange={setBizType}
            onNext={() => setStep(2)}
            onBack={() => setStep(0)}
          />
        )}
        {step === 2 && (
          <StepProfile
            profile={profile}
            onChange={setProfile}
            onNext={() => setStep(3)}
            onBack={() => setStep(1)}
          />
        )}
        {step === 3 && (
          <StepConnect
            companyId={companyProfile?.id || null}
            onNext={() => setStep(4)}
            onBack={() => setStep(2)}
            onSkip={() => { setSkippedConnect(true); setStep(4); }}
          />
        )}
        {step === 4 && (
          <StepDone
            bizType={bizType || "product"}
            profile={profile}
            companyName={companyName}
            onComplete={handleComplete}
          />
        )}
      </div>
    </div>
  );
}
