// BEGIN CHANGE: Staff Notice popup (home/site, 5 min TTL, closable) 2026-09-11
"use client";

import { useEffect, useState } from "react";
import { apiUrl } from "@/lib/api";

type NoticePayload = {
  message: string;
  author: string;
  createdAt: number;
  updatedAt: number;
  expiresAt: number;
};

type ApiResp = {
  ok?: boolean;
  active?: boolean;
  notice?: NoticePayload | null;
  ttlSec?: number;
};

const STORAGE_KEY = "wa_staff_notice_dismiss_v1";

function dismissKey(notice: NoticePayload) {
  return `${notice.updatedAt || notice.createdAt}:${notice.message.slice(0, 48)}`;
}

export function StaffNoticePopup() {
  const [notice, setNotice] = useState<NoticePayload | null>(null);
  const [open, setOpen] = useState(false);

  useEffect(() => {
    let cancelled = false;
    let timer: ReturnType<typeof setTimeout> | undefined;

    async function load() {
      try {
        const res = await fetch(apiUrl("staff-notice.php"), { cache: "no-store" });
        const data = (await res.json()) as ApiResp;
        if (cancelled || !data?.ok || !data.active || !data.notice) {
          if (!cancelled) {
            setNotice(null);
            setOpen(false);
          }
          return;
        }
        const n = data.notice;
        const key = dismissKey(n);
        try {
          if (sessionStorage.getItem(STORAGE_KEY) === key) {
            setNotice(null);
            setOpen(false);
            return;
          }
        } catch {
          /* ignore */
        }
        setNotice(n);
        setOpen(true);
        const msLeft = Math.max(0, (n.expiresAt || 0) * 1000 - Date.now());
        if (msLeft > 0) {
          timer = setTimeout(() => {
            setOpen(false);
            setNotice(null);
          }, msLeft);
        }
      } catch {
        /* silent */
      }
    }

    load();
    return () => {
      cancelled = true;
      if (timer) clearTimeout(timer);
    };
  }, []);

  function close() {
    if (notice) {
      try {
        sessionStorage.setItem(STORAGE_KEY, dismissKey(notice));
      } catch {
        /* ignore */
      }
    }
    setOpen(false);
  }

  if (!open || !notice) return null;

  const when =
    notice.updatedAt || notice.createdAt
      ? new Date((notice.updatedAt || notice.createdAt) * 1000).toLocaleString()
      : "-";

  return (
    <div
      className="fixed inset-0 z-[80] flex items-start justify-center bg-black/45 p-4 pt-[12vh] sm:pt-[15vh]"
      role="dialog"
      aria-modal="true"
      aria-labelledby="wa-staff-notice-title"
      onClick={close}
    >
      <div
        className="w-full max-w-md rounded-xl border border-border bg-panel p-5 shadow-xl"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="mb-3 flex items-start justify-between gap-3">
          <div>
            <p className="text-xs font-medium uppercase tracking-wide text-brand">Staff Notice</p>
            <h2 id="wa-staff-notice-title" className="mt-1 text-lg font-semibold text-foreground">
              Aviso da staff
            </h2>
          </div>
          <button
            type="button"
            onClick={close}
            className="rounded-lg border border-border px-2.5 py-1 text-sm text-muted hover:border-brand/40 hover:text-foreground"
            aria-label="Fechar"
          >
            X
          </button>
        </div>
        <p className="whitespace-pre-wrap text-sm leading-relaxed text-foreground">{notice.message}</p>
        <div className="mt-4 border-t border-border pt-3 text-xs text-muted">
          <p>
            Por <span className="font-medium text-foreground">{notice.author || "-"}</span>
          </p>
          <p className="mt-0.5">{when}</p>
        </div>
        <button
          type="button"
          onClick={close}
          className="mt-4 w-full rounded-lg bg-brand px-4 py-2 text-sm font-medium text-background"
        >
          Entendi
        </button>
      </div>
    </div>
  );
}
// END CHANGE: Staff Notice popup
