// BEGIN CHANGE: item 10 - sino de notificacoes (bolinha vermelha + dropdown) para todos os usuarios logados
"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import Link from "next/link";
import { useAuth } from "@/auth/AuthProvider";
import { apiUrl } from "@/lib/api";

type NotifRow = {
  id: number;
  scope: string;
  title: string;
  body: string;
  link: string;
  type: string;
  created: number;
  read: boolean;
};

function fmt(ts: number) {
  if (!ts) return "";
  try {
    return new Date(ts * 1000).toLocaleString();
  } catch {
    return "";
  }
}

export function NotificationBell() {
  const { token, ready } = useAuth();
  const [open, setOpen] = useState(false);
  const [unread, setUnread] = useState(0);
  const [items, setItems] = useState<NotifRow[]>([]);
  const [loaded, setLoaded] = useState(false);
  const boxRef = useRef<HTMLDivElement | null>(null);

  const loadCount = useCallback(() => {
    if (!token) return;
    fetch(apiUrl("notifications.php?countOnly=1"), {
      headers: { Authorization: `Bearer ${token}` },
    })
      .then((r) => (r.ok ? r.json() : null))
      .then((json) => {
        if (json && typeof json.unread === "number") setUnread(json.unread);
      })
      .catch(() => {});
  }, [token]);

  const loadList = useCallback(() => {
    if (!token) return;
    fetch(apiUrl("notifications.php?limit=30"), {
      headers: { Authorization: `Bearer ${token}` },
    })
      .then((r) => (r.ok ? r.json() : null))
      .then((json) => {
        if (!json) return;
        if (typeof json.unread === "number") setUnread(json.unread);
        setItems((json.data || []) as NotifRow[]);
        setLoaded(true);
      })
      .catch(() => {});
  }, [token]);

  // Polling leve da contagem (a cada 60s)
  useEffect(() => {
    if (!ready || !token) return;
    loadCount();
    const id = window.setInterval(loadCount, 60000);
    return () => window.clearInterval(id);
  }, [ready, token, loadCount]);

  // Fecha ao clicar fora
  useEffect(() => {
    function onDoc(e: MouseEvent) {
      if (!boxRef.current) return;
      if (!boxRef.current.contains(e.target as Node)) setOpen(false);
    }
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, []);

  async function markAllRead() {
    if (!token) return;
    try {
      const r = await fetch(apiUrl("notifications.php"), {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ action: "mark_read", id: 0 }),
      });
      const json = await r.json().catch(() => ({}));
      if (r.ok) {
        if (typeof json.unread === "number") setUnread(json.unread);
        if (json.data) setItems(json.data as NotifRow[]);
      }
    } catch {
      /* ignore */
    }
  }

  if (!ready || !token) return null;

  return (
    <div ref={boxRef} className="relative">
      <button
        type="button"
        aria-label="Notificacoes"
        onClick={() => {
          const next = !open;
          setOpen(next);
          if (next) loadList();
        }}
        className="relative inline-flex h-9 w-9 items-center justify-center rounded-lg border border-border text-muted transition-colors hover:text-foreground"
      >
        <svg viewBox="0 0 24 24" className="h-5 w-5" fill="none" stroke="currentColor" strokeWidth="1.8" aria-hidden>
          <path d="M18 8a6 6 0 1 0-12 0c0 7-3 9-3 9h18s-3-2-3-9" strokeLinecap="round" strokeLinejoin="round" />
          <path d="M13.7 21a2 2 0 0 1-3.4 0" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
        {unread > 0 && (
          <span className="absolute -right-0.5 -top-0.5 inline-flex min-w-[16px] items-center justify-center rounded-full bg-red-500 px-1 text-[10px] font-semibold leading-4 text-white">
            {unread > 99 ? "99+" : unread}
          </span>
        )}
      </button>

      {open && (
        <div className="absolute right-0 top-full z-40 mt-2 w-80 max-w-[calc(100vw-2rem)] rounded-lg border border-border bg-background shadow-lg">
          <div className="flex items-center justify-between border-b border-border/70 px-3 py-2">
            <span className="text-sm font-medium">Notificacoes</span>
            {unread > 0 && (
              <button
                type="button"
                className="text-xs text-brand hover:underline"
                onClick={markAllRead}
              >
                Marcar todas como lidas
              </button>
            )}
          </div>
          <div className="max-h-80 overflow-auto">
            {!loaded && <p className="px-3 py-4 text-sm text-muted">Carregando...</p>}
            {loaded && items.length === 0 && (
              <p className="px-3 py-4 text-sm text-muted">Nenhuma notificacao.</p>
            )}
            <ul className="divide-y divide-border/40">
              {items.map((n) => {
                const inner = (
                  <div className={`px-3 py-2.5 ${n.read ? "opacity-70" : ""}`}>
                    <div className="flex items-start gap-2">
                      {!n.read && (
                        <span className="mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full bg-red-500" aria-hidden />
                      )}
                      <div className="min-w-0">
                        <p className="text-sm font-medium text-foreground">{n.title}</p>
                        {n.body && <p className="mt-0.5 text-xs text-muted">{n.body}</p>}
                        <p className="mt-1 text-[10px] text-muted">{fmt(n.created)}</p>
                      </div>
                    </div>
                  </div>
                );
                return (
                  <li key={n.id}>
                    {n.link ? (
                      <Link href={n.link} onClick={() => setOpen(false)} className="block hover:bg-brand/5">
                        {inner}
                      </Link>
                    ) : (
                      inner
                    )}
                  </li>
                );
              })}
            </ul>
          </div>
        </div>
      )}
    </div>
  );
}
// END CHANGE
