'use client';

/**
 * Voice-note player card — renders the optional 60-second audio message
 * the patient recorded when booking. The audio file lives on the backend
 * at /api/v2/uploads/voice-notes/<id>.<ext>; the URL we receive is that
 * relative path. We prefix it with the API origin so the browser can
 * fetch it cross-port in dev.
 */

import { useMemo } from 'react';
import { Mic } from 'lucide-react';
import { AUTH_CONFIG } from '@/lib/auth-config';

function formatDuration(sec: number | null | undefined): string {
  if (sec == null || !Number.isFinite(sec)) return '—';
  const s = Math.max(0, Math.round(sec));
  return `0:${s.toString().padStart(2, '0')}`;
}

export function VoiceNoteCard({
  url,
  durationSeconds,
  mimeType,
}: {
  url: string;
  durationSeconds?: number | null;
  mimeType?: string | null;
}) {
  // The voice note URL stored on the appointment is a path starting with
  // /api/v2/uploads/voice-notes/. The browser is on a different port from
  // the backend in dev, so we resolve it against the configured API base.
  const audioSrc = useMemo(() => {
    if (!url) return '';
    if (url.startsWith('http')) return url;
    try {
      const base = new URL(AUTH_CONFIG.apiBaseUrl);
      return `${base.protocol}//${base.host}${url}`;
    } catch {
      return url;
    }
  }, [url]);

  if (!url) return null;

  return (
    <div className="rounded-lg border border-brand-500/30 bg-brand-500/5 p-3">
      <div className="flex items-center gap-2">
        <Mic className="h-4 w-4 text-brand-700" />
        <div className="min-w-0">
          <p className="text-[12px] font-semibold text-ink-1">
            Patient voice note · {formatDuration(durationSeconds)}
          </p>
          <p className="text-[11px] text-ink-3">
            Recorded at booking — play before the consult to hear context.
          </p>
        </div>
      </div>
      <audio
        controls
        preload="metadata"
        src={audioSrc}
        className="mt-2 w-full"
      >
        {mimeType ? <source src={audioSrc} type={mimeType} /> : null}
        Your browser doesn&apos;t support audio playback.
      </audio>
    </div>
  );
}
