const { useEffect: useEffectAD, useState: useStateAD } = React;

window.AdDrawer = function AdDrawer({ ad, onClose }) {
  const [playing, setPlaying] = useStateAD(false);

  useEffectAD(() => {
    if (!ad) return;
    setPlaying(!!ad.__autoPlay);
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [ad?.id, ad?.__autoPlay]);

  if (!ad) return null;
  const p = PLATFORMS[ad.platform] || PLATFORMS.foreplay;
  const raw = ad.raw && typeof ad.raw === 'object' ? ad.raw : {};
  const creativeUrl = ad.creativeUrl
    || ad.videoUrl
    || raw.creative_url
    || raw.creativeUrl
    || raw.video
    || raw.video_url
    || raw.video_hd_url
    || raw.video_sd_url
    || raw.videoMediaPath
    || raw.video_media_path
    || null;
  const thumbnailUrl = ad.thumbnailUrl
    || raw.thumbnail_url
    || raw.thumbnail
    || raw.thumb_url
    || raw.thumb
    || raw.image_url
    || raw.image
    || null;
  const transcript = ad.transcript || [];
  const transcriptSource = ad.transcriptSource
    || ad.transcript_source
    || raw.transcript_source
    || raw.transcriptSource
    || (raw.brandsearch_transcript && raw.brandsearch_transcript.status)
    || (transcript.length > 0 ? 'generated' : 'missing');
  const isFallbackTranscript = ['copy_fallback', 'fallback', 'unavailable', 'empty'].includes(transcriptSource)
    || ad.isVoiceTranscript === false;
  const transcriptProvider = ad.transcriptProvider
    || ad.transcript_provider
    || raw.transcript_provider
    || (raw.brandsearch_transcript && raw.brandsearch_transcript.provider)
    || null;
  const transcriptModel = ad.transcriptModel
    || ad.transcript_model
    || raw.transcript_model
    || (raw.brandsearch_transcript && raw.brandsearch_transcript.model)
    || null;
  const providerLabel = transcriptProvider
    ? ` · ${transcriptProvider}${transcriptModel ? ` / ${transcriptModel}` : ''}`
    : '';
  const transcriptSourceLabel = isFallbackTranscript
    ? 'Fallback copy'
    : transcriptSource === 'generated_cached'
      ? `Real transcript (cached)${providerLabel}`
      : transcriptSource === 'generated'
        ? `Real transcript${providerLabel}`
        : transcriptSource === 'source_transcription'
          ? 'Source transcript'
          : transcriptSource === 'existing'
            ? `Real transcript${providerLabel}`
          : 'Transcript status unknown';
  const metricChips = RESILIA_ADAPT.metricChips(ad);
  const scoreText = (typeof ad.score === 'number')
    ? (ad.score > 10 ? Math.round(ad.score) : ad.score.toFixed(1))
    : '—';

  const copyReasoning = () => {
    if (ad.reasoning) navigator.clipboard?.writeText(ad.reasoning);
  };
  const copyTranscript = () => {
    const text = ad.transcriptRaw || transcript.map(l => `[${l.t}] ${l.body}`).join('\n');
    if (text) navigator.clipboard?.writeText(text);
  };
  const copyVideoUrl = () => {
    if (creativeUrl) navigator.clipboard?.writeText(creativeUrl);
  };

  return (
    <>
      <div className="drawer-scrim" onClick={onClose} />
      <aside className="drawer" role="dialog" aria-label="Ad details">
        <header className="drawer-hdr">
          <span className="ad-plat" style={{ background: p.bg, color: p.color, position: 'static' }}>
            <span className="ad-plat-dot" style={{ background: p.color }} />
            {p.label}
          </span>
          <span className="drawer-id">{ad.id}</span>
          <div style={{ flex: 1 }} />
          <button className="icon-btn" onClick={onClose} title="Close (Esc)">
            <Icon name="x" size={16} />
          </button>
        </header>

        <div className="drawer-body">
          <div className="drawer-media" style={{ background: creativeUrl ? '#111827' : ad.thumb }}>
            {playing && creativeUrl ? (
              <video
                src={creativeUrl}
                poster={thumbnailUrl || undefined}
                controls
                autoPlay
                playsInline
                preload="auto"
                onCanPlay={(e) => {
                  const playPromise = e.currentTarget.play();
                  if (playPromise && typeof playPromise.catch === 'function') playPromise.catch(() => {});
                }}
                style={{ width: '100%', height: '100%', objectFit: 'cover', borderRadius: 'inherit' }}
              />
            ) : (
              <>
                {thumbnailUrl && (
                  <img
                    src={thumbnailUrl}
                    alt={`${ad.brand || 'Ad'} thumbnail`}
                    style={{ width: '100%', height: '100%', objectFit: 'cover', borderRadius: 'inherit' }}
                  />
                )}
                <button
                  className="ad-play"
                  style={{ width: 56, height: 56, border: 'none', cursor: creativeUrl ? 'pointer' : 'default' }}
                  onClick={() => creativeUrl && setPlaying(true)}
                  title={creativeUrl ? 'Play' : 'No video available'}
                  disabled={!creativeUrl}
                >
                  <Icon name="play" size={20} />
                </button>
                {ad.duration && (
                  <span className="ad-duration" style={{ bottom: 12, right: 12 }}>{ad.duration}</span>
                )}
              </>
            )}
          </div>

          {creativeUrl && (
            <div className="drawer-section">
              <div className="drawer-section-hdr">
                <Icon name="film" size={14} />
                <span className="drawer-section-title">Video URL</span>
                <span className="drawer-section-meta">Creative source</span>
                <div style={{ flex: 1 }} />
                <button className="ghost-btn" onClick={copyVideoUrl}>
                  <Icon name="copy" size={12} /> Copy
                </button>
              </div>
              <div className="transcript-body" style={{ fontSize: 12, lineHeight: 1.4, wordBreak: 'break-all' }}>
                <a href={creativeUrl} target="_blank" rel="noreferrer">{creativeUrl}</a>
              </div>
            </div>
          )}

          <div className="drawer-section">
            <h3 className="drawer-brand">{ad.brand}</h3>
            {ad.copy && <p className="drawer-copy">{ad.copy}</p>}
            <div className="drawer-stats">
              <div className="stat">
                <span className="stat-label">Winning score</span>
                <span className="stat-value stat-score">
                  <Icon name="trend" size={12} />
                  {scoreText}
                </span>
              </div>
              <div className="stat">
                <span className="stat-label">Running</span>
                <span className="stat-value">{ad.daysRunning ? `${ad.daysRunning}d` : '—'}</span>
              </div>
              {metricChips.map(({ label, statLabel, value, title }) => (
                <div className="stat" key={label} title={title}>
                  <span className="stat-label">{statLabel}</span>
                  <span className="stat-value">{value}</span>
                </div>
              ))}
              <div className="stat">
                <span className="stat-label">CTA</span>
                <span className="stat-value">{ad.cta || '—'}</span>
              </div>
              <div className="stat">
                <span className="stat-label">Scraped</span>
                <span className="stat-value">{ad.scrapedAt || '—'}</span>
              </div>
            </div>
          </div>

          <div className="drawer-section">
            <div className="drawer-section-hdr">
              <Icon name="bolt" size={14} />
              <span className="drawer-section-title">Why it scored</span>
              <span className="drawer-section-meta">
                {ad.reasoning ? 'Evaluator reasoning' : 'Not scored by autoresearch'}
              </span>
              <div style={{ flex: 1 }} />
              <button
                className="ghost-btn"
                disabled={!ad.reasoning}
                onClick={copyReasoning}
              >
                <Icon name="copy" size={12} /> Copy
              </button>
            </div>
            {ad.reasoning ? (
              <div className="transcript-body" style={{ fontSize: 13, lineHeight: 1.5 }}>
                {ad.reasoning}
              </div>
            ) : (
              <div className="transcript-body" style={{ color: 'var(--fg-3)', fontSize: 13 }}>
                Manual-search ads don't carry reasoning. Pass to Filter or run AutoSearch
                to get a scored rationale.
              </div>
            )}
          </div>

          <div className="drawer-section">
            <div className="drawer-section-hdr">
              <Icon name="caption" size={14} />
              <span className="drawer-section-title">Transcript</span>
              <span className="drawer-section-meta">
                {transcript.length > 0
                  ? `${transcriptSourceLabel} · ${transcript.length} lines`
                  : ad.transcriptStatus === 'fallback'
                    ? 'Transcript generation failed; using copy fallback elsewhere'
                    : 'No transcript available'}
              </span>
              <div style={{ flex: 1 }} />
              <button
                className="ghost-btn"
                disabled={transcript.length === 0}
                onClick={copyTranscript}
              >
                <Icon name="copy" size={12} /> Copy
              </button>
            </div>
            {transcript.length > 0 ? (
              <>
                {isFallbackTranscript && (
                  <div
                    className="transcript-body"
                    style={{ color: 'var(--fg-3)', fontSize: 13, marginBottom: 8 }}
                  >
                    This is the platform caption/description fallback, not audio transcribed from the video.
                  </div>
                )}
                <div className="transcript-body">
                  {transcript.map((line, i) => (
                    <div key={i} className="transcript-line">
                      <span className="transcript-t">{line.t}</span>
                      <span className="transcript-body-text">{line.body}</span>
                    </div>
                  ))}
                </div>
              </>
            ) : (
              <div className="transcript-body" style={{ color: 'var(--fg-3)', fontSize: 13 }}>
                Transcript not yet scraped for this ad.
              </div>
            )}
          </div>
        </div>
      </aside>
    </>
  );
};
