"use client";

import { useEffect, useState } from "react";
import Link from "next/link";

function Badge({ count }: { count: number }) {
  if (count <= 0) return null;
  return (
    <span className="absolute -top-1.5 -right-2.5 min-w-[18px] h-[18px] flex items-center justify-center bg-red-500 text-white text-[10px] font-bold rounded-full px-1 leading-none">
      {count > 99 ? "99+" : count}
    </span>
  );
}

function Dot() {
  return (
    <span className="absolute -top-0.5 -right-1 w-2 h-2 bg-red-500 rounded-full" />
  );
}

interface NavBadgesProps {
  variant?: "desktop" | "mobile";
}

export function NavBadgeMessages({ variant = "desktop" }: NavBadgesProps) {
  const [msgCount, setMsgCount] = useState(0);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let mounted = true;

    const fetchCount = async () => {
      try {
        const res = await fetch("/api/messages?countOnly=true");
        if (res.ok) {
          const data = await res.json();
          if (mounted) setMsgCount(data?.data?.unread ?? 0);
        }
      } catch {
        // silent fail
      } finally {
        if (mounted) setLoading(false);
      }
    };

    fetchCount();
    const interval = setInterval(fetchCount, 30000);
    return () => {
      mounted = false;
      clearInterval(interval);
    };
  }, []);

  if (variant === "mobile") {
    return (
      <Link href="/messages" className="block py-2 text-text-muted hover:text-white">
        Messages
        {!loading && msgCount > 0 && (
          <span className="ml-2 inline-flex items-center justify-center min-w-[18px] h-[18px] bg-red-500 text-white text-[10px] font-bold rounded-full px-1">
            {msgCount > 99 ? "99+" : msgCount}
          </span>
        )}
      </Link>
    );
  }

  return (
    <Link
      href="/messages"
      className="relative text-text-muted hover:text-white transition-colors"
    >
      Messages
      {!loading && msgCount > 0 && <Badge count={msgCount} />}
    </Link>
  );
}

export function NavBadgeNotifications({ variant = "desktop" }: NavBadgesProps) {
  const [notifCount, setNotifCount] = useState(0);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let mounted = true;
    // Adaptive poll: start at 30s, double after 3 consecutive zeros (cap 5min);
    // reset to 30s as soon as a non-zero count comes back. Reduces load when
    // a session has nothing to show without harming responsiveness.
    let zeroStreak = 0;
    let intervalMs = 30_000;
    const MAX_INTERVAL = 5 * 60_000;
    let timer: ReturnType<typeof setTimeout> | null = null;

    const schedule = () => {
      if (!mounted) return;
      timer = setTimeout(async () => {
        await fetchCount();
        schedule();
      }, intervalMs);
    };

    const fetchCount = async () => {
      try {
        const res = await fetch("/api/notifications/count");
        if (res.ok) {
          const data = await res.json();
          const next = data?.data?.unread ?? 0;
          if (mounted) setNotifCount(next);
          if (next > 0) {
            zeroStreak = 0;
            intervalMs = 30_000;
          } else {
            zeroStreak += 1;
            if (zeroStreak >= 3) intervalMs = Math.min(intervalMs * 2, MAX_INTERVAL);
          }
        }
      } catch {
        // silent fail
      } finally {
        if (mounted) setLoading(false);
      }
    };

    fetchCount();
    schedule();

    // Mark-all-read button dispatches this event — zero the count immediately
    // instead of waiting for the next poll.
    const onMarkAllRead = () => {
      if (mounted) setNotifCount(0);
    };
    window.addEventListener("notifications:mark-all-read", onMarkAllRead);

    return () => {
      mounted = false;
      if (timer) clearTimeout(timer);
      window.removeEventListener("notifications:mark-all-read", onMarkAllRead);
    };
  }, []);

  if (variant === "mobile") {
    return (
      <Link href="/notifications" className="block py-2 text-text-muted hover:text-white">
        Notifications
        {!loading && notifCount > 0 && (
          <span className="ml-2 inline-flex items-center justify-center min-w-[18px] h-[18px] bg-red-500 text-white text-[10px] font-bold rounded-full px-1">
            {notifCount > 99 ? "99+" : notifCount}
          </span>
        )}
      </Link>
    );
  }

  return (
    <Link
      href="/notifications"
      className="relative text-text-muted hover:text-white transition-colors"
    >
      Notifications
      {!loading && notifCount > 0 && <Badge count={notifCount} />}
    </Link>
  );
}
