/* global React */
// Terminal LatAm — Notification / alerts center

const TN_T = window.T_THEME;
const TN_FM = window.T_FM;
const TN_FS = window.T_FS;
const TN_B = window.TerminalBtn;

const ALERTS = [
  { id: "n01", t: "11:38", sev: "P0", cat: "Anomaly", title: "UAR · CPL spike +34% últimos 90 min", body: "Driver: ad set Hero-V2 perdió delivery a Form-Direct (creative cannibalization)", action: "diagnose", account: "uar", read: false },
  { id: "n02", t: "11:24", sev: "P0", cat: "Tracking", title: "Meta CAPI · 2.1% events sin event_id (dedup falla)", body: "GTM container web-uar-prd · server tag rule rota desde 11:18", action: "fix", account: "uar", read: false },
  { id: "n03", t: "10:55", sev: "P1", cat: "Compliance", title: "TikTok Perú · nuevo enforcement guideline (educación)", body: "ADS-LATAM bulletin 2026-W19 · revisar 3 creatives UAR con claim 'admisión garantizada'", action: "review", account: "uar", read: false },
  { id: "n04", t: "10:32", sev: "P1", cat: "Anomaly", title: "Vivienda Lima · MER bajó 14% día/día", body: "Likely cause: lead quality post-form drop (CRM events delay 4h+)", action: "diagnose", account: "vl", read: false },
  { id: "n05", t: "10:11", sev: "P2", cat: "Tracking", title: "Hubspot ↔ Meta sync delay 18 min (esperado <5)", body: "Webhook Zapier · rate limit hit 3x consecutivo · normaliza solo o intervengo?", action: "ack", account: "sf", read: true },
  { id: "n06", t: "09:42", sev: "P1", cat: "Anomaly", title: "SeguroFácil · 47 ad sets activos (anti-pattern)", body: "Detected at 09:42 · evidence Apr+May audit · plan consolidar a 11", action: "diagnose", account: "sf", read: false },
  { id: "n07", t: "09:14", sev: "P2", cat: "Compliance", title: "México · LFPDPPP refresh consent banner (deadline 31 May)", body: "Vivienda Lima property landing /surco · revisar opt-in flow", action: "review", account: "vl", read: true },
  { id: "n08", t: "08:58", sev: "P2", cat: "Tracking", title: "GA4 conversion 'lead_qual' · 0 events últimas 6h", body: "Probable: deploy LP rompió selector · Pablo, mira con dev", action: "ack", account: "uar", read: true },
  { id: "n09", t: "08:30", sev: "P1", cat: "Anomaly", title: "Spend pacing UAR · -8% vs target 11:00", body: "Auto-corrigiendo · bid +12% en hot audiences · monitor 30 min", action: "ack", account: "uar", read: true },
  { id: "n10", t: "07:15", sev: "P2", cat: "Routine", title: "Daily audit completed · score 86 (+3 vs ayer)", body: "5 hallazgos · 2 ya resueltos auto · 3 en Inbox", action: "open", account: "all", read: true },
  { id: "n11", t: "06:48", sev: "P2", cat: "Routine", title: "MMM nightly build · meridian.run · finished", body: "Apr coefs estables · Meta 0.81 · GAds 1.12 · TT 0.34 · LinkedIn 1.47", action: "open", account: "all", read: true },
  { id: "n12", t: "Yest", sev: "P2", cat: "Compliance", title: "Argentina · DNPDP audit reminder 15 jun", body: "Año-1 since enforcement · prep checklist", action: "review", account: "all", read: true },
];

const SEV_COL = { P0: "red", P1: "amber", P2: "cyan" };

const NotificationBell = ({ onClick, count }) => {
  const TN_t = window.T_THEME;
  return (
    <button onClick={onClick} title="Notifications" style={{
      position: "relative", height: "100%", padding: "0 14px", background: "transparent",
      border: "none", borderLeft: `1px solid ${TN_t.line}`, color: count ? TN_t.amber : TN_t.mute,
      cursor: "pointer", fontFamily: TN_t.FM, fontSize: 14,
    }}>
      <span style={{ display: "inline-block", transform: count ? "rotate(-12deg)" : "none", transition: "transform 0.3s" }}>🔔</span>
      {count > 0 && (
        <span style={{
          position: "absolute", top: 6, right: 6, minWidth: 18, height: 18, padding: "0 4px",
          background: TN_t.red, color: TN_t.bg, fontSize: 9, fontFamily: window.T_FM, fontWeight: 700,
          borderRadius: 99, display: "flex", alignItems: "center", justifyContent: "center",
          boxShadow: `0 0 8px ${TN_t.red}88`, animation: "blink 2s infinite",
        }}>{count}</span>
      )}
    </button>
  );
};

const NotificationDrawer = ({ open, onClose, onOpenScreen }) => {
  const [filter, setFilter] = React.useState("All");
  const [items, setItems] = React.useState(ALERTS);
  const [tab, setTab] = React.useState("alerts"); // alerts | settings

  const filters = ["All", "P0", "P1", "Compliance", "Tracking", "Anomaly"];
  const filtered = items.filter(i => {
    if (filter === "All") return true;
    if (filter === "P0" || filter === "P1") return i.sev === filter;
    return i.cat === filter;
  });
  const unread = items.filter(i => !i.read).length;

  const ack = (id) => setItems(arr => arr.map(i => i.id === id ? { ...i, read: true } : i));
  const ackAll = () => setItems(arr => arr.map(i => ({ ...i, read: true })));

  if (!open) return null;

  return (
    <>
      <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,0.4)", zIndex: 7900 }} />
      <div style={{
        position: "fixed", top: 0, right: 0, bottom: 0, width: 480, zIndex: 8000,
        background: TN_T.bg, borderLeft: `1px solid ${TN_T.line}`, boxShadow: "-20px 0 60px rgba(0,0,0,0.5)",
        display: "flex", flexDirection: "column", fontFamily: TN_FS,
      }}>
        {/* HEADER */}
        <div style={{ padding: "14px 18px", borderBottom: `1px solid ${TN_T.line}` }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 10 }}>
            <span style={{ fontFamily: TN_FM, fontSize: 11, color: TN_T.amber, letterSpacing: "0.18em" }}>// ALERTS</span>
            <span style={{ fontSize: 11, color: TN_T.mute }}>{unread} sin leer · {items.length} totales</span>
            <button onClick={onClose} style={{ marginLeft: "auto", background: "none", border: `1px solid ${TN_T.line}`, color: TN_T.mute, fontFamily: TN_FM, fontSize: 10, padding: "4px 8px", cursor: "pointer" }}>ESC</button>
          </div>
          <div style={{ display: "flex", gap: 0, borderBottom: `1px solid ${TN_T.line}`, marginBottom: 12 }}>
            {[["alerts","ALERTAS"],["settings","CANALES"]].map(([k,l]) => (
              <button key={k} onClick={() => setTab(k)} style={{
                padding: "8px 14px", background: "none", border: "none", borderBottom: `2px solid ${tab===k?TN_T.amber:"transparent"}`,
                color: tab===k?TN_T.amber:TN_T.mute, fontFamily: TN_FM, fontSize: 10, letterSpacing: "0.14em", cursor: "pointer",
              }}>{l}</button>
            ))}
          </div>
          {tab === "alerts" && (
            <div style={{ display: "flex", flexWrap: "wrap", gap: 5 }}>
              {filters.map(f => (
                <button key={f} onClick={() => setFilter(f)} style={{
                  padding: "4px 10px", background: filter===f?TN_T.surface:"transparent",
                  border: `1px solid ${filter===f?TN_T.amber:TN_T.line}`, color: filter===f?TN_T.amber:TN_T.mute,
                  fontFamily: TN_FM, fontSize: 10, letterSpacing: "0.1em", cursor: "pointer",
                }}>{f}</button>
              ))}
              <button onClick={ackAll} style={{
                marginLeft: "auto", padding: "4px 10px", background: "transparent", border: `1px solid ${TN_T.line}`,
                color: TN_T.green, fontFamily: TN_FM, fontSize: 10, letterSpacing: "0.1em", cursor: "pointer",
              }}>✓ MARK ALL READ</button>
            </div>
          )}
        </div>

        {/* CONTENT */}
        <div style={{ flex: 1, overflowY: "auto" }}>
          {tab === "alerts" ? (
            filtered.map(it => {
              const col = TN_T[SEV_COL[it.sev]];
              return (
                <div key={it.id} style={{
                  padding: "12px 18px", borderBottom: `1px solid ${TN_T.line}`,
                  borderLeft: `3px solid ${col}`, background: it.read ? TN_T.bg : TN_T.surface,
                  position: "relative",
                }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
                    <span style={{ fontFamily: TN_FM, fontSize: 9, color: col, letterSpacing: "0.16em", padding: "2px 6px", border: `1px solid ${col}` }}>{it.sev}</span>
                    <span style={{ fontFamily: TN_FM, fontSize: 9, color: TN_T.muteDim, letterSpacing: "0.12em" }}>{it.cat.toUpperCase()}</span>
                    <span style={{ fontFamily: TN_FM, fontSize: 9, color: TN_T.muteDim }}>{it.account.toUpperCase()}</span>
                    <span style={{ marginLeft: "auto", fontFamily: TN_FM, fontSize: 10, color: TN_T.muteDim }}>{it.t}</span>
                    {!it.read && <span style={{ width: 6, height: 6, background: TN_T.amber, borderRadius: 99, position: "absolute", top: 14, right: 12 }} />}
                  </div>
                  <div style={{ fontSize: 12, color: TN_T.ink, fontWeight: 500, marginBottom: 4, lineHeight: 1.4 }}>{it.title}</div>
                  <div style={{ fontSize: 11, color: TN_T.mute, lineHeight: 1.5, marginBottom: 8 }}>{it.body}</div>
                  <div style={{ display: "flex", gap: 5 }}>
                    <TN_B onClick={() => ack(it.id)}>{it.read ? "READ" : "ACKNOWLEDGE"}</TN_B>
                    {it.action === "diagnose" && <TN_B kind="amber" onClick={() => { onOpenScreen("diagnose"); onClose(); }}>OPEN IN DIAGNOSE</TN_B>}
                    {it.action === "fix" && <TN_B kind="red" onClick={() => onOpenScreen("optimize")}>FIX NOW</TN_B>}
                    {it.action === "review" && <TN_B kind="amber" onClick={() => onOpenScreen("comply")}>REVIEW</TN_B>}
                    {it.action === "open" && <TN_B kind="cyan">OPEN</TN_B>}
                  </div>
                </div>
              );
            })
          ) : (
            <div style={{ padding: "16px 18px" }}>
              <div style={{ fontSize: 10, color: TN_T.muteDim, letterSpacing: "0.14em", marginBottom: 14 }}>// CANALES DE NOTIFICACIÓN</div>
              {[
                { ch: "Dashboard (este drawer)", levels: ["P0","P1","P2"], on: true },
                { ch: "Email · pablo@bluenose.pe", levels: ["P0","P1"], on: true },
                { ch: "WhatsApp · +51 999 ███ 142", levels: ["P0"], on: true },
                { ch: "Slack · #media-alerts", levels: ["P0","P1"], on: true },
                { ch: "Push (mobile · futuro)", levels: ["P0"], on: false },
              ].map((c,i) => (
                <div key={i} style={{ padding: "12px 0", borderBottom: `1px solid ${TN_T.line}`, display: "grid", gridTemplateColumns: "1fr 110px 60px", gap: 10, alignItems: "center" }}>
                  <div>
                    <div style={{ fontSize: 12, color: c.on ? TN_T.ink : TN_T.muteDim, fontWeight: 500 }}>{c.ch}</div>
                    <div style={{ fontSize: 10, color: TN_T.muteDim, marginTop: 3 }}>recibe · {c.levels.join(" · ")}</div>
                  </div>
                  <div style={{ display: "flex", gap: 4 }}>
                    {["P0","P1","P2"].map(lv => (
                      <span key={lv} style={{
                        padding: "2px 6px", fontSize: 9, fontFamily: TN_FM, letterSpacing: "0.1em",
                        border: `1px solid ${c.levels.includes(lv) ? TN_T[SEV_COL[lv]] : TN_T.line}`,
                        color: c.levels.includes(lv) ? TN_T[SEV_COL[lv]] : TN_T.muteDim,
                      }}>{lv}</span>
                    ))}
                  </div>
                  <span style={{ textAlign: "right", fontSize: 11, color: c.on ? TN_T.green : TN_T.muteDim, fontFamily: TN_FM, letterSpacing: "0.12em" }}>{c.on ? "● ON" : "○ OFF"}</span>
                </div>
              ))}
              <div style={{ marginTop: 16, padding: "12px 14px", background: TN_T.surface, border: `1px solid ${TN_T.cyan}`, borderLeftWidth: 3, fontSize: 11, color: TN_T.ink, lineHeight: 1.6 }}>
                <span style={{ color: TN_T.cyan, letterSpacing: "0.14em", fontFamily: TN_FM }}>// QUIET HOURS </span>
                21:00 - 07:00 · solo P0 fuera de horario · weekend digest agrupado domingo 18:00.
              </div>
            </div>
          )}
        </div>
      </div>
    </>
  );
};

window.NotificationBell = NotificationBell;
window.NotificationDrawer = NotificationDrawer;
window.MA_ALERTS = ALERTS;
