'use client';

import { useEffect, useRef } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { apiGet } from '@/lib/api/client';

type Note = {
  id: string;
  title: string;
  link: string | null;
  payload?: Record<string, unknown>;
  createdAt: string;
};

const SEEN_KEY = 'crm.notif.client.seen';
const MAX_SEEN = 200;
const POLL_MS = 45_000;

function readSeen(): Set<string> {
  try {
    const raw = JSON.parse(localStorage.getItem(SEEN_KEY) || '[]') as unknown;
    return new Set(Array.isArray(raw) ? raw.filter((x): x is string => typeof x === 'string') : []);
  } catch {
    return new Set();
  }
}

function writeSeen(ids: Set<string>) {
  const list = [...ids].slice(-MAX_SEEN);
  localStorage.setItem(SEEN_KEY, JSON.stringify(list));
}

function deliveryFlags(payload: Record<string, unknown> | undefined) {
  const raw = payload?.__delivery;
  if (!raw || typeof raw !== 'object' || Array.isArray(raw))
    return { popup: false, browser: false };
  const row = raw as Record<string, unknown>;
  return { popup: row.popup === true, browser: row.browser === true };
}

/**
 * Delivers pop-up (toast) and browser Notification API channels for recent unread
 * in-app notifications. Mobile is intentionally not handled here.
 */
export function ClientNotificationDelivery() {
  const toast = useToast();
  const seenRef = useRef<Set<string> | null>(null);
  if (seenRef.current === null && typeof window !== 'undefined') {
    seenRef.current = readSeen();
  }

  useEffect(() => {
    let alive = true;
    const seen = seenRef.current ?? new Set<string>();

    const run = async () => {
      try {
        const res = await apiGet<{ data: Note[] }>('/notifications', {
          params: { limit: 20, unread: true },
        });
        if (!alive) return;
        for (const note of res.data) {
          if (seen.has(note.id)) continue;
          const flags = deliveryFlags(note.payload);
          if (!flags.popup && !flags.browser) {
            seen.add(note.id);
            continue;
          }
          // Only surface notifications from the last 15 minutes so a backlog does not toast-storm.
          const age = Date.now() - new Date(note.createdAt).getTime();
          if (age > 15 * 60_000) {
            seen.add(note.id);
            continue;
          }
          if (flags.popup) {
            toast(note.title, 'info', {
              durationMs: 6000,
              ...(note.link ? { link: { label: 'Open', href: note.link } } : {}),
            });
          }
          if (flags.browser && typeof Notification !== 'undefined') {
            if (Notification.permission === 'granted') {
              try {
                const n = new Notification(note.title, {
                  body: 'AdMedia CRM',
                  tag: note.id,
                });
                if (note.link) {
                  n.onclick = () => {
                    window.focus();
                    window.location.href = note.link!;
                  };
                }
              } catch {
                /* ignore — permission revoked mid-flight */
              }
            }
          }
          seen.add(note.id);
        }
        writeSeen(seen);
      } catch {
        /* ignore transient API errors */
      }
    };

    void run();
    const t = window.setInterval(run, POLL_MS);
    return () => {
      alive = false;
      window.clearInterval(t);
    };
  }, [toast]);

  return null;
}
