// ─── Onboarding + Pricing screens ──────────────────────────────

const PROJECT_PALETTE = ["#c8ff3d", "#ff5a1f", "#3da9ff", "#a584ff", "#ffcc4d", "#ff3d8a"];
const PLAN_TO_ENUM = { Starter: "starter", Growth: "growth", Scale: "scale", Enterprise: "enterprise" };

function Onboarding({ t, goto, lang, proj, setProj, session }) {
  const [step, setStep] = useState(0); // 0 project, 1 details, 2 pricing
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");
  const stepDefs = [
    { label: lang === "fr" ? "Le projet" : "The project", sublabel: lang === "fr" ? "Nom, entreprise, site" : "Name, company, site" },
    { label: lang === "fr" ? "La description" : "The description", sublabel: lang === "fr" ? "Quelques phrases" : "A few sentences" },
    { label: lang === "fr" ? "La formule" : "Your plan", sublabel: lang === "fr" ? "Niveau d'autonomie" : "Autonomy level" },
  ];

  const goNext = async () => {
    setError("");
    if (step < 2) {
      if (step === 0 && !proj.name?.trim()) {
        setError(lang === "fr" ? "Donnez un nom à votre projet." : "Give your project a name.");
        return;
      }
      setStep(step + 1);
      return;
    }
    if (!session?.user) { goto("auth"); return; }
    setBusy(true);
    try {
      const color = PROJECT_PALETTE[Math.floor(Math.random() * PROJECT_PALETTE.length)];
      const { error: err } = await window.sb.from("projects").insert({
        user_id: session.user.id,
        name: proj.name.trim(),
        company: proj.company?.trim() || null,
        website: proj.website?.trim() || null,
        description: proj.description?.trim() || null,
        sector: proj.sector?.trim() || null,
        plan: PLAN_TO_ENUM[proj.plan] || "growth",
        color,
        status: "building",
      });
      if (err) throw err;
      setProj(window.EMPTY_PROJECT);
      goto("projects");
    } catch (e) {
      setError(e.message || (lang === "fr" ? "Échec de la création du projet." : "Failed to create the project."));
    } finally {
      setBusy(false);
    }
  };
  const goBack = () => {
    if (step > 0) setStep(step - 1);
    else goto("landing");
  };

  return (
    <div className="onb">
      <aside className="onb-side">
        <div className="kicker">{lang === "fr" ? "onboarding" : "onboarding"}</div>
        <h3 style={{ fontSize: 22, lineHeight: 1.2 }}>
          {lang === "fr" ? "On a juste 3 questions." : "Just 3 quick questions."}
        </h3>
        <div className="onb-steps">
          {stepDefs.map((s, i) => (
            <div key={i} className={`onb-step ${i === step ? "active" : ""} ${i < step ? "done" : ""}`} onClick={() => setStep(i)}>
              <div className="num">{i < step ? "✓" : i + 1}</div>
              <div>
                <div className="label">{s.label}</div>
                <div className="sublabel">{s.sublabel}</div>
              </div>
            </div>
          ))}
        </div>

        <div style={{ marginTop: "auto", fontSize: 12, color: "var(--muted)", fontFamily: "var(--font-mono)" }}>
          {lang === "fr"
            ? "Quand vous validez, l'agent #63 (Orchestrateur) brief immédiatement les 67 autres."
            : "Once validated, agent #63 (Orchestrator) instantly briefs the 67 others."}
        </div>
      </aside>

      <main className="onb-main">
        <div className="progress">{t.onb.step} {step + 1} {t.onb.of} 3</div>

        {step === 0 && <StepProject t={t} lang={lang} proj={proj} setProj={setProj} />}
        {step === 1 && <StepDescription t={t} lang={lang} proj={proj} setProj={setProj} />}
        {step === 2 && <StepPlan t={t} lang={lang} proj={proj} setProj={setProj} />}

        {error && (
          <div style={{ marginTop: 16, padding: "10px 12px", borderRadius: 8, background: "rgba(255,90,31,.12)", border: "1px solid rgba(255,90,31,.4)", color: "#ff5a1f", fontSize: 13 }}>
            {error}
          </div>
        )}

        <div className="onb-actions">
          <button className="btn btn-text" onClick={goBack} disabled={busy}>← {t.onb.back}</button>
          <button className="btn btn-primary btn-lg" onClick={goNext} disabled={busy}>
            {busy ? "…" : (step === 2 ? t.onb.finalize : t.onb.next)} <Icon.arrow/>
          </button>
        </div>
      </main>
    </div>
  );
}

function StepProject({ t, lang, proj, setProj }) {
  return (
    <>
      <h2>{t.onb.title}</h2>
      <p className="sub">{t.onb.sub}</p>
      <div className="onb-form">
        <div className="onb-row-2">
          <div className="field">
            <label>{t.onb.project_name}</label>
            <input value={proj.name} onChange={e => setProj({ ...proj, name: e.target.value })} placeholder={t.onb.project_name_ph} autoFocus/>
          </div>
          <div className="field">
            <label>{t.onb.company_name}</label>
            <input value={proj.company} onChange={e => setProj({ ...proj, company: e.target.value })} placeholder={t.onb.company_name_ph} />
          </div>
        </div>
        <div className="field">
          <label>{t.onb.website}</label>
          <input value={proj.website} onChange={e => setProj({ ...proj, website: e.target.value })} placeholder={t.onb.website_ph} />
          <span className="hint">{lang === "fr" ? "Si vous en avez un, on l'analyse pour gagner du temps." : "If you have one, we'll parse it to save you time."}</span>
        </div>
      </div>
    </>
  );
}

function StepDescription({ t, lang, proj, setProj }) {
  return (
    <>
      <h2>{lang === "fr" ? "En quoi ça consiste ?" : "What's it about?"}</h2>
      <p className="sub">{lang === "fr" ? "Deux phrases suffisent. On extrapolera." : "Two sentences will do. We'll extrapolate."}</p>
      <div className="onb-form">
        <div className="field">
          <label>{t.onb.description}</label>
          <textarea value={proj.description} onChange={e => setProj({ ...proj, description: e.target.value })} placeholder={t.onb.description_ph} rows="6"></textarea>
          <span className="hint">{t.onb.hint_desc}</span>
        </div>
        <div className="field">
          <label>{t.onb.sector}</label>
          <div className="chips">
            {t.onb.sector_options.map((s, i) => (
              <button key={i} type="button"
                className={`chip ${proj.sector === s ? "selected" : ""}`}
                onClick={() => setProj({ ...proj, sector: s })}>
                {s}
              </button>
            ))}
          </div>
        </div>
      </div>
    </>
  );
}

function StepPlan({ t, lang, proj, setProj }) {
  return (
    <>
      <h2>{lang === "fr" ? "Quel niveau d'autonomie ?" : "What level of autonomy?"}</h2>
      <p className="sub">{lang === "fr" ? "Vous pouvez ajuster à tout moment." : "Adjust any time."}</p>
      <div className="onb-form" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
        {t.pricing.tiers.map((tr, i) => {
          const selected = proj.plan === tr.name;
          return (
            <button key={tr.name} type="button"
              onClick={() => setProj({ ...proj, plan: tr.name })}
              style={{
                textAlign: "left",
                padding: 18,
                background: selected ? "var(--surface-2)" : "var(--surface)",
                border: `1px solid ${selected ? "var(--accent)" : "var(--border)"}`,
                borderRadius: 12,
                cursor: "pointer",
                display: "flex", flexDirection: "column", gap: 6,
                position: "relative",
              }}>
              {tr.highlight && <span style={{ position: "absolute", top: 12, right: 12, fontSize: 10, color: "var(--accent)", fontFamily: "var(--font-mono)", letterSpacing: "0.08em", textTransform: "uppercase" }}>{tr.highlight_label}</span>}
              <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
                <span style={{ fontWeight: 600, fontSize: 16 }}>{tr.name}</span>
                <span style={{ color: "var(--muted)", fontSize: 13 }}>{tr.price}{tr.price !== "Sur-mesure" && tr.price !== "Custom" ? t.pricing.per_month : ""}</span>
              </div>
              <span style={{ color: "var(--text-2)", fontSize: 13 }}>{tr.tagline}</span>
              <span style={{ marginTop: 4, fontSize: 12, fontFamily: "var(--font-mono)", color: "var(--muted)" }}>{tr.features[1]}</span>
            </button>
          );
        })}
      </div>
      <div style={{ marginTop: 16, fontSize: 13, color: "var(--muted)" }}>
        {lang === "fr" ? "Pas sûr ? " : "Not sure? "}
        <button style={{ color: "var(--accent)", textDecoration: "underline" }}>{lang === "fr" ? "Voir les détails complets →" : "See full details →"}</button>
      </div>
    </>
  );
}

// ── PRICING (standalone full page) ──────────────────────────────
function Pricing({ t, goto, lang }) {
  const [yearly, setYearly] = useState(false);
  return (
    <div className="pricing">
      <div className="container">
        <div className="head">
          <h2>{t.pricing.title}</h2>
          <p className="sub">{t.pricing.sub}</p>
          <div className="billing-toggle">
            <button className={!yearly ? "on" : ""} onClick={() => setYearly(false)}>{t.pricing.monthly}</button>
            <button className={yearly ? "on" : ""} onClick={() => setYearly(true)}>{t.pricing.yearly} <span className="save">{t.pricing.yearly_off}</span></button>
          </div>
        </div>

        <div className="tiers">
          {t.pricing.tiers.map((tr, i) => {
            const isEnterprise = tr.price === "Sur-mesure" || tr.price === "Custom";
            const yearlyPrice = !isEnterprise && yearly
              ? tr.price.replace(/(\d+)/, (m) => Math.round(parseInt(m) * 0.8))
              : tr.price;
            return (
              <div key={tr.name} className={`tier ${tr.highlight ? "highlight" : ""}`}>
                {tr.highlight && <span className="badge">{tr.highlight_label}</span>}
                <div>
                  <div className="name">{tr.name}</div>
                  <div className="tagline">{tr.tagline}</div>
                </div>
                <div className="price-row">
                  <span className="price">{yearlyPrice}</span>
                  {!isEnterprise && <span className="period">{t.pricing.per_month}</span>}
                </div>
                <ul>
                  {tr.features.map((f, j) => (
                    <li key={j}><span className="check"></span><span>{f}</span></li>
                  ))}
                </ul>
                <button className={`btn ${tr.highlight ? "btn-primary" : "btn-ghost"} btn-lg`} onClick={() => goto("dashboard")}>
                  {isEnterprise ? t.pricing.cta_enterprise : t.pricing.cta} <Icon.arrow/>
                </button>
              </div>
            );
          })}
        </div>

        <div className="faq">
          <h3>{t.pricing.faq_title}</h3>
          {t.pricing.faq.map((f, i) => (
            <div className="faq-row" key={i}>
              <div className="faq-q">{f.q}</div>
              <div className="faq-a">{f.a}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Onboarding, Pricing });
