/* notificaciones.jsx — centro de notificaciones unificado (Bloque 8).
   Se usa en el panel del restaurante y en el admin: campana con contador de no
   leídas + drawer con TODO el histórico (no solo las no leídas), "marcar todas
   como leídas" y refresco por Realtime. RLS (notificaciones_select_own /
   admin_all) acota lo visible; marcar leídas pasa por la RPC
   marcar_notificaciones_leidas. Registra window.CampanaNotificaciones. */
const { useState: nState, useEffect: nEffect } = React;

const NOTIF_ICONO = {
  multa_generada: "flag",
  docs_por_vencer: "layers",
  pedido_asignado: "truck",
  pedido_reasignado: "truck",
  pedido_cancelado: "flag",
  emergencia_repartidor: "flag",
  incidente_entrega: "flag",
  incidente_urgente: "flag",
  reasignacion_automatica: "truck",
  asignacion_pendiente: "clock",
  checkin_repartidor: "user",
};

function fechaNotif(f) {
  const d = new Date(f);
  const hoy = new Date();
  const esHoy = d.toDateString() === hoy.toDateString();
  return esHoy
    ? d.toLocaleTimeString("es-CO", { hour: "numeric", minute: "2-digit" })
    : d.toLocaleDateString("es-CO", { day: "numeric", month: "short" }) + " · " + d.toLocaleTimeString("es-CO", { hour: "numeric", minute: "2-digit" });
}

function CampanaNotificaciones() {
  const [abierto, setAbierto] = nState(false);
  const [notifs, setNotifs] = nState(undefined); // undefined = cargando
  const [busy, setBusy] = nState(false);

  const cargar = () => {
    if (!window.treego_db) { setNotifs([]); return; }
    window.treego_db
      .from("notificaciones")
      .select("id, tipo, titulo, mensaje, leida, fecha")
      .order("fecha", { ascending: false })
      .limit(200)
      .then(({ data }) => setNotifs(data || []), () => setNotifs([]));
  };

  nEffect(() => {
    cargar();
    if (!window.treego_db) return;
    /* refresco liviano: nueva notificación → recargar (canal único por sesión) */
    if (!window.__treegoNotifChannel) {
      window.__treegoNotifChannel = window.treego_db
        .channel("notificaciones-centro")
        .on("postgres_changes", { event: "INSERT", schema: "public", table: "notificaciones" }, () => {
          clearTimeout(window.__treegoNotifReload);
          window.__treegoNotifReload = setTimeout(() => window.dispatchEvent(new Event("treego-notifs")), 500);
        })
        .subscribe();
    }
    const onNueva = () => cargar();
    window.addEventListener("treego-notifs", onNueva);
    return () => window.removeEventListener("treego-notifs", onNueva);
  }, []);

  const noLeidas = (notifs || []).filter((n) => !n.leida).length;

  async function marcarTodas() {
    if (busy || !window.treego_db) return;
    setBusy(true);
    await window.treego_db.rpc("marcar_notificaciones_leidas", { p_ids: null });
    setBusy(false);
    cargar();
  }

  return (
    <React.Fragment>
      <button className="icon-btn" title={noLeidas ? noLeidas + " sin leer" : "Notificaciones"} onClick={() => setAbierto(true)} style={{ position: "relative" }}>
        <Icon name="bell2" />
        {noLeidas > 0 && (
          <span style={{ position: "absolute", top: 4, right: 4, minWidth: 15, height: 15, borderRadius: 8, background: "var(--red, #e5484d)", color: "#fff", fontSize: 9.5, fontWeight: 800, display: "grid", placeItems: "center", padding: "0 3px" }}>
            {noLeidas > 99 ? "99+" : noLeidas}
          </span>
        )}
      </button>

      {abierto && (
        <React.Fragment>
          <div className="drawer-bg" onClick={() => setAbierto(false)}></div>
          <aside className="drawer" style={{ display: "flex", flexDirection: "column" }}>
            <button className="dx" onClick={() => setAbierto(false)}>✕</button>
            <div className="between" style={{ marginBottom: 4, paddingRight: 34 }}>
              <h2 style={{ fontSize: 20 }}>Notificaciones</h2>
            </div>
            <div className="between" style={{ marginBottom: 14 }}>
              <span className="muted" style={{ fontSize: 12.5 }}>{noLeidas ? noLeidas + " sin leer · " : ""}{(notifs || []).length} en total</span>
              {noLeidas > 0 && (
                <button className="btn btn-ghost" style={{ padding: "5px 10px", fontSize: 12 }} disabled={busy} onClick={marcarTodas}>
                  {busy ? "Marcando…" : "Marcar todas leídas"}
                </button>
              )}
            </div>
            <div style={{ overflowY: "auto", flex: 1, display: "flex", flexDirection: "column", gap: 8 }}>
              {notifs === undefined && <p className="muted" style={{ fontSize: 13 }}>Cargando…</p>}
              {notifs && notifs.length === 0 && (
                <p className="muted" style={{ fontSize: 13, textAlign: "center", marginTop: 30 }}>No tienes notificaciones todavía.</p>
              )}
              {(notifs || []).map((n) => (
                <div key={n.id} style={{ display: "flex", gap: 10, padding: "10px 12px", borderRadius: 12, border: "1px solid var(--line)", background: n.leida ? "transparent" : "var(--panel-2)", opacity: n.leida ? 0.75 : 1 }}>
                  <span style={{ width: 30, height: 30, borderRadius: 8, display: "grid", placeItems: "center", background: "var(--panel-3, var(--panel-2))", color: n.leida ? "var(--ink-3)" : "var(--g2)", flex: "none" }}>
                    <Icon name={NOTIF_ICONO[n.tipo] || "bell2"} style={{ width: 15, height: 15 }} />
                  </span>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: 13.5, fontWeight: n.leida ? 500 : 700 }}>{n.titulo}</div>
                    {n.mensaje && <div className="muted" style={{ fontSize: 12.5, marginTop: 2 }}>{n.mensaje}</div>}
                    <div className="muted" style={{ fontSize: 11, marginTop: 4 }}>{fechaNotif(n.fecha)}{!n.leida ? " · nueva" : ""}</div>
                  </div>
                </div>
              ))}
            </div>
          </aside>
        </React.Fragment>
      )}
    </React.Fragment>
  );
}

Object.assign(window, { CampanaNotificaciones });
