'use client';

import { useState, useEffect } from 'react';
import { Note } from '@/lib/types';
import { toast } from 'sonner';

export function useReminderCheck(notes: Note[]) {
  const [notifiedReminders, setNotifiedReminders] = useState<Set<string>>(new Set());

  useEffect(() => {
    const checkReminders = () => {
      const now = new Date();
      const dueReminders: string[] = [];

      // First pass: collect which reminders are due
      notes.forEach(note => {
        if (!note.reminder) return;
        const reminderDate = new Date(note.reminder);

        if (reminderDate <= now && !notifiedReminders.has(note.id)) {
          dueReminders.push(note.id);
          toast.info("🔔 Reminder: " + (note.title || "Untitled Note"));
        }
      });

      // Second pass: update state only once with all due reminders
      if (dueReminders.length > 0) {
        setNotifiedReminders(prev => {
          const newSet = new Set(prev);
          dueReminders.forEach(id => newSet.add(id));
          return newSet;
        });
      }
    };

    // Check immediately
    checkReminders();

    // Then check every 30 seconds
    const interval = setInterval(checkReminders, 30000);

    return () => clearInterval(interval);
  }, [notes]);
}
