"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import type { AnnounceKind } from "@/game/Game";

export interface Banner {
  id: number;
  kind: AnnounceKind;
  text: string;
  sub?: string;
}

const HOLD_MS = 1250;
const BIG: AnnounceKind[] = ["victory", "defeat", "round"];

/** Queue for the centre-top banners: one at a time, ~1.2 s each, never overlapping. A burst keeps only the newest few. */
export function useAnnouncer() {
  const [cur, setCur] = useState<Banner | null>(null);
  const queue = useRef<Banner[]>([]);
  const busy = useRef(false);
  const timer = useRef(0);
  const seq = useRef(0);

  const next = useCallback(() => {
    const b = queue.current.shift();
    if (!b) {
      busy.current = false;
      setCur(null);
      return;
    }
    busy.current = true;
    setCur(b);
    // a long queue plays faster so a warning is never shown after it stopped mattering
    const hold = queue.current.length >= 2 ? HOLD_MS * 0.7 : HOLD_MS;
    timer.current = window.setTimeout(next, hold);
  }, []);

  const push = useCallback(
    (kind: AnnounceKind, text: string, sub?: string) => {
      const b: Banner = { id: ++seq.current, kind, text, sub };
      if (BIG.includes(kind)) queue.current = [];
      queue.current.push(b);
      if (queue.current.length > 3) queue.current.splice(0, queue.current.length - 3);
      if (!busy.current) next();
      else if (BIG.includes(kind)) {
        window.clearTimeout(timer.current);
        next();
      }
    },
    [next],
  );

  useEffect(() => () => window.clearTimeout(timer.current), []);
  return { cur, push };
}

export function Announcer({ banner }: { banner: Banner | null }) {
  return (
    <div className="announcer" aria-live="assertive">
      {banner && (
        <div key={banner.id} className={`ann ann-${banner.kind}`}>
          <div className="ann-text">{banner.text}</div>
          <div className="ann-bar" />
          {banner.sub && <div className="ann-sub">{banner.sub}</div>}
        </div>
      )}
    </div>
  );
}
