// Clip review modal — used from monitoring and search

function ClipModal({ event, track, onClose, onFindAgain }) {
  const { t, lang } = useI18n();
  const trk = track || (event && lookupTrack(event.track_id));
  const cam = lookupCamera(event ? event.camera_id : trk?.camera_id);
  const zone = event ? lookupZone(event.zone_id) : (trk && lookupZone(trk.zones_visited[0]));
  const identity = lookupIdentity(event ? event.identity_id : trk?.identity_id);
  const clip = lookupClip(event ? event.clip_id : trk?.representative_clip_id || `clip-1${String(parseInt(trk?.id?.split('-')[1] || '1000', 10) - 1000).padStart(3, '0')}`);

  const [playing, setPlaying] = React.useState(false);
  const [progress, setProgress] = React.useState(0.18);

  React.useEffect(() => {
    if (!playing) return;
    const id = setInterval(() => {
      setProgress((p) => {
        const nx = p + 0.012;
        if (nx >= 1) { setPlaying(false); return 1; }
        return nx;
      });
    }, 100);
    return () => clearInterval(id);
  }, [playing]);

  React.useEffect(() => {
    function onKey(e) { if (e.key === 'Escape') onClose?.(); }
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  const duration = clip?.duration_s ?? 15;
  const t_now = Math.floor(progress * duration);
  const evts = event ? event.ts : Date.now() - 800000;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-navy-950/80 backdrop-blur-sm animate-fadeIn"
      onClick={onClose}
    >
      <div
        className="bg-navy-900 border border-slate-700 rounded-lg shadow-2xl w-full max-w-5xl max-h-[92vh] overflow-hidden flex flex-col"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="flex items-center justify-between gap-3 px-4 py-3 border-b border-slate-700/70 shrink-0">
          <div className="flex items-center gap-3 min-w-0">
            {event && <SeverityBadge severity={event.severity} />}
            <div className="font-display text-base font-semibold text-slate-100 truncate">
              {event ? t(`kind.${event.kind}`) : (trk?.caption || 'Trilho')}
            </div>
            <Pill tone="ghost"><Icons.Video size={11} /> {cam?.name}</Pill>
            {zone && (
              <Pill tone="ghost">
                <span className="w-1.5 h-1.5 rounded-full" style={{ background: ZONE_ROLES[zone.semantic_role]?.color }} />
                {zone.name}
              </Pill>
            )}
          </div>
          <IconButton icon={Icons.X} label={t('common.close')} onClick={onClose} />
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-[1.4fr_1fr] min-h-0 overflow-auto">
          {/* Video area */}
          <div className="bg-navy-950 flex flex-col">
            <div className="relative aspect-video">
              <SyntheticThumb camera={cam} track={trk} className="absolute inset-0" showBox={true} />
              {zone && <ZoneOverlay zone={zone} faint={false} />}
              {/* Timecode */}
              <div className="absolute top-3 left-3 font-mono text-[11px] text-white/90 bg-black/40 px-2 py-1 rounded backdrop-blur-sm flex items-center gap-2">
                <span className="w-1.5 h-1.5 rounded-full bg-red-500 animate-pulseDot" />
                REC · {formatDateTime(evts)}
              </div>
              <div className="absolute top-3 right-3 font-mono text-[11px] text-white/90 bg-black/40 px-2 py-1 rounded backdrop-blur-sm">
                {cam?.short} · {cam?.resolution}
              </div>
              {/* Center play button when paused */}
              {!playing && progress < 1 && (
                <button
                  onClick={() => setPlaying(true)}
                  className="absolute inset-0 flex items-center justify-center group"
                  aria-label="Play"
                >
                  <div className="w-16 h-16 rounded-full bg-black/40 border border-white/30 backdrop-blur-sm flex items-center justify-center group-hover:bg-forest-600/50 transition-colors">
                    <Icons.Play size={28} className="text-white ml-1" />
                  </div>
                </button>
              )}
            </div>
            {/* Player controls */}
            <div className="bg-navy-900 px-4 py-3 border-t border-slate-800">
              <div className="flex items-center gap-3">
                <IconButton
                  icon={playing ? Icons.Pause : Icons.Play}
                  label={playing ? 'Pause' : 'Play'}
                  onClick={() => setPlaying((p) => !p)}
                  variant="outline"
                />
                <div className="font-mono text-[11px] text-slate-400 tabular-nums shrink-0">
                  00:{String(t_now).padStart(2, '0')} / 00:{String(duration).padStart(2, '0')}
                </div>
                <div className="flex-1 relative">
                  <div className="h-1.5 bg-slate-750 rounded-full overflow-hidden">
                    <div className="absolute inset-y-0 left-0 bg-forest-500 rounded-full" style={{ width: `${progress * 100}%` }} />
                  </div>
                  <input
                    type="range"
                    min="0"
                    max="1"
                    step="0.01"
                    value={progress}
                    onChange={(e) => setProgress(parseFloat(e.target.value))}
                    className="absolute inset-0 opacity-0 cursor-pointer w-full"
                    aria-label="Scrubber"
                  />
                </div>
                {clip && (
                  <Pill tone="ghost" className="font-mono">
                    <Icons.Clock size={11} />
                    {t('modal.retentionDays', { n: clip.retention_until })}
                  </Pill>
                )}
              </div>
            </div>

            {/* Caption */}
            {trk?.caption && (
              <div className="px-4 py-3 border-t border-slate-800">
                <div className="text-[10px] uppercase tracking-wider text-slate-500 font-medium mb-1">{t('modal.caption')}</div>
                <p className="text-[13px] text-slate-200 leading-relaxed">"{trk.caption}"</p>
              </div>
            )}
          </div>

          {/* Right metadata pane */}
          <div className="bg-slate-850/40 border-l border-slate-800 p-4 space-y-4 overflow-auto">
            {/* Identity */}
            <div>
              <div className="text-[10px] uppercase tracking-wider text-slate-500 font-medium mb-2">{t('modal.identity')}</div>
              <div className="flex items-center gap-3">
                <IdentityAvatar identity={identity} size={40} />
                <div className="min-w-0">
                  <div className="font-medium text-slate-100 text-sm truncate">
                    {identity ? identity.name : t('modal.unknown')}
                  </div>
                  <div className="text-[11px] text-slate-400 truncate">
                    {identity ? identity.role : (trk?.class === 'vehicle' ? t('class.vehicle') : trk?.class === 'animal' ? t('class.animal') : 'Pessoa não enrolada')}
                  </div>
                </div>
              </div>
            </div>

            {/* Metadata grid */}
            <div>
              <div className="text-[10px] uppercase tracking-wider text-slate-500 font-medium mb-2">{t('modal.metadata')}</div>
              <dl className="grid grid-cols-[max-content_1fr] gap-x-3 gap-y-1.5 text-[12px]">
                <dt className="text-slate-500">{t('modal.time')}</dt>
                <dd className="text-slate-200 font-mono">{formatDateTime(evts)}</dd>
                <dt className="text-slate-500">{t('modal.camera')}</dt>
                <dd className="text-slate-200">{cam?.name} <span className="text-slate-500 font-mono">· {cam?.short}</span></dd>
                {zone && (
                  <>
                    <dt className="text-slate-500">{t('modal.zone')}</dt>
                    <dd className="text-slate-200">
                      <span className="inline-flex items-center gap-1.5">
                        <span className="w-1.5 h-1.5 rounded-full" style={{ background: ZONE_ROLES[zone.semantic_role]?.color }} />
                        {zone.name}
                        <span className="text-slate-500 text-[11px]">· {lang === 'pt-PT' ? ZONE_ROLES[zone.semantic_role]?.label_pt : ZONE_ROLES[zone.semantic_role]?.label_en}</span>
                      </span>
                    </dd>
                  </>
                )}
                <dt className="text-slate-500">{t('modal.duration')}</dt>
                <dd className="text-slate-200 font-mono">{duration}s</dd>
                {event?.payload?.confidence && (
                  <>
                    <dt className="text-slate-500">{t('modal.confidence')}</dt>
                    <dd className="text-forest-400 font-mono">{(event.payload.confidence * 100).toFixed(1)}%</dd>
                  </>
                )}
                {event?.payload?.rule && (
                  <>
                    <dt className="text-slate-500">Regra</dt>
                    <dd className="text-slate-200">{event.payload.rule}</dd>
                  </>
                )}
                {event?.payload?.dwellTime && (
                  <>
                    <dt className="text-slate-500">Tempo</dt>
                    <dd className="text-slate-200 font-mono">{Math.floor(event.payload.dwellTime / 60)}m {event.payload.dwellTime % 60}s</dd>
                  </>
                )}
              </dl>
            </div>

            {/* Attributes */}
            {trk?.attributes && (trk.attributes.clothing || trk.attributes.carrying?.length || trk.attributes.vehicle) && (
              <div>
                <div className="text-[10px] uppercase tracking-wider text-slate-500 font-medium mb-2">{t('modal.attributes')}</div>
                {trk.attributes.clothing && (
                  <div className="space-y-1 mb-2">
                    <div className="text-[10px] uppercase tracking-wider text-slate-500">{t('modal.clothing')}</div>
                    <div className="flex flex-wrap gap-1">
                      {trk.attributes.clothing.upper && <Pill tone="slate">{t('modal.upper')}: {trk.attributes.clothing.upper}</Pill>}
                      {trk.attributes.clothing.lower && <Pill tone="slate">{t('modal.lower')}: {trk.attributes.clothing.lower}</Pill>}
                      {trk.attributes.clothing.outerwear && <Pill tone="slate">{t('modal.outerwear')}: {trk.attributes.clothing.outerwear}</Pill>}
                    </div>
                  </div>
                )}
                {trk.attributes.vehicle && (
                  <div className="space-y-1 mb-2">
                    <div className="text-[10px] uppercase tracking-wider text-slate-500">Veículo</div>
                    <div className="flex flex-wrap gap-1">
                      <Pill tone="slate">{trk.attributes.vehicle.kind}</Pill>
                      <Pill tone="slate">{trk.attributes.vehicle.color}</Pill>
                      <Pill tone="slate" className="font-mono">{trk.attributes.vehicle.plate}</Pill>
                    </div>
                  </div>
                )}
                {trk.attributes.carrying?.length > 0 && (
                  <div className="space-y-1">
                    <div className="text-[10px] uppercase tracking-wider text-slate-500">{t('modal.carrying')}</div>
                    <div className="flex flex-wrap gap-1">
                      {trk.attributes.carrying.map((c, i) => (
                        <Pill tone="navy" key={i}><Icons.Backpack size={11} /> {c}</Pill>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            )}

            {/* Zones visited */}
            {trk?.zones_visited?.length > 0 && (
              <div>
                <div className="text-[10px] uppercase tracking-wider text-slate-500 font-medium mb-2">{t('modal.zones')}</div>
                <div className="flex flex-wrap gap-1.5">
                  {trk.zones_visited.map((zid) => {
                    const z = lookupZone(zid);
                    if (!z) return null;
                    return (
                      <Pill tone="slate" key={zid}>
                        <span className="w-1.5 h-1.5 rounded-full" style={{ background: ZONE_ROLES[z.semantic_role]?.color }} />
                        {z.name}
                      </Pill>
                    );
                  })}
                </div>
              </div>
            )}

            {/* Find again CTA */}
            <button
              onClick={() => onFindAgain?.(trk)}
              className="w-full mt-2 flex items-center gap-2 justify-center bg-forest-600 hover:bg-forest-500 text-white rounded h-10 text-[13px] font-medium border border-forest-500 transition-colors"
            >
              <Icons.Scan size={15} />
              {t('modal.findAgain')}
            </button>

            {/* Compliance footer */}
            <div className="mt-2 pt-3 border-t border-slate-800 flex items-center justify-between text-[10px] text-slate-500">
              <span className="inline-flex items-center gap-1.5">
                <Icons.Shield size={11} className="text-forest-500" />
                {t('compliance.law')} · {t('compliance.retention')}
              </span>
              <span className="font-mono">audit_id: aud_{clip?.id?.slice(-6) || '000000'}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

window.ClipModal = ClipModal;
