/* Notion-style workspace + self-improving meta page */

const SEED_PAGES = [
  { id: "home",       icon: "🏠", title: "Espace KCC", parent: null,    children: ["weekly", "okrs", "playbook"] },
  { id: "weekly",     icon: "📅", title: "Sync hebdo", parent: "home",  children: ["weekly-may10"] },
  { id: "weekly-may10",icon:"📝", title: "10 mai · CR sync", parent: "weekly", children: [] },
  { id: "okrs",       icon: "🎯", title: "OKRs Q2 2026", parent: "home", children: [] },
  { id: "playbook",   icon: "📕", title: "Playbook KCC", parent: "home", children: ["pb-rfq", "pb-launch", "pb-recon"] },
  { id: "pb-rfq",     icon: "📋", title: "Lancer une RFQ", parent: "playbook", children: [] },
  { id: "pb-launch",  icon: "🚀", title: "Lancement produit", parent: "playbook", children: [] },
  { id: "pb-recon",   icon: "🏦", title: "Réconciliation mensuelle", parent: "playbook", children: [] },
  { id: "scratch",    icon: "💡", title: "Brouillons & idées", parent: null, children: [] },
];

const SEED_BLOCKS = {
  "okrs": [
    { id: "b1", type: "h1",     text: "OKRs Q2 2026" },
    { id: "b2", type: "callout",text: "Cap : +30% revenu vs Q1 · 6 nouveaux SKUs validés · cash buffer 5 mois", emoji: "🎯" },
    { id: "b3", type: "h2",     text: "O1 · Doubler la marge sur le top 5" },
    { id: "b4", type: "todo",   text: "Renégocier MOQ Hangzhou BambooLine", done: false },
    { id: "b5", type: "todo",   text: "Auditer ACOS sur Tapis souris XL",  done: true },
    { id: "b6", type: "todo",   text: "Switcher fournisseur Foshan Auto",  done: false },
    { id: "b7", type: "h2",     text: "O2 · Lancer 6 SKUs validés en pipeline" },
    { id: "b8", type: "text",   text: "Carly leads · Kevin support sourcing. Voir [recherche] et [opportunity]." },
    { id: "b9", type: "h2",     text: "O3 · Préparer levée de fonds Q3" },
    { id: "b10",type: "text",   text: "Clarens prépare le deck + chiffres financiers consolidés." },
  ],
  "weekly-may10": [
    { id: "w1", type: "h1",     text: "Sync hebdo · 10 mai 2026" },
    { id: "w2", type: "text",   text: "Présents : Clarens, Kevin, Carly · 45 min" },
    { id: "w3", type: "h2",     text: "Décisions" },
    { id: "w4", type: "todo",   text: "On passe sur MOQ 175 avec BambooLine si commit Q3+Q4", done: true },
    { id: "w5", type: "todo",   text: "Carly lance la Couverture pondérée 4kg en juin",        done: false },
    { id: "w6", type: "h2",     text: "À discuter la semaine prochaine" },
    { id: "w7", type: "text",   text: "Stratégie EU · marketplace Amazon DE/FR · ouvrir un compte test" },
  ],
  "home": [
    { id: "h1", type: "h1",     text: "Espace KCC Holdings" },
    { id: "h2", type: "callout",text: "Tout ce qui n'est pas un dashboard vit ici. Pages éditables, blocs déplaçables, slash-commands.", emoji: "✨" },
    { id: "h3", type: "text",   text: "Glissez les blocs avec ⠿ · tapez / pour insérer · @page pour mentionner · [annuaire] reste cliquable." },
  ],
};

const BLOCK_TYPES = [
  { id: "h1",      icon: "H1",  label: "Titre 1"    },
  { id: "h2",      icon: "H2",  label: "Titre 2"    },
  { id: "text",    icon: "¶",   label: "Paragraphe" },
  { id: "todo",    icon: "☐",   label: "Tâche"      },
  { id: "callout", icon: "💡",  label: "Callout"    },
  { id: "code",    icon: "</>", label: "Code"       },
  { id: "divider", icon: "—",   label: "Séparateur" },
  { id: "quote",   icon: "❝",   label: "Citation"   },
];

const Workspace = ({ onNavigate }) => {
  const toast = useToast();
  // Persistance localStorage — sync KV à chaque save
  const LS_PAGES = "kcc:workspace-pages";
  const LS_BLOCKS = "kcc:workspace-blocks";
  const loadLS = (k, fb) => { try { const v = localStorage.getItem(k); return v ? JSON.parse(v) : fb; } catch { return fb; } };
  const [pages, setPagesRaw] = useState(() => loadLS(LS_PAGES, SEED_PAGES));
  const [blocks, setBlocksRaw] = useState(() => loadLS(LS_BLOCKS, SEED_BLOCKS));
  const [currentId, setCurrentId] = useState("home");
  const [expanded, setExpanded] = useState({ home: true, playbook: true, weekly: true });

  // Wrapper qui persiste à chaque update
  const setPages = (updater) => {
    setPagesRaw((prev) => {
      const next = typeof updater === "function" ? updater(prev) : updater;
      try { localStorage.setItem(LS_PAGES, JSON.stringify(next)); } catch {}
      // Sync best-effort KV (silencieux si offline)
      fetch("/api/sync", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ col: "workspace-pages", items: next }) }).catch(() => null);
      return next;
    });
  };
  const setBlocks = (updater) => {
    setBlocksRaw((prev) => {
      const next = typeof updater === "function" ? updater(prev) : updater;
      try { localStorage.setItem(LS_BLOCKS, JSON.stringify(next)); } catch {}
      fetch("/api/sync", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ col: "workspace-blocks", items: next }) }).catch(() => null);
      return next;
    });
  };

  // Création de page
  const createPage = () => {
    const title = prompt("Titre de la nouvelle page");
    if (!title) return;
    const id = "p-" + Date.now().toString(36);
    setPages((prev) => [...prev, { id, parent: null, icon: "📄", title }]);
    setBlocks((prev) => ({ ...prev, [id]: [{ id: "b-" + Date.now(), type: "text", text: "" }] }));
    setCurrentId(id);
    toast({ message: `Page « ${title} » créée`, tone: "green" });
  };

  const cur = pages.find((p) => p.id === currentId) || pages[0];
  const curBlocks = blocks[currentId] || [{ id: "empty", type: "text", text: "Cliquez ici pour commencer à écrire…" }];

  const updateBlock = (id, patch) => {
    setBlocks((b) => ({
      ...b,
      [currentId]: (b[currentId] || []).map((bl) => bl.id === id ? { ...bl, ...patch } : bl),
    }));
  };

  const addBlock = (type) => {
    const id = "b-" + Date.now();
    setBlocks((b) => ({
      ...b,
      [currentId]: [...(b[currentId] || []), { id, type, text: "", done: false }],
    }));
  };

  const removeBlock = (id) => {
    setBlocks((b) => ({ ...b, [currentId]: (b[currentId] || []).filter((bl) => bl.id !== id) }));
  };

  const renderTree = (parentId, depth = 0) => {
    return pages.filter((p) => p.parent === parentId).map((p) => {
      const open = expanded[p.id];
      const childCount = pages.filter((c) => c.parent === p.id).length;
      return (
        <React.Fragment key={p.id}>
          <div onClick={() => setCurrentId(p.id)} style={{
            display: "flex", alignItems: "center", gap: 4,
            padding: "4px 8px", paddingLeft: 8 + depth * 14,
            borderRadius: 5, cursor: "pointer",
            background: currentId === p.id ? "var(--bg-3)" : "transparent",
            color: currentId === p.id ? "var(--text)" : "var(--text-muted)",
            fontSize: 13,
          }}>
            {childCount > 0 ? (
              <button className="icon-btn" onClick={(e) => { e.stopPropagation(); setExpanded({ ...expanded, [p.id]: !open }); }} style={{ width: 18, height: 18 }}>
                <Icon name={open ? "chevronDown" : "chevronRight"} size={10}/>
              </button>
            ) : <span style={{ width: 18 }}/>}
            <span style={{ fontSize: 14 }}>{p.icon}</span>
            <span style={{ flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{p.title}</span>
          </div>
          {open && childCount > 0 && renderTree(p.id, depth + 1)}
        </React.Fragment>
      );
    });
  };

  const renderBlock = (b) => {
    const common = {
      contentEditable: true,
      suppressContentEditableWarning: true,
      onBlur: (e) => updateBlock(b.id, { text: e.currentTarget.innerText }),
      style: { outline: "none", padding: "3px 4px", borderRadius: 4 },
    };
    if (b.type === "h1") return <h1 {...common} style={{ ...common.style, fontSize: 32, fontWeight: 600, letterSpacing: "-0.02em", margin: "16px 0 8px" }}>{b.text}</h1>;
    if (b.type === "h2") return <h2 {...common} style={{ ...common.style, fontSize: 22, fontWeight: 600, letterSpacing: "-0.015em", margin: "16px 0 6px" }}>{b.text}</h2>;
    if (b.type === "callout") return (
      <div style={{ display: "flex", gap: 12, padding: 14, background: "var(--bg-2)", border: "1px solid var(--border-subtle)", borderRadius: 8, margin: "10px 0" }}>
        <span style={{ fontSize: 20 }}>{b.emoji || "💡"}</span>
        <div {...common} style={{ ...common.style, flex: 1, fontSize: 13.5, lineHeight: 1.55 }}>{b.text}</div>
      </div>
    );
    if (b.type === "todo") return (
      <div style={{ display: "flex", gap: 8, alignItems: "flex-start", padding: "4px 0" }}>
        <input type="checkbox" checked={b.done} onChange={(e) => updateBlock(b.id, { done: e.target.checked })} style={{ accentColor: "var(--accent)", marginTop: 6 }}/>
        <div {...common} style={{ ...common.style, flex: 1, fontSize: 13.5, lineHeight: 1.55, textDecoration: b.done ? "line-through" : "none", color: b.done ? "var(--text-dim)" : "var(--text)" }}>{b.text}</div>
      </div>
    );
    if (b.type === "code") return <pre {...common} style={{ ...common.style, fontFamily: "var(--font-mono)", fontSize: 12, background: "var(--bg-2)", padding: 12, borderRadius: 6, margin: "8px 0" }}>{b.text}</pre>;
    if (b.type === "quote") return <blockquote {...common} style={{ ...common.style, borderLeft: "3px solid var(--accent)", paddingLeft: 14, fontSize: 14, fontStyle: "italic", color: "var(--text-muted)", margin: "10px 0" }}>{b.text}</blockquote>;
    if (b.type === "divider") return <hr style={{ border: "none", borderTop: "1px solid var(--border-subtle)", margin: "16px 0" }}/>;
    return <div {...common} style={{ ...common.style, fontSize: 14, lineHeight: 1.65, color: "var(--text)" }}>{b.text}</div>;
  };

  return (
    <div style={{ display: "grid", gridTemplateColumns: "260px 1fr", height: "100%" }}>
      <div style={{ borderRight: "1px solid var(--border-subtle)", display: "flex", flexDirection: "column", overflow: "hidden" }}>
        <div style={{ padding: "12px 14px", borderBottom: "1px solid var(--border-subtle)" }}>
          <div className="row" style={{ gap: 6 }}>
            <Icon name="layers" size={14}/>
            <span style={{ fontSize: 13.5, fontWeight: 600 }}>Workspace</span>
            <button className="icon-btn" style={{ width: 22, height: 22, marginLeft: "auto" }} title="Nouvelle page" onClick={createPage}>
              <Icon name="plus" size={12}/>
            </button>
          </div>
        </div>
        <div style={{ flex: 1, overflow: "auto", padding: "8px 6px" }}>
          {renderTree(null)}
        </div>
        <div style={{ padding: 10, borderTop: "1px solid var(--border-subtle)" }}>
          <button className="btn" data-variant="ghost" data-size="sm" style={{ width: "100%", justifyContent: "flex-start" }} onClick={() => {
            let trash = []; try { trash = JSON.parse(localStorage.getItem("kcc:workspace-trash") || "[]"); } catch {}
            if (!trash.length) { toast({ message: "Corbeille vide", tone: "blue" }); return; }
            if (confirm(`Restaurer ${trash.length} page(s) supprimée(s) ?`)) {
              setPages((prev) => [...prev, ...trash]);
              localStorage.removeItem("kcc:workspace-trash");
              toast({ message: `${trash.length} page(s) restaurée(s)`, tone: "green" });
            }
          }}>
            <Icon name="trash" size={12}/> Corbeille
          </button>
        </div>
      </div>

      <div style={{ overflow: "auto" }}>
        <div style={{ maxWidth: 760, margin: "0 auto", padding: "40px 60px 60px" }}>
          <div className="row" style={{ gap: 8, fontSize: 11.5, color: "var(--text-dim)", marginBottom: 18 }}>
            <span>{pages.filter((p) => cur && cur.parent === p.id).map((p) => p.title).join(" / ")}</span>
          </div>
          <div className="row" style={{ gap: 12, marginBottom: 12 }}>
            <span style={{ fontSize: 56, lineHeight: 1 }}>{cur.icon}</span>
          </div>
          <div contentEditable suppressContentEditableWarning style={{
            fontSize: 40, fontWeight: 600, letterSpacing: "-0.025em",
            outline: "none", marginBottom: 24, color: "var(--text)",
          }}>{cur.title}</div>

          <div>
            {curBlocks.map((b) => (
              <div key={b.id} style={{ display: "flex", alignItems: "flex-start", gap: 4, position: "relative" }}
                onMouseEnter={(e) => e.currentTarget.querySelector(".block-handle").style.opacity = "1"}
                onMouseLeave={(e) => e.currentTarget.querySelector(".block-handle").style.opacity = "0"}>
                <div className="block-handle" style={{ opacity: 0, display: "flex", flexDirection: "column", paddingTop: 4, transition: "opacity 120ms" }}>
                  <button className="icon-btn" style={{ width: 18, height: 18 }} title="Glisser">⠿</button>
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>{renderBlock(b)}</div>
              </div>
            ))}
          </div>

          <div className="row" style={{ gap: 6, marginTop: 16, flexWrap: "wrap" }}>
            <span style={{ fontSize: 11, color: "var(--text-faint)", marginRight: 4 }}>Ajouter :</span>
            {BLOCK_TYPES.map((bt) => (
              <button key={bt.id} onClick={() => addBlock(bt.id)} className="btn" data-variant="ghost" data-size="sm" style={{ height: 22, padding: "0 8px", fontSize: 11 }}>
                <span className="mono" style={{ fontSize: 10, marginRight: 4, color: "var(--text-faint)" }}>{bt.icon}</span>
                {bt.label}
              </button>
            ))}
          </div>

          <div style={{ marginTop: 28, padding: 14, background: "var(--bg-2)", borderRadius: 10, fontSize: 12, color: "var(--text-muted)", lineHeight: 1.6 }}>
            <div className="row" style={{ gap: 6, marginBottom: 6 }}>
              <JarvisLogo size={14} glow={false}/>
              <strong style={{ color: "var(--text)" }}>JARVIS</strong>
              <Badge tone="blue" dot>analyse cette page</Badge>
            </div>
            Suggérer un résumé · Convertir les puces en tâches · Traduire en anglais · Détecter les actions sans assignation
          </div>
        </div>
      </div>
    </div>
  );
};

/* ─── Self-improving meta page ────────────────────────────────────── */
const SelfImprove = () => {
  const toast = useToast();
  const [iterations] = useState([
    { v: "3.4.0", date: "10 mai", scope: "Messages live + mentions [annuaire]",                  initiator: "Clarens", learned: "Les mentions [page] sont utilisées 3× plus que prévu — étendre la liste" },
    { v: "3.3.0", date: "8 mai",  scope: "JARVIS overlay omniprésent + ⌘+J",                     initiator: "Clarens", learned: "Pic d'engagement +47% sur les pages où le bouton flottant apparaît" },
    { v: "3.2.0", date: "6 mai",  scope: "Paramètres 12 sections + Autopilot",                    initiator: "Clarens", learned: "Section Apparence ouverte 12× plus que Notifications — repositionner" },
    { v: "3.1.0", date: "4 mai",  scope: "Édition en place sur cartes produits",                 initiator: "Carly",   learned: "92% des éditions concernent prix/stock — surfacer ces 2 champs au survol" },
  ]);

  const [proposals, setProposals] = useState([
    { id: "p1", impact: "Élevé",  category: "UX",         title: "Pin Messages tout en haut de la sidebar pour Carly",
      reason: "Carly a passé 38 min cette semaine à scroller jusqu'à Messages · 4× plus que les autres.",
      diff: "sidebar.jsx : reorder NAV pour user.role === 'cpo'",
      status: "pending" },
    { id: "p2", impact: "Moyen", category: "Données",    title: "Mettre en cache les KPIs Dashboard côté KV",
      reason: "Dashboard se recharge 8.2s en moyenne · 73% du temps c'est le recalcul des marges.",
      diff: "cron/kpi-recalc · TTL 300s sur kpi:dashboard:*",
      status: "pending" },
    { id: "p3", impact: "Élevé",  category: "Workflow",   title: "Auto-créer une tâche quand un statut produit passe en Commandé",
      reason: "100% des produits Commandé ont eu un suivi manuel créé · automatiser le pattern.",
      diff: "products.jsx : trigger task on status='commande'",
      status: "pending" },
    { id: "p4", impact: "Faible", category: "Visuel",     title: "Réduire la taille des badges de statut sur mobile",
      reason: "Sur viewport < 400px, les badges débordent dans 14% des cas observés.",
      diff: "styles.css : badge { max-width: clamp() }",
      status: "pending" },
    { id: "p5", impact: "Élevé",  category: "JARVIS",     title: "Ajouter un tool `compute_taxes(period)` à JARVIS",
      reason: "5 fois cette semaine, Clarens a demandé un calcul TPS/TVQ et JARVIS a renvoyé une approximation.",
      diff: "features-jarvis.jsx : new tool · backend endpoint /api/v1/finance/taxes-compute",
      status: "pending" },
  ]);

  const [running, setRunning] = useState(false);
  const [logs, setLogs] = useState([]);

  const runAutoImprovement = async () => {
    if (running) return;
    setRunning(true);
    setLogs([]);
    const steps = [
      { tone: "blue",   text: "Scan des sessions utilisateurs (7 derniers jours)…" },
      { tone: "blue",   text: "Analyse des patterns de friction (clics frustration, abandons)…" },
      { tone: "blue",   text: "Cross-référence avec les feature flags actifs…" },
      { tone: "blue",   text: "Génération d'hypothèses d'amélioration par le modèle…" },
      { tone: "green",  text: "3 nouvelles propositions ajoutées · revue manuelle requise" },
    ];
    for (let i = 0; i < steps.length; i++) {
      await new Promise((r) => setTimeout(r, 700 + Math.random() * 400));
      setLogs((l) => [...l, { ...steps[i], ts: new Date().toLocaleTimeString("fr-CA", { hour: "2-digit", minute: "2-digit", second: "2-digit" }) }]);
    }
    setRunning(false);
    toast({ message: "Cycle d'auto-amélioration terminé", tone: "green" });
  };

  const apply = (id) => {
    setProposals((p) => p.map((x) => x.id === id ? { ...x, status: "applied" } : x));
    toast({ message: "Proposition appliquée · diff committé", tone: "green" });
  };
  const dismiss = (id) => {
    setProposals((p) => p.map((x) => x.id === id ? { ...x, status: "dismissed" } : x));
  };

  return (
    <div className="page" style={{ maxWidth: 1300 }}>
      <div className="page-head">
        <div>
          <div className="page-title">Auto-amélioration</div>
          <div className="page-sub">JARVIS observe l'usage du portail et propose des améliorations · vous validez · le code se modifie</div>
        </div>
        <button className="btn" data-variant="primary" onClick={runAutoImprovement} disabled={running}>
          <Icon name={running ? "refresh" : "zap"} size={13}/> {running ? "Cycle en cours…" : "Lancer un cycle"}
        </button>
      </div>

      {/* Live logs */}
      {(running || logs.length > 0) && (
        <div className="card" style={{ marginBottom: 14, padding: 14, fontFamily: "var(--font-mono)", fontSize: 11.5, background: "#0a0d12", color: "#cdd5e0" }}>
          {logs.map((l, i) => (
            <div key={i} style={{ padding: "3px 0", color: l.tone === "green" ? "var(--green)" : l.tone === "red" ? "var(--red)" : "var(--cyan)" }}>
              <span style={{ color: "#5b6573", marginRight: 8 }}>[{l.ts}]</span>{l.text}
            </div>
          ))}
          {running && <div style={{ color: "var(--accent)", padding: "3px 0" }}>▍</div>}
        </div>
      )}

      {/* KPIs */}
      <div className="grid" style={{ gridTemplateColumns: "repeat(4, 1fr)", marginBottom: 14 }}>
        <KpiCard label="Cycles ce mois"      value="14"   delta={40}/>
        <KpiCard label="Propositions appliquées" value="38" delta={22}/>
        <KpiCard label="Friction réduite"    value="-28 %" delta={28} sparkColor="var(--green)"/>
        <KpiCard label="Auto-déployements"   value="12"   muted/>
      </div>

      {/* Pending proposals */}
      <div className="card" style={{ padding: 0, marginBottom: 14 }}>
        <div className="card-head">
          <div><div className="card-title">Propositions en attente</div><div className="card-sub">{proposals.filter((p) => p.status === "pending").length} à examiner · {proposals.filter((p) => p.status === "applied").length} appliquées cette session</div></div>
        </div>
        {proposals.map((p) => (
          <div key={p.id} style={{
            display: "grid", gridTemplateColumns: "auto 1fr auto",
            gap: 14, padding: 16, borderTop: "1px solid var(--border-subtle)",
            opacity: p.status !== "pending" ? 0.55 : 1,
          }}>
            <div style={{ width: 32, height: 32, borderRadius: 8, background: "var(--accent-soft)", color: "var(--accent)", display: "grid", placeItems: "center", flexShrink: 0 }}>
              <Icon name="sparkles" size={15}/>
            </div>
            <div>
              <div className="row" style={{ gap: 8, marginBottom: 4 }}>
                <span style={{ fontSize: 13, fontWeight: 600 }}>{p.title}</span>
                <Badge tone={p.impact === "Élevé" ? "blue" : p.impact === "Moyen" ? "amber" : "muted"}>Impact {p.impact.toLowerCase()}</Badge>
                <Badge tone="muted">{p.category}</Badge>
                {p.status === "applied"   && <Badge tone="green" dot>Appliqué</Badge>}
                {p.status === "dismissed" && <Badge tone="muted">Rejeté</Badge>}
              </div>
              <div style={{ fontSize: 12, color: "var(--text-muted)", lineHeight: 1.5 }}>{p.reason}</div>
              <div className="mono" style={{ marginTop: 6, fontSize: 10.5, color: "var(--text-faint)" }}>
                <span style={{ color: "var(--accent)" }}>diff:</span> {p.diff}
              </div>
            </div>
            {p.status === "pending" && (
              <div className="row" style={{ gap: 6 }}>
                <button className="btn" data-size="sm" onClick={() => dismiss(p.id)}>Rejeter</button>
                <button className="btn" data-size="sm" onClick={() => toast({ message: `${p.title} — diff : ${p.diff}`, tone: "blue" })}><Icon name="eye" size={11}/> Aperçu</button>
                <button className="btn" data-size="sm" data-variant="primary" onClick={() => apply(p.id)}>
                  <Icon name="check" size={11}/> Appliquer
                </button>
              </div>
            )}
          </div>
        ))}
      </div>

      {/* History */}
      <div className="card" style={{ padding: 0 }}>
        <div className="card-head"><div><div className="card-title">Historique des cycles</div><div className="card-sub">14 cycles ce mois · 100% réversibles via Backups</div></div></div>
        <table className="table">
          <thead><tr><th>Version</th><th>Date</th><th>Améliorations</th><th>Initiateur</th><th>Apprentissage</th></tr></thead>
          <tbody>
            {iterations.map((it) => (
              <tr key={it.v}>
                <td><span className="mono" style={{ color: "var(--accent)", fontWeight: 600 }}>v{it.v}</span></td>
                <td className="mono muted">{it.date}</td>
                <td>{it.scope}</td>
                <td><span className="row" style={{ gap: 6 }}><Avatar user={it.initiator.toLowerCase()} size="sm"/>{it.initiator}</span></td>
                <td className="muted" style={{ fontSize: 11.5, maxWidth: 360 }}>{it.learned}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

Object.assign(window, { Workspace, SelfImprove });
