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

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

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

  if (!ad) return null;
  const p = PLATFORMS[ad.platform] || PLATFORMS.foreplay;
  const transcript = ad.transcript || [];
  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);
  };

  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: ad.thumb }}>
            {playing && ad.creativeUrl ? (
              <video
                src={ad.creativeUrl}
                poster={ad.thumbnailUrl || undefined}
                controls
                autoPlay
                style={{ width: '100%', height: '100%', objectFit: 'cover', borderRadius: 'inherit' }}
              />
            ) : (
              <>
                <button
                  className="ad-play"
                  style={{ width: 56, height: 56, border: 'none', cursor: ad.creativeUrl ? 'pointer' : 'default' }}
                  onClick={() => ad.creativeUrl && setPlaying(true)}
                  title={ad.creativeUrl ? 'Play' : 'No video available'}
                  disabled={!ad.creativeUrl}
                >
                  <Icon name="play" size={20} />
                </button>
                {ad.duration && (
                  <span className="ad-duration" style={{ bottom: 12, right: 12 }}>{ad.duration}</span>
                )}
              </>
            )}
          </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 Autoresearch
                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
                  ? `${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 ? (
              <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>
    </>
  );
};
