/* Alerts — Centralized sourcing alerts (same data as the daily digest) */

const TONE_META = {
  red:   { label: "Critique",     icon: "alert", group: "danger"  },
  amber: { label: "Attention",    icon: "bell",  group: "warn"    },
  green: { label: "Opportunité",  icon: "check", group: "success" },
};

const AlertCard = ({ a, onGo, onDelete }) => {
  const meta = TONE_META[a.tone] || TONE_META.amber;
  return (
    <div
      className="card"
      style={{
        padding: 14, cursor: "pointer",
        borderLeft: `3px solid var(--${a.tone === "red" ? "red" : a.tone === "amber" ? "amber" : "green"})`,
      }}
      onClick={() => onGo && a.page && onGo(a.page)}
    >
      <div className="between" style={{ alignItems: "flex-start", gap: 10 }}>
        <div style={{ flex: 1 }}>
          <div className="row" style={{ gap: 8, marginBottom: 4 }}>
            <Badge tone={a.tone === "red" ? "red" : a.tone === "amber" ? "amber" : "green"} dot>
              {meta.label}
            </Badge>
            <span className="mono" style={{ fontSize: 10.5, color: "var(--text-faint)" }}>{a.time}</span>
          </div>
          <div style={{ fontSize: 13.5, fontWeight: 550, marginBottom: 4 }}>{a.title}</div>
          <div className="muted" style={{ fontSize: 12 }}>{a.sub}</div>
        </div>
        <div className="row" style={{ gap: 4 }}>
          {a.page && (
            <button
              className="btn" data-variant="ghost" data-size="sm"
              onClick={(e) => { e.stopPropagation(); onGo(a.page); }}
            >
              Ouvrir <Icon name="chevron-right" size={11} />
            </button>
          )}
          <button
            className="btn" data-variant="ghost" data-size="sm"
            title="Mettre à la corbeille"
            onClick={(e) => { e.stopPropagation(); onDelete && onDelete(a); }}
            style={{ color: "var(--red)" }}
          >
            <Icon name="x" size={11} />
          </button>
        </div>
      </div>
    </div>
  );
};

const Alerts = ({ onNavigate }) => {
  const [filter, setFilter] = useState("all");
  const [, force] = useState(0);
  const toast = (window.useToast || (() => () => {}))();
  const trashHook = (window.useKCCTrash || (() => ({ items: [], send: async () => {} })))();

  const [newOpen, setNewOpen] = useState(false);
  const [draft, setDraft] = useState({ title: "", sub: "", tone: "amber", time: "" });

  const create = async () => {
    if (!draft.title?.trim()) return;
    const id = "al-" + Date.now().toString(36);
    const fresh = {
      id,
      title: draft.title.trim(),
      sub: draft.sub.trim() || "—",
      tone: draft.tone || "amber",
      time: draft.time.trim() || new Date().toLocaleString("fr-CA"),
    };
    ALERTS.push(fresh);
    setNewOpen(false);
    setDraft({ title: "", sub: "", tone: "amber", time: "" });
    force(x => x + 1);
    try {
      await fetch("/api/sync", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ col: "alerts", items: [fresh] }),
      });
    } catch (_) {}
    toast?.({ message: "Alerte créée", tone: "green" });
  };

  const deleteAlert = async (target) => {
    if (!target) return;
    if (!window.confirm(`Mettre "${target.title}" à la corbeille ?`)) return;
    const idx = ALERTS.findIndex(a => a.id === target.id);
    if (idx >= 0) ALERTS.splice(idx, 1);
    await trashHook.send("alerts", target);
    force(x => x + 1);
    toast?.({ message: `"${target.title}" → corbeille`, tone: "muted" });
  };

  const counts = {
    all: ALERTS.length,
    red: ALERTS.filter(a => a.tone === "red").length,
    amber: ALERTS.filter(a => a.tone === "amber").length,
    green: ALERTS.filter(a => a.tone === "green").length,
  };

  const visible = filter === "all" ? ALERTS : ALERTS.filter(a => a.tone === filter);

  const newModal = newOpen && (
    <div onClick={() => setNewOpen(false)} style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,0.55)", zIndex: 9999, display: "grid", placeItems: "center" }}>
      <div className="card" onClick={(e) => e.stopPropagation()} style={{ width: 480, padding: 20 }}>
        <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 14 }}>Nouvelle alerte</div>
        <div className="stack" style={{ gap: 10 }}>
          <div>
            <div style={{ fontSize: 11, color: "var(--text-dim)", marginBottom: 4 }}>Titre *</div>
            <div className="input" style={{ height: 32, padding: "0 10px" }}>
              <input autoFocus value={draft.title} onChange={(e) => setDraft(d => ({ ...d, title: e.target.value }))} placeholder="ex: Stock bas — Diffuseur 500ml" style={{ flex: 1, background: "transparent", border: "none", outline: "none", color: "var(--text)", fontSize: 12.5 }}/>
            </div>
          </div>
          <div>
            <div style={{ fontSize: 11, color: "var(--text-dim)", marginBottom: 4 }}>Sous-titre</div>
            <div className="input" style={{ height: 32, padding: "0 10px" }}>
              <input value={draft.sub} onChange={(e) => setDraft(d => ({ ...d, sub: e.target.value }))} placeholder="Détails…" style={{ flex: 1, background: "transparent", border: "none", outline: "none", color: "var(--text)", fontSize: 12.5 }}/>
            </div>
          </div>
          <div>
            <div style={{ fontSize: 11, color: "var(--text-dim)", marginBottom: 4 }}>Ton</div>
            <select value={draft.tone} onChange={(e) => setDraft(d => ({ ...d, tone: e.target.value }))} className="input" style={{ height: 32, width: "100%" }}>
              <option value="red">Critique</option>
              <option value="amber">Attention</option>
              <option value="green">Opportunité</option>
            </select>
          </div>
          <div>
            <div style={{ fontSize: 11, color: "var(--text-dim)", marginBottom: 4 }}>Heure</div>
            <div className="input" style={{ height: 32, padding: "0 10px" }}>
              <input value={draft.time} onChange={(e) => setDraft(d => ({ ...d, time: e.target.value }))} placeholder="auto si vide" style={{ flex: 1, background: "transparent", border: "none", outline: "none", color: "var(--text)", fontSize: 12.5 }}/>
            </div>
          </div>
        </div>
        <div className="row" style={{ marginTop: 16, justifyContent: "flex-end", gap: 8 }}>
          <button className="btn" onClick={() => setNewOpen(false)}>Annuler</button>
          <button className="btn" data-variant="primary" onClick={create} disabled={!draft.title.trim()}>Créer</button>
        </div>
      </div>
    </div>
  );

  return (
    <div className="page" style={{ maxWidth: 980 }}>
      <div className="page-head">
        <div>
          <div className="page-title">Alertes sourcing</div>
          <div className="page-sub">
            {counts.red} critique{counts.red > 1 ? "s" : ""} ·
            {" "}{counts.amber} attention ·
            {" "}{counts.green} opportunité{counts.green > 1 ? "s" : ""}
            {" "}· même flux que le Daily Digest
          </div>
        </div>
        <div className="row" style={{ gap: 6 }}>
          <button className="btn" data-variant="ghost">
            <Icon name="refresh" size={12} /> Actualiser
          </button>
          <button className="btn" data-variant="primary" onClick={() => setNewOpen(true)}>
            <Icon name="plus" size={12} /> Nouvelle alerte
          </button>
        </div>
      </div>

      <div className="row" style={{ gap: 6, marginBottom: 12, flexWrap: "wrap" }}>
        <button className="btn" data-variant={filter === "all" ? "primary" : "ghost"} onClick={() => setFilter("all")}>
          Toutes · {counts.all}
        </button>
        <button className="btn" data-variant={filter === "red" ? "primary" : "ghost"} onClick={() => setFilter("red")}>
          <Badge tone="red" dot /> Critique · {counts.red}
        </button>
        <button className="btn" data-variant={filter === "amber" ? "primary" : "ghost"} onClick={() => setFilter("amber")}>
          <Badge tone="amber" dot /> Attention · {counts.amber}
        </button>
        <button className="btn" data-variant={filter === "green" ? "primary" : "ghost"} onClick={() => setFilter("green")}>
          <Badge tone="green" dot /> Opportunité · {counts.green}
        </button>
      </div>

      <div className="stack" style={{ gap: 10 }}>
        {visible.map(a => <AlertCard key={a.id} a={a} onGo={onNavigate} onDelete={deleteAlert} />)}
        {visible.length === 0 && (
          <div className="card" style={{ padding: 30, textAlign: "center", color: "var(--text-faint)" }}>
            Aucune alerte — clique « + Nouvelle alerte » pour en créer une.
          </div>
        )}
      </div>
      {newModal}
    </div>
  );
};

window.Alerts = Alerts;
