'use client';

import { useTranslations } from 'next-intl';
import { Loader2, X } from 'lucide-react';
import type { VoiceCaptureState } from '@/lib/voice/useVoiceCapture';

const METER_BARS = 9;

function formatElapsed(ms: number): string {
  const totalSeconds = Math.floor(Math.max(0, ms) / 1000);
  const minutes = Math.floor(totalSeconds / 60);
  const seconds = totalSeconds % 60;
  return `${minutes}:${String(seconds).padStart(2, '0')}`;
}

/**
 * Live recording / processing strip.
 *
 * Sits between the header row and the chip strip rather than inside the segmented control:
 * the header is `sm:justify-between`, so growing the button mid-recording would shift the
 * whole row.
 */
export function VoiceRecordingBar({ voice }: { voice: VoiceCaptureState }) {
  const t = useTranslations('treatment');

  if (voice.phase === 'idle') return null;

  const isRecording = voice.phase === 'recording';

  return (
    <div
      className="flex items-center gap-3 rounded-[var(--radius-md)] border border-border/70 bg-background-secondary/70 px-3 py-2"
      role="status"
      aria-live="polite"
    >
      {isRecording ? (
        <>
          <span className="h-2 w-2 shrink-0 animate-pulse rounded-full bg-red-500" aria-hidden />
          <span className="shrink-0 text-sm tabular-nums text-text-primary">
            {formatElapsed(voice.elapsedMs)}
            {voice.maxMs != null ? (
              <span className="text-text-muted"> / {formatElapsed(voice.maxMs)}</span>
            ) : null}
          </span>
          <LevelMeter level={voice.level} />
        </>
      ) : (
        <>
          <Loader2 className="h-4 w-4 shrink-0 animate-spin text-text-secondary" aria-hidden />
          <span className="text-sm text-text-secondary">{t('voiceProcessing')}</span>
        </>
      )}

      <button
        type="button"
        onClick={voice.onCancel}
        title={t('voiceCancel')}
        aria-label={t('voiceCancel')}
        className="ms-auto inline-flex shrink-0 items-center gap-1 rounded-[var(--radius-md)] px-2 py-1 text-xs text-text-secondary transition-colors hover:bg-red-500/15 hover:text-red-600 focus:outline-none focus-visible:ring-2 focus-visible:ring-red-500/40"
      >
        <X className="h-3.5 w-3.5" aria-hidden />
        {t('voiceCancel')}
      </button>
    </div>
  );
}

/** Proves the microphone is actually hearing something — silence looks identical otherwise. */
function LevelMeter({ level }: { level: number }) {
  return (
    <span className="flex h-4 flex-1 items-end gap-0.5" aria-hidden>
      {Array.from({ length: METER_BARS }, (_, index) => {
        // Bars light up left to right as the level rises, with a floor so the meter never
        // looks dead while a quiet voice is still being captured.
        const threshold = (index + 1) / METER_BARS;
        const active = level >= threshold * 0.9;
        const height = active ? 30 + threshold * 70 : 20;
        return (
          <span
            key={index}
            className={`w-1 rounded-sm transition-all duration-75 ${
              active ? 'bg-primary' : 'bg-border'
            }`}
            style={{ height: `${height}%` }}
          />
        );
      })}
    </span>
  );
}
