"use client";

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

/**
 * Header pill that links to the inbox and shows an unread badge.
 *
 * Polls `/api/messages/unread-count` every 30s. The endpoint returns 0
 * for anonymous viewers, so the component just hides itself in that case
 * — no flash of "Inbox (0)" for logged-out users.
 */
type Props = {
  /** Absolute path to inbox — `/nalog/poruke` or `/portal/poruke`. */
  href: string;
};

export function MessagesHeaderLink({ href }: Props) {
  const [count, setCount] = useState<number>(0);
  const [hydrated, setHydrated] = useState(false);
  const [authed, setAuthed] = useState(false);

  useEffect(() => {
    let cancelled = false;
    let timer: ReturnType<typeof setTimeout>;

    async function load() {
      try {
        const res = await fetch("/api/messages/unread-count", { cache: "no-store" });
        if (!res.ok) return;
        const data = (await res.json()) as { count?: number };
        if (cancelled) return;
        setCount(typeof data.count === "number" ? data.count : 0);
        // If we got a 200 with a count, viewer is authenticated (visitor or portal).
        setAuthed(true);
        setHydrated(true);
      } catch {
        if (cancelled) return;
        setHydrated(true);
      }
    }

    void load();
    function schedule() {
      timer = setTimeout(async () => {
        if (cancelled) return;
        await load();
        schedule();
      }, 30_000);
    }
    schedule();

    return () => {
      cancelled = true;
      if (timer) clearTimeout(timer);
    };
  }, []);

  // Don't render until we know whether the viewer is authenticated. The
  // `me` check is implicit — `count` only comes back > 0 for authed users.
  if (!hydrated || !authed) return null;

  return (
    <Link
      href={href}
      aria-label={count > 0 ? `Poruke (${count} novih)` : "Poruke"}
      title="Poruke"
      className="relative hidden h-10 w-10 shrink-0 items-center justify-center rounded-full border border-border bg-white text-foreground transition hover:border-primary/30 hover:bg-[#fff4f0] hover:text-primary md:inline-flex"
    >
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
      </svg>
      {count > 0 && (
        <span
          aria-hidden="true"
          className="absolute -right-1 -top-1 inline-flex h-5 min-w-[20px] items-center justify-center rounded-full bg-[#c2410c] px-1 text-[10px] font-bold leading-none text-white shadow-[0_2px_8px_rgba(194,65,12,0.4)]"
        >
          {count > 99 ? "99+" : count}
        </span>
      )}
    </Link>
  );
}
