"use client";

import { useEffect, useState } from "react";
import { COUNTDOWN_LABEL, formatBanner, parseCountdownEndMs } from "@/lib/site-countdown";

function StaticHeroTitle() {
  return (
    <h1 className="text-4xl md:text-5xl lg:text-6xl font-extrabold tracking-tight mb-8 drop-shadow-2xl">
      Sorteo{" "}
      <span className="text-transparent bg-clip-text bg-gradient-to-r from-[#7c3aed] via-[#b84dff] to-[#0ea5c6] pb-2 inline-block">
        El Capataz
      </span>
    </h1>
  );
}

type Props = { initialEndIso: string | null };

/**
 * Misma marca en servidor y primer render cliente (sin Date.now() en el HTML).
 * Tras montar, si hay fecha futura, el titular central pasa a la cuenta regresiva.
 */
export default function HeroSorteoHeading({ initialEndIso }: Props) {
  const [mounted, setMounted] = useState(false);
  const [endMs, setEndMs] = useState<number | null>(() => parseCountdownEndMs(initialEndIso));
  const [now, setNow] = useState(() => Date.now());

  useEffect(() => {
    setMounted(true);
  }, []);

  useEffect(() => {
    setEndMs(parseCountdownEndMs(initialEndIso));
  }, [initialEndIso]);

  useEffect(() => {
    if (!mounted) return;
    const id = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(id);
  }, [mounted]);

  if (!mounted) {
    return <StaticHeroTitle />;
  }

  if (endMs == null || endMs <= Date.now()) {
    return <StaticHeroTitle />;
  }

  const remaining = endMs - now;
  if (remaining <= 0) {
    return <StaticHeroTitle />;
  }

  return (
    <h1 className="mb-8 flex flex-col items-center text-center w-full max-w-3xl mx-auto font-extrabold tracking-tight drop-shadow-2xl">
      <div
        className="w-full rounded-2xl md:rounded-3xl border-2 border-[#eab308]/90 bg-gray-950/75 backdrop-blur-md px-5 py-6 md:px-10 md:py-8 animate-countdown-frame"
        role="timer"
        aria-live="polite"
        aria-atomic="true"
      >
        <div className="flex flex-col items-center gap-3 md:gap-4">
          <span className="text-3xl md:text-4xl lg:text-5xl drop-shadow-[0_0_14px_rgba(250,204,21,0.55)]" aria-hidden>
            ✈️
          </span>
          <span className="text-xl md:text-2xl lg:text-3xl text-transparent bg-clip-text bg-gradient-to-r from-[#facc15] via-[#84cc16] to-[#22c55e]">
            {COUNTDOWN_LABEL}
          </span>
          <span className="countdown-time-glow font-black tabular-nums tracking-tight text-3xl sm:text-4xl md:text-5xl lg:text-6xl leading-tight block drop-shadow-[0_2px_24px_rgba(34,197,94,0.35)]">
            {formatBanner(remaining)}
          </span>
          <span className="text-xs md:text-sm font-semibold uppercase tracking-[0.2em] text-[#a3e635]/90">
            Tiempo restante
          </span>
        </div>
      </div>
    </h1>
  );
}
