/* Paramètres — multi-section settings hub.
   Single source of truth: useTweaks state (passed in as `t` + `setTweak`).
   JARVIS Autopilot can also write here via the same setTweak handle. */

const SETTINGS_SECTIONS = [
  { id: "profile",       label: "Profil",           icon: "users" },
  { id: "appearance",    label: "Apparence",        icon: "sun" },
  { id: "layout",        label: "Mise en page",     icon: "grid" },
  { id: "regional",      label: "Régional",         icon: "calendar" },
  { id: "notifications", label: "Notifications",    icon: "bell" },
  { id: "data",          label: "Données & seuils", icon: "chart" },
  { id: "calc",          label: "ProfitCalc",       icon: "dollar" },
  { id: "security",      label: "Sécurité",         icon: "shield" },
  { id: "team",          label: "Équipe",           icon: "users" },
  { id: "updates",       label: "Mises à jour",      icon: "sparkles", badge: "v" + (window.KCC_VERSION || "3.4") },
  { id: "integrations",  label: "Intégrations",     icon: "link" },
  { id: "autopilot",     label: "JARVIS Autopilot", icon: "sparkles", badge: "IA" },
  { id: "trash",         label: "Corbeille",        icon: "trash" },
  { id: "advanced",      label: "Avancé",           icon: "wrench" },
];

// Trash bin section — restore or permanently delete any item moved to the bin from anywhere in the site.
const TrashSection = () => {
  const trash = (window.useKCCTrash || (() => ({ items: [], restore: () => {}, remove: () => {}, empty: () => {} })))();
  const toast = (window.useToast || (() => () => {}))();
  const items = trash.items || [];

  // Group by type for cleaner display
  const groups = items.reduce((acc, it) => {
    const t = it._kccType || "autre";
    (acc[t] = acc[t] || []).push(it);
    return acc;
  }, {});
  const typeKeys = Object.keys(groups);

  const labelFor = (it) => it.name || it.title || it.label || it.product || it.subject || it.id;

  const onRestore = async (id) => {
    const r = await trash.restore(id);
    toast?.({ message: r ? `Restauré : ${labelFor(r)}` : "Restauré", tone: "green" });
  };
  const onRemove = (it) => {
    if (!window.confirm(`Supprimer définitivement "${labelFor(it)}" ?`)) return;
    trash.remove(it.id);
    toast?.({ message: "Élément supprimé définitivement", tone: "muted" });
  };
  const onEmpty = () => {
    if (!items.length) return;
    if (!window.confirm(`Vider la corbeille ? ${items.length} élément(s) seront supprimés définitivement.`)) return;
    trash.empty();
    toast?.({ message: "Corbeille vidée", tone: "muted" });
  };

  return (
    <div className="stack" style={{ gap: 14 }}>
      <div className="between">
        <div>
          <div style={{ fontSize: 14, fontWeight: 600 }}>Corbeille</div>
          <div className="muted" style={{ fontSize: 11.5, marginTop: 2 }}>
            {items.length} élément(s) · restaure ou supprime définitivement
          </div>
        </div>
        <button className="btn" onClick={onEmpty} disabled={!items.length} style={{ color: items.length ? "var(--red)" : "var(--text-faint)" }}>
          <Icon name="trash" size={12}/> Vider la corbeille
        </button>
      </div>

      {items.length === 0 ? (
        <div className="card" style={{ padding: 30, textAlign: "center", color: "var(--text-faint)", fontSize: 13 }}>
          La corbeille est vide. Les éléments supprimés ailleurs dans le site apparaîtront ici.
        </div>
      ) : (
        <div className="stack" style={{ gap: 14 }}>
          {typeKeys.map(type => (
            <div key={type} className="card" style={{ padding: 12 }}>
              <div className="between" style={{ marginBottom: 8 }}>
                <div style={{ fontSize: 12.5, fontWeight: 600, textTransform: "capitalize" }}>
                  {window.KCCTrash?.entityLabel?.(type) || type} <span className="muted" style={{ fontWeight: 400 }}>({groups[type].length})</span>
                </div>
              </div>
              <div className="stack" style={{ gap: 6 }}>
                {groups[type].map(it => (
                  <div key={it.id} className="row between" style={{ padding: "8px 10px", borderRadius: 6, background: "var(--bg-3)" }}>
                    <div>
                      <div style={{ fontSize: 12.5, fontWeight: 550 }}>{labelFor(it)}</div>
                      <div className="muted" style={{ fontSize: 10.5 }}>
                        supprimé {it._trashedAt ? new Date(it._trashedAt).toLocaleString("fr-CA") : "—"}
                      </div>
                    </div>
                    <div className="row" style={{ gap: 6 }}>
                      <button className="btn" data-size="sm" onClick={() => onRestore(it.id)}>
                        <Icon name="refresh" size={11}/> Restaurer
                      </button>
                      <button className="btn" data-variant="ghost" data-size="sm" onClick={() => onRemove(it)} title="Supprimer définitivement">
                        <Icon name="x" size={11}/>
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

const GoogleCalendarIcon = ({ size = 22 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
    <rect x="3" y="4" width="18" height="17" rx="2" fill="#4285F4"/>
    <rect x="3" y="4" width="18" height="4" fill="#1A73E8"/>
    <text x="12" y="17" textAnchor="middle" fill="white" fontSize="9" fontWeight="700" fontFamily="Arial, sans-serif">31</text>
  </svg>
);

const ACCENTS = ["#5fa8ff", "#7c3aed", "#10b981", "#f59e0b", "#ec4899"];
const CURRENCIES = ["CAD", "USD", "EUR", "CNY"];
const LOCALES = ["fr-CA", "en-CA", "en-US", "fr-FR"];
const TIMEZONES = ["America/Montreal", "America/Toronto", "America/Los_Angeles", "Europe/Paris", "Asia/Shanghai"];

// Small reusable row helpers ─────────────────────────────────────────
const Row = ({ label, sub, children, hint }) => (
  <div style={{
    display: "grid", gridTemplateColumns: "1fr 280px",
    alignItems: "center", gap: 20,
    padding: "14px 0", borderBottom: "1px solid var(--border-subtle)",
  }}>
    <div>
      <div style={{ fontSize: 13, fontWeight: 500 }}>{label}</div>
      {sub && <div style={{ fontSize: 11.5, color: "var(--text-dim)", marginTop: 2 }}>{sub}</div>}
      {hint && <div className="mono" style={{ fontSize: 10.5, color: "var(--text-faint)", marginTop: 4 }}>{hint}</div>}
    </div>
    <div style={{ justifySelf: "end", display: "flex", alignItems: "center", gap: 8, minWidth: 0 }}>{children}</div>
  </div>
);

const Segmented = ({ value, onChange, options }) => (
  <div style={{ display: "flex", background: "var(--bg-2)", border: "1px solid var(--border-subtle)", borderRadius: 7, padding: 2 }}>
    {options.map(o => (
      <button key={o.value ?? o} onClick={() => onChange(o.value ?? o)} style={{
        height: 26, padding: "0 10px", borderRadius: 5, fontSize: 11.5,
        background: (value === (o.value ?? o)) ? "var(--bg-4)" : "transparent",
        color: (value === (o.value ?? o)) ? "var(--text)" : "var(--text-dim)",
        fontWeight: (value === (o.value ?? o)) ? 600 : 400,
        cursor: "pointer", border: "none",
      }}>{o.label ?? o}</button>
    ))}
  </div>
);

const Toggle = ({ value, onChange }) => (
  <button onClick={() => onChange(!value)} style={{
    width: 36, height: 20, borderRadius: 999, position: "relative",
    background: value ? "var(--accent)" : "var(--bg-4)",
    transition: "background 150ms", border: "none", cursor: "pointer", padding: 0,
  }}>
    <div style={{
      position: "absolute", top: 2, left: value ? 18 : 2,
      width: 16, height: 16, borderRadius: "50%", background: "#fff",
      transition: "left 150ms", boxShadow: "0 1px 2px oklch(0 0 0 / 0.3)",
    }}/>
  </button>
);

const NumberInput = ({ value, onChange, prefix = "", suffix = "", width = 100 }) => (
  <div style={{ display: "flex", alignItems: "center", gap: 4 }}>
    {prefix && <span className="mono" style={{ fontSize: 12, color: "var(--text-dim)" }}>{prefix}</span>}
    <input type="number" value={value} onChange={(e) => onChange(Number(e.target.value))}
      style={{ width, height: 28, padding: "0 8px", background: "var(--bg-2)", border: "1px solid var(--border)", borderRadius: 6, color: "var(--text)", fontSize: 12.5, fontFamily: "var(--font-mono)" }}/>
    {suffix && <span className="mono" style={{ fontSize: 12, color: "var(--text-dim)" }}>{suffix}</span>}
  </div>
);

const Select = ({ value, onChange, options }) => (
  <select value={value} onChange={(e) => onChange(e.target.value)}
    style={{ height: 28, padding: "0 28px 0 10px", background: "var(--bg-2)", border: "1px solid var(--border)", borderRadius: 6, color: "var(--text)", fontSize: 12.5,
      appearance: "none",
      backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='0 0 16 16' fill='none' stroke='%2398a0ad' stroke-width='2'><path d='M3 6l5 4 5-4'/></svg>\")",
      backgroundRepeat: "no-repeat", backgroundPosition: "right 8px center",
    }}>
    {options.map(o => <option key={o.value ?? o} value={o.value ?? o}>{o.label ?? o}</option>)}
  </select>
);

// JARVIS Autopilot suggestions ──────────────────────────────────────
const SEED_SUGGESTIONS = [
  { id: "s1", impact: "Élevé", category: "Apparence", icon: "moon",
    title: "Passer en thème sombre après 18h",
    detail: "Vous consultez le portail tard le soir (3 sessions après 19h cette semaine). Auto-switch dark/light selon l'heure réduit la fatigue oculaire.",
    apply: (setTweak) => setTweak({ theme: "dark" }) },
  { id: "s2", impact: "Moyen", category: "Mise en page", icon: "grid",
    title: "Densité compacte pour la Recherche produits",
    detail: "Vous filtrez souvent par catégorie + statut. La densité compacte affiche 30% de cartes en plus sans scroll.",
    apply: (setTweak) => setTweak({ density: "compact" }) },
  { id: "s3", impact: "Élevé", category: "Seuils", icon: "bell",
    title: "Relever le seuil de stock critique à 30 unités",
    detail: "Avec une vélocité moyenne de 9 u/j, un seuil à 25 vous laisse 2.8 jours de buffer — trop juste pour les délais Shenzhen (28j).",
    apply: (setTweak) => setTweak({ stockThreshold: 30 }) },
  { id: "s4", impact: "Faible", category: "Apparence", icon: "settings",
    title: "Échelle texte 105% sur écrans haute densité",
    detail: "Vos sessions desktop sont majoritaires (87%). Texte 105% améliore la lisibilité sans rogner le contenu.",
    apply: (setTweak) => setTweak({ fontScale: 105 }) },
  { id: "s5", impact: "Élevé", category: "Notifications", icon: "mail",
    title: "Decaler le Daily Digest à 06:30",
    detail: "Le digest arrive à 07:00 mais vous ouvrez l'app vers 06:45 en moyenne. Décaler de 30 min vous donne le récap avant la première session.",
    apply: (setTweak) => setTweak({ emailTime: "06:30" }) },
];

const ImpactBadge = ({ level }) => {
  const tone = level === "Élevé" ? "blue" : level === "Moyen" ? "amber" : "muted";
  return <Badge tone={tone}>Impact {level.toLowerCase()}</Badge>;
};

const AutopilotPanel = ({ t, setTweak }) => {
  const toast = useToast();
  const [applied, setApplied] = useState(new Set());
  const [dismissed, setDismissed] = useState(new Set());
  const [generating, setGenerating] = useState(false);
  const [suggestions, setSuggestions] = useState(SEED_SUGGESTIONS);

  const generateMore = async () => {
    if (generating) return;
    setGenerating(true);
    try {
      const prompt = `Tu es JARVIS Autopilot. Génère 2 suggestions courtes d'amélioration UI pour le portail KCC (Amazon FBA, langue française).
État actuel: theme=${t.theme}, density=${t.density}, layout=${t.dashLayout}/${t.researchLayout}, accent=${t.accent}, stockThreshold=${t.stockThreshold}, marginThreshold=${t.marginThreshold}, emailTime=${t.emailTime}.
Réponds en JSON pur (aucun markdown), tableau de 2 objets avec ces clés exactes: title (string court fr), detail (1 phrase fr), category (one of: Apparence/Mise en page/Seuils/Notifications), impact (Élevé/Moyen/Faible), tweak (object: {key:value} avec une seule clé parmi: theme, accent, density, fontScale, dashLayout, researchLayout, stockThreshold, marginThreshold, emailTime).`;
      const raw = await window.claude.complete(prompt);
      const cleaned = raw.replace(/```json|```/g, "").trim();
      const parsed = JSON.parse(cleaned);
      const newOnes = parsed.map((s, i) => ({
        id: "ai-" + Date.now() + "-" + i,
        impact: s.impact,
        category: s.category,
        icon: s.category === "Apparence" ? "sparkles" : s.category === "Mise en page" ? "grid" : s.category === "Seuils" ? "target" : "mail",
        title: s.title,
        detail: s.detail,
        apply: (setT) => setT(s.tweak),
      }));
      setSuggestions(prev => [...newOnes, ...prev]);
      toast({ message: `${newOnes.length} nouvelles suggestions JARVIS`, tone: "blue" });
    } catch (e) {
      toast({ message: "JARVIS n'a pas pu générer de suggestions", tone: "red" });
    } finally {
      setGenerating(false);
    }
  };

  const applyOne = (s) => {
    s.apply(setTweak);
    setApplied(prev => new Set([...prev, s.id]));
    toast({ message: `Appliqué : ${s.title}`, tone: "green" });
  };
  const dismissOne = (s) => setDismissed(prev => new Set([...prev, s.id]));

  const visible = suggestions.filter(s => !dismissed.has(s.id));

  return (
    <div className="stack" style={{ gap: 16 }}>
      {/* Header card */}
      <div style={{
        background: "linear-gradient(135deg, color-mix(in oklch, var(--accent) 16%, var(--bg-1)), var(--bg-1) 70%)",
        border: "1px solid color-mix(in oklch, var(--accent) 30%, var(--border))",
        borderRadius: 14, padding: 18,
      }}>
        <div className="row" style={{ gap: 14 }}>
          <JarvisLogo size={42} pulse={t.autopilotOn}/>
          <div style={{ flex: 1 }}>
            <div className="row" style={{ gap: 8 }}>
              <span style={{ fontSize: 16, fontWeight: 600, letterSpacing: "-0.01em" }}>JARVIS Autopilot</span>
              <Badge tone={t.autopilotOn ? "green" : "muted"} dot>{t.autopilotOn ? "Actif" : "Inactif"}</Badge>
            </div>
            <div style={{ fontSize: 12.5, color: "var(--text-dim)", marginTop: 4, maxWidth: 540 }}>
              JARVIS observe votre usage et propose des optimisations du portail. Chaque suggestion est explicite — rien n'est changé sans votre validation.
            </div>
          </div>
          <Toggle value={t.autopilotOn} onChange={(v) => setTweak("autopilotOn", v)} />
        </div>

        <div className="grid" style={{ gridTemplateColumns: "repeat(4, 1fr)", gap: 10, marginTop: 16 }}>
          {[
            { label: "Apparence",       key: "autopilotApperance"  },
            { label: "Mises en page",   key: "autopilotLayouts"    },
            { label: "Seuils d'alertes",key: "autopilotThresholds" },
            { label: "Copy & textes",   key: "autopilotCopy"       },
          ].map(p => (
            <label key={p.key} style={{
              display: "flex", alignItems: "center", gap: 8,
              padding: 10, background: "var(--bg-2)", border: "1px solid var(--border-subtle)",
              borderRadius: 8, cursor: t.autopilotOn ? "pointer" : "not-allowed",
              opacity: t.autopilotOn ? 1 : 0.5,
            }}>
              <input type="checkbox" checked={!!t[p.key]} disabled={!t.autopilotOn}
                onChange={(e) => setTweak(p.key, e.target.checked)}
                style={{ accentColor: "var(--accent)" }}/>
              <span style={{ fontSize: 12, fontWeight: 500 }}>{p.label}</span>
            </label>
          ))}
        </div>
      </div>

      {/* Suggestions */}
      <div className="card" style={{ padding: 0 }}>
        <div className="card-head">
          <div>
            <div className="card-title">Suggestions actives</div>
            <div className="card-sub">{visible.length} suggestion{visible.length > 1 ? "s" : ""} · basé sur 7 jours d'usage</div>
          </div>
          <button className="btn" data-size="sm" onClick={generateMore} disabled={generating || !t.autopilotOn} style={{ marginLeft: "auto" }}>
            <Icon name={generating ? "refresh" : "sparkles"} size={12}/>
            {generating ? "Génération…" : "Générer plus"}
          </button>
        </div>
        <div>
          {visible.length === 0 && (
            <div style={{ padding: 30, textAlign: "center", color: "var(--text-dim)", fontSize: 13 }}>
              Aucune suggestion active.
              <button onClick={generateMore} style={{ marginLeft: 8, color: "var(--accent)", background: "none", border: "none", cursor: "pointer", fontSize: 13 }}>Demander à JARVIS</button>
            </div>
          )}
          {visible.map((s) => {
            const isApplied = applied.has(s.id);
            return (
              <div key={s.id} style={{
                display: "grid", gridTemplateColumns: "auto 1fr auto",
                gap: 14, padding: "14px 16px", borderTop: "1px solid var(--border-subtle)",
                alignItems: "flex-start",
                opacity: isApplied ? 0.6 : 1,
              }}>
                <div style={{
                  width: 32, height: 32, borderRadius: 8,
                  background: "var(--accent-soft)", color: "var(--accent)",
                  display: "grid", placeItems: "center", flexShrink: 0,
                }}>
                  <Icon name={s.icon} size={15}/>
                </div>
                <div style={{ minWidth: 0 }}>
                  <div className="row" style={{ gap: 8, marginBottom: 3 }}>
                    <span style={{ fontSize: 13, fontWeight: 550 }}>{s.title}</span>
                    <ImpactBadge level={s.impact}/>
                    <Badge tone="muted">{s.category}</Badge>
                    {isApplied && <Badge tone="green" dot>Appliqué</Badge>}
                  </div>
                  <div style={{ fontSize: 12, color: "var(--text-dim)", lineHeight: 1.5 }}>{s.detail}</div>
                </div>
                <div className="row" style={{ gap: 6 }}>
                  {!isApplied && <button className="btn" data-size="sm" onClick={() => dismissOne(s)}>Rejeter</button>}
                  {!isApplied && <button className="btn" data-variant="primary" data-size="sm" onClick={() => applyOne(s)}>
                    <Icon name="check" size={11}/> Appliquer
                  </button>}
                  {isApplied && <button className="btn" data-variant="ghost" data-size="sm" onClick={() => { setApplied(prev => { const n = new Set(prev); n.delete(s.id); return n; }); }}>
                    <Icon name="refresh" size={11}/> Annuler
                  </button>}
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* History */}
      <div className="card" style={{ padding: 0 }}>
        <div className="card-head">
          <div><div className="card-title">Historique des actions Autopilot</div><div className="card-sub">Tout est réversible · 30 jours de rétention</div></div>
        </div>
        <table className="table">
          <thead><tr><th>Quand</th><th>Action</th><th>Détail</th><th>Statut</th></tr></thead>
          <tbody>
            {[
              { d:"il y a 3h",  act:"Auto-switch thème",       detail:"sombre → clair à 09:14 (lever soleil)", status:"appliqué",   tone:"green" },
              { d:"hier 21:14", act:"Auto-switch thème",       detail:"clair → sombre à 18:42 (coucher)",      status:"appliqué",   tone:"green" },
              { d:"il y a 2j",  act:"Suggestion ignorée",       detail:"Densité compacte sur Finances",          status:"ignoré",     tone:"muted" },
              { d:"il y a 5j",  act:"Seuil PPC ajusté",         detail:"ACOS 28% → 24% (votre confirmation)",    status:"appliqué",   tone:"green" },
              { d:"il y a 1 sem.",act:"Position Daily Digest", detail:"07:00 → 06:30 (votre confirmation)",     status:"appliqué",   tone:"green" },
            ].map((r,i) => (
              <tr key={i}>
                <td className="mono muted">{r.d}</td>
                <td>{r.act}</td>
                <td className="muted">{r.detail}</td>
                <td><Badge tone={r.tone} dot>{r.status}</Badge></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

// Profile section ─────────────────────────────────────────────────────
const ProfileSection = () => {
  const toast = useToast();
  const [p, setP] = useState({
    name: "Clarens",
    role: "CFO · Finance & Ops",
    email: "clarens@kcc.ca",
    phone: "+1 (514) 555-0142",
    bio: "Co-fondateur KCC Holdings · 4 ans Amazon FBA · spécialisé en finance & opérations.",
  });
  const update = (k, v) => { setP(s => ({ ...s, [k]: v })); toast({ message: `${k} mis à jour`, tone: "blue" }); };
  return (
    <div className="card">
      <div className="card-head"><div><div className="card-title">Profil</div><div className="card-sub">Cliquez sur n'importe quel champ pour modifier</div></div></div>
      <div className="card-body" style={{ display: "flex", gap: 18 }}>
        <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 8 }}>
          <Avatar user="clarens" size="lg" />
          <button className="btn" data-variant="ghost" data-size="sm">Changer</button>
        </div>
        <div style={{ flex: 1 }}>
          <Row label="Nom complet"><span style={{ fontSize: 13.5 }}><Editable value={p.name} onChange={(v) => update("name", v)}/></span></Row>
          <Row label="Rôle"><span style={{ fontSize: 13.5 }}><Editable value={p.role} onChange={(v) => update("role", v)}/></span></Row>
          <Row label="Email"><span style={{ fontSize: 13.5 }}><Editable value={p.email} onChange={(v) => update("email", v)}/></span></Row>
          <Row label="Téléphone"><span style={{ fontSize: 13.5 }}><Editable value={p.phone} onChange={(v) => update("phone", v)}/></span></Row>
          <Row label="Bio courte"><span style={{ fontSize: 12.5, color: "var(--text-dim)", textAlign: "right", maxWidth: 280 }}><Editable value={p.bio} onChange={(v) => update("bio", v)}/></span></Row>
        </div>
      </div>
    </div>
  );
};

// Sections ────────────────────────────────────────────────────────────
const AppearanceSection = ({ t, setTweak, onSetTheme, onSetAccent }) => (
  <div className="card">
    <div className="card-head"><div><div className="card-title">Apparence</div><div className="card-sub">Thème, accent, densité, polices</div></div></div>
    <div className="card-body">
      <Row label="Thème" sub="Sombre / clair / auto selon l'heure">
        <div style={{ display: "flex", gap: 8 }}>
          {[
            { id: "dark",  label: "Sombre", bg: "#11141a", fg: "#e4e7ee" },
            { id: "light", label: "Clair",  bg: "#ffffff", fg: "#1a1d23" },
          ].map((opt) => (
            <button key={opt.id} onClick={() => onSetTheme(opt.id)} style={{
              padding: 0, borderRadius: 8, overflow: "hidden",
              border: t.theme === opt.id ? "2px solid var(--accent)" : "1px solid var(--border)",
              background: "transparent", cursor: "pointer",
            }}>
              <div style={{ width: 110, height: 56, background: opt.bg, padding: 8, display: "flex", flexDirection: "column", gap: 4 }}>
                <div style={{ width: 30, height: 5, borderRadius: 2, background: opt.fg, opacity: 0.85 }}/>
                <div style={{ width: 50, height: 4, borderRadius: 2, background: opt.fg, opacity: 0.35 }}/>
                <div style={{ display: "flex", gap: 3, marginTop: "auto" }}>
                  <div style={{ width: 18, height: 6, borderRadius: 2, background: t.accent }}/>
                  <div style={{ width: 18, height: 6, borderRadius: 2, background: opt.fg, opacity: 0.2 }}/>
                </div>
              </div>
              <div style={{ padding: "5px 10px", fontSize: 11.5, fontWeight: 550 }}>{opt.label}</div>
            </button>
          ))}
        </div>
      </Row>
      <Row label="Couleur d'accent" sub="Utilisée pour les actions primaires, focus, et liens">
        <div style={{ display: "flex", gap: 8 }}>
          {ACCENTS.map((c) => (
            <button key={c} onClick={() => onSetAccent(c)} title={c} style={{
              width: 28, height: 28, borderRadius: 8, border: "none", background: c, cursor: "pointer",
              boxShadow: t.accent === c ? `0 0 0 2px var(--bg-1), 0 0 0 4px ${c}` : "none",
            }}/>
          ))}
        </div>
      </Row>
      <Row label="Densité" sub="Compact gagne ~25% d'espace vertical">
        <Segmented value={t.density} onChange={(v) => setTweak("density", v)} options={["compact", "comfy"]}/>
      </Row>
      <Row label="Échelle du texte" hint={`${t.fontScale}% · ${Math.round(13.5 * t.fontScale / 100 * 10)/10}px base`}>
        <input type="range" min={90} max={120} step={1} value={t.fontScale}
          onChange={(e) => setTweak("fontScale", Number(e.target.value))}
          style={{ width: 200, accentColor: "var(--accent)" }}/>
      </Row>
      <Row label="Sidebar réduite par défaut">
        <Toggle value={t.sidebarCollapsed} onChange={(v) => setTweak("sidebarCollapsed", v)}/>
      </Row>
      <Row label="Animations & transitions">
        <Toggle value={t.animations} onChange={(v) => setTweak("animations", v)}/>
      </Row>
      <Row label="Chiffres en monospace" sub="Pour l'alignement des colonnes de chiffres">
        <Toggle value={t.monoNumerals} onChange={(v) => setTweak("monoNumerals", v)}/>
      </Row>
    </div>
  </div>
);

const LayoutSection = ({ t, setTweak }) => (
  <div className="card">
    <div className="card-head"><div><div className="card-title">Mise en page</div><div className="card-sub">Variantes par défaut pour les pages principales</div></div></div>
    <div className="card-body">
      <Row label="Dashboard" sub="bento = cartes pastel · classic = grille dense">
        <Segmented value={t.dashLayout} onChange={(v) => setTweak("dashLayout", v)} options={["bento", "classic"]}/>
      </Row>
      <Row label="Recherche produits" sub="cards = visuel · grille = tableau dense">
        <Segmented value={t.researchLayout} onChange={(v) => setTweak("researchLayout", v)} options={["cards", "grille"]}/>
      </Row>
      <Row label="Pill sync (topbar)" sub="Affiche l'indicateur D1 / KV / CIBC connecté">
        <Toggle value={t.showSync} onChange={(v) => setTweak("showSync", v)}/>
      </Row>
      <Row label="Colonnes masquées en grille" sub="Affiche ASIN, coût, fees par défaut">
        <Toggle value={t.showHiddenColumns} onChange={(v) => setTweak("showHiddenColumns", v)}/>
      </Row>
      <Row label="Raccourcis clavier" sub="⌘K, G+D, G+R, N+P, …">
        <Toggle value={t.shortcutsEnabled} onChange={(v) => setTweak("shortcutsEnabled", v)}/>
      </Row>
    </div>
  </div>
);

const RegionalSection = ({ t, setTweak }) => (
  <div className="card">
    <div className="card-head"><div><div className="card-title">Régional</div><div className="card-sub">Langue, devise, fuseau horaire, formats</div></div></div>
    <div className="card-body">
      <Row label="Langue de l'interface"><Select value={t.locale} onChange={(v) => setTweak("locale", v)} options={LOCALES}/></Row>
      <Row label="Devise d'affichage" sub="Les prix en USD seront convertis"><Select value={t.currency} onChange={(v) => setTweak("currency", v)} options={CURRENCIES}/></Row>
      <Row label="Fuseau horaire"><Select value={t.timezone} onChange={(v) => setTweak("timezone", v)} options={TIMEZONES}/></Row>
      <Row label="Format de date">
        <Segmented value={t.dateFormat} onChange={(v) => setTweak("dateFormat", v)} options={[
          { value: "DD MMM",     label: "10 mai" },
          { value: "DD/MM/YYYY", label: "10/05/2026" },
          { value: "YYYY-MM-DD", label: "2026-05-10" },
        ]}/>
      </Row>
      <Row label="Premier jour de la semaine">
        <Segmented value={t.weekStart} onChange={(v) => setTweak("weekStart", v)} options={[
          { value: "monday", label: "Lundi" },
          { value: "sunday", label: "Dimanche" },
        ]}/>
      </Row>
    </div>
  </div>
);

const NotificationsSection = ({ t, setTweak }) => (
  <div className="card">
    <div className="card-head"><div><div className="card-title">Notifications</div><div className="card-sub">Email digest, alertes in-app, kill-switch</div></div></div>
    <div className="card-body">
      <Row label="Daily Digest par email" sub="Récapitulatif quotidien avec KPIs et alertes">
        <Segmented value={t.emailFreq} onChange={(v) => setTweak("emailFreq", v)} options={[
          { value: "off",     label: "Désactivé" },
          { value: "daily",   label: "Quotidien" },
          { value: "weekly",  label: "Hebdo" },
        ]}/>
      </Row>
      <Row label="Heure d'envoi du digest" sub="Heure locale Montréal">
        <Select value={t.emailTime} onChange={(v) => setTweak("emailTime", v)} options={["06:00","06:30","07:00","07:30","08:00","09:00"]}/>
      </Row>
      <Row label="Notifications in-app" sub="Toasts en bas à droite">
        <Toggle value={t.inAppNotifs} onChange={(v) => setTweak("inAppNotifs", v)}/>
      </Row>
      <Row label="Alertes critiques seulement" sub="Ignore les alertes vertes / informationnelles">
        <Toggle value={t.criticalOnly} onChange={(v) => setTweak("criticalOnly", v)}/>
      </Row>
      <Row label="Son sur alerte critique">
        <Toggle value={t.soundOn} onChange={(v) => setTweak("soundOn", v)}/>
      </Row>
      <Row label="Kill-switch global emails" sub="Coupe tous les envois Resend immédiatement" hint="KV key: kcc:email:killswitch">
        <Toggle value={t.emailKillSwitch} onChange={(v) => setTweak("emailKillSwitch", v)}/>
      </Row>
    </div>
  </div>
);

const DataSection = ({ t, setTweak }) => (
  <div className="card">
    <div className="card-head"><div><div className="card-title">Données & seuils d'alertes</div><div className="card-sub">Niveaux à partir desquels JARVIS et l'app déclenchent les alertes</div></div></div>
    <div className="card-body">
      <Row label="Seuil stock critique" sub="Alerte rouge en-dessous">
        <NumberInput value={t.stockThreshold} onChange={(v) => setTweak("stockThreshold", v)} suffix="unités"/>
      </Row>
      <Row label="Seuil marge minimum" sub="Alerte rouge en-dessous">
        <NumberInput value={t.marginThreshold} onChange={(v) => setTweak("marginThreshold", v)} suffix="%"/>
      </Row>
      <Row label="Seuil BSR maximum" sub="Au-delà = produit sous-performant">
        <NumberInput value={t.bsrThreshold} onChange={(v) => setTweak("bsrThreshold", v)} width={120}/>
      </Row>
      <Row label="ACOS maximum acceptable" sub="Plafond PPC avant alerte">
        <NumberInput value={t.acosThreshold} onChange={(v) => setTweak("acosThreshold", v)} suffix="%"/>
      </Row>
    </div>
  </div>
);

const CalcSection = ({ t, setTweak }) => (
  <div className="card">
    <div className="card-head"><div><div className="card-title">ProfitCalcPro — valeurs par défaut</div><div className="card-sub">Sliders initialisés à ces valeurs</div></div></div>
    <div className="card-body">
      <Row label="Referral fee Amazon par défaut"><NumberInput value={t.referralDefault} onChange={(v) => setTweak("referralDefault", v)} suffix="%"/></Row>
      <Row label="Frais FBA par défaut"><NumberInput value={t.fbaDefault} onChange={(v) => setTweak("fbaDefault", v)} prefix="$"/></Row>
      <Row label="Cap PPC par unité"><NumberInput value={t.ppcCapDefault} onChange={(v) => setTweak("ppcCapDefault", v)} prefix="$"/></Row>
    </div>
  </div>
);

const SecuritySection = ({ onOpenAuth }) => {
  const toast = useToast();
  return (
    <div className="card">
      <div className="card-head"><div><div className="card-title">Sécurité</div><div className="card-sub">2FA, sessions actives, journal d'audit</div></div></div>
      <div className="card-body stack" style={{ gap: 12 }}>
        <Row label="Authentification 2FA" sub="Code par email · TTL 10min · max 5 essais">
          <Badge tone="green" dot>Actif</Badge>
        </Row>
        <Row label="Verrouillage automatique" sub="Déconnexion après inactivité">
          <Select value="30min" onChange={() => {}} options={["10min", "30min", "1h", "4h", "jamais"]}/>
        </Row>
        <div style={{ padding: 12, background: "var(--bg-2)", borderRadius: 8 }}>
          <div className="between">
            <div>
              <div style={{ fontSize: 13, fontWeight: 550 }}>Session courante · iPhone Safari</div>
              <div className="mono" style={{ fontSize: 11, color: "var(--text-dim)" }}>Montréal, QC · expire dans 23h 47min</div>
            </div>
            <button className="btn" data-size="sm" data-variant="danger">Révoquer</button>
          </div>
        </div>
        <div style={{ padding: 12, background: "var(--bg-2)", borderRadius: 8 }}>
          <div className="between">
            <div>
              <div style={{ fontSize: 13, fontWeight: 550 }}>MacBook Pro · Chrome</div>
              <div className="mono" style={{ fontSize: 11, color: "var(--text-dim)" }}>Activité il y a 2 min</div>
            </div>
            <Badge tone="muted">Approuvé</Badge>
          </div>
        </div>
        <button className="btn" onClick={onOpenAuth} style={{ alignSelf: "flex-start" }}>
          <Icon name="shield" size={13}/> Tester le flow 2FA
        </button>
      </div>
    </div>
  );
};

const TeamSection = () => {
  const toast = useToast();
  const [members, setMembers] = useState([
    { id: "clarens", name: "Clarens", role: "CFO · Finance & Ops",      email: "clarens@kcc.ca", perms: "Admin" },
    { id: "kevin",   name: "Kevin",   role: "COO · Fournisseurs",        email: "kevin@kcc.ca",   perms: "Éditeur" },
    { id: "carly",   name: "Carly",   role: "CPO · Sélection produits",  email: "carly@kcc.ca",   perms: "Éditeur" },
  ]);
  return (
    <div className="card" style={{ padding: 0 }}>
      <div className="card-head">
        <div><div className="card-title">Équipe</div><div className="card-sub">3 membres actifs · gérez les rôles et permissions</div></div>
        <button className="btn" data-variant="primary" data-size="sm" style={{ marginLeft: "auto" }}><Icon name="plus" size={12}/> Inviter</button>
      </div>
      <table className="table">
        <thead><tr><th>Membre</th><th>Rôle</th><th>Email</th><th>Permissions</th><th></th></tr></thead>
        <tbody>
          {members.map((m, i) => (
            <tr key={m.id}>
              <td><span className="row" style={{ gap: 8 }}><Avatar user={m.id} size="sm"/>
                <Editable value={m.name} onChange={(v) => setMembers(arr => arr.map((x, j) => j === i ? { ...x, name: v } : x))}/>
              </span></td>
              <td><Editable value={m.role} onChange={(v) => setMembers(arr => arr.map((x, j) => j === i ? { ...x, role: v } : x))}/></td>
              <td className="mono muted"><Editable value={m.email} onChange={(v) => setMembers(arr => arr.map((x, j) => j === i ? { ...x, email: v } : x))}/></td>
              <td>
                <select value={m.perms}
                  onChange={(e) => { setMembers(arr => arr.map((x, j) => j === i ? { ...x, perms: e.target.value } : x)); toast({ message: `${m.name} → ${e.target.value}`, tone: "blue" }); }}
                  style={{ background: "transparent", border: "1px dashed transparent", color: "var(--text)", fontSize: 12, padding: "2px 6px", borderRadius: 4, cursor: "pointer" }}
                  onMouseEnter={(e) => e.currentTarget.style.borderColor = "var(--accent)"}
                  onMouseLeave={(e) => e.currentTarget.style.borderColor = "transparent"}>
                  {["Admin", "Éditeur", "Lecteur"].map(o => <option key={o} value={o}>{o}</option>)}
                </select>
              </td>
              <td><button className="icon-btn" style={{ width: 22, height: 22 }}><Icon name="moreH" size={13}/></button></td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

const IntegrationsSection = () => {
  const toast = useToast();
  const [sheetsConnected, setSheetsConnected] = useState(false);
  const [calConnected, setCalConnected] = useState(true);
  const integrations = [
    { name: "Amazon Seller Central CA", status: "connecté", desc: "OAuth SP-API · données ventes/inventaire temps réel", icon: "box",   tone: "green", action: null },
    {
      name: "Google Sheets",
      status: sheetsConnected ? "connecté" : "prêt à connecter",
      desc: "Sync bidirectionnelle : produits, fournisseurs, P&L mensuel · OAuth 2.0",
      special: "sheets",
      tone: sheetsConnected ? "green" : "blue",
      action: () => { setSheetsConnected(true); toast({ message: "Google Sheets connecté · 3 feuilles détectées", tone: "green" }); },
      scopes: ["spreadsheets.read", "spreadsheets.write", "drive.metadata.readonly"],
    },
    {
      name: "Google Calendar",
      status: calConnected ? "connecté" : "prêt à connecter",
      desc: "Synchronisation événements · 3 calendriers (Clarens, Kevin, Carly) fusionnés",
      special: "gcal",
      tone: calConnected ? "green" : "blue",
      action: calConnected ? () => { setCalConnected(false); toast({ message: "Google Calendar déconnecté", tone: "amber" }); } : () => { setCalConnected(true); toast({ message: "Google Calendar reconnecté", tone: "green" }); },
      scopes: ["calendar.events.readonly", "calendar.events.write"],
    },
    { name: "CIBC Business Banking",    status: "connecté", desc: "Open Banking · réconciliation comptable", icon: "dollar", tone: "green", action: null },
    { name: "Resend (emails)",          status: "connecté", desc: "API key · Daily Digest et alertes", icon: "mail",    tone: "green", action: null },
    { name: "Cloudflare D1 + KV",       status: "connecté", desc: "Stockage primaire · sync multi-appareils", icon: "cube",    tone: "green", action: null },
    { name: "Slack #ops",               status: "désactivé", desc: "Notifications alertes critiques",          icon: "bell",    tone: "muted", action: () => toast({ message: "Connexion Slack — ouverture OAuth…", tone: "blue" }) },
    { name: "QuickBooks Online",        status: "à venir",   desc: "Export comptable mensuel",                 icon: "chart",   tone: "muted", action: null },
  ];
  return (
    <div className="card" style={{ padding: 0 }}>
      <div className="card-head"><div><div className="card-title">Intégrations</div><div className="card-sub">{integrations.filter(i => i.status === "connecté").length} actives · sécurisées par OAuth/API keys</div></div></div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 1, background: "var(--border-subtle)" }}>
        {integrations.map((i) => (
          <div key={i.name} style={{ padding: 16, background: "var(--bg-1)", display: "flex", gap: 12 }}>
            <div style={{ width: 36, height: 36, borderRadius: 8, background: i.special ? "transparent" : "var(--bg-3)", display: "grid", placeItems: "center", flexShrink: 0, padding: i.special ? 0 : 0, border: i.special ? "1px solid var(--border-subtle)" : "none" }}>
              {i.special === "sheets"
                ? <GoogleSheetsIcon size={22}/>
                : i.special === "gcal"
                ? <GoogleCalendarIcon size={22}/>
                : <Icon name={i.icon} size={16}/>}
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
                <span style={{ fontSize: 13, fontWeight: 550 }}>{i.name}</span>
                <Badge tone={i.tone} dot>{i.status}</Badge>
              </div>
              <div style={{ fontSize: 11.5, color: "var(--text-dim)", marginTop: 3 }}>{i.desc}</div>
              {i.scopes && (
                <div className="mono" style={{ marginTop: 6, fontSize: 10, color: "var(--text-faint)" }}>
                  scopes: {i.scopes.map(s => <span key={s} style={{ background: "var(--bg-3)", padding: "1px 5px", borderRadius: 3, marginRight: 4, color: "var(--text-muted)" }}>{s}</span>)}
                </div>
              )}
              {i.action && (
                <button className="btn" data-variant={i.status === "connecté" ? "ghost" : "primary"} data-size="sm" onClick={i.action} style={{ marginTop: 8, height: 24, fontSize: 11.5 }}>
                  {i.status === "connecté" ? <><Icon name="settings" size={11}/> Gérer</> : <><Icon name="link" size={11}/> Connecter</>}
                </button>
              )}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

// Tiny Google Sheets pseudo-logo
const GoogleSheetsIcon = ({ size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" style={{ display: "inline-block", verticalAlign: -2 }}>
    <rect x="4" y="2" width="14" height="20" rx="1.5" fill="#0F9D58"/>
    <rect x="6.5" y="7" width="9" height="1.5" fill="#fff"/>
    <rect x="6.5" y="10.5" width="9" height="1.5" fill="#fff"/>
    <rect x="6.5" y="14" width="9" height="1.5" fill="#fff"/>
    <rect x="10" y="6" width="0.8" height="11" fill="#0F9D58"/>
  </svg>
);

window.GoogleSheetsIcon = GoogleSheetsIcon;

const AdvancedSection = ({ t, setTweak }) => {
  const toast = useToast();
  return (
    <div className="stack" style={{ gap: 14 }}>
      <div className="card">
        <div className="card-head"><div><div className="card-title">Avancé</div><div className="card-sub">Réservé aux administrateurs</div></div></div>
        <div className="card-body">
          <Row label="Tutoriel onboarding au démarrage">
            <Toggle value={t.showOnboarding} onChange={(v) => setTweak("showOnboarding", v)}/>
          </Row>
          <Row label="Mode développeur" sub="Affiche les data-ids et les chronos de rendu">
            <Toggle value={false} onChange={() => toast({ message: "Mode dev réservé aux builds staging", tone: "amber" })}/>
          </Row>
          <Row label="Export complet des données" sub="JSON · 47 MB · 18 produits, 7 fournisseurs, 13 mois">
            <button className="btn" data-size="sm"><Icon name="download" size={12}/> Exporter</button>
          </Row>
          <Row label="Réinitialiser tous les paramètres" sub="Restore les valeurs par défaut · profil et données conservés">
            <button className="btn" data-size="sm" data-variant="danger"
              onClick={() => { Object.keys(TWEAK_DEFAULTS).forEach(k => setTweak(k, TWEAK_DEFAULTS[k])); toast({ message: "Paramètres réinitialisés", tone: "blue" }); }}>
              <Icon name="refresh" size={12}/> Réinitialiser
            </button>
          </Row>
        </div>
      </div>
      <div className="card">
        <div className="card-head"><div><div className="card-title">Audit log</div><div className="card-sub">5 dernières actions · {USERS.length} utilisateurs actifs</div></div></div>
        <table className="table">
          <thead><tr><th>Quand</th><th>Qui</th><th>Action</th><th>Cible</th></tr></thead>
          <tbody>
            {[
              { d:"14:32",  who:"clarens",  act:"Connexion réussie",        target:"2FA · iPhone Safari" },
              { d:"14:18",  who:"carly",    act:"Modifié statut produit",   target:"Distributeur croquettes → Commandé" },
              { d:"13:55",  who:"kevin",    act:"Créé RFQ",                 target:"Yiwu OutdoorPro · RFQ-0042" },
              { d:"13:21",  who:"clarens",  act:"Réconciliation banque",    target:"CIBC · 18 transactions matchées" },
              { d:"12:04",  who:"carly",    act:"Import CSV",                target:"Seller Central · 142 lignes" },
            ].map((r,i) => (
              <tr key={i}>
                <td className="mono muted">{r.d}</td>
                <td><span className="row" style={{gap:6}}><Avatar user={r.who} size="sm"/><span style={{textTransform:"capitalize"}}>{r.who}</span></span></td>
                <td>{r.act}</td>
                <td className="muted">{r.target}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

// Main shell ──────────────────────────────────────────────────────────
const SettingsHub = ({ t, setTweak, onSetTheme, onSetAccent, onOpenAuth, onOpenChangelog }) => {
  const [section, setSection] = useState("profile");
  const renderSection = () => {
    switch (section) {
      case "profile":       return <ProfileSection/>;
      case "appearance":    return <AppearanceSection t={t} setTweak={setTweak} onSetTheme={onSetTheme} onSetAccent={onSetAccent}/>;
      case "layout":        return <LayoutSection t={t} setTweak={setTweak}/>;
      case "regional":      return <RegionalSection t={t} setTweak={setTweak}/>;
      case "notifications": return <NotificationsSection t={t} setTweak={setTweak}/>;
      case "data":          return <DataSection t={t} setTweak={setTweak}/>;
      case "calc":          return <CalcSection t={t} setTweak={setTweak}/>;
      case "security":      return <SecuritySection onOpenAuth={onOpenAuth}/>;
      case "team":          return <TeamSection/>;
      case "integrations":  return <IntegrationsSection/>;
      case "updates":       return <UpdatesSection onOpenChangelog={onOpenChangelog}/>;
      case "autopilot":     return <AutopilotPanel t={t} setTweak={setTweak}/>;
      case "trash":         return <TrashSection/>;
      case "advanced":      return <AdvancedSection t={t} setTweak={setTweak}/>;
      default: return null;
    }
  };
  return (
    <div className="page" style={{ maxWidth: 1300, padding: "18px 20px 60px" }}>
      <div className="page-head">
        <div>
          <div className="page-title">Paramètres</div>
          <div className="page-sub">Personnalisation complète du portail · synchronisé via KV multi-appareils</div>
        </div>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "220px 1fr", gap: 24, alignItems: "flex-start" }}>
        {/* Section nav */}
        <nav style={{ position: "sticky", top: 60 }}>
          {SETTINGS_SECTIONS.map(s => (
            <button key={s.id} onClick={() => setSection(s.id)} style={{
              display: "flex", alignItems: "center", gap: 10, width: "100%",
              height: 32, padding: "0 10px", marginBottom: 2,
              border: "none", borderRadius: 6,
              background: section === s.id ? "var(--bg-3)" : "transparent",
              color: section === s.id ? "var(--text)" : "var(--text-muted)",
              cursor: "pointer", fontSize: 13, fontWeight: section === s.id ? 600 : 450,
              textAlign: "left",
            }}>
              <Icon name={s.icon} size={14} style={{ color: section === s.id ? "var(--accent)" : "var(--text-dim)" }}/>
              <span style={{ flex: 1 }}>{s.label}</span>
              {s.badge && <span className="nav-tag" data-tone="accent">{s.badge}</span>}
            </button>
          ))}
        </nav>
        <div>{renderSection()}</div>
      </div>
    </div>
  );
};

window.SettingsHub = SettingsHub;
