"use client";

import { createContext, useContext, useEffect, useState } from "react";
import { usePathname } from "next/navigation";
import { useAuth } from "./auth-context";
import { useCreatePost } from "./create-post-context";
import type { AppNotification, ConversationSummary } from "./types";

type BadgeState = {
  unreadNotifications: number;
  unreadMessages: number;
};

const BadgeContext = createContext<BadgeState | null>(null);

export function BadgeProvider({ children }: { children: React.ReactNode }) {
  const { user } = useAuth();
  const pathname = usePathname();
  const { postsVersion } = useCreatePost();
  const [unreadNotifications, setUnreadNotifications] = useState(0);
  const [unreadMessages, setUnreadMessages] = useState(0);

  useEffect(() => {
    if (!user) return;
    let cancelled = false;
    function poll() {
      fetch("/api/notifications")
        .then((r) => (r.ok ? r.json() : []))
        .then((items: AppNotification[]) => {
          if (!cancelled) setUnreadNotifications(items.filter((n) => !n.read).length);
        })
        .catch(() => {});
      fetch("/api/messages")
        .then((r) => (r.ok ? r.json() : []))
        .then((convos: ConversationSummary[]) => {
          if (!cancelled) setUnreadMessages(convos.reduce((sum, c) => sum + c.unreadCount, 0));
        })
        .catch(() => {});
    }
    poll();
    const interval = setInterval(poll, 15000);
    return () => {
      cancelled = true;
      clearInterval(interval);
    };
    // Re-poll immediately after visiting /activity or /messages (which clear
    // reads server-side) or after posting.
  }, [user, pathname, postsVersion]);

  return (
    <BadgeContext.Provider value={{ unreadNotifications, unreadMessages }}>
      {children}
    </BadgeContext.Provider>
  );
}

export function useBadges() {
  const ctx = useContext(BadgeContext);
  if (!ctx) throw new Error("useBadges must be used inside <BadgeProvider>");
  return ctx;
}
