/* ============================================================
   ensō rse — Quizz onboarding · app shell + routeur + accueil
   ============================================================ */

const ACCENTS = {
  env: { "--accent-500": "#00AF8F", "--accent-600": "#00997D", "--accent-700": "#006956", "--accent-200": "#D7F4EE", "--accent-100": "#F5FFFC" },
  soc: { "--accent-500": "#973CE7", "--accent-600": "#8F0DF2", "--accent-700": "#6109B3", "--accent-200": "#E4CFFC", "--accent-100": "#FAF5FE" },
  gov: { "--accent-500": "#FE7C48", "--accent-600": "#F7703B", "--accent-700": "#B03707", "--accent-200": "#FFDBCC", "--accent-100": "#FFF8F5" }
};

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "env",
  "textScale": 16,
  "resultView": "both",
  "showEnsoMotif": true
} /*EDITMODE-END*/;

/* ---------- Accès manager ----------
   Mot de passe de l'espace manager. Pour le changer : modifie la valeur ci-dessous.
   (Protection simple côté navigateur — suffisante pour un usage interne.) */
const MANAGER_PASSWORD = "enso-manager";
const MGR_UNLOCK_KEY = "enso_mgr_ok_v1";

function ManagerGate({ onUnlock, onBack }) {
  const [pw, setPw] = useState("");
  const [err, setErr] = useState(false);
  const submit = () => {
    if (pw === MANAGER_PASSWORD) {
      try { sessionStorage.setItem(MGR_UNLOCK_KEY, "1"); } catch (e) {}
      onUnlock();
    } else { setErr(true); }
  };
  return (
    <div className="fade-up" style={{ maxWidth: 440, margin: "0 auto", padding: "8px 24px", minHeight: "100%", display: "flex", flexDirection: "column", justifyContent: "center" }}>
      <div style={{ background: "var(--bg-surface)", border: "1px solid var(--border-default)", borderRadius: "var(--r-xl)", padding: 34, boxShadow: "var(--shadow-md)" }}>
        <div style={{ width: 56, height: 56, borderRadius: 16, background: "var(--color-soc-100)", display: "grid", placeItems: "center", color: "var(--color-soc-600)", marginBottom: 20 }}>
          <Icon name="shield" size={28} />
        </div>
        <h1 style={{ fontSize: "var(--fs-2xl)", marginBottom: 8 }}>Espace manager protégé</h1>
        <p className="muted" style={{ fontSize: "var(--fs-base)", lineHeight: 1.5, marginBottom: 22 }}>
          Saisis le mot de passe pour accéder aux résultats des recrues.
        </p>
        <label style={{ fontWeight: 600, fontSize: "var(--fs-sm)", display: "block", marginBottom: 8 }}>Mot de passe</label>
        <input type="password" value={pw} autoFocus
          onChange={(e) => { setPw(e.target.value); setErr(false); }}
          onKeyDown={(e) => { if (e.key === "Enter") submit(); }}
          placeholder="••••••••"
          style={{ width: "100%", padding: "13px 16px", borderRadius: "var(--r-md)", fontFamily: "var(--font-body)", fontSize: "var(--fs-base)",
            border: err ? "1.5px solid var(--danger-500)" : "1px solid var(--border-strong)", background: "#fff", color: "var(--fg-default)", marginBottom: err ? 8 : 20 }} />
        {err && <div style={{ color: "var(--danger-fg)", fontSize: "var(--fs-sm)", marginBottom: 16, display: "flex", alignItems: "center", gap: 6 }}>
          <Icon name="alert-triangle" size={15} /> Mot de passe incorrect.
        </div>}
        <div style={{ display: "flex", gap: 10 }}>
          <Btn variant="ghost" icon="arrow-left" onClick={onBack}>Retour</Btn>
          <Btn variant="primary" iconRight="arrow-right" full onClick={submit}>Entrer</Btn>
        </div>
      </div>
    </div>);

}

/* ---------- accueil (choix du rôle) ---------- */
function HomeScreen({ onPick }) {
  const cards = [
  { k: "recrue", icon: "graduation-cap", title: "Je suis une recrue", color: "var(--color-env-500)",
    desc: "Passe ton quizz d'arrivée ou retrouve ton espace : tes résultats, ta progression et ton programme de formation.",
    cta: "Accéder à mon espace", tone: "env" },
  { k: "manager", icon: "users", title: "Je suis manager", color: "var(--color-soc-500)",
    desc: "Consulte les niveaux d'entrée de tes recrues, repère les lacunes et reçois des pistes pour adapter ton discours.",
    cta: "Voir l'espace manager", tone: "soc" }];

  return (
    <div className="fade-up" style={{ maxWidth: 980, margin: "0 auto", padding: "40px 24px 60px", minHeight: "100%", display: "flex", flexDirection: "column", justifyContent: "center" }}>
      <div style={{ textAlign: "center", marginBottom: 46 }}>
        <div style={{ display: "inline-flex", marginBottom: 22 }}><Logo height={42} /></div>
        <h1 style={{ fontSize: "var(--fs-4xl)", lineHeight: 1.05, marginBottom: 14, letterSpacing: "-0.02em" }}>
          La RSE devient <span style={{ color: "var(--color-env-500)" }}>simple</span>.
        </h1>
        <p className="muted" style={{ fontSize: "var(--fs-lg)", maxWidth: 600, margin: "0 auto", lineHeight: 1.5 }}>Le quizz d'onboarding ensō rse : on mesure ce que tu sais déjà pour construire un parcours qui te ressemble et le remesurer après quelques semaines.

        </p>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 22 }}>
        {cards.map((c) =>
        <HomePick key={c.k} c={c} onClick={() => onPick(c.k)} />
        )}
      </div>
    </div>);

}
function HomePick({ c, onClick }) {
  const [h, setH] = useState(false);
  return (
    <div onClick={onClick} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
    style={{ background: "var(--bg-surface)", border: "1px solid var(--border-default)", borderRadius: "var(--r-xl)",
      padding: 32, cursor: "pointer", transition: "box-shadow .22s var(--ease-out), transform .22s, border-color .22s",
      boxShadow: h ? "var(--shadow-lg)" : "var(--shadow-sm)", transform: h ? "translateY(-3px)" : "none",
      borderColor: h ? c.color : "var(--border-default)", display: "flex", flexDirection: "column", gap: 18 }}>
      <div style={{ width: 60, height: 60, borderRadius: 16, background: `color-mix(in srgb, ${c.color} 12%, white)`, display: "grid", placeItems: "center", color: c.color }}>
        <Icon name={c.icon} size={30} />
      </div>
      <div>
        <h2 style={{ fontSize: "var(--fs-xl)", marginBottom: 8 }}>{c.title}</h2>
        <p className="muted" style={{ fontSize: "var(--fs-base)", lineHeight: 1.5 }}>{c.desc}</p>
      </div>
      <div style={{ display: "inline-flex", alignItems: "center", gap: 8, fontWeight: 600, color: c.color, marginTop: "auto" }}>
        {c.cta} <Icon name="arrow-right" size={18} style={{ transform: h ? "translateX(3px)" : "none", transition: "transform .16s" }} />
      </div>
    </div>);

}

/* ---------- header ---------- */
function Header({ view, onHome, onSwitch }) {
  return (
    <header style={{ height: 60, flex: "none", background: "rgba(255,255,255,.9)", backdropFilter: "blur(10px)",
      borderBottom: "1px solid var(--border-default)", display: "flex", alignItems: "center", justifyContent: "space-between", padding: "0 24px", zIndex: 20 }}>
      <button onClick={onHome} style={{ background: "none", border: "none", padding: 0, display: "flex", alignItems: "center", gap: 10, cursor: "pointer" }}>
        <Logo height={26} />
        <span style={{ height: 20, width: 1, background: "var(--border-strong)" }} />
        <span style={{ fontFamily: "var(--font-body)", fontWeight: 600, fontSize: "var(--fs-sm)", color: "var(--fg-muted)" }}>Quizz onboarding</span>
      </button>
      {view !== "home" &&
      <div style={{ display: "flex", gap: 4, background: "var(--color-neutral-50)", borderRadius: "var(--r-pill)", padding: 4, border: "1px solid var(--border-default)" }}>
          {[{ k: "recrue", l: "Recrue", ic: "graduation-cap" }, { k: "manager", l: "Manager", ic: "users" }].map((o) => {
          const on = view === o.k;
          return (
            <button key={o.k} onClick={() => onSwitch(o.k)}
            style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "7px 16px", borderRadius: "var(--r-pill)", border: "none",
              background: on ? "var(--bg-surface)" : "transparent", boxShadow: on ? "var(--shadow-xs)" : "none",
              fontFamily: "var(--font-body)", fontWeight: 600, fontSize: "var(--fs-sm)", color: on ? "var(--accent-700)" : "var(--fg-muted)", cursor: "pointer", transition: "all .15s" }}>
                <Icon name={o.ic} size={16} />{o.l}
              </button>);

        })}
        </div>
      }
    </header>);

}

/* ---------- app ---------- */
function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [view, setView] = useState("home");
  const [recrueInitial, setRecrueInitial] = useState(null);
  const [mgr, setMgr] = useState({ screen: "list", id: null });
  const [ret, setRet] = useState(null); // return target after recrue flow
  const [tick, setTick] = useState(0); // force refresh after store writes
  const [mgrUnlocked, setMgrUnlocked] = useState(() => {
    try { return sessionStorage.getItem(MGR_UNLOCK_KEY) === "1"; } catch (e) { return false; }
  });

  // apply tweaks → CSS vars
  useEffect(() => {
    const root = document.documentElement;
    const acc = ACCENTS[t.accent] || ACCENTS.env;
    Object.entries(acc).forEach(([k, v]) => root.style.setProperty(k, v));
    document.body.style.fontSize = t.textScale + "px";
    window.__viz = t.resultView;
    window.__motif = t.showEnsoMotif;
  }, [t.accent, t.textScale, t.resultView, t.showEnsoMotif]);

  // re-render quand la base partagée (SQLite) se synchronise au boot
  useEffect(() => {
    const h = () => setTick(x => x + 1);
    window.addEventListener("enso-store-changed", h);
    return () => window.removeEventListener("enso-store-changed", h);
  }, []);

  const goHome = () => {setView("home");setRecrueInitial(null);setMgr({ screen: "list", id: null });setRet(null);};
  const switchMode = (m) => {
    if (m === "recrue") {setRecrueInitial(null);setRet(null);setView("recrue");} else
    if (mgrUnlocked) {setMgr({ screen: "list", id: null });setView("manager");} else
    {setView("managerLock");}
  };

  // manager triggers a recruit's quiz
  const passQuiz = (id) => {
    const r = window.Store.get(id);
    setRecrueInitial(r);setRet({ view: "manager", mgr: { screen: "detail", id } });setView("recrue");
  };
  const afterRecrue = () => {
    setTick((x) => x + 1);
    if (ret) {setView(ret.view);setMgr(ret.mgr);setRet(null);setRecrueInitial(null);} else
    goHome();
  };

  return (
    <div style={{ height: "100vh", display: "flex", flexDirection: "column", overflow: "hidden" }}>
      {window.__motif !== false &&
      <div aria-hidden="true" style={{ position: "fixed", top: -160, right: -160, width: 520, height: 520, pointerEvents: "none", opacity: .5, zIndex: 0 }}>
          <EnsoRing size={520} stroke={3} color="var(--color-env-200)" track="transparent" pct={100} />
        </div>
      }
      <Header view={view} onHome={goHome} onSwitch={switchMode} />
      <main style={{ flex: 1, overflow: "auto", position: "relative", zIndex: 1 }}>
        {view === "home" && <HomeScreen onPick={switchMode} />}
        {view === "managerLock" &&
        <ManagerGate
          onUnlock={() => { setMgrUnlocked(true); setMgr({ screen: "list", id: null }); setView("manager"); }}
          onBack={goHome} />
        }
        {view === "recrue" && <RecrueFlow key={recrueInitial?.id || "new" + tick} initialRecruit={recrueInitial} onHome={afterRecrue} />}
        {view === "manager" &&
        <div style={{ padding: "32px 24px" }}>
            {mgr.screen === "list" ?
          <ManagerHome key={tick} onOpen={(id) => setMgr({ screen: "detail", id })} onInvite={() => setView("recrue")} /> :
          <RecruitDetail key={tick + mgr.id} id={mgr.id} onBack={() => setMgr({ screen: "list", id: null })} onPassQuiz={passQuiz} />}
          </div>
        }
      </main>

      <TweaksPanel title="Tweaks">
        <TweakSection label="Identité" />
        <TweakColor label="Couleur d'accent" value={t.accent === "env" ? "#00AF8F" : t.accent === "soc" ? "#973CE7" : "#FE7C48"}
        options={["#00AF8F", "#973CE7", "#FE7C48"]}
        onChange={(v) => setTweak("accent", v === "#00AF8F" ? "env" : v === "#973CE7" ? "soc" : "gov")} />
        <TweakToggle label="Motif ensō en filigrane" value={t.showEnsoMotif} onChange={(v) => setTweak("showEnsoMotif", v)} />
        <TweakSection label="Lisibilité" />
        <TweakSlider label="Taille du texte" value={t.textScale} min={14} max={18} step={1} unit="px" onChange={(v) => setTweak("textScale", v)} />
        <TweakSection label="Résultat recrue" />
        <TweakRadio label="Affichage" value={t.resultView} options={["both", "radar", "bars"]}
        onChange={(v) => setTweak("resultView", v)} />
      </TweaksPanel>
    </div>);

}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);