/**
 * RecordingIndicator — red "REC" pill with a running session
 * timer, shown in the UserArea while a voice recording is in
 * progress. Clicking it prompts to stop. Gated on the
 * `isRecording` flag from VoiceContext; renders `null` otherwise
 * so the UserArea footer shape stays consistent.
 */
import { useEffect, useState } from 'react';
import { useVoice } from '../../contexts/VoiceContext';
import styles from './RecordingIndicator.module.css';

function formatElapsed(ms: number): string {
	if (!Number.isFinite(ms) || ms < 0) return '00:00';
	const total = Math.floor(ms / 1000);
	const h = Math.floor(total / 3600);
	const m = Math.floor((total % 3600) / 60);
	const s = total % 60;
	const mm = String(m).padStart(2, '0');
	const ss = String(s).padStart(2, '0');
	return h > 0 ? `${h}:${mm}:${ss}` : `${mm}:${ss}`;
}

export function RecordingIndicator() {
	const voice = useVoice() as any;
	const isRecording = !!voice?.isRecording;
	const startedAt: number | null = voice?.recordingStartedAt ?? null;
	const stopRecording: (() => Promise<void>) | undefined = voice?.stopRecording;

	const [now, setNow] = useState(() => Date.now());

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

	if (!isRecording || !startedAt) return null;

	const elapsed = now - startedAt;

	const handleClick = async () => {
		const ok = window.confirm('Stop recording this call?');
		if (!ok) return;
		await stopRecording?.();
	};

	return (
		<button
			type="button"
			className={styles.pill}
			onClick={handleClick}
			aria-label={`Stop recording (${formatElapsed(elapsed)})`}
			title="Click to stop recording"
		>
			<span className={styles.dot} aria-hidden />
			<span className={styles.label}>REC</span>
			<span className={styles.timer}>{formatElapsed(elapsed)}</span>
		</button>
	);
}
