// CompanyProfileWizard
//
// The "brain" that makes the rest of the dashboard dynamic. Runs full-screen the
// first time a new company connects (gated on companies.setup_complete !== true)
// and is re-openable from Settings → "Company Settings" in edit mode.
//
// Five steps: Business Type → Industry → Key Numbers (KPIs) → Fiscal Year &
// Reporting → Confirmation. On save it writes the profile to the existing
// `companies` table (the app's single profile table — saveCompanyProfile in
// app.jsx writes there too) and flips setup_complete to true.
//
// Loaded as a global via <script type="text/babel"> in app.html; exposed as
// window.CompanyProfileWizard. Self-contained IIFE so its local `useState` etc.
// don't collide with the other babel scripts sharing global scope.
//
// Props: { scopedCompanyId, companyProfile, editMode, onComplete, onExit }
//   onComplete(savedProfile) — called after a successful save with the merged row.
//   onExit()                 — called when the user cancels (edit mode only).

(function () {
  const { useState, useMemo, useEffect } = React;

  // ── Design tokens (match the dashboard design system) ──────────────────────
  const COLORS = {
    bg: "#F7F8FB",
    card: "#FFFFFF",
    cardBorder: "#E4E8F0",
    accent: "#1C4ED8",
    accentSoft: "#EEF2FF",
    text1: "#1A2233",
    text2: "#475569",
    muted: "#6B7A99",
  };
  const CARD_SHADOW = "0 1px 4px rgba(0,0,0,0.06), 0 0 0 1px " + COLORS.cardBorder;

  // ── Step 1 catalog — 8 business types ──────────────────────────────────────
  // archetype = canonical slug consumed by FinancialOverview.getKpiConfig and
  // PerduraProfileEngine.classify. kpiKey selects the Step-3 suggestion list.
  const BUSINESS_TYPES = [
    { id: "retail",        archetype: "retail",        kpiKey: "retail",        icon: "🛍️", name: "Retail",                  desc: "You sell physical products to customers" },
    { id: "distribution",  archetype: "distribution",  kpiKey: "distribution",  icon: "📦", name: "Distribution / Wholesale", desc: "You supply goods to other businesses" },
    { id: "manufacturing", archetype: "manufacturing", kpiKey: "manufacturing", icon: "🏭", name: "Manufacturing",           desc: "You make the products you sell" },
    { id: "saas",          archetype: "saas",          kpiKey: "saas",          icon: "💻", name: "SaaS / Software",          desc: "You sell software subscriptions" },
    { id: "services",      archetype: "services",      kpiKey: "services",      icon: "🔧", name: "Professional Services",    desc: "You bill clients for time or projects" },
    { id: "ecommerce",     archetype: "ecommerce",     kpiKey: "ecommerce",     icon: "🛒", name: "E-commerce",               desc: "You sell online, ship to customers" },
    { id: "medical",       archetype: "clinic",        kpiKey: "medical",       icon: "🏥", name: "Medical / Healthcare",     desc: "Clinic, practice, or health services" },
    { id: "nonprofit",     archetype: "nonprofit",     kpiKey: "nonprofit",     icon: "🤝", name: "Nonprofit",                desc: "Donations, grants, and community programmes" },
  ];

  // ── Step 2 catalog — industry sub-classification per business type ──────────
  const INDUSTRIES = {
    retail:        ["Apparel", "Grocery", "Home Goods", "Electronics", "Other Retail"],
    distribution:  ["Industrial Supply", "Food & Beverage", "Building Materials", "Medical Supplies", "Other Distribution"],
    manufacturing: ["Precision Components", "Consumer Goods", "Food Production", "Industrial Equipment", "Other Manufacturing"],
    saas:          ["B2B SaaS", "B2C App", "Developer Tools", "Vertical SaaS", "Other Software"],
    services:      ["Legal", "Accounting", "Engineering", "Marketing", "Consulting", "Other"],
    ecommerce:     ["Apparel & Accessories", "Home & Lifestyle", "Health & Beauty", "Electronics", "Other E-commerce"],
    medical:       ["Primary Care", "Specialist", "Dental", "Allied Health", "Other"],
    nonprofit:     ["Religious Organisation", "Charity", "Education", "Community", "Other"],
  };
  const INDUSTRY_HINT = {
    retail:        "Sets the product/inventory benchmarks and seasonality we apply.",
    distribution:  "Tunes margin, inventory-turn and DSO/DPO expectations for your trade.",
    manufacturing: "Calibrates cost-of-goods and production-margin benchmarks.",
    saas:          "Selects the SaaS benchmark set (retention, burn, runway).",
    services:      "Tailors utilisation and project-margin benchmarks to your practice.",
    ecommerce:     "Applies online-retail conversion, AOV and fulfilment benchmarks.",
    medical:       "Sets payer-mix, collections and visit benchmarks for your speciality.",
    nonprofit:     "Applies fund-accounting and programme-ratio benchmarks.",
  };

  // ── Step 3 catalog — suggested KPIs per archetype, with tooltips ────────────
  const KPI_SUGGESTIONS = {
    retail: [
      { name: "Revenue",          tip: "Total sales across all products and channels in the period." },
      { name: "Gross Margin %",   tip: "Revenue minus cost of goods, as a percentage of revenue." },
      { name: "Inventory Turns",  tip: "How many times you sell through and replace stock per year." },
      { name: "Average Order Value", tip: "Average revenue per order — basket size." },
      { name: "Net Profit",       tip: "What's left after all costs and operating expenses." },
    ],
    services: [
      { name: "Revenue",        tip: "Total fees billed for time and projects in the period." },
      { name: "Utilisation %",  tip: "Share of available staff hours that are billable." },
      { name: "Gross Margin %", tip: "Revenue minus direct delivery cost, as a percentage." },
      { name: "Project Margin", tip: "Profit on delivered projects after direct costs." },
      { name: "Days of Cash",   tip: "How many days of operating expense your cash covers." },
    ],
    saas: [
      { name: "MRR",                    tip: "Monthly recurring revenue from active subscriptions." },
      { name: "Net Revenue Retention",  tip: "Revenue kept and expanded from existing customers." },
      { name: "Gross Margin %",         tip: "Revenue minus cost to serve, as a percentage." },
      { name: "Burn Rate",              tip: "Net cash consumed per month." },
      { name: "Runway",                 tip: "Months of cash left at the current burn rate." },
    ],
    nonprofit: [
      { name: "Total Donations",  tip: "All contributions, grants and gifts received in the period." },
      { name: "Surplus Margin %", tip: "Operating surplus as a percentage of total income." },
      { name: "Days of Cash",     tip: "How many days of expense your reserves cover." },
      { name: "Opex Ratio",       tip: "Operating expense as a share of total income." },
      { name: "Donation Mix %",   tip: "Concentration of income across donor and grant sources." },
    ],
    distribution: [
      { name: "Revenue",         tip: "Total goods supplied to customers in the period." },
      { name: "Gross Margin %",  tip: "Revenue minus cost of goods, as a percentage." },
      { name: "Inventory Turns", tip: "How many times you sell through stock per year." },
      { name: "DSO",             tip: "Days Sales Outstanding — average days to collect receivables." },
      { name: "DPO",             tip: "Days Payable Outstanding — average days you take to pay suppliers." },
    ],
    medical: [
      { name: "Revenue",              tip: "Net patient revenue collected in the period." },
      { name: "Net Collections Rate", tip: "Share of collectable charges actually collected." },
      { name: "AR Days",              tip: "Average days to collect on patient/payer accounts." },
      { name: "Payer Mix %",          tip: "Distribution of revenue across payers and plans." },
      { name: "Visits per Provider",  tip: "Encounter volume per provider — capacity utilisation." },
    ],
    // Not specified in the brief — sensible, computable defaults so every type
    // gets a real suggestion list rather than an empty step.
    manufacturing: [
      { name: "Revenue",         tip: "Total value of products sold in the period." },
      { name: "Gross Margin %",  tip: "Revenue minus cost of goods manufactured, as a percentage." },
      { name: "Inventory Turns", tip: "How many times you sell through and rebuild stock per year." },
      { name: "Net Profit",      tip: "What's left after all costs and operating expenses." },
      { name: "Days of Cash",    tip: "How many days of operating expense your cash covers." },
    ],
    ecommerce: [
      { name: "Revenue",             tip: "Total online sales across all channels in the period." },
      { name: "Gross Margin %",      tip: "Revenue minus cost of goods and fulfilment, as a percentage." },
      { name: "Average Order Value", tip: "Average revenue per order — basket size." },
      { name: "Net Profit",          tip: "What's left after all costs and operating expenses." },
      { name: "Days of Cash",        tip: "How many days of operating expense your cash covers." },
    ],
  };

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

  const CURRENCIES = [
    { code: "USD", label: "US Dollar (USD $)" },
    { code: "EUR", label: "Euro (EUR €)" },
    { code: "GBP", label: "British Pound (GBP £)" },
    { code: "ZAR", label: "South African Rand (ZAR R)" },
    { code: "AUD", label: "Australian Dollar (AUD $)" },
    { code: "CAD", label: "Canadian Dollar (CAD $)" },
    { code: "NZD", label: "New Zealand Dollar (NZD $)" },
    { code: "ILS", label: "Israeli Shekel (ILS ₪)" },
  ];

  const TOTAL_STEPS = 5;
  const MIN_KPIS = 3;
  const MAX_KPIS = 6;

  // ── small primitives ────────────────────────────────────────────────────────
  function PrimaryButton({ children, onClick, disabled }) {
    return (
      <button
        onClick={onClick}
        disabled={disabled}
        style={{
          background: disabled ? "#A9B6D6" : COLORS.accent,
          color: "white", border: "none", borderRadius: 7,
          padding: "10px 20px", fontWeight: 600, fontSize: 14,
          cursor: disabled ? "not-allowed" : "pointer",
          transition: "background 0.12s ease",
        }}
      >
        {children}
      </button>
    );
  }

  function GhostButton({ children, onClick }) {
    return (
      <button
        onClick={onClick}
        style={{
          background: "transparent", color: COLORS.text2,
          border: "1px solid " + COLORS.cardBorder, borderRadius: 7,
          padding: "10px 18px", fontWeight: 600, fontSize: 14, cursor: "pointer",
        }}
      >
        {children}
      </button>
    );
  }

  function ProgressBar({ step }) {
    return (
      <div style={{ display: "flex", gap: 8, marginBottom: 28 }}>
        {Array.from({ length: TOTAL_STEPS }).map((_, i) => (
          <div
            key={i}
            style={{
              flex: 1, height: 6, borderRadius: 999,
              background: i < step ? COLORS.accent : "#E4E8F0",
              transition: "background 0.2s ease",
            }}
          />
        ))}
      </div>
    );
  }

  function StepHeader({ step, question, sub }) {
    return (
      <div style={{ marginBottom: 22 }}>
        <div style={{ fontSize: 11, color: COLORS.muted, fontWeight: 600, letterSpacing: 0.3, marginBottom: 6 }}>
          Step {step} of {TOTAL_STEPS}
        </div>
        <div style={{ fontSize: 24, fontWeight: 700, color: COLORS.text1, letterSpacing: -0.4 }}>
          {question}
        </div>
        {sub ? <div style={{ fontSize: 14, color: COLORS.text2, marginTop: 8, lineHeight: 1.5 }}>{sub}</div> : null}
      </div>
    );
  }

  // ── the wizard ──────────────────────────────────────────────────────────────
  function CompanyProfileWizard(props) {
    const { scopedCompanyId, companyProfile, editMode, onComplete, onExit } = props || {};
    const prof = companyProfile || {};

    // Resolve an initial business-type id from an existing profile (edit mode /
    // re-run). Match by stored business_type id first, then by archetype slug.
    const initialType = useMemo(() => {
      const byId = BUSINESS_TYPES.find((b) => b.id === prof.business_type);
      if (byId) return byId.id;
      const byArch = BUSINESS_TYPES.find((b) => b.archetype === prof.archetype);
      if (byArch) return byArch.id;
      return null;
    }, [prof.business_type, prof.archetype]);

    const [step, setStep] = useState(1);
    const [typeId, setTypeId] = useState(initialType);
    const [industry, setIndustry] = useState(prof.industry || "");
    const [selectedKpis, setSelectedKpis] = useState(
      Array.isArray(prof.selected_kpis) && prof.selected_kpis.length ? prof.selected_kpis.slice() : null
    );
    const [fiscalMonth, setFiscalMonth] = useState(Number(prof.fiscal_year_start_month) || 1);
    const [basis, setBasis] = useState(prof.reporting_basis || "accrual");
    const [currency, setCurrency] = useState(prof.currency || prof.base_currency || "USD");
    const [saving, setSaving] = useState(false);
    const [error, setError] = useState(null);

    // KPI suggestions loaded from the admin-curated kpi_library table, keyed by
    // archetype. Null until a load resolves; an empty load falls back to the
    // hardcoded catalog so the step always has options (offline / demo / empty DB).
    const [dbKpis, setDbKpis] = useState(null); // { arche, list:[{name,tip,isDefault}] } | null

    const typeObj = BUSINESS_TYPES.find((b) => b.id === typeId) || null;
    const archetype = typeObj ? typeObj.archetype : null;
    const industryList = typeObj ? (INDUSTRIES[typeObj.id] || []) : [];

    useEffect(() => {
      let cancelled = false;
      setDbKpis(null);
      const db = window.supabaseClient;
      if (!db || !archetype) return;
      db.from("kpi_library")
        .select("kpi_key,kpi_name,description,is_default,display_order")
        .eq("archetype", archetype)
        .is("industry", null)
        .eq("active", true)
        .order("display_order", { ascending: true })
        .then(({ data }) => {
          if (cancelled) return;
          if (Array.isArray(data) && data.length) {
            setDbKpis({ arche: archetype, list: data.map((r) => ({ name: r.kpi_name, tip: r.description, isDefault: !!r.is_default })) });
          }
        }, () => { /* read failed — keep the hardcoded fallback */ });
      return () => { cancelled = true; };
    }, [archetype]);

    // Effective suggestion list: DB rows for this archetype when present, else the
    // hardcoded catalog (which carries no is_default flags).
    const hardcodedList = typeObj ? (KPI_SUGGESTIONS[typeObj.kpiKey] || []).map((k) => ({ name: k.name, tip: k.tip, isDefault: false })) : [];
    const kpiList = (dbKpis && dbKpis.arche === archetype && dbKpis.list.length) ? dbKpis.list : hardcodedList;

    // Default selection: the library's is_default rows if any are flagged,
    // otherwise the first 4 — unless the profile already carried an explicit choice.
    const defaultKpiNames = useMemo(() => {
      const flagged = kpiList.filter((k) => k.isDefault).map((k) => k.name);
      return (flagged.length ? flagged : kpiList.slice(0, 4).map((k) => k.name)).slice(0, MAX_KPIS);
    }, [kpiList]);

    const effectiveKpis = useMemo(() => {
      if (Array.isArray(selectedKpis)) return selectedKpis;
      return defaultKpiNames;
    }, [selectedKpis, defaultKpiNames]);

    const toggleKpi = (name) => {
      const cur = effectiveKpis.slice();
      const idx = cur.indexOf(name);
      if (idx >= 0) {
        if (cur.length <= MIN_KPIS) return; // enforce minimum
        cur.splice(idx, 1);
      } else {
        if (cur.length >= MAX_KPIS) return; // enforce maximum
        cur.push(name);
      }
      setSelectedKpis(cur);
    };

    // When the business type changes, reset the industry + KPI selection so we
    // don't carry a stale sub-classification from a different archetype.
    const chooseType = (id) => {
      if (id === typeId) return;
      setTypeId(id);
      setIndustry("");
      setSelectedKpis(null);
    };

    const canNext = (() => {
      if (step === 1) return !!typeId;
      if (step === 2) return !!industry;
      if (step === 3) return effectiveKpis.length >= MIN_KPIS;
      return true;
    })();

    const goNext = () => { setError(null); setStep((s) => Math.min(TOTAL_STEPS, s + 1)); };
    const goBack = () => { setError(null); setStep((s) => Math.max(1, s - 1)); };

    async function handleSave() {
      if (!typeObj) return;
      setSaving(true);
      setError(null);
      const update = {
        business_type: typeObj.id,        // keeps classify() + the legacy setup gate working
        archetype,                        // canonical slug for getKpiConfig / classify
        industry,
        selected_kpis: effectiveKpis,     // user override for the secondary KPI row
        fiscal_year_start_month: fiscalMonth,
        fiscal_year_start: MONTHS[fiscalMonth - 1], // keep the legacy text column in sync
        reporting_basis: basis,
        currency,
        base_currency: currency,
        setup_complete: true,
      };
      try {
        const db = window.supabaseClient;
        if (db && scopedCompanyId) {
          const { error: dbErr } = await db.from("companies").update(update).eq("id", scopedCompanyId);
          if (dbErr) throw dbErr;
        }
        const merged = Object.assign({}, prof, update);
        if (onComplete) onComplete(merged);
      } catch (e) {
        console.error("[CompanyProfileWizard] save failed", e);
        setError((e && e.message) || "Could not save your profile. Please try again.");
        setSaving(false);
      }
    }

    // ── step bodies ───────────────────────────────────────────────────────────
    const renderStep1 = () => (
      <div>
        <StepHeader step={1} question="What type of business is this?" />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14 }}>
          {BUSINESS_TYPES.map((b) => {
            const on = b.id === typeId;
            return (
              <button
                key={b.id}
                onClick={() => chooseType(b.id)}
                style={{
                  textAlign: "left", cursor: "pointer",
                  background: on ? COLORS.accentSoft : COLORS.card,
                  border: on ? "2px solid " + COLORS.accent : "1px solid " + COLORS.cardBorder,
                  boxShadow: on ? "none" : CARD_SHADOW,
                  borderRadius: 10, padding: on ? "17px 15px" : "18px 16px",
                  display: "flex", flexDirection: "column", gap: 8, minHeight: 124,
                  transition: "all 0.12s ease",
                }}
              >
                <span style={{ fontSize: 26, lineHeight: 1 }}>{b.icon}</span>
                <span style={{ fontSize: 15, fontWeight: 700, color: COLORS.text1 }}>{b.name}</span>
                <span style={{ fontSize: 12, color: COLORS.text2, lineHeight: 1.4 }}>{b.desc}</span>
              </button>
            );
          })}
        </div>
      </div>
    );

    const renderStep2 = () => (
      <div>
        <StepHeader
          step={2}
          question="Which industry best describes it?"
          sub={typeObj ? `Sub-classification for ${typeObj.name}.` : null}
        />
        <label style={{ display: "block", fontSize: 12, fontWeight: 600, color: COLORS.muted, marginBottom: 8 }}>
          Industry
        </label>
        <select
          value={industry}
          onChange={(e) => setIndustry(e.target.value)}
          style={{
            width: "100%", padding: "12px 14px", fontSize: 15, color: COLORS.text1,
            background: COLORS.card, border: "1px solid " + COLORS.cardBorder,
            borderRadius: 8, cursor: "pointer", appearance: "auto",
          }}
        >
          <option value="" disabled>Select an industry…</option>
          {industryList.map((opt) => <option key={opt} value={opt}>{opt}</option>)}
        </select>
        <div style={{ fontSize: 13, color: COLORS.text2, marginTop: 14, lineHeight: 1.5 }}>
          {typeObj ? (INDUSTRY_HINT[typeObj.id] || "") : ""}
        </div>
      </div>
    );

    const renderStep3 = () => (
      <div>
        <StepHeader
          step={3}
          question="What are the 3–5 numbers you watch most closely?"
          sub={`Pick the metrics that matter most. We pre-selected the top ones for a ${typeObj ? typeObj.name.toLowerCase() : "business"} — toggle to taste (${MIN_KPIS}–${MAX_KPIS}).`}
        />
        <div style={{ display: "flex", flexWrap: "wrap", gap: 10 }}>
          {kpiList.map((k) => {
            const on = effectiveKpis.indexOf(k.name) >= 0;
            const atMax = !on && effectiveKpis.length >= MAX_KPIS;
            const atMin = on && effectiveKpis.length <= MIN_KPIS;
            return (
              <button
                key={k.name}
                title={k.tip}
                onClick={() => toggleKpi(k.name)}
                disabled={atMax}
                style={{
                  display: "inline-flex", alignItems: "center", gap: 8,
                  background: on ? COLORS.accentSoft : COLORS.card,
                  border: on ? "2px solid " + COLORS.accent : "1px solid " + COLORS.cardBorder,
                  color: on ? COLORS.accent : COLORS.text1,
                  borderRadius: 999, padding: on ? "8px 15px" : "9px 16px",
                  fontSize: 13.5, fontWeight: 600,
                  cursor: atMax ? "not-allowed" : (atMin ? "default" : "pointer"),
                  opacity: atMax ? 0.5 : 1,
                  transition: "all 0.12s ease",
                }}
              >
                <span style={{
                  width: 15, height: 15, borderRadius: 4, flex: "0 0 auto",
                  display: "inline-flex", alignItems: "center", justifyContent: "center",
                  background: on ? COLORS.accent : "transparent",
                  border: on ? "none" : "1.5px solid #C3CCDE",
                  color: "white", fontSize: 10, fontWeight: 800,
                }}>{on ? "✓" : ""}</span>
                {k.name}
              </button>
            );
          })}
        </div>
        <div style={{ fontSize: 12, color: COLORS.muted, marginTop: 16 }}>
          {effectiveKpis.length} selected · minimum {MIN_KPIS}, maximum {MAX_KPIS}. Hover any chip to see what it measures.
        </div>
      </div>
    );

    const renderStep4 = () => {
      const toggleBtn = (val, label) => {
        const on = basis === val;
        return (
          <button
            onClick={() => setBasis(val)}
            style={{
              flex: 1, padding: "12px 16px", fontSize: 14, fontWeight: 600,
              background: on ? COLORS.accentSoft : COLORS.card,
              border: on ? "2px solid " + COLORS.accent : "1px solid " + COLORS.cardBorder,
              color: on ? COLORS.accent : COLORS.text1,
              borderRadius: 8, cursor: "pointer", transition: "all 0.12s ease",
            }}
          >
            {label}
          </button>
        );
      };
      const fieldLabel = (txt) => (
        <label style={{ display: "block", fontSize: 12, fontWeight: 600, color: COLORS.muted, marginBottom: 8 }}>{txt}</label>
      );
      return (
        <div>
          <StepHeader step={4} question="Fiscal year & reporting" />
          <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
            <div>
              {fieldLabel("When does your fiscal year start?")}
              <select
                value={fiscalMonth}
                onChange={(e) => setFiscalMonth(Number(e.target.value))}
                style={{
                  width: "100%", padding: "12px 14px", fontSize: 15, color: COLORS.text1,
                  background: COLORS.card, border: "1px solid " + COLORS.cardBorder,
                  borderRadius: 8, cursor: "pointer", appearance: "auto",
                }}
              >
                {MONTHS.map((m, i) => <option key={m} value={i + 1}>{m}</option>)}
              </select>
            </div>
            <div>
              {fieldLabel("How do you report finances?")}
              <div style={{ display: "flex", gap: 12 }}>
                {toggleBtn("cash", "Cash basis")}
                {toggleBtn("accrual", "Accrual basis")}
              </div>
            </div>
            <div>
              {fieldLabel("What currency do you operate in?")}
              <select
                value={currency}
                onChange={(e) => setCurrency(e.target.value)}
                style={{
                  width: "100%", padding: "12px 14px", fontSize: 15, color: COLORS.text1,
                  background: COLORS.card, border: "1px solid " + COLORS.cardBorder,
                  borderRadius: 8, cursor: "pointer", appearance: "auto",
                }}
              >
                {CURRENCIES.map((c) => <option key={c.code} value={c.code}>{c.label}</option>)}
              </select>
            </div>
          </div>
        </div>
      );
    };

    const renderStep5 = () => {
      const summaryRow = (label, value) => (
        <div style={{ display: "flex", justifyContent: "space-between", gap: 16, padding: "10px 0", borderBottom: "1px solid " + COLORS.cardBorder }}>
          <span style={{ fontSize: 13, color: COLORS.muted, fontWeight: 600 }}>{label}</span>
          <span style={{ fontSize: 13.5, color: COLORS.text1, fontWeight: 600, textAlign: "right" }}>{value}</span>
        </div>
      );
      const k = effectiveKpis;
      const previewKpis = k.slice(0, 3).join(", ") + (k.length > 3 ? "…" : "");
      const preview = `Your dashboard will show ${typeObj ? typeObj.name.toLowerCase() : ""}-specific insights for a ${industry || "—"} business, tracking ${previewKpis || "your chosen metrics"} as your primary metrics.`;
      return (
        <div>
          <StepHeader step={5} question="Confirm your profile" sub="Here's how your dashboard will be set up. You can change any of this later from Company Settings." />
          <div style={{ background: COLORS.card, border: "1px solid " + COLORS.cardBorder, boxShadow: CARD_SHADOW, borderRadius: 10, padding: "8px 18px 16px" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "14px 0 12px", borderBottom: "1px solid " + COLORS.cardBorder }}>
              <span style={{ fontSize: 30, lineHeight: 1 }}>{typeObj ? typeObj.icon : "🏢"}</span>
              <div>
                <div style={{ fontSize: 16, fontWeight: 700, color: COLORS.text1 }}>{typeObj ? typeObj.name : "—"}</div>
                <div style={{ fontSize: 13, color: COLORS.text2 }}>{industry || "—"}</div>
              </div>
            </div>
            {summaryRow("Key numbers", k.join(", "))}
            {summaryRow("Fiscal year starts", MONTHS[fiscalMonth - 1])}
            {summaryRow("Reporting basis", basis === "cash" ? "Cash basis" : "Accrual basis")}
            {summaryRow("Currency", currency)}
          </div>
          <div style={{ marginTop: 18, padding: "14px 16px", background: COLORS.accentSoft, borderRadius: 8, fontSize: 14, color: COLORS.text1, lineHeight: 1.55 }}>
            {preview}
          </div>
          {error ? (
            <div style={{ marginTop: 14, padding: "10px 14px", background: "#FEF2F2", border: "1px solid #FECACA", borderRadius: 8, fontSize: 13, color: "#B91C1C" }}>
              {error}
            </div>
          ) : null}
        </div>
      );
    };

    const body = (
      step === 1 ? renderStep1() :
      step === 2 ? renderStep2() :
      step === 3 ? renderStep3() :
      step === 4 ? renderStep4() :
                   renderStep5()
    );

    // ── footer nav ──────────────────────────────────────────────────────────
    const footer = (
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 30 }}>
        <div>
          {step > 1
            ? <GhostButton onClick={goBack}>← Back</GhostButton>
            : (editMode && onExit ? <GhostButton onClick={onExit}>Cancel</GhostButton> : <span />)}
        </div>
        <div>
          {step < TOTAL_STEPS
            ? <PrimaryButton onClick={goNext} disabled={!canNext}>Next →</PrimaryButton>
            : <PrimaryButton onClick={handleSave} disabled={saving}>{saving ? "Saving…" : "Save & Launch Dashboard →"}</PrimaryButton>}
        </div>
      </div>
    );

    return (
      <div style={{ minHeight: "100vh", background: COLORS.bg, padding: "48px 20px", boxSizing: "border-box" }}>
        <div style={{ maxWidth: 720, margin: "0 auto" }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 22 }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: COLORS.accent, letterSpacing: 0.2 }}>
              {editMode ? "Company Settings" : "Welcome — let's set up your dashboard"}
            </div>
            {prof.name ? <div style={{ fontSize: 13, color: COLORS.muted }}>{prof.name}</div> : null}
          </div>
          <ProgressBar step={step} />
          {body}
          {footer}
        </div>
      </div>
    );
  }

  window.CompanyProfileWizard = CompanyProfileWizard;
})();
