'use client';

import { useState, useEffect } from 'react';

interface CountdownTimerProps {
  targetDateString: string; // e.g. "September 19, 2026 06:00:00"
}

export function CountdownTimer({ targetDateString }: CountdownTimerProps) {
  const [timeLeft, setTimeLeft] = useState<{
    days: number;
    hours: number;
    minutes: number;
    seconds: number;
    isPast: boolean;
  }>({
    days: 0,
    hours: 0,
    minutes: 0,
    seconds: 0,
    isPast: false,
  });

  useEffect(() => {
    const targetDate = new Date(targetDateString).getTime();

    const calculate = () => {
      const now = new Date().getTime();
      const difference = targetDate - now;

      if (difference <= 0) {
        setTimeLeft({
          days: 0,
          hours: 0,
          minutes: 0,
          seconds: 0,
          isPast: true,
        });
        return;
      }

      const days = Math.floor(difference / (1000 * 60 * 60 * 24));
      const hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      const minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
      const seconds = Math.floor((difference % (1000 * 60)) / 1000);

      setTimeLeft({ days, hours, minutes, seconds, isPast: false });
    };

    calculate();
    const interval = setInterval(calculate, 1000);
    return () => clearInterval(interval);
  }, [targetDateString]);

  const units = [
    { label: 'Days', value: timeLeft.days },
    { label: 'Hours', value: timeLeft.hours },
    { label: 'Minutes', value: timeLeft.minutes },
    { label: 'Seconds', value: timeLeft.seconds },
  ];

  return (
    <div className="grid grid-cols-4 gap-1.5 sm:gap-3 max-w-md mx-auto">
      {units.map((unit, idx) => (
        <div
          key={idx}
          className="flex flex-col items-center justify-center p-2 sm:p-3.5 rounded-xl bg-white border border-neutral-200 shadow-xs"
        >
          <span className="text-xl sm:text-3xl font-black text-emerald-800 font-mono tracking-tight">
            {String(unit.value).padStart(2, '0')}
          </span>
          <span className="text-[9px] sm:text-xs font-bold uppercase tracking-wider text-neutral-500 mt-0.5">
            {unit.label}
          </span>
        </div>
      ))}
    </div>
  );
}
