'use client';

import { useT } from '@/lib/i18n/react';
import { formatAgorotPricePrefixed } from '@/lib/money';
import { formatCountdownSeconds, getCountdownStage } from '@/lib/countdown';
import { useCountdown } from '@/lib/hooks/useCountdown';
import type { Config } from './config';
import type { TickerDeal } from './loadData';

function TickerPill({ deal }: { deal: TickerDeal }) {
  const secs = useCountdown(deal.windowEnd);

  if (secs === null || secs === 0) return null;

  const stage = getCountdownStage(secs);
  const timerCls =
    stage === 'hot'
      ? 'text-danger-300'
      : stage === 'warm'
        ? 'text-danger-200'
        : 'text-brand-primary-200';

  const { text } = formatCountdownSeconds(secs);

  return (
    <a
      href={deal.heSlug ? `/deals/${deal.heSlug}` : '/deals'}
      className="inline-flex shrink-0 items-center gap-2.5 rounded-full border border-white/10 bg-white/[0.06] px-3 py-1.5 no-underline"
    >
      <span
        className={`font-[family-name:var(--font-en)] text-sm font-bold tabular-nums ${timerCls}`}
        dir="ltr"
      >
        {text}
      </span>
      <span className="text-sm text-white">{deal.title}</span>
      <span className="text-brand-primary-300 font-[family-name:var(--font-en)] text-xs font-semibold tabular-nums">
        {formatAgorotPricePrefixed(Math.round(deal.discountedPrice * 100))}
      </span>
    </a>
  );
}

export function Component({ config: _config, data }: { config: Config; data: unknown }) {
  const deals = (data ?? []) as TickerDeal[];
  const t = useT('ticker-strip');

  if (!deals || deals.length === 0) return null;

  const loop = [...deals, ...deals];

  return (
    <div
      className="bg-brand-primary-950 shrink-0 overflow-hidden"
      aria-label={t('label')}
      role="region"
    >
      <div className="text-brand-primary-200 flex items-center gap-2 px-3.5 pt-2.5 pb-1.5 font-[family-name:var(--font-he)] text-xs font-semibold tracking-[0.08em] uppercase">
        <span className="bg-danger-500 h-2 w-2 animate-pulse rounded-full" aria-hidden="true" />
        {t('closing_soon')}
      </div>
      <div className="animate-ticker flex gap-4 ps-3.5 pb-2.5 whitespace-nowrap" aria-hidden="true">
        {loop.map((deal, i) => (
          <TickerPill key={`${deal.id}-${i}`} deal={deal} />
        ))}
      </div>
    </div>
  );
}
