'use client';

import { useEffect, useState, useCallback } from 'react';
import { useGameStore } from '@/stores/gameStore';
import { apiFetch } from '@/lib/api';

export interface LatestNotificationItem {
  id: string;
  type: string;
  title: string;
  message: string;
  is_read: boolean;
  link?: string | null;
  created_at: string;
}

interface UseLatestNotificationResult {
  latest: LatestNotificationItem | null;
  items: LatestNotificationItem[];
  unreadCount: number;
  loading: boolean;
  refresh: () => Promise<void>;
  markAsRead: (id: string) => Promise<void>;
}

/**
 * Returns the latest unread notification for the current player
 * + the total unread count. Polls every 60s and exposes a manual refresh.
 *
 * Uses the existing `/api/player/:id/notifications` endpoint that Header.tsx
 * already consumes — no new backend surface introduced.
 */
export function useLatestNotification(): UseLatestNotificationResult {
  const { player } = useGameStore();
  const [items, setItems] = useState<LatestNotificationItem[]>([]);
  const [loading, setLoading] = useState(false);

  const refresh = useCallback(async () => {
    if (!player?.id) return;
    setLoading(true);
    try {
      const data = await apiFetch<LatestNotificationItem[]>(`/api/player/${player.id}/notifications`);
      setItems(Array.isArray(data) ? data : []);
    } catch {
      /* silent — Header shows the authoritative errored state */
    } finally {
      setLoading(false);
    }
  }, [player?.id]);

  useEffect(() => {
    refresh();
    const id = setInterval(refresh, 60_000);
    return () => clearInterval(id);
  }, [refresh]);

  const markAsRead = useCallback(
    async (notifId: string) => {
      if (!player?.id) return;
      try {
        await apiFetch(`/api/player/${player.id}/notifications/${notifId}/read`, { method: 'PUT' });
        setItems((prev) => prev.map((n) => (n.id === notifId ? { ...n, is_read: true } : n)));
      } catch {
        /* silent */
      }
    },
    [player?.id],
  );

  const unread = items.filter((n) => !n.is_read);
  const latest = unread.length > 0 ? unread[0] : null;

  return { latest, items, unreadCount: unread.length, loading, refresh, markAsRead };
}
