/* global React, ReactDOM, lecygne,
   ScreenDashboard, ScreenCommandes, ScreenClients, ScreenCatalogue,
   ScreenParametres, ScreenUtilisateurs */
// =====================================================================
// Le Cygne — coquille applicative : authentification, barre latérale
// (avec section Administration), routage et application du branding.
// Chargé en DERNIER : il référence les composants d'écran globaux.
// =====================================================================

const { useState, useEffect, useCallback } = React;

// ---- Thème clair / sombre (mémorisé dans localStorage) ----------------
function getTheme() {
  try { return localStorage.getItem("lecygne-theme") || "light"; } catch (_) { return "light"; }
}
function applyTheme(theme) {
  document.documentElement.setAttribute("data-theme", theme);
  try { localStorage.setItem("lecygne-theme", theme); } catch (_) {}
}
applyTheme(getTheme()); // appliqué dès le chargement (pas de flash)

function ThemeToggle({ full }) {
  const [theme, setTheme] = useState(getTheme());
  function toggle() {
    const next = theme === "dark" ? "light" : "dark";
    setTheme(next); applyTheme(next);
  }
  return (
    <button className="btn sm" onClick={toggle}
      title="Basculer le thème" style={full ? { width: "100%", justifyContent: "center" } : null}>
      <Icon name={theme === "dark" ? "sun" : "moon"} size={15} />
      {theme === "dark" ? "Mode clair" : "Mode sombre"}
    </button>
  );
}

// ---- Application du branding société sur le thème ---------------------
function applyBranding(company) {
  if (!company) return;
  const root = document.documentElement;
  if (company.primary_color) root.style.setProperty("--primary", company.primary_color);
  document.title = `${company.display_name || "Le Cygne"} — Gestion pressing`;
}

// ---- Marque (logo + nom) — réutilisée sidebar + login -----------------
function Brand({ company }) {
  const name = (company && company.display_name) || "Le Cygne";
  const logo = company && company.logo_url;
  return (
    <div className="brand">
      {logo
        ? <img src={logo} alt={name} />
        : <span className="brand-mark">⚜</span>}
      <span>{name}</span>
    </div>
  );
}

// =====================================================================
//  Écran de connexion
// =====================================================================
function AuthScreen({ company }) {
  const [mode, setMode] = useState("signin"); // signin | signup
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [fullName, setFullName] = useState("");
  const [err, setErr] = useState("");
  const [busy, setBusy] = useState(false);

  async function submit(e) {
    e.preventDefault();
    setErr(""); setBusy(true);
    try {
      const res = mode === "signin"
        ? await lecygne.auth.signIn(email, password)
        : await lecygne.auth.signUp(email, password, fullName);
      if (res.error) setErr(res.error.message);
      else if (mode === "signup" && !res.data.session)
        setErr("Compte créé. Vérifiez votre e-mail pour confirmer, puis connectez-vous.");
    } catch (e) { setErr(String(e.message || e)); }
    finally { setBusy(false); }
  }

  return (
    <div className="auth-wrap">
      <form className="auth-card" onSubmit={submit}>
        <div style={{ display: "flex", justifyContent: "flex-end", marginBottom: -8 }}>
          <ThemeToggle />
        </div>
        <Brand company={company} />
        <p className="sub">Gestion pressing / blanchisserie</p>
        {mode === "signup" && (<>
          <label>Nom complet</label>
          <input className="field" value={fullName} onChange={(e) => setFullName(e.target.value)} required />
        </>)}
        <label>E-mail</label>
        <input className="field" type="email" value={email} onChange={(e) => setEmail(e.target.value)} required />
        <label>Mot de passe</label>
        <input className="field" type="password" value={password} onChange={(e) => setPassword(e.target.value)} required />
        {err && <div className="auth-err">{err}</div>}
        <button className="btn primary" disabled={busy}>
          {busy ? "…" : mode === "signin" ? "Se connecter" : "Créer le compte"}
        </button>
        <p className="hint" style={{ textAlign: "center", marginTop: 14 }}>
          {mode === "signin"
            ? <>Pas de compte ? <a href="#" onClick={(e) => { e.preventDefault(); setMode("signup"); setErr(""); }}>Créer un compte</a></>
            : <>Déjà un compte ? <a href="#" onClick={(e) => { e.preventDefault(); setMode("signin"); setErr(""); }}>Se connecter</a></>}
        </p>
      </form>
    </div>
  );
}

// =====================================================================
//  Navigation
// =====================================================================
const NAV = [
  { group: "Exploitation", items: [
    { id: "dashboard",  ico: "home",    label: "Tableau de bord" },
    { id: "commandes",  ico: "receipt", label: "Commandes" },
    { id: "factures",   ico: "file",    label: "Factures & BL" },
    { id: "clients",    ico: "users",   label: "Clients" },
    { id: "catalogue",  ico: "tag",     label: "Catalogue & tarifs" },
  ]},
  { group: "Administration", adminOnly: true, items: [
    { id: "parametres",   ico: "settings", label: "Paramètres société" },
    { id: "utilisateurs", ico: "userCog",  label: "Utilisateurs" },
    { id: "audit",        ico: "history",  label: "Journal d'audit" },
  ]},
  { group: "Super-administration", superAdminOnly: true, items: [
    { id: "societes", ico: "building", label: "Sociétés & licences" },
  ]},
];

function Sidebar({ company, profile, route, setRoute, onSignOut, onOpenSearch }) {
  const isAdmin = profile && (profile.role === "admin" || profile.is_super_admin);
  const isSuper = profile && profile.is_super_admin;
  return (
    <aside className="side">
      <Brand company={company} />
      <button className="side-search" onClick={onOpenSearch}>
        Rechercher… <kbd>Ctrl K</kbd>
      </button>
      {NAV.map((grp) => {
        if (grp.adminOnly && !isAdmin) return null;
        if (grp.superAdminOnly && !isSuper) return null;
        return (
          <div key={grp.group}>
            <div className="nav-group">{grp.group}</div>
            {grp.items.map((it) => (
              <button key={it.id}
                className={"nav" + (route === it.id ? " active" : "")}
                onClick={() => setRoute(it.id)}>
                <span className="ico"><Icon name={it.ico} /></span>{it.label}
              </button>
            ))}
          </div>
        );
      })}
      <div className="side-foot">
        <div className="who">
          {profile && profile.full_name}<br />
          <span style={{ color: "var(--hint)" }}>{profile && profile.role}</span>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
          <ThemeToggle full />
          <button className="btn sm" onClick={onSignOut}>↩ Se déconnecter</button>
        </div>
      </div>
    </aside>
  );
}

// =====================================================================
//  Routeur d'écrans
// =====================================================================
function ScreenRouter({ route, ctx }) {
  switch (route) {
    case "dashboard":    return <ScreenDashboard ctx={ctx} />;
    case "commandes":    return <ScreenCommandes ctx={ctx} />;
    case "factures":     return <ScreenFactures ctx={ctx} />;
    case "clients":      return <ScreenClients ctx={ctx} />;
    case "catalogue":    return <ScreenCatalogue ctx={ctx} />;
    case "parametres":   return <ScreenParametres ctx={ctx} />;
    case "utilisateurs": return <ScreenUtilisateurs ctx={ctx} />;
    case "audit":        return <ScreenAudit ctx={ctx} />;
    case "societes":     return <ScreenSocietes ctx={ctx} />;
    default:             return <ScreenDashboard ctx={ctx} />;
  }
}

// =====================================================================
//  Racine
// =====================================================================
function LicenseBlock({ company, license, onSignOut }) {
  const st = (license && lecygne.LICENSE_STATUS[license.status]) || {};
  return (
    <div className="auth-wrap">
      <div className="auth-card">
        <Brand company={company} />
        <p className="sub">Accès suspendu</p>
        <div className="auth-err" style={{ marginTop: 0 }}>
          La licence de « {company && company.display_name} » est <b>{(st.fr || "inactive").toLowerCase()}</b>
          {license && license.end_date ? ` (échéance : ${lecygne.fmtDate(license.end_date)})` : ""}.<br />
          Contactez votre prestataire (REFT Africa) pour la réactiver.
        </div>
        <button className="btn" style={{ width: "100%", justifyContent: "center", marginTop: 16 }}
          onClick={onSignOut}>↩ Se déconnecter</button>
      </div>
    </div>
  );
}

function App() {
  const [session, setSession] = useState(undefined); // undefined = en cours
  const [company, setCompany] = useState(null);
  const [profile, setProfile] = useState(null);
  const [license, setLicense] = useState(undefined); // undefined = en cours
  const [route, setRoute] = useState("dashboard");
  const [bootError, setBootError] = useState("");
  const [seed, setSeed] = useState(null);            // pré-remplissage recherche écran
  const [paletteOpen, setPaletteOpen] = useState(false);

  function navTo(r, term) {
    setRoute(r);
    setSeed({ route: r, term: term || "", n: (seed ? seed.n : 0) + 1 });
  }

  // Raccourci global Ctrl/Cmd+K → palette de recherche
  useEffect(() => {
    function onKey(e) {
      if ((e.ctrlKey || e.metaKey) && (e.key === "k" || e.key === "K")) {
        e.preventDefault(); setPaletteOpen((o) => !o);
      }
    }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  // Branding chargé tôt (visible aussi sur l'écran de connexion)
  const reloadCompany = useCallback(async () => {
    const c = await lecygne.company.getActive();
    setCompany(c); applyBranding(c);
  }, []);

  useEffect(() => {
    lecygne.auth.getSession().then((s) => setSession(s || null));
    const off = lecygne.auth.onChange((s) => {
      lecygne._clearProfileCache();
      setSession(s || null);
    });
    return off;
  }, []);

  useEffect(() => { reloadCompany(); }, [reloadCompany, session]);

  useEffect(() => {
    if (!session) { setProfile(null); return; }
    lecygne._clearProfileCache();
    lecygne.getProfile().then(setProfile).catch((e) => setBootError(String(e)));
  }, [session]);

  // Licence de la société (le super-admin n'est jamais bloqué)
  useEffect(() => {
    if (!profile) { setLicense(undefined); return; }
    if (profile.is_super_admin) { setLicense(null); setRoute("societes"); return; }
    lecygne.license.getForCurrent().then((l) => setLicense(l || null));
  }, [profile]);

  if (session === undefined) return <div className="spinner">Chargement…</div>;
  if (!session) return <AuthScreen company={company} />;
  if (!profile) return <div className="spinner">Chargement du profil…</div>;

  const isSuper = profile.is_super_admin;
  if (!isSuper && license === undefined) return <div className="spinner">Vérification de la licence…</div>;
  if (!isSuper && !lecygne.license.isActive(license))
    return <LicenseBlock company={company} license={license} onSignOut={() => lecygne.auth.signOut()} />;

  const ctx = { company, profile, license, reloadCompany, setRoute, navTo, seed };

  return (
    <div className="app">
      <Sidebar company={company} profile={profile} route={route} setRoute={setRoute}
        onSignOut={() => lecygne.auth.signOut()} onOpenSearch={() => setPaletteOpen(true)} />
      <main className="main">
        {bootError && <div className="auth-err">{bootError}</div>}
        <ScreenRouter route={route} ctx={ctx} />
      </main>
      <CommandPalette open={paletteOpen} onClose={() => setPaletteOpen(false)} navTo={navTo} />
    </div>
  );
}

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