/* KitRate — creator onboarding wizard (profile → handles/metrics → audience) */

function WizardShell({ step, setStep, steps, children, onBack, onNext, nextLabel, nextDisabled }) {
  return (
    <div style={{ maxWidth: 880, margin: "0 auto", padding: "44px 32px 80px" }} data-screen-label={"Onboarding — " + steps[step]}>
      {/* progress */}
      <div style={{ display: "flex", alignItems: "center", gap: 0, marginBottom: 40 }}>
        {steps.map((s, i) => (
          <React.Fragment key={s}>
            <button onClick={() => i < step && setStep(i)} style={{
              background: "none", border: "none", padding: 0, display: "flex", alignItems: "center", gap: 9,
              cursor: i < step ? "pointer" : "default", opacity: i > step ? 0.45 : 1
            }}>
              <span style={{
                width: 24, height: 24, borderRadius: "50%", fontSize: 11.5, fontFamily: "var(--mono)",
                display: "inline-flex", alignItems: "center", justifyContent: "center",
                background: i <= step ? "var(--accent)" : "var(--surface-2)",
                color: i <= step ? "var(--accent-ink)" : "var(--muted)",
                border: i === step ? "none" : "1px solid var(--line)"
              }}>{i < step ? "✓" : i + 1}</span>
              <span style={{ fontSize: 13, fontWeight: i === step ? 600 : 500, color: i === step ? "var(--ink)" : "var(--muted)" }}>{s}</span>
            </button>
            {i < steps.length - 1 && <div style={{ flex: 1, height: 1, background: "var(--line-strong)", margin: "0 14px", minWidth: 20 }}></div>}
          </React.Fragment>
        ))}
      </div>

      <div className="kr-fade-in" key={step}>{children}</div>

      <div style={{ display: "flex", justifyContent: "space-between", marginTop: 36, paddingTop: 22, borderTop: "1px solid var(--line)" }}>
        <button className="kr-btn kr-btn-ghost" onClick={onBack}><KrIcon d={ICONS.arrowLeft} size={14} /> Back</button>
        <button className="kr-btn kr-btn-primary" onClick={onNext} disabled={nextDisabled} style={nextDisabled ? { opacity: 0.45, cursor: "not-allowed" } : null}>
          {nextLabel} <KrIcon d={ICONS.arrowRight} size={14} />
        </button>
      </div>
    </div>
  );
}

/* ---- step 1: profile basics ---- */
function StepProfile({ p, set, bm }) {
  return (
    <div>
      <SectionHead eyebrow="Step 1 of 3" title="Who are you?" desc="The essentials a brand sees first: name, niche, where you're based, and how to reach you." />
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0 24px" }} className="kr-wizard-grid">
        <Field label="Full name" error={p._touched && !p.name ? "Brands need a name on the cover." : null}>
          <input className={"kr-input" + (p._touched && !p.name ? " kr-invalid" : "")} value={p.name} placeholder="e.g. Michael Heckert" onChange={(e) => set({ name: e.target.value })} />
        </Field>
        <Field label="One-line tagline" hint="Shows under your name on the cover.">
          <input className="kr-input" value={p.tagline} placeholder="Pro bare-knuckle fighter. Building businesses between rounds." onChange={(e) => set({ tagline: e.target.value })} />
        </Field>
        <Field label="Niche / category">
          <select className="kr-select" value={p.nicheId} onChange={(e) => {
            const n = bm.nicheMults.find(x => x.id === e.target.value);
            set({ nicheId: e.target.value, nicheLabel: n ? n.label : "" });
          }}>
            <option value="">Select a niche…</option>
            {bm.nicheMults.filter(n => n.status !== "outdated").map(n => <option key={n.id} value={n.id}>{n.label}</option>)}
          </select>
        </Field>
        <Field label="Location">
          <input className="kr-input" value={p.location} placeholder="City, Country" onChange={(e) => set({ location: e.target.value })} />
        </Field>
        <Field label="Region (for rate benchmarks)">
          <select className="kr-select" value={p.regionId} onChange={(e) => set({ regionId: e.target.value })}>
            {bm.regionMults.map(r => <option key={r.id} value={r.id}>{r.label}</option>)}
          </select>
        </Field>
        <Field label="Contact email">
          <input className="kr-input" type="email" value={p.email} placeholder="partnerships@you.com" onChange={(e) => set({ email: e.target.value })} />
        </Field>
        <Field label="Website / portfolio" style={{ gridColumn: "1 / -1" }}>
          <input className="kr-input" value={p.website} placeholder="yourname.com" onChange={(e) => set({ website: e.target.value })} />
        </Field>
        <Field label="Short bio" hint="2–4 sentences. You can refine this in the editor — KitRate can also draft it for you." style={{ gridColumn: "1 / -1" }}>
          <textarea className="kr-textarea" rows={4} value={p.bio} onChange={(e) => set({ bio: e.target.value })}></textarea>
        </Field>
      </div>
    </div>
  );
}

/* ---- step 2: handles + metrics ---- */
const PLATFORM_DEFS = [
  { key: "instagram", label: "Instagram", fields: ["followers", "avgViews", "avgStoryViews", "engagement"] },
  { key: "tiktok", label: "TikTok", fields: ["followers", "avgViews", "engagement"] },
  { key: "youtube", label: "YouTube", fields: ["followers", "avgViews", "engagement"] }
];
const METRIC_LABELS = {
  followers: ["Followers / subscribers", ""],
  avgViews: ["Avg short-form views", "Last 10 Reels / videos / Shorts"],
  avgStoryViews: ["Avg story views", ""],
  engagement: ["Engagement rate %", "(likes + comments) ÷ followers"]
};

function validHandle(h) {
  return /^@?[A-Za-z0-9._]{2,30}$/.test((h || "").trim());
}

function PlatformCard({ def, data, onChange, onRemove, integration, onConnect, onSync, onDisconnect }) {
  const [importing, setImporting] = useState(false);
  const [importError, setImportError] = useState(null);
  const connected = !!integration?.connected;
  const configured = !!integration?.configured;
  const handleBad = !connected && data.handle && !validHandle(data.handle);
  const updateManual = (patch) => onChange({
    ...patch,
    source: "manual",
    verified: false,
    syncedAt: null,
    metricWindow: "Creator provided"
  });

  return (
    <div className="kr-card" style={{ padding: 20, marginBottom: 16 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 14 }}>
        <PlatformMark name={def.key} />
        <div style={{ fontWeight: 600, fontSize: 15 }}>{def.label}</div>
        <div style={{ flex: 1 }}></div>
        {!connected && <button className="kr-btn kr-btn-ghost kr-btn-sm" onClick={onRemove}>Remove</button>}
      </div>
      <div className={"kr-connection-strip" + (connected ? " connected" : "")}>
        <div>
          <strong>{connected ? def.label + " connected" : configured ? "Verify these metrics" : def.label + " OAuth setup required"}</strong>
          <span>{connected
            ? (integration.username || "Authorized account") + (integration.syncedAt ? " · synced " + new Date(integration.syncedAt).toLocaleDateString() : "")
            : configured
              ? "OAuth imports account-owned performance and keeps credentials server-side."
              : "Add this provider's OAuth credentials to enable verified imports."}</span>
        </div>
        <div>
          {connected ? <>
            <button className="kr-btn kr-btn-primary kr-btn-sm" onClick={async () => {
              setImporting(true); setImportError(null);
              try { await onSync(); }
              catch (error) { setImportError(error.message); }
              finally { setImporting(false); }
            }} disabled={importing}>{importing ? "Syncing…" : "Sync now"}</button>
            <button className="kr-btn kr-btn-ghost kr-btn-sm" onClick={onDisconnect}>Disconnect</button>
          </> : <button className="kr-btn kr-btn-primary kr-btn-sm" onClick={onConnect} disabled={!configured}>
            <KrIcon d={ICONS.link} size={13} /> {configured ? "Connect " + def.label : "Setup required"}
          </button>}
        </div>
      </div>
      <div style={{ marginTop: 14 }}>
        <input className={"kr-input" + (handleBad ? " kr-invalid" : "")} value={data.handle || ""} placeholder="@handle"
          readOnly={connected} onChange={(e) => updateManual({ handle: e.target.value })} />
        {handleBad && <div className="kr-error-text">Invalid handle — letters, numbers, dots and underscores only.</div>}
      </div>
      {importError && (
        <div style={{ display: "flex", gap: 8, marginTop: 10, fontSize: 12.5, color: "var(--warn)", background: "var(--warn-soft)", padding: "8px 12px", borderRadius: 8 }}>
          <KrIcon d={ICONS.warn} size={14} style={{ flexShrink: 0, marginTop: 1 }} /> {importError}
        </div>
      )}
      {data.source && <EvidenceRail evidence={data} confidence={null} compact />}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(150px, 1fr))", gap: 12, marginTop: 14 }}>
        {def.fields.map(f => (
          <div key={f}>
            <label className="kr-label" style={{ fontSize: 11.5 }}>{METRIC_LABELS[f][0]}</label>
            <input className="kr-input" inputMode="decimal" value={data[f] ?? ""} placeholder="0"
              readOnly={connected}
              onChange={(e) => {
                const v = e.target.value.replace(/[^0-9.]/g, "");
                updateManual({ [f]: v === "" ? null : parseFloat(v) });
              }} />
            {METRIC_LABELS[f][1] && <div className="kr-hint" style={{ fontSize: 10.5 }}>{METRIC_LABELS[f][1]}</div>}
          </div>
        ))}
      </div>
    </div>
  );
}

function StepMetrics({ p, set, integrations, onConnectIntegration, onSyncIntegration, onDisconnectIntegration }) {
  const active = PLATFORM_DEFS.filter(d => p.platforms[d.key]);
  const inactive = PLATFORM_DEFS.filter(d => !p.platforms[d.key]);
  const setPlat = (key, patch) => set({ platforms: { ...p.platforms, [key]: { ...(p.platforms[key] || {}), ...patch } } });

  return (
    <div>
      <SectionHead eyebrow="Step 2 of 3" title="Platforms & metrics"
        desc="Connect accounts for verified rates, or enter creator-provided analytics manually. KitRate never invents social metrics." />
      <IntegrationNote>
        Instagram, YouTube and TikTok use owner-authorized OAuth imports. Manual values remain clearly labeled and receive lower confidence than platform-verified data.
      </IntegrationNote>
      {active.map(def => (
        <PlatformCard key={def.key} def={def} data={p.platforms[def.key]}
          onChange={(patch) => setPlat(def.key, patch)}
          onRemove={() => set({ platforms: { ...p.platforms, [def.key]: null } })}
          integration={integrations?.[def.key]}
          onConnect={() => onConnectIntegration(def.key)}
          onSync={() => onSyncIntegration(def.key)}
          onDisconnect={() => onDisconnectIntegration(def.key)} />
      ))}
      {active.length === 0 && (
        <EmptyState icon="spark" title="No platforms yet" desc="Add at least one platform below — Instagram, TikTok or YouTube — to generate rates." />
      )}
      <div style={{ display: "flex", gap: 10, flexWrap: "wrap", marginTop: 6 }}>
        {inactive.map(def => (
          <button key={def.key} className="kr-btn kr-btn-secondary kr-btn-sm" onClick={() => setPlat(def.key, { handle: "", followers: null })}>
            <KrIcon d={ICONS.plus} size={13} /> Add {def.label}
          </button>
        ))}
      </div>

      <div style={{ marginTop: 26, paddingTop: 20, borderTop: "1px solid var(--line)" }}>
        <div className="kr-label" style={{ marginBottom: 10 }}>Other links (shown in your kit)</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }} className="kr-wizard-grid">
          {[["x", "X / Twitter", "@handle"], ["linkedin", "LinkedIn", "linkedin.com/in/…"]].map(([k, lbl, ph]) => (
            <div key={k}>
              <label className="kr-label" style={{ fontSize: 11.5 }}>{lbl}</label>
              <input className="kr-input" value={(p.links && p.links[k]) || ""} placeholder={ph}
                onChange={(e) => set({ links: { ...(p.links || {}), [k]: e.target.value } })} />
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ---- step 3: audience & proof ---- */
function StepAudience({ p, set }) {
  const a = p.audience || {};
  const setA = (patch) => set({ audience: { ...a, ...patch } });
  const male = a.genderSplit ? a.genderSplit.male : 50;

  const setBrand = (i, patch) => {
    const arr = [...(p.pastBrands || [])];
    arr[i] = { ...arr[i], ...patch };
    set({ pastBrands: arr });
  };

  return (
    <div>
      <SectionHead eyebrow="Step 3 of 3" title="Audience & proof"
        desc="Demographics and past brand work raise your rate confidence from medium to high — and give brands a reason to say yes." />

      <div className="kr-card" style={{ padding: 20, marginBottom: 16 }}>
        <div style={{ fontWeight: 600, fontSize: 14.5, marginBottom: 14 }}>Audience snapshot</div>
        <Field label={"Gender split — " + male + "% male / " + (100 - male) + "% female & other"}>
          <input type="range" min={0} max={100} value={male} style={{ width: "100%", accentColor: "var(--accent)" }}
            onChange={(e) => setA({ genderSplit: { male: +e.target.value, female: 100 - +e.target.value, other: 0 } })} />
        </Field>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0 24px" }} className="kr-wizard-grid">
          <Field label="Top countries" hint="Comma-separated, in order.">
            <input className="kr-input" value={(a.topGeos || []).join(", ")} placeholder="United States, United Kingdom…"
              onChange={(e) => setA({ topGeos: e.target.value.split(",").map(s => s.trim()).filter(Boolean) })} />
          </Field>
          <Field label="Top cities">
            <input className="kr-input" value={(a.topCities || []).join(", ")} placeholder="New York, Los Angeles…"
              onChange={(e) => setA({ topCities: e.target.value.split(",").map(s => s.trim()).filter(Boolean) })} />
          </Field>
        </div>
        <Field label="Age ranges" hint="Estimate is fine — pull from your platform analytics.">
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 10 }}>
            {["18–24", "25–34", "35–44", "45+"].map((r) => {
              const row = (a.ageRanges || []).find(x => x.range === r);
              return (
                <div key={r}>
                  <label className="kr-label" style={{ fontSize: 11, fontFamily: "var(--mono)" }}>{r}</label>
                  <input className="kr-input" inputMode="numeric" value={row ? row.pct : ""} placeholder="%"
                    onChange={(e) => {
                      const pct = e.target.value === "" ? null : Math.min(100, parseInt(e.target.value.replace(/\D/g, "") || 0));
                      const others = (a.ageRanges || []).filter(x => x.range !== r);
                      setA({ ageRanges: pct == null ? others : [...others, { range: r, pct }].sort((x, y) => x.range.localeCompare(y.range)) });
                    }} />
                </div>
              );
            })}
          </div>
        </Field>
      </div>

      <div className="kr-card" style={{ padding: 20 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
          <div style={{ fontWeight: 600, fontSize: 14.5 }}>Past brand work <span style={{ fontWeight: 400, color: "var(--muted)", fontSize: 12.5 }}>(optional, raises confidence)</span></div>
          <button className="kr-btn kr-btn-secondary kr-btn-sm" onClick={() => set({ pastBrands: [...(p.pastBrands || []), { name: "", category: "", result: "" }] })}>
            <KrIcon d={ICONS.plus} size={13} /> Add brand
          </button>
        </div>
        {(p.pastBrands || []).length === 0 && (
          <p style={{ fontSize: 13, color: "var(--muted)" }}>No brand work yet? That's fine — your kit will lead with audience and content instead.</p>
        )}
        {(p.pastBrands || []).map((b, i) => (
          <div key={i} style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1.4fr auto", gap: 10, marginBottom: 10, alignItems: "center" }} className="kr-wizard-grid">
            <input className="kr-input" value={b.name} placeholder="Brand name" onChange={(e) => setBrand(i, { name: e.target.value })} />
            <input className="kr-input" value={b.category} placeholder="Category" onChange={(e) => setBrand(i, { category: e.target.value })} />
            <input className="kr-input" value={b.result} placeholder="Result (e.g. 212K views, 1.8× ROAS)" onChange={(e) => setBrand(i, { result: e.target.value })} />
            <button className="kr-btn kr-btn-ghost kr-btn-sm" onClick={() => set({ pastBrands: p.pastBrands.filter((_, j) => j !== i) })} aria-label="Remove brand"><KrIcon d={ICONS.x} size={13} /></button>
          </div>
        ))}
      </div>

      <div className="kr-card" style={{ padding: 20, marginBottom: 16 }}>
        <div style={{ fontWeight: 600, fontSize: 14.5, marginBottom: 4 }}>Your business floor</div>
        <p style={{ fontSize: 12.5, color: "var(--muted)", marginBottom: 14 }}>These costs protect your walk-away number. They are never shown to brands.</p>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }} className="kr-wizard-grid">
          <Field label="Hourly production floor">
            <input className="kr-input" inputMode="decimal" value={p.businessTerms?.hourlyFloor ?? 75} onChange={(e) => set({ businessTerms: { ...(p.businessTerms || {}), hourlyFloor: +e.target.value.replace(/[^0-9.]/g, "") || 0 } })} />
          </Field>
          <Field label="Typical production hours">
            <input className="kr-input" inputMode="decimal" value={p.businessTerms?.defaultProductionHours ?? 6} onChange={(e) => set({ businessTerms: { ...(p.businessTerms || {}), defaultProductionHours: +e.target.value.replace(/[^0-9.]/g, "") || 0 } })} />
          </Field>
          <Field label="Manager commission %">
            <input className="kr-input" inputMode="decimal" value={p.businessTerms?.managerPct ?? 0} onChange={(e) => set({ businessTerms: { ...(p.businessTerms || {}), managerPct: +e.target.value.replace(/[^0-9.]/g, "") || 0 } })} />
          </Field>
        </div>
        <label className="kr-binary-row">
          <input type="checkbox" checked={p.ugcAvailable === true} onChange={(e) => set({ ugcAvailable: e.target.checked })} />
          <span><strong>Offer UGC production</strong><small>Add brand-owned photo and video rates that do not depend on audience size.</small></span>
        </label>
      </div>
    </div>
  );
}

/* ---- wizard root ---- */
function Wizard({ profile, setProfile, bm, onFinish, onExit, integrations, onConnectIntegration, onSyncIntegration, onDisconnectIntegration }) {
  const [step, setStep] = useState(0);
  const [generating, setGenerating] = useState(false);
  const steps = ["Profile", "Platforms & metrics", "Audience & proof"];
  const set = (patch) => setProfile({ ...profile, ...patch });

  const hasPlatform = Object.values(profile.platforms || {}).some(pl => pl && pl.followers);

  const finish = () => {
    setGenerating(true);
    setTimeout(() => { setGenerating(false); onFinish(); }, 1600);
  };

  if (generating) {
    return (
      <div style={{ maxWidth: 520, margin: "0 auto", padding: "120px 32px", textAlign: "center" }} className="kr-fade-in">
        <div style={{ width: 44, height: 44, margin: "0 auto 22px", border: "3px solid var(--line)", borderTopColor: "var(--accent)", borderRadius: "50%", animation: "krSpin 0.8s linear infinite" }}></div>
        <div className="kr-serif" style={{ fontSize: 24, marginBottom: 8 }}>Benchmarking your rates…</div>
        <p style={{ color: "var(--muted)", fontSize: 13.5 }}>Comparing your metrics against current creator-economy benchmarks and assembling your kit.</p>
      </div>
    );
  }

  return (
    <WizardShell step={step} setStep={setStep} steps={steps}
      onBack={() => step === 0 ? onExit() : setStep(step - 1)}
      onNext={() => {
        if (step === 0 && !profile.name) { set({ _touched: true }); return; }
        step === steps.length - 1 ? finish() : setStep(step + 1);
      }}
      nextLabel={step === steps.length - 1 ? "Generate my rates & kit" : "Continue"}
      nextDisabled={step === 1 && !hasPlatform}>
      {step === 0 && <StepProfile p={profile} set={set} bm={bm} />}
      {step === 1 && <StepMetrics p={profile} set={set} integrations={integrations}
        onConnectIntegration={onConnectIntegration} onSyncIntegration={onSyncIntegration}
        onDisconnectIntegration={onDisconnectIntegration} />}
      {step === 2 && <StepAudience p={profile} set={set} />}
    </WizardShell>
  );
}

window.Wizard = Wizard;
