// ── Public onboarding wizard (Phase 5) ───────────────────────────────────────
// Unauthenticated, tokenized customer onboarding. Reached at /onboarding?token=…
// (routed by subdomain.js → app.jsx view "public_onboarding"). Reads the token,
// pre-fills from pending_onboarding via the onboarding edge function, walks the
// same 6-step wizard as the admin NewCustomerWizard, and on submit calls the
// `complete` action — which parks a company_onboarding row in 'pending_review'
// for admin approval. No account is created here; approval does that.
//
// Self-contained: the admin wizard's helpers (useAdm, Field, AInput, callAdmin,
// BIZ_MODELS…) live in page-admin.jsx and are not in scope here, so this file
// defines its own minimal equivalents and hits the edge function directly.

const PO_BIZ_MODELS = [
  { v: "saas", icon: "☁️", l: "SaaS / Subscription" },
  { v: "retail", icon: "🛍️", l: "Retail / E-commerce" },
  { v: "manufacturing", icon: "🏭", l: "Manufacturing" },
  { v: "services", icon: "💼", l: "Professional Services" },
  { v: "healthcare", icon: "🏥", l: "Healthcare" },
  { v: "other", icon: "📊", l: "Other" },
];
const PO_COMPANY_TYPES = [
  { v: "llc", l: "LLC" }, { v: "c_corp", l: "C-Corp" }, { v: "s_corp", l: "S-Corp" },
  { v: "partnership", l: "Partnership" }, { v: "sole_prop", l: "Sole Proprietor" }, { v: "nonprofit", l: "Non-profit" },
];
const PO_CHALLENGES = [
  "Cash flow visibility", "Understanding profitability", "Managing expenses", "AR / collections",
  "Payroll costs", "Inventory management", "Tax planning", "Board reporting",
  "Fundraising readiness", "Growth planning",
];
const PO_FY_END = ["December", "March", "June", "September"];
const PO_FY_START_MONTH = { December: 1, March: 4, June: 7, September: 10 };
const PO_GL = [{ v: "xero", icon: "🟦", l: "Xero" }, { v: "qbo", icon: "🟩", l: "QuickBooks" }, { v: "other", icon: "📊", l: "Other / Manual" }];
const PO_REV_BANDS = ["Under $500K", "$500K – $1M", "$1M – $3M", "$3M – $8M", "$8M – $15M", "$15M – $30M", "$30M+"];

function poSlug(name) {
  return (name || "").toLowerCase().replace(/[^a-z0-9]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
}

async function poCall(method, path, body) {
  const base = `${window.SUPABASE_URL}/functions/v1/onboarding`;
  const res = await fetch(`${base}${path}`, {
    method,
    headers: {
      "Content-Type": "application/json",
      "Apikey": window.SUPABASE_ANON_KEY,
      "Authorization": `Bearer ${window.SUPABASE_ANON_KEY}`,
    },
    body: body ? JSON.stringify(body) : undefined,
  });
  const data = await res.json().catch(() => ({}));
  if (!res.ok) throw new Error(data.error || "Request failed");
  return data;
}

function PublicOnboardingPage() {
  const { useState, useEffect } = React;
  const token = new URLSearchParams(window.location.search).get("token");

  const [phase, setPhase] = useState("loading"); // loading | no-token | invalid | wizard | done
  const [loadErr, setLoadErr] = useState("");
  const [changeNotes, setChangeNotes] = useState(null);

  const [step, setStep] = useState(0);
  const [submitting, setSubmitting] = useState(false);
  const [submitErr, setSubmitErr] = useState("");

  // Wizard state (keys match the shape the edge function's approve flow reads).
  const [bizModel, setBizModel] = useState("");
  const [name, setName] = useState("");
  const [subdomain, setSubdomain] = useState("");
  const [companyType, setCompanyType] = useState("");
  const [industry, setIndustry] = useState("");
  const [revBand, setRevBand] = useState("");
  const [empCount, setEmpCount] = useState("");
  const [fyEnd, setFyEnd] = useState("December");
  const [country, setCountry] = useState("US");
  const [phone, setPhone] = useState("");
  const [website, setWebsite] = useState("");
  const [challenges, setChallenges] = useState([]);
  const [ownerName, setOwnerName] = useState("");
  const [ownerEmail, setOwnerEmail] = useState("");
  const [glProvider, setGlProvider] = useState("");
  const [glConnect, setGlConnect] = useState("later");

  useEffect(() => {
    if (!token) { setPhase("no-token"); return; }
    (async () => {
      try {
        const { pending } = await poCall("GET", `?action=get-pending&token=${encodeURIComponent(token)}`);
        const w = pending.wizard_data || {};
        setName(w.companyName || pending.company_name || "");
        setSubdomain(w.subdomain || poSlug(w.companyName || pending.company_name || ""));
        setBizModel(w.businessModel || "");
        setCompanyType(w.companyType || "");
        setIndustry(w.industry || "");
        setRevBand(w.revenue_band || "");
        setEmpCount(w.employee_count != null ? String(w.employee_count) : "");
        setFyEnd(w.fiscal_year_end || "December");
        setCountry(w.country || "US");
        setPhone(w.phone || "");
        setWebsite(w.website || "");
        setChallenges(Array.isArray(w.challenges) ? w.challenges : []);
        setOwnerName(w.ownerName || "");
        setOwnerEmail(w.ownerEmail || pending.email || "");
        setGlProvider(w.gl_provider || "");
        setGlConnect(w.gl_connect || "later");
        setChangeNotes(pending.change_request_notes || null);
        setPhase("wizard");
      } catch (e) {
        setLoadErr(e.message || "This link is not valid.");
        setPhase("invalid");
      }
    })();
  }, [token]);

  useEffect(() => { if (name && !subdomain) setSubdomain(poSlug(name)); }, [name]);

  const toggleChallenge = (c) => setChallenges(prev => prev.includes(c) ? prev.filter(x => x !== c) : [...prev, c]);

  async function submit() {
    setSubmitErr("");
    setSubmitting(true);
    try {
      const wizard_data = {
        companyName: name, subdomain: subdomain || poSlug(name),
        businessModel: bizModel, companyType, industry,
        revenue_band: revBand, employee_count: empCount ? parseInt(empCount) : null,
        fiscal_year_end: fyEnd, fiscal_year_start_month: PO_FY_START_MONTH[fyEnd] || 1,
        country, phone, website,
        challenges, ownerName, ownerEmail,
        gl_provider: glProvider || null, gl_connect: glConnect,
      };
      await poCall("POST", "", { action: "complete", token, wizard_data });
      setPhase("done");
    } catch (e) {
      setSubmitErr(e.message || "Could not submit. Please try again.");
    } finally {
      setSubmitting(false);
    }
  }

  // ── Shells ──────────────────────────────────────────────────────────────
  const Page = ({ children }) => (
    <div style={{ minHeight: "100vh", background: "#f4f3ef", fontFamily: "-apple-system,BlinkMacSystemFont,'Segoe UI',Helvetica,Arial,sans-serif", padding: "40px 16px" }}>
      <div style={{ maxWidth: 640, margin: "0 auto" }}>
        <div style={{ background: "#0c1220", borderRadius: "12px 12px 0 0", padding: "26px 34px", textAlign: "center" }}>
          <p style={{ margin: 0, fontSize: 11, fontWeight: 600, letterSpacing: "0.12em", textTransform: "uppercase", color: "rgba(255,255,255,0.45)" }}>PerduraCFO · Financial Intelligence</p>
          <h1 style={{ margin: "8px 0 0", fontSize: 22, fontWeight: 700, color: "#fff", letterSpacing: "-0.03em" }}>Account Setup</h1>
        </div>
        <div style={{ background: "#fff", borderRadius: "0 0 12px 12px", padding: "32px 34px", boxShadow: "0 1px 3px rgba(0,0,0,0.06)" }}>
          {children}
        </div>
        <p style={{ textAlign: "center", fontSize: 11, color: "#94a3b8", marginTop: 18 }}>Powered by Perdura Capital LLC</p>
      </div>
    </div>
  );

  const green = "#059669", ink = "#0c1220", muted = "#64748b", border = "#d8dee6";
  const btn = { padding: "11px 22px", borderRadius: 8, fontSize: 14, fontWeight: 600, cursor: "pointer", border: "none" };
  const btnPrimary = { ...btn, background: green, color: "#fff" };
  const btnGhost = { ...btn, background: "transparent", color: muted, border: `1px solid ${border}` };
  const inp = { width: "100%", padding: "10px 12px", borderRadius: 8, border: `1px solid ${border}`, fontSize: 14, boxSizing: "border-box" };
  const label = { display: "block", fontSize: 12, fontWeight: 600, color: ink, marginBottom: 6 };

  if (phase === "loading") {
    return <Page><div style={{ textAlign: "center", padding: 40, color: muted }}>Loading your setup…</div></Page>;
  }
  if (phase === "no-token") {
    return <Page><div style={{ textAlign: "center", padding: 24 }}>
      <div style={{ fontSize: 34, marginBottom: 10 }}>🔑</div>
      <h2 style={{ fontSize: 17, color: ink, margin: "0 0 8px" }}>No invite link found</h2>
      <p style={{ fontSize: 13.5, color: muted, lineHeight: 1.6 }}>Please contact your PerduraCFO administrator for an invite link to set up your account.</p>
    </div></Page>;
  }
  if (phase === "invalid") {
    return <Page><div style={{ textAlign: "center", padding: 24 }}>
      <div style={{ fontSize: 34, marginBottom: 10 }}>⚠️</div>
      <h2 style={{ fontSize: 17, color: ink, margin: "0 0 8px" }}>This link can't be used</h2>
      <p style={{ fontSize: 13.5, color: muted, lineHeight: 1.6 }}>{loadErr}</p>
    </div></Page>;
  }
  if (phase === "done") {
    return <Page><div style={{ textAlign: "center", padding: 24 }}>
      <div style={{ fontSize: 40, marginBottom: 10 }}>✅</div>
      <h2 style={{ fontSize: 18, color: ink, margin: "0 0 10px" }}>Submitted!</h2>
      <p style={{ fontSize: 13.5, color: muted, lineHeight: 1.6 }}>
        Your account is being reviewed. You'll receive a welcome email with your login within 24 hours.
      </p>
    </div></Page>;
  }

  const steps = ["Business", "Company", "Challenges", "You", "Accounting", "Review"];

  return (
    <Page>
      <div style={{ marginBottom: 20 }}>
        <div style={{ fontSize: 12, color: muted, marginBottom: 8 }}>Step {step + 1} of {steps.length} — {steps[step]}</div>
        <div style={{ display: "flex", gap: 5 }}>
          {steps.map((s, i) => (
            <div key={s} style={{ flex: 1, height: 4, borderRadius: 2, background: i <= step ? green : "#e5e7eb" }} />
          ))}
        </div>
      </div>

      {changeNotes && step === 0 && (
        <div style={{ background: "#fff7ed", border: "1px solid #fed7aa", borderRadius: 8, padding: "12px 14px", marginBottom: 18, fontSize: 12.5, color: "#9a3412", lineHeight: 1.5 }}>
          <strong>Changes requested:</strong> {changeNotes}
        </div>
      )}
      {submitErr && <div style={{ background: "#fef2f2", border: "1px solid #fecaca", color: "#b91c1c", borderRadius: 8, padding: "10px 14px", marginBottom: 16, fontSize: 12.5 }}>{submitErr}</div>}

      {step === 0 && (
        <div>
          <p style={{ fontSize: 13.5, color: muted, marginBottom: 16 }}>What best describes your business?</p>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
            {PO_BIZ_MODELS.map(b => (
              <button key={b.v} onClick={() => setBizModel(b.v)} style={{
                textAlign: "left", padding: "14px 16px", borderRadius: 10, cursor: "pointer", background: bizModel === b.v ? "#ecfdf5" : "#fff",
                border: bizModel === b.v ? `1.5px solid ${green}` : `1px solid ${border}`,
              }}>
                <div style={{ fontSize: 22, marginBottom: 6 }}>{b.icon}</div>
                <div style={{ fontSize: 13, fontWeight: 600, color: ink }}>{b.l}</div>
              </button>
            ))}
          </div>
          <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 24 }}>
            <button style={btnPrimary} disabled={!bizModel} onClick={() => setStep(1)}>Next →</button>
          </div>
        </div>
      )}

      {step === 1 && (
        <div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
            <div style={{ gridColumn: "1 / -1" }}>
              <label style={label}>Company name</label>
              <input style={inp} value={name} onChange={e => setName(e.target.value)} placeholder="Acme Inc." />
            </div>
            <div>
              <label style={label}>Entity type</label>
              <select style={inp} value={companyType} onChange={e => setCompanyType(e.target.value)}>
                <option value="">Select…</option>
                {PO_COMPANY_TYPES.map(t => <option key={t.v} value={t.v}>{t.l}</option>)}
              </select>
            </div>
            <div>
              <label style={label}>Industry</label>
              <input style={inp} value={industry} onChange={e => setIndustry(e.target.value)} placeholder="e.g. Healthcare" />
            </div>
            <div>
              <label style={label}>Revenue band</label>
              <select style={inp} value={revBand} onChange={e => setRevBand(e.target.value)}>
                <option value="">Select…</option>
                {PO_REV_BANDS.map(r => <option key={r} value={r}>{r}</option>)}
              </select>
            </div>
            <div>
              <label style={label}>Employees</label>
              <input style={inp} type="number" min="1" value={empCount} onChange={e => setEmpCount(e.target.value)} placeholder="50" />
            </div>
            <div>
              <label style={label}>Fiscal year end</label>
              <select style={inp} value={fyEnd} onChange={e => setFyEnd(e.target.value)}>
                {PO_FY_END.map(m => <option key={m} value={m}>{m}</option>)}
              </select>
            </div>
            <div>
              <label style={label}>Country</label>
              <select style={inp} value={country} onChange={e => setCountry(e.target.value)}>
                {["US", "Canada", "UK", "Australia", "Other"].map(c => <option key={c} value={c}>{c}</option>)}
              </select>
            </div>
            <div>
              <label style={label}>Phone</label>
              <input style={inp} value={phone} onChange={e => setPhone(e.target.value)} placeholder="+1 (555) 000-0000" />
            </div>
            <div>
              <label style={label}>Website</label>
              <input style={inp} value={website} onChange={e => setWebsite(e.target.value)} placeholder="https://acme.com" />
            </div>
          </div>
          <div style={{ display: "flex", justifyContent: "space-between", marginTop: 24 }}>
            <button style={btnGhost} onClick={() => setStep(0)}>← Back</button>
            <button style={btnPrimary} disabled={!name} onClick={() => setStep(2)}>Next →</button>
          </div>
        </div>
      )}

      {step === 2 && (
        <div>
          <p style={{ fontSize: 13.5, color: muted, marginBottom: 16 }}>What do you most want help with? (Select any.)</p>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
            {PO_CHALLENGES.map(c => {
              const on = challenges.includes(c);
              return (
                <button key={c} onClick={() => toggleChallenge(c)} style={{
                  textAlign: "left", display: "flex", alignItems: "center", gap: 10, padding: "11px 14px", borderRadius: 8, cursor: "pointer",
                  fontSize: 12.5, fontWeight: 500, color: ink, background: on ? "#ecfdf5" : "#fff",
                  border: on ? `1.5px solid ${green}` : `1px solid ${border}`,
                }}>
                  <span style={{ width: 16, height: 16, borderRadius: 4, flexShrink: 0, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 11, color: "#fff", background: on ? green : "transparent", border: on ? "none" : `2px solid ${border}` }}>{on ? "✓" : ""}</span>
                  {c}
                </button>
              );
            })}
          </div>
          <div style={{ display: "flex", justifyContent: "space-between", marginTop: 24 }}>
            <button style={btnGhost} onClick={() => setStep(1)}>← Back</button>
            <button style={btnPrimary} onClick={() => setStep(3)}>Next →</button>
          </div>
        </div>
      )}

      {step === 3 && (
        <div>
          <p style={{ fontSize: 13.5, color: muted, marginBottom: 16 }}>You'll be the account owner. We'll send your login to this email once approved.</p>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
            <div>
              <label style={label}>Full name</label>
              <input style={inp} value={ownerName} onChange={e => setOwnerName(e.target.value)} placeholder="Jane Smith" />
            </div>
            <div>
              <label style={label}>Email address</label>
              <input style={{ ...inp, background: "#f8fafc", color: muted }} value={ownerEmail} readOnly title="This is the email your invite was sent to" />
            </div>
          </div>
          <div style={{ display: "flex", justifyContent: "space-between", marginTop: 24 }}>
            <button style={btnGhost} onClick={() => setStep(2)}>← Back</button>
            <button style={btnPrimary} disabled={!ownerName} onClick={() => setStep(4)}>Next →</button>
          </div>
        </div>
      )}

      {step === 4 && (
        <div>
          <p style={{ fontSize: 13.5, color: muted, marginBottom: 16 }}>Which accounting software do you use?</p>
          <div style={{ display: "flex", gap: 10, marginBottom: 16 }}>
            {PO_GL.map(g => (
              <button key={g.v} onClick={() => setGlProvider(g.v)} style={{
                flex: 1, padding: "16px 12px", borderRadius: 10, cursor: "pointer", fontSize: 13, fontWeight: 600, color: ink,
                background: glProvider === g.v ? "#ecfdf5" : "#fff", border: glProvider === g.v ? `1.5px solid ${green}` : `1px solid ${border}`,
              }}>
                <div style={{ fontSize: 24, marginBottom: 6 }}>{g.icon}</div>{g.l}
              </button>
            ))}
          </div>
          {glProvider && glProvider !== "other" && (
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              {[["later", "Connect later"], ["now", "I'd like help connecting now"]].map(([v, l]) => (
                <label key={v} style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 12.5, color: muted, cursor: "pointer" }}>
                  <input type="radio" name="glc" checked={glConnect === v} onChange={() => setGlConnect(v)} style={{ accentColor: green }} />{l}
                </label>
              ))}
            </div>
          )}
          <div style={{ display: "flex", justifyContent: "space-between", marginTop: 24 }}>
            <button style={btnGhost} onClick={() => setStep(3)}>← Back</button>
            <button style={btnPrimary} onClick={() => setStep(5)}>Next →</button>
          </div>
        </div>
      )}

      {step === 5 && (
        <div>
          <div style={{ border: `1px solid ${border}`, borderRadius: 10, overflow: "hidden" }}>
            {[
              ["Company", name],
              ["Business", (PO_BIZ_MODELS.find(b => b.v === bizModel) || {}).l || bizModel],
              ["Entity type", (PO_COMPANY_TYPES.find(t => t.v === companyType) || {}).l || companyType || "—"],
              industry && ["Industry", industry],
              revBand && ["Revenue band", revBand],
              ["Fiscal year end", fyEnd],
              ["Country", country],
              challenges.length && ["Challenges", challenges.join(", ")],
              ["Accounting", glProvider ? `${(PO_GL.find(g => g.v === glProvider) || {}).l} · connect ${glConnect}` : "—"],
              ["Owner", ownerName ? `${ownerName} (${ownerEmail})` : ownerEmail],
            ].filter(Boolean).map(([k, v], i) => (
              <div key={k} style={{ display: "flex", justifyContent: "space-between", gap: 16, padding: "11px 16px", fontSize: 12.5, borderBottom: i < 9 ? `1px solid ${border}` : "none" }}>
                <span style={{ color: muted }}>{k}</span>
                <span style={{ color: ink, fontWeight: 500, textAlign: "right" }}>{v || "—"}</span>
              </div>
            ))}
          </div>
          <div style={{ fontSize: 12.5, color: muted, marginTop: 16, padding: "12px 14px", background: "#f8f7f4", borderRadius: 8, lineHeight: 1.5 }}>
            When you submit, our team reviews your setup and creates your account. You'll get a welcome email at <strong style={{ color: ink }}>{ownerEmail}</strong> within 24 hours.
          </div>
          <div style={{ display: "flex", justifyContent: "space-between", marginTop: 24 }}>
            <button style={btnGhost} onClick={() => setStep(4)}>← Back</button>
            <button style={btnPrimary} disabled={submitting} onClick={submit}>{submitting ? "Submitting…" : "Submit for review"}</button>
          </div>
        </div>
      )}
    </Page>
  );
}

window.PublicOnboardingPage = PublicOnboardingPage;
