/* Changelog system — versioned releases + drawer + "what's new" toast.

   Each release: { v, date, type: 'major'|'minor'|'fix'|'feature', items[] }.
   Newest first.
   The latest version is compared against localStorage["kcc:seen_version"] to
   detect updates and surface the bell + auto-open the drawer on first visit. */

const KCC_VERSION = "3.4.0";

const CHANGELOG = [
  {
    v: "3.4.0", date: "10 mai 2026", type: "feature",
    title: "Messages temps réel · 3 comptes · liens contextuels",
    items: [
      { kind: "new",      text: "Module **Messages** : canaux #équipe-kcc, #alertes + DMs entre Clarens / Kevin / Carly · sync cross-tab en live" },
      { kind: "new",      text: "Mentions inline : `[annuaire]`, `[finance]`, `[calendrier]`… deviennent des liens cliquables qui naviguent" },
      { kind: "new",      text: "Sélecteur de compte dans la topbar — bascule entre les 3 cofondateurs" },
      { kind: "new",      text: "Calendrier complet (vue semaine + mois) avec événements partagés et détails par clic" },
      { kind: "new",      text: "Intégrations **Google Sheets** et **Google Calendar** prêtes à connecter (OAuth scopes affichés)" },
    ],
  },
  {
    v: "3.3.0", date: "8 mai 2026", type: "feature",
    title: "JARVIS opérateur omniprésent",
    items: [
      { kind: "new",      text: "Bouton flottant JARVIS sur toutes les pages · raccourci **⌘+J**" },
      { kind: "new",      text: "Pill **« JARVIS opère »** dans la topbar avec latence temps réel" },
      { kind: "new",      text: "Onglet **Activité live** : sync SP-API, recalculs marges, alertes auto" },
      { kind: "improve",  text: "Navigation par instructions : « ouvre le calendrier » dans le chat → bascule la page" },
      { kind: "improve",  text: "Attribution JARVIS sous le titre du Dashboard avec timestamp du dernier recalcul" },
    ],
  },
  {
    v: "3.2.0", date: "6 mai 2026", type: "feature",
    title: "Paramètres étendus · 12 sections · JARVIS Autopilot",
    items: [
      { kind: "new",      text: "Refonte Paramètres en hub à 12 sections (Profil · Apparence · Layout · Régional · Notifs · Sécurité · Équipe · Intégrations · Autopilot · Avancé)" },
      { kind: "new",      text: "**JARVIS Autopilot** : suggestions d'amélioration UI applicables en 1 clic + bouton « Générer plus » qui appelle le modèle" },
      { kind: "new",      text: "Sélecteur de thème graphique (aperçu visuel sombre/clair) dans Apparence" },
      { kind: "improve",  text: "Seuils d'alertes éditables (stock, marge, BSR, ACOS)" },
      { kind: "improve",  text: "Gestion des 3 membres équipe avec permissions inline" },
    ],
  },
  {
    v: "3.1.0", date: "4 mai 2026", type: "feature",
    title: "Édition en place · variations Dashboard / Recherche",
    items: [
      { kind: "new",      text: "Cartes produits **éditables** : clic sur prix, coût, stock, statut, responsable" },
      { kind: "new",      text: "Profil utilisateur éditable champ par champ" },
      { kind: "new",      text: "Variantes Dashboard (**bento** / classique) et Recherche (**cartes** / grille)" },
      { kind: "improve",  text: "Recalcul automatique de la marge sur édition de prix ou coût" },
    ],
  },
  {
    v: "3.0.2", date: "2 mai 2026", type: "fix",
    title: "Correctifs sync + 2FA",
    items: [
      { kind: "fix",      text: "Code 2FA expiré n'invalide plus la session courante" },
      { kind: "fix",      text: "ProfitCalcPro : reset slider ne replaçait pas le scénario par défaut" },
      { kind: "fix",      text: "Kanban : drag entre statuts perdait le ASIN dans les très petites colonnes" },
    ],
  },
  {
    v: "3.0.0", date: "1 mai 2026", type: "major",
    title: "Portail v3 · refonte complète",
    items: [
      { kind: "new",      text: "Refonte complète : sidebar Linear-esque, données denses Bloomberg, monospace pour les chiffres" },
      { kind: "new",      text: "Sync multi-appareils via D1 + KV (Cloudflare)" },
      { kind: "new",      text: "Authentification 2FA · code email · TTL 10min" },
      { kind: "new",      text: "Daily Digest email · 1 envoi max / 24h · template HTML inline" },
    ],
  },
];

const LATEST = CHANGELOG[0];

// Set globals so other files can read version without importing
window.KCC_VERSION = KCC_VERSION;
window.KCC_HAS_UPDATE = (() => {
  try { return localStorage.getItem("kcc:seen_version") !== KCC_VERSION; }
  catch { return true; }
})();

const KIND_LABEL = {
  new:     { label: "Nouveau",       tone: "blue" },
  feature: { label: "Fonctionnalité", tone: "violet" },
  improve: { label: "Amélioré",      tone: "cyan" },
  fix:     { label: "Correctif",     tone: "amber" },
  major:   { label: "Majeur",        tone: "violet" },
  minor:   { label: "Mineur",        tone: "muted" },
};

const renderText = (text) => {
  const html = text
    .replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>")
    .replace(/`([^`]+)`/g, '<code style="font-family:var(--font-mono);background:var(--bg-3);padding:1px 5px;border-radius:3px;font-size:11.5px;color:var(--accent)">$1</code>');
  return <span dangerouslySetInnerHTML={{ __html: html }}/>;
};

const ChangelogDrawer = ({ open, onClose }) => {
  useEffect(() => {
    if (open) {
      try { localStorage.setItem("kcc:seen_version", KCC_VERSION); } catch {}
      window.KCC_HAS_UPDATE = false;
    }
  }, [open]);

  if (!open) return null;
  return (
    <div onClick={onClose} style={{
      position: "fixed", inset: 0, zIndex: 60,
      background: "oklch(0 0 0 / 0.4)", backdropFilter: "blur(4px)",
      display: "flex", justifyContent: "flex-end",
      animation: "cl-fade 200ms ease-out",
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: 480, maxWidth: "100vw", height: "100%",
        background: "var(--bg-1)", borderLeft: "1px solid var(--border)",
        display: "flex", flexDirection: "column",
        boxShadow: "-20px 0 40px -10px oklch(0 0 0 / 0.4)",
        animation: "cl-slide 250ms cubic-bezier(0.2, 0.7, 0.3, 1)",
      }}>
        {/* Header */}
        <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--border-subtle)" }}>
          <div className="row" style={{ gap: 10 }}>
            <div style={{
              width: 32, height: 32, borderRadius: 8,
              background: "linear-gradient(135deg, var(--accent), oklch(0.55 0.18 270))",
              display: "grid", placeItems: "center", color: "white",
            }}>
              <Icon name="sparkles" size={16}/>
            </div>
            <div style={{ flex: 1 }}>
              <div className="row" style={{ gap: 8 }}>
                <span style={{ fontSize: 15, fontWeight: 600 }}>Nouveautés du portail</span>
                <Badge tone="blue" dot>v{KCC_VERSION}</Badge>
              </div>
              <div style={{ fontSize: 11.5, color: "var(--text-dim)", marginTop: 2 }}>
                {CHANGELOG.length} releases · dernière : {LATEST.date}
              </div>
            </div>
            <button className="icon-btn" onClick={onClose}><Icon name="x"/></button>
          </div>
        </div>

        {/* Body */}
        <div style={{ flex: 1, overflow: "auto", padding: "16px 20px" }}>
          {CHANGELOG.map((rel, i) => (
            <div key={rel.v} style={{ marginBottom: 22 }}>
              <div className="row" style={{ gap: 8, marginBottom: 4 }}>
                <span className="mono" style={{ fontSize: 11, color: i === 0 ? "var(--accent)" : "var(--text-faint)", fontWeight: 600 }}>v{rel.v}</span>
                <span className="mono" style={{ fontSize: 11, color: "var(--text-faint)" }}>·</span>
                <span className="mono" style={{ fontSize: 11, color: "var(--text-faint)" }}>{rel.date}</span>
                {i === 0 && <Badge tone="blue" dot>Actuel</Badge>}
              </div>
              <div style={{ fontSize: 14, fontWeight: 600, letterSpacing: "-0.01em", marginBottom: 10 }}>{rel.title}</div>
              <div style={{ borderLeft: i === 0 ? "2px solid var(--accent)" : "2px solid var(--border-subtle)", paddingLeft: 14 }}>
                {rel.items.map((it, j) => (
                  <div key={j} style={{ display: "flex", gap: 8, padding: "5px 0", fontSize: 12.5, lineHeight: 1.5 }}>
                    <Badge tone={KIND_LABEL[it.kind]?.tone || "muted"}>{KIND_LABEL[it.kind]?.label || it.kind}</Badge>
                    <span style={{ flex: 1, minWidth: 0, color: "var(--text-muted)" }}>{renderText(it.text)}</span>
                  </div>
                ))}
              </div>
            </div>
          ))}
          <div style={{ paddingTop: 14, borderTop: "1px solid var(--border-subtle)", fontSize: 11, color: "var(--text-faint)", textAlign: "center" }}>
            Cadence de release : ~2/semaine · changelog complet sur <span className="mono" style={{ color: "var(--text-muted)" }}>kcc-admin.pages.dev/changelog</span>
          </div>
        </div>
      </div>

      <style>{`
        @keyframes cl-fade  { from { opacity: 0; } to { opacity: 1; } }
        @keyframes cl-slide { from { transform: translateX(40px); } to { transform: translateX(0); } }
      `}</style>
    </div>
  );
};

// Compact "what's new" card for the dashboard
const WhatsNewCard = ({ onOpen }) => {
  const top = LATEST.items.slice(0, 3);
  return (
    <div onClick={onOpen} style={{
      background: "linear-gradient(135deg, color-mix(in oklch, var(--accent) 14%, var(--bg-1)), var(--bg-1) 80%)",
      border: "1px solid color-mix(in oklch, var(--accent) 28%, var(--border))",
      borderRadius: 14, padding: 16, cursor: "pointer",
      transition: "transform 120ms, box-shadow 120ms",
    }}
    onMouseEnter={(e) => { e.currentTarget.style.transform = "translateY(-1px)"; e.currentTarget.style.boxShadow = "0 8px 24px -8px oklch(0 0 0 / 0.3)"; }}
    onMouseLeave={(e) => { e.currentTarget.style.transform = "none"; e.currentTarget.style.boxShadow = "none"; }}>
      <div className="row" style={{ gap: 8, marginBottom: 8 }}>
        <Icon name="sparkles" size={14} style={{ color: "var(--accent)" }}/>
        <span style={{ fontSize: 11, color: "var(--text-faint)", textTransform: "uppercase", letterSpacing: ".08em", fontWeight: 600 }}>Quoi de neuf · v{LATEST.v}</span>
        <span className="mono" style={{ marginLeft: "auto", fontSize: 10, color: "var(--text-faint)" }}>{LATEST.date}</span>
      </div>
      <div style={{ fontSize: 14, fontWeight: 600, letterSpacing: "-0.01em", marginBottom: 8 }}>{LATEST.title}</div>
      <div className="stack" style={{ gap: 4 }}>
        {top.map((it, i) => (
          <div key={i} style={{ display: "flex", gap: 6, fontSize: 11.5, color: "var(--text-muted)" }}>
            <span style={{ color: "var(--accent)" }}>•</span>
            <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{it.text.replace(/[*`]/g, "")}</span>
          </div>
        ))}
      </div>
      <div className="row" style={{ marginTop: 10, fontSize: 11.5, color: "var(--accent)", fontWeight: 500 }}>
        Voir tout le changelog <Icon name="chevronRight" size={11}/>
      </div>
    </div>
  );
};

// Tiny "vous utilisez vN.M, dernière vN.M+1" toast when an update is detected
const UpdateToast = ({ onOpen, onDismiss }) => (
  <div style={{
    position: "fixed", bottom: 90, right: 20, zIndex: 55,
    background: "var(--bg-1)",
    border: "1px solid color-mix(in oklch, var(--accent) 30%, var(--border))",
    borderRadius: 12, padding: "12px 14px",
    boxShadow: "0 12px 32px -8px oklch(0 0 0 / 0.4), 0 0 0 1px var(--accent-soft)",
    maxWidth: 320,
    animation: "cl-slide 250ms cubic-bezier(0.2, 0.7, 0.3, 1)",
  }}>
    <div className="row" style={{ gap: 10 }}>
      <div style={{ width: 28, height: 28, borderRadius: 8, background: "var(--accent-soft)", color: "var(--accent)", display: "grid", placeItems: "center", flexShrink: 0 }}>
        <Icon name="sparkles" size={14}/>
      </div>
      <div style={{ minWidth: 0, flex: 1 }}>
        <div style={{ fontSize: 13, fontWeight: 550 }}>Nouvelle mise à jour · v{KCC_VERSION}</div>
        <div style={{ fontSize: 11, color: "var(--text-dim)", marginTop: 2, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{LATEST.title}</div>
      </div>
      <button className="icon-btn" onClick={onDismiss} style={{ width: 22, height: 22 }}><Icon name="x" size={12}/></button>
    </div>
    <div className="row" style={{ gap: 6, marginTop: 10 }}>
      <button className="btn" data-size="sm" data-variant="ghost" onClick={onDismiss}>Plus tard</button>
      <button className="btn" data-size="sm" data-variant="primary" onClick={onOpen} style={{ marginLeft: "auto" }}>Voir les nouveautés →</button>
    </div>
  </div>
);

// Settings section — Mises à jour
const UpdatesSection = ({ onOpenChangelog }) => (
  <div className="stack" style={{ gap: 14 }}>
    <div className="card">
      <div className="card-head"><div><div className="card-title">Mises à jour</div><div className="card-sub">Canal de diffusion · fréquence · préférences de notification</div></div></div>
      <div className="card-body">
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          {[
            { l: "Version actuelle", v: "v" + KCC_VERSION, sub: LATEST.date },
            { l: "Cadence",          v: "~2 / semaine",     sub: "Auto-déploy via CI" },
            { l: "Canal",            v: "Production",       sub: "Stable · validé" },
            { l: "Dernière mise à jour", v: LATEST.date,    sub: LATEST.title.slice(0, 40) + "…" },
          ].map((k) => (
            <div key={k.l} style={{ padding: 10, background: "var(--bg-2)", border: "1px solid var(--border-subtle)", borderRadius: 8 }}>
              <div style={{ fontSize: 10.5, color: "var(--text-dim)", textTransform: "uppercase", letterSpacing: ".06em" }}>{k.l}</div>
              <div className="num" style={{ fontSize: 16, fontWeight: 600, marginTop: 4 }}>{k.v}</div>
              <div style={{ fontSize: 10.5, color: "var(--text-faint)", marginTop: 2 }}>{k.sub}</div>
            </div>
          ))}
        </div>
        <button className="btn" data-variant="primary" onClick={onOpenChangelog} style={{ marginTop: 14 }}>
          <Icon name="sparkles" size={13}/> Voir le changelog complet
        </button>
      </div>
    </div>

    <div className="card" style={{ padding: 0 }}>
      <div className="card-head"><div><div className="card-title">Historique des déploiements</div><div className="card-sub">6 dernières releases</div></div></div>
      <table className="table">
        <thead><tr><th>Version</th><th>Date</th><th>Type</th><th>Résumé</th></tr></thead>
        <tbody>
          {CHANGELOG.map((rel, i) => (
            <tr key={rel.v}>
              <td><span className="mono" style={{ color: i === 0 ? "var(--accent)" : "var(--text)", fontWeight: 600 }}>v{rel.v}</span></td>
              <td className="mono muted">{rel.date}</td>
              <td><Badge tone={KIND_LABEL[rel.type]?.tone || "muted"}>{KIND_LABEL[rel.type]?.label || rel.type}</Badge></td>
              <td className="muted" style={{ maxWidth: 320, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{rel.title}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  </div>
);

window.ChangelogDrawer = ChangelogDrawer;
window.WhatsNewCard = WhatsNewCard;
window.UpdateToast = UpdateToast;
window.UpdatesSection = UpdatesSection;
window.KCC_LATEST_RELEASE = LATEST;
window.KCC_CHANGELOG = CHANGELOG;
