import { useEffect, useState } from "react";
import { Clock } from "lucide-react";

/**
 * Small live clock for page headers. Updates aligned to the next minute
 * boundary so it doesn't drift after long sessions. Shows in the user's
 * locale ("HH:MM" 24h or "h:mm AM/PM" depending on locale).
 *
 * Designed to live next to the language picker / settings / avatar in the
 * top-right area. On phones it stays compact; on tablets/TV it renders
 * a tiny bit larger to match the surrounding controls.
 */
const HeaderClock = ({
  className = "",
  testId = "header-clock",
}: {
  className?: string;
  testId?: string;
}) => {
  const [text, setText] = useState<string>(() =>
    new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }),
  );

  useEffect(() => {
    const tick = () =>
      setText(
        new Date().toLocaleTimeString([], {
          hour: "2-digit",
          minute: "2-digit",
        }),
      );
    // Align to next minute boundary
    const now = new Date();
    const ms = (60 - now.getSeconds()) * 1000 - now.getMilliseconds();
    let interval: number | undefined;
    const timeout = window.setTimeout(() => {
      tick();
      interval = window.setInterval(tick, 60_000);
    }, Math.max(250, ms));
    return () => {
      window.clearTimeout(timeout);
      if (interval !== undefined) window.clearInterval(interval);
    };
  }, []);

  return (
    <div
      className={`flex items-center gap-1.5 px-2.5 h-9 sm:h-10 rounded-full glass text-foreground/90 ${className}`}
      data-testid={testId}
    >
      <Clock className="w-3.5 h-3.5 text-primary" strokeWidth={2} />
      <span className="text-[11px] sm:text-xs font-medium tabular-nums tracking-wide">
        {text}
      </span>
    </div>
  );
};

export default HeaderClock;
