'use client'

import { useEffect, useState } from 'react'

import { useI18n } from '@/components/providers/i18n-provider'
import { cn } from '@/lib/cn'

/**
 * The incident clock (§22).
 *
 * It counts down from an *estimate*, and the label says so on the same line as the
 * digits — a countdown that looks certain invites an operator to trust it as one, which
 * is precisely the mistake this platform exists to avoid.
 */
export function IncidentClock({
  seconds,
  className,
}: {
  seconds: number | null
  className?: string
}) {
  const { t } = useI18n()
  const [remaining, setRemaining] = useState(seconds)

  useEffect(() => {
    setRemaining(seconds)
    if (seconds === null) return
    const timer = setInterval(() => {
      setRemaining((current) => (current === null ? null : Math.max(0, current - 1)))
    }, 1000)
    return () => clearInterval(timer)
  }, [seconds])

  if (remaining === null) {
    return (
      <div className={cn('text-center', className)}>
        <p className="text-xs text-text-muted">{t('preventionWindow.none')}</p>
      </div>
    )
  }

  const hours = Math.floor(remaining / 3600)
  const minutes = Math.floor((remaining % 3600) / 60)
  const secs = remaining % 60
  const pad = (value: number) => value.toString().padStart(2, '0')

  return (
    <div className={cn('text-center', className)}>
      <p className="text-[10px] uppercase tracking-[0.14em] text-text-faint">
        {t('warRoom.incidentClock')}
      </p>
      <p
        className={cn(
          'tnum mt-1 text-4xl font-semibold tracking-tight tabular-nums sm:text-5xl',
          remaining < 600 ? 'text-critical' : remaining < 1800 ? 'text-watch' : 'text-text',
        )}
        aria-live="off"
      >
        {pad(hours)}:{pad(minutes)}:{pad(secs)}
      </p>
      <p className="mt-1 text-[10px] text-accent">{t('warRoom.estimated')}</p>
    </div>
  )
}
