/* Onboarding — a first-run journey: user role → goals → connect accounts →
   set up brand (brief, voice, assets) → invite others → choose a starting point
   (plan posts/campaigns or audit performance). Shown until completed; can be
   re-run from Settings. All simulated/local. Exposed as window.Onboarding. */
(function () {
  const S = window.CroprStore;
  const D = window.CROPR_DATA;

  const fieldStyle = { width: "100%", boxSizing: "border-box", fontFamily: "inherit", fontSize: 14, color: "var(--fg1)", background: "var(--surface)", border: "1px solid var(--border-strong)", borderRadius: 10, padding: "10px 12px", outline: "none" };
  const Label = ({ children }) => <span style={{ fontSize: 12, fontWeight: 600, color: "var(--fg2)", display: "block", marginBottom: 6 }}>{children}</span>;
  const readFile = async (f, cb) => { if (!f) return; const m = await window.LeapUpload.readAndHost(f); if (m) cb(m); };

  // a big selectable option card (icon + label + desc), single or multi
  function OptionCard({ on, icon, label, desc, onClick }) {
    return (
      <button onClick={onClick} style={{ display: "flex", alignItems: "flex-start", gap: 14, textAlign: "left", cursor: "pointer", fontFamily: "inherit",
        border: `1.5px solid ${on ? "var(--leap-teal)" : "var(--border)"}`, background: on ? "var(--accent-weak)" : "var(--surface)", borderRadius: 16, padding: "16px 18px", width: "100%", transition: "border-color 140ms, background 140ms" }}>
        <span style={{ width: 42, height: 42, borderRadius: 12, flex: "none", display: "grid", placeItems: "center", background: on ? "var(--gradient-core)" : "var(--bg-muted)" }}><Icon name={icon} size={21} color={on ? "#fff" : "var(--fg2)"} /></span>
        <span style={{ minWidth: 0 }}>
          <span style={{ display: "flex", alignItems: "center", gap: 8 }}><span style={{ fontSize: 15, fontWeight: 700, color: "var(--fg1)" }}>{label}</span>{on && <Icon name="check-circle" size={16} color="var(--accent)" />}</span>
          {desc && <span style={{ display: "block", fontSize: 12.5, color: "var(--fg3)", marginTop: 2 }}>{desc}</span>}
        </span>
      </button>
    );
  }

  function Onboarding({ onDone, onToast }) {
    const ob = S.getOnboarding();
    const [step, setStep] = React.useState(0);
    const [role, setRole] = React.useState(ob.role || null);
    const [goals, setGoals] = React.useState(ob.goals || []);
    const [connected, setConnected] = React.useState(ob.connected || []);
    const [brief, setBrief] = React.useState(S.getBrand().brandBrief || "");
    const [voice, setVoice] = React.useState(S.getBrand().brandVoice || "");
    const [assetCount, setAssetCount] = React.useState(0);
    const [invRole, setInvRole] = React.useState("creator");
    const [invEmail, setInvEmail] = React.useState("");
    const [invited, setInvited] = React.useState([]);
    // agency client setup (loop)
    const [clName, setClName] = React.useState("");
    const [clBrief, setClBrief] = React.useState("");
    const [clVoice, setClVoice] = React.useState("");
    const [clAssets, setClAssets] = React.useState([]);
    const [createdClients, setCreatedClients] = React.useState([]);

    const isAgency = role === "agency";
    // step keys differ for agencies (per-client setup instead of one brand + invite)
    const STEP_KEYS = isAgency ? ["role", "goals", "connect", "clients", "finish"] : ["role", "goals", "connect", "brand", "invite", "finish"];
    const STEP_LABELS = { role: "Role", goals: "Goals", connect: "Connect", brand: "Brand", invite: "Invite", clients: "Clients", finish: "Start" };
    const key = STEP_KEYS[Math.min(step, STEP_KEYS.length - 1)];
    const lastStep = STEP_KEYS.length - 1;

    const toggleGoal = (id) => setGoals((g) => g.includes(id) ? g.filter((x) => x !== id) : [...g, id]);
    const toggleConn = (id) => setConnected((c) => c.includes(id) ? c.filter((x) => x !== id) : [...c, id]);
    const roleOpts = S.getRoles().filter((r) => r.id !== "admin").map((r) => ({ value: r.id, label: r.name }));
    const persistProgress = () => S.setOnboarding({ role, goals, connected });

    const addInvite = () => {
      const e = invEmail.trim();
      if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e)) { onToast && onToast("Enter a valid email", "error"); return; }
      S.addMember(e.split("@")[0], e, invRole);
      setInvited((l) => [...l, { email: e, roleId: invRole }]); setInvEmail(""); onToast && onToast("Invite sent (simulated)");
    };
    const addClientOnb = () => {
      if (!clName.trim()) { onToast && onToast("Name the client first", "error"); return; }
      const c = S.addClient({ name: clName.trim(), brandBrief: clBrief, brandVoice: clVoice });
      clAssets.forEach((a) => S.addAsset({ name: a.name, url: a.url, kind: a.kind, category: "logo", keywords: [], platforms: [], clientId: c.id }));
      setCreatedClients((l) => [...l, { id: c.id, name: c.name, color: c.color }]);
      setClName(""); setClBrief(""); setClVoice(""); setClAssets([]);
      onToast && onToast(`“${c.name}” added — set up another or continue`);
    };

    const finish = (dest) => {
      if (isAgency) { if (createdClients.length) S.setActiveClient(createdClients[0].id); }
      else { S.setBrand({ brandBrief: brief, brandVoice: voice }); }
      S.completeOnboarding({ role, goals, connected }); onDone(dest);
    };
    const skipAll = () => { if (!isAgency) S.setBrand({ brandBrief: brief, brandVoice: voice }); S.completeOnboarding({ role, goals, connected, skipped: true }); onDone("dashboard"); };
    const next = () => { persistProgress(); setStep((s) => Math.min(lastStep, s + 1)); };
    const back = () => setStep((s) => Math.max(0, s - 1));

    const canNext = key === "role" ? !!role : true;

    return (
      <div style={{ position: "fixed", inset: 0, zIndex: 200, background: "var(--bg)", display: "flex", flexDirection: "column", overflow: "auto" }}>
        {/* header */}
        <div style={{ display: "flex", alignItems: "center", padding: "18px 28px", borderBottom: "1px solid var(--border)", flex: "none" }}>
          <img src="assets/leap-logo.svg" alt="Leap" style={{ height: 28 }} />
          <div style={{ flex: 1 }} />
          <button onClick={skipAll} style={{ border: 0, background: "none", cursor: "pointer", fontFamily: "inherit", fontSize: 13, fontWeight: 600, color: "var(--fg3)" }}>Skip setup</button>
        </div>
        {/* progress */}
        <div style={{ display: "flex", gap: 6, padding: "16px 28px 0", maxWidth: 640, margin: "0 auto", width: "100%", boxSizing: "border-box" }}>
          {STEP_KEYS.map((s, i) => <div key={s} style={{ flex: 1, height: 5, borderRadius: 999, background: i <= step ? "var(--gradient-core)" : "var(--bg-muted)" }} />)}
        </div>

        <div style={{ flex: 1, padding: "22px 28px 40px", maxWidth: 640, margin: "0 auto", width: "100%", boxSizing: "border-box" }}>
          {key === "role" && (
            <div>
              <div style={{ fontSize: 12.5, fontWeight: 700, color: "var(--accent)", fontFamily: "var(--font-mono)", textTransform: "uppercase", letterSpacing: ".12em" }}>Welcome to Leap</div>
              <h2 style={{ fontSize: 26, margin: "6px 0 4px" }}>Who are you posting for?</h2>
              <p style={{ fontSize: 14, color: "var(--fg3)", marginBottom: 22 }}>This tailors your workspace, defaults and suggestions.</p>
              <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                {D.ONBOARD_ROLES.map((r) => <OptionCard key={r.id} on={role === r.id} icon={r.icon} label={r.label} desc={r.desc} onClick={() => setRole(r.id)} />)}
              </div>
            </div>
          )}

          {key === "goals" && (
            <div>
              <h2 style={{ fontSize: 26, margin: "0 0 4px" }}>What are your main goals?</h2>
              <p style={{ fontSize: 14, color: "var(--fg3)", marginBottom: 22 }}>Pick any that apply — we'll point you at the right tools first.</p>
              <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                {D.ONBOARD_GOALS.map((g) => <OptionCard key={g.id} on={goals.includes(g.id)} icon={g.icon} label={g.label} desc={g.desc} onClick={() => toggleGoal(g.id)} />)}
              </div>
            </div>
          )}

          {key === "connect" && (
            <div>
              <h2 style={{ fontSize: 26, margin: "0 0 4px" }}>Connect your accounts</h2>
              <p style={{ fontSize: 14, color: "var(--fg3)", marginBottom: 22 }}>Connect the social accounts you'll publish to. You can add the API credentials any time in Settings → Integrations.</p>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }} className="profile-grid">
                {D.PLATFORMS.map((p) => {
                  const on = connected.includes(p.id);
                  return (
                    <button key={p.id} onClick={() => toggleConn(p.id)} style={{ display: "flex", alignItems: "center", gap: 12, textAlign: "left", cursor: "pointer", fontFamily: "inherit",
                      border: `1.5px solid ${on ? "var(--leap-teal)" : "var(--border)"}`, background: on ? "var(--accent-weak)" : "var(--surface)", borderRadius: 14, padding: "12px 14px" }}>
                      <PlatformLogo platform={p.id} size={30} style={{ borderRadius: 8, flex: "none" }} />
                      <span style={{ fontSize: 14, fontWeight: 700, color: "var(--fg1)", flex: 1 }}>{p.label}</span>
                      {on ? <Badge color="#0E8A50" bg="var(--success-bg)" dot>Connected</Badge> : <span style={{ fontSize: 12.5, fontWeight: 600, color: "var(--accent)" }}>Connect</span>}
                    </button>
                  );
                })}
              </div>
              <div style={{ display: "flex", gap: 8, alignItems: "center", marginTop: 16, fontSize: 12, color: "var(--fg4)" }}><Icon name="info" size={14} color="var(--fg4)" />More integrations — Microsoft 365, ClickUp, the AI service — live in Settings → Integrations.</div>
            </div>
          )}

          {key === "brand" && (
            <div>
              <h2 style={{ fontSize: 26, margin: "0 0 4px" }}>Set up your brand</h2>
              <p style={{ fontSize: 14, color: "var(--fg3)", marginBottom: 20 }}>This is what the AI uses to generate on-brand ideas and posts. You can refine it later in Settings → Brand.</p>
              <div style={{ marginBottom: 16 }}>
                <div style={{ fontSize: 13, fontWeight: 700, marginBottom: 6, display: "flex", alignItems: "center", gap: 7 }}><Icon name="building-2" size={16} color="var(--accent)" />Brand brief</div>
                <textarea value={brief} onChange={(e) => setBrief(e.target.value)} rows={3} placeholder="Who you are, what you offer, and who you're for." style={{ ...fieldStyle, resize: "vertical", lineHeight: 1.5 }} />
              </div>
              <div style={{ marginBottom: 16 }}>
                <div style={{ fontSize: 13, fontWeight: 700, marginBottom: 6, display: "flex", alignItems: "center", gap: 7 }}><Icon name="mic" size={16} color="var(--accent)" />Brand voice</div>
                <textarea value={voice} onChange={(e) => setVoice(e.target.value)} rows={2} placeholder="How your brand sounds — e.g. playful, warm, plain-spoken, no jargon." style={{ ...fieldStyle, resize: "vertical", lineHeight: 1.5 }} />
              </div>
              <div>
                <div style={{ fontSize: 13, fontWeight: 700, marginBottom: 6, display: "flex", alignItems: "center", gap: 7 }}><Icon name="image" size={16} color="var(--accent)" />Brand assets</div>
                <label style={{ display: "flex", alignItems: "center", gap: 10, border: "1.5px dashed var(--border-strong)", borderRadius: 12, padding: "14px 16px", cursor: "pointer", color: "var(--fg3)" }}>
                  <Icon name="upload-cloud" size={20} color="var(--fg4)" />
                  <span style={{ fontSize: 13 }}>{assetCount ? `${assetCount} asset${assetCount === 1 ? "" : "s"} added — add more` : "Upload logos, photos or templates to reuse"}</span>
                  <input type="file" accept="image/*,video/*" multiple style={{ display: "none" }} onChange={(e) => { const fs = [...(e.target.files || [])]; fs.forEach((f) => readFile(f, (m) => S.addAsset({ name: m.name, url: m.url, kind: m.kind, category: "logo", keywords: [], platforms: [] }))); setAssetCount((n) => n + fs.length); e.target.value = ""; }} />
                </label>
              </div>
            </div>
          )}

          {key === "invite" && (
            <div>
              <h2 style={{ fontSize: 26, margin: "0 0 4px" }}>Invite your team</h2>
              <p style={{ fontSize: 14, color: "var(--fg3)", marginBottom: 20 }}>Bring in teammates to plan, review and publish together. Optional — you can always add people later.</p>
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center", marginBottom: 14 }}>
                <input value={invEmail} onChange={(e) => setInvEmail(e.target.value)} placeholder="teammate@email.com" onKeyDown={(e) => { if (e.key === "Enter") addInvite(); }} style={{ ...fieldStyle, flex: 1, minWidth: 200 }} />
                <Select value={invRole} onChange={setInvRole} options={roleOpts} style={{ width: 150 }} />
                <Button variant="primary" icon="user-plus" onClick={addInvite}>Invite</Button>
              </div>
              {invited.length === 0
                ? <div style={{ fontSize: 12.5, color: "var(--fg4)" }}>No invites yet.</div>
                : <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                    {invited.map((iv, i) => (
                      <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 14px", border: "1px solid var(--border)", borderRadius: 12 }}>
                        <span style={{ width: 30, height: 30, borderRadius: 999, background: "var(--accent-weak)", display: "grid", placeItems: "center", flex: "none" }}><Icon name="mail" size={15} color="var(--accent)" /></span>
                        <span style={{ fontSize: 13.5, fontWeight: 600, flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{iv.email}</span>
                        <Badge color="var(--accent)" bg="var(--accent-weak)">{(S.getRoles().find((r) => r.id === iv.roleId) || {}).name || iv.roleId}</Badge>
                        <span style={{ fontSize: 11.5, color: "#0E8A50", fontWeight: 600 }}>Invited</span>
                      </div>
                    ))}
                  </div>}
            </div>
          )}

          {key === "clients" && (
            <div>
              <h2 style={{ fontSize: 26, margin: "0 0 4px" }}>Set up your client accounts</h2>
              <p style={{ fontSize: 14, color: "var(--fg3)", marginBottom: 20 }}>Each client is a separate account with its own brand, voice and assets. Add your first client — then set up another, or continue.</p>
              {createdClients.length > 0 && (
                <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginBottom: 16 }}>
                  {createdClients.map((cc) => (
                    <span key={cc.id} style={{ display: "inline-flex", alignItems: "center", gap: 8, border: "1px solid var(--border)", borderRadius: 999, padding: "5px 12px 5px 6px", fontSize: 13, fontWeight: 600 }}>
                      <span style={{ width: 22, height: 22, borderRadius: 6, background: cc.color, color: "#fff", display: "grid", placeItems: "center", fontSize: 11, fontWeight: 800 }}>{cc.name.slice(0, 1).toUpperCase()}</span>
                      {cc.name}<Icon name="check-circle" size={15} color="#0E8A50" />
                    </span>
                  ))}
                </div>
              )}
              <Card pad={18} style={{ border: "1.5px solid var(--border)" }}>
                <div style={{ fontSize: 13, fontWeight: 700, marginBottom: 12, display: "flex", alignItems: "center", gap: 7 }}><Icon name="user-plus" size={16} color="var(--accent)" />{createdClients.length ? "Add another client" : "Add your first client"}</div>
                <div style={{ marginBottom: 12 }}><Label>Client name</Label><input value={clName} onChange={(e) => setClName(e.target.value)} placeholder="e.g. Riverside Coffee Co." style={fieldStyle} /></div>
                <div style={{ marginBottom: 12 }}><Label>Brand brief</Label><textarea value={clBrief} onChange={(e) => setClBrief(e.target.value)} rows={2} placeholder="Who this client is, what they offer, and who they're for." style={{ ...fieldStyle, resize: "vertical", lineHeight: 1.5 }} /></div>
                <div style={{ marginBottom: 12 }}><Label>Brand voice</Label><textarea value={clVoice} onChange={(e) => setClVoice(e.target.value)} rows={2} placeholder="How this client sounds — e.g. warm and playful." style={{ ...fieldStyle, resize: "vertical", lineHeight: 1.5 }} /></div>
                <div style={{ marginBottom: 14 }}>
                  <Label>Brand assets {clAssets.length ? `· ${clAssets.length} added` : ""}</Label>
                  <label style={{ display: "flex", alignItems: "center", gap: 10, border: "1.5px dashed var(--border-strong)", borderRadius: 12, padding: "12px 14px", cursor: "pointer", color: "var(--fg3)" }}>
                    <Icon name="upload-cloud" size={18} color="var(--fg4)" />
                    <span style={{ fontSize: 12.5 }}>{clAssets.length ? "Add more assets" : "Upload the client's logos, photos or templates"}</span>
                    <input type="file" accept="image/*,video/*" multiple style={{ display: "none" }} onChange={(e) => { const fs = [...(e.target.files || [])]; fs.forEach((f) => readFile(f, (m) => setClAssets((a) => [...a, m]))); e.target.value = ""; }} />
                  </label>
                </div>
                <Button variant="primary" icon="plus" onClick={addClientOnb}>{createdClients.length ? "Add this client" : "Add client"}</Button>
              </Card>
            </div>
          )}

          {key === "finish" && (
            <div>
              <div style={{ textAlign: "center", marginBottom: 24 }}>
                <span style={{ width: 60, height: 60, borderRadius: 17, background: "var(--gradient-core)", display: "inline-grid", placeItems: "center" }}><Icon name="check" size={30} color="#fff" /></span>
                <h2 style={{ fontSize: 26, margin: "14px 0 4px" }}>You're all set</h2>
                <p style={{ fontSize: 14, color: "var(--fg3)" }}>Where would you like to start?</p>
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }} className="profile-grid">
                <button onClick={() => finish("campaigns")} style={{ textAlign: "left", cursor: "pointer", fontFamily: "inherit", border: 0, borderRadius: 18, padding: 22, color: "#fff", background: "var(--gradient-core)" }}>
                  <Icon name="megaphone" size={26} color="#fff" />
                  <div style={{ fontSize: 17, fontWeight: 700, marginTop: 12 }}>Start planning posts &amp; campaigns</div>
                  <div style={{ fontSize: 13, opacity: .95, marginTop: 4 }}>Draft a campaign or compose your first post.</div>
                  <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 12, fontSize: 13, fontWeight: 700 }}>Let's go <Icon name="arrow-right" size={16} color="#fff" /></div>
                </button>
                <button onClick={() => finish("dashboard")} style={{ textAlign: "left", cursor: "pointer", fontFamily: "inherit", border: "1px solid var(--border)", borderRadius: 18, padding: 22, background: "var(--surface)", color: "var(--fg1)" }}>
                  <span style={{ width: 42, height: 42, borderRadius: 12, background: "var(--accent-weak)", display: "grid", placeItems: "center" }}><Icon name="bar-chart-3" size={22} color="var(--accent)" /></span>
                  <div style={{ fontSize: 17, fontWeight: 700, marginTop: 12 }}>Audit my social performance</div>
                  <div style={{ fontSize: 13, color: "var(--fg3)", marginTop: 4 }}>See your analytics dashboard and KPIs.</div>
                  <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 12, fontSize: 13, fontWeight: 700, color: "var(--accent)" }}>View dashboard <Icon name="arrow-right" size={16} color="var(--accent)" /></div>
                </button>
              </div>
            </div>
          )}
        </div>

        {/* footer nav (hidden on the final choice step) */}
        {key !== "finish" && (
          <div style={{ flex: "none", borderTop: "1px solid var(--border)", padding: "14px 28px" }}>
            <div style={{ maxWidth: 640, margin: "0 auto", display: "flex", alignItems: "center", gap: 10 }}>
              <Button variant="secondary" icon="arrow-left" onClick={back} disabled={step === 0}>Back</Button>
              <div style={{ flex: 1 }} />
              {(key === "connect" || key === "brand" || key === "invite" || key === "clients") && <button onClick={next} style={{ border: 0, background: "none", cursor: "pointer", fontFamily: "inherit", fontSize: 13, fontWeight: 600, color: "var(--fg3)" }}>Skip this step</button>}
              <Button variant="primary" iconRight="arrow-right" onClick={next} disabled={!canNext}>Continue</Button>
            </div>
          </div>
        )}
      </div>
    );
  }
  window.Onboarding = Onboarding;
})();
