// Onboarding overlay — 3-step welcome flow
window.OnboardingOverlay = function OnboardingOverlay({ t, lang, onClose }) {
  const [step, setStep] = React.useState(0);
  const Icons = window.Icons;
  const [picked, setPicked] = React.useState(new Set(["invoices", "docs", "tasks"]));

  const steps = [
    { id: "welcome", title: t("welcome"), desc: t("onb_sub") },
    { id: "company", title: t("step_company"), desc: lang === "es" ? "Empezamos con los datos de tu empresa." : "Let's start with your company details." },
    { id: "modules", title: t("step_modules"), desc: lang === "es" ? "Activa los módulos que vas a usar — los podrás cambiar después." : "Enable the modules you'll use — you can change this later." },
    { id: "team", title: t("step_team"), desc: lang === "es" ? "Invita a tu equipo. O sáltatelo y hazlo más tarde." : "Invite your team. Or skip and do it later." },
  ];

  const cur = steps[step];

  const moduleOpts = [
    { id: "invoices", label: t("invoices"), icon: "FileText" },
    { id: "docs", label: t("docs"), icon: "Book" },
    { id: "drive", label: t("drive"), icon: "Folder" },
    { id: "tasks", label: t("tasks"), icon: "Kanban" },
    { id: "chat", label: t("chat"), icon: "Chat" },
    { id: "social", label: t("social"), icon: "Megaphone" },
    { id: "servers", label: t("servers"), icon: "Server" },
  ];

  const toggle = (id) => {
    const next = new Set(picked);
    if (next.has(id)) next.delete(id); else next.add(id);
    setPicked(next);
  };

  return (
    <div className="onb-overlay">
      <div className="onb-card">
        {/* Progress dots */}
        <div style={{ display: "flex", gap: 6, marginBottom: 28 }}>
          {steps.map((s, i) => (
            <div key={i} style={{ flex: 1, height: 3, borderRadius: 2, background: i <= step ? "var(--brand)" : "var(--border)", transition: "background 200ms" }} />
          ))}
        </div>

        {step === 0 && (
          <div style={{ textAlign: "center" }}>
            <div style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 20 }}>
              <img src="assets/logo-small.png" alt="V" style={{ width: 56, height: 56 }} />
            </div>
            <h1 style={{ margin: 0, fontSize: 28, fontWeight: 700, letterSpacing: "-0.02em" }}>
              {t("welcome")}<span style={{ color: "var(--brand)" }}>.</span>
            </h1>
            <p style={{ color: "var(--text-muted)", margin: "10px 0 0", fontSize: 14, lineHeight: 1.55 }}>{cur.desc}</p>
          </div>
        )}

        {step === 1 && (
          <div>
            <h2 style={{ margin: 0, fontSize: 20, fontWeight: 600, letterSpacing: "-0.01em" }}>{cur.title}</h2>
            <p style={{ color: "var(--text-muted)", margin: "6px 0 20px", fontSize: 13 }}>{cur.desc}</p>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
              <label className="field">{lang === "es" ? "Nombre legal" : "Legal name"}<input className="input" placeholder="Vildez SL" /></label>
              <label className="field">{lang === "es" ? "ID fiscal" : "Tax ID"}<input className="input" placeholder="B-00000000" /></label>
              <label className="field">{lang === "es" ? "País" : "Country"}<input className="input" defaultValue={lang === "es" ? "España" : "Spain"} /></label>
              <label className="field">{lang === "es" ? "Industria" : "Industry"}<input className="input" placeholder="SaaS / Tech" /></label>
              <label className="field" style={{ gridColumn: "1 / -1" }}>{lang === "es" ? "Tamaño del equipo" : "Team size"}
                <div className="tab-bar" style={{ width: "fit-content" }}>
                  {["1", "2-5", "6-15", "16-50", "50+"].map(s => (
                    <button key={s} className={s === "2-5" ? "active" : ""}>{s}</button>
                  ))}
                </div>
              </label>
            </div>
          </div>
        )}

        {step === 2 && (
          <div>
            <h2 style={{ margin: 0, fontSize: 20, fontWeight: 600, letterSpacing: "-0.01em" }}>{cur.title}</h2>
            <p style={{ color: "var(--text-muted)", margin: "6px 0 20px", fontSize: 13 }}>{cur.desc}</p>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8 }}>
              {moduleOpts.map(m => {
                const Ic = window.Icons[m.icon];
                const on = picked.has(m.id);
                return (
                  <button key={m.id} onClick={() => toggle(m.id)}
                    style={{
                      padding: "12px 10px",
                      border: `1px solid ${on ? "var(--brand)" : "var(--border)"}`,
                      borderRadius: "var(--r)",
                      background: on ? "var(--brand-soft)" : "var(--bg-elev)",
                      color: "var(--text)",
                      cursor: "pointer",
                      display: "flex",
                      flexDirection: "column",
                      alignItems: "center",
                      gap: 6,
                      transition: "all 120ms",
                      fontFamily: "inherit",
                      fontSize: 12,
                      fontWeight: 500,
                    }}
                  >
                    <Ic style={{ width: 18, height: 18, color: on ? "var(--brand)" : "var(--text-muted)" }} />
                    {m.label}
                  </button>
                );
              })}
            </div>
          </div>
        )}

        {step === 3 && (
          <div>
            <h2 style={{ margin: 0, fontSize: 20, fontWeight: 600, letterSpacing: "-0.01em" }}>{cur.title}</h2>
            <p style={{ color: "var(--text-muted)", margin: "6px 0 20px", fontSize: 13 }}>{cur.desc}</p>
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              {[0, 1, 2].map(i => (
                <OnboardingInviteRow key={i} lang={lang} />
              ))}
              <button className="btn ghost" style={{ alignSelf: "flex-start", marginTop: 4 }}>
                <Icons.Plus /> {lang === "es" ? "Añadir otro" : "Add another"}
              </button>
            </div>
          </div>
        )}

        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 32, paddingTop: 20, borderTop: "1px solid var(--border)" }}>
          <button className="btn ghost" onClick={onClose}>{t("skip")}</button>
          <div style={{ display: "flex", gap: 8 }}>
            {step > 0 && <window.Btn variant="ghost" onClick={() => setStep(step - 1)}>{t("back")}</window.Btn>}
            {step < steps.length - 1 ? (
              <window.Btn variant="brand" onClick={() => setStep(step + 1)}>{t("continue")} →</window.Btn>
            ) : (
              <window.Btn variant="brand" onClick={onClose}>{t("finish")} →</window.Btn>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

function OnboardingInviteRow({ lang }) {
  const [role, setRole] = React.useState("member");
  return (
    <div style={{ display: "flex", gap: 8 }}>
      <input className="input" placeholder={lang === "es" ? "email@empresa.com" : "name@company.com"} style={{ flex: 1 }} />
      <window.Select
        value={role}
        onChange={setRole}
        width={130}
        options={[
          { value: "member", label: lang === "es" ? "Miembro" : "Member" },
          { value: "admin",  label: lang === "es" ? "Admin" : "Admin" },
        ]}
      />
    </div>
  );
}

Object.assign(window, { OnboardingOverlay: window.OnboardingOverlay });
