// Detailed Ad Modal — full V3 styling, V1-level depth
// Big creative on left (with platform meta + nav arrows), rich analytics on right with tabs

const AdDetailModal = ({ ad, onClose, onAskAI, onPrev, onNext }) => {
  const [tab, setTab] = React.useState('overview');

  // synthetic timeseries for sparkline — must run unconditionally (hooks rule)
  const series = React.useMemo(() => {
    if (!ad) return [];
    const seed = ad.id || 1;
    const out = [];
    for (let i = 0; i < ad.daysActive; i++) {
      const x = i / Math.max(1, ad.daysActive - 1);
      const base = 0.3 + 0.6 * (1 - Math.pow(1 - x, 2));
      const wobble = Math.sin((seed + i) * 0.7) * 0.12 + Math.sin((seed * 2 + i) * 1.3) * 0.06;
      out.push(Math.max(0.05, Math.min(1, base + wobble)));
    }
    return out;
  }, [ad?.id, ad?.daysActive]);

  if (!ad) return null;

  const spendK = (ad.estSpend / 1000).toFixed(1);
  const reachK = (ad.reach / 1000).toFixed(0);

  const Sparkline = ({ values, height = 60, stroke = 'var(--accent)' }) => {
    const n = values.length;
    if (!n) return null;
    const w = 100;
    const points = values.map((v, i) => `${(i / (n - 1 || 1)) * w},${(1 - v) * height}`).join(' ');
    const area = `0,${height} ${points} ${w},${height}`;
    return (
      <svg width="100%" height={height} viewBox={`0 0 ${w} ${height}`} preserveAspectRatio="none" style={{ display: 'block' }}>
        <defs>
          <linearGradient id={`spark-${ad.id}`} x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="var(--accent)" stopOpacity="0.25"/>
            <stop offset="100%" stopColor="var(--accent)" stopOpacity="0"/>
          </linearGradient>
        </defs>
        <polygon points={area} fill={`url(#spark-${ad.id})`}/>
        <polyline points={points} fill="none" stroke={stroke} strokeWidth="1.5" vectorEffect="non-scaling-stroke" strokeLinejoin="round" strokeLinecap="round"/>
      </svg>
    );
  };

  const platforms = ad.platform === 'meta'
    ? [{ k: 'fb',  label: 'Facebook' },  { k: 'ig', label: 'Instagram' }, { k: 'msg', label: 'Messenger' }, { k: 'an', label: 'Audience Net' }]
    : [{ k: 'tt', label: 'TikTok' }];

  const variants = [
    { id: 'A', spend: ad.estSpend, days: ad.daysActive, status: 'active' },
    { id: 'B', spend: Math.round(ad.estSpend * 0.7), days: Math.round(ad.daysActive * 0.6), status: 'active' },
    { id: 'C', spend: Math.round(ad.estSpend * 0.4), days: Math.round(ad.daysActive * 0.3), status: 'paused' },
    { id: 'D', spend: Math.round(ad.estSpend * 0.25), days: Math.round(ad.daysActive * 0.2), status: 'paused' },
  ];

  const transcript = [
    { t: '0:00', text: "I've been drinking this every morning for 90 days." },
    { t: '0:06', text: "The afternoon crash — completely gone." },
    { t: '0:13', text: "75 ingredients in one scoop, mixed with cold water." },
    { t: '0:21', text: "Link in bio if you want to try it." },
  ];

  const similar = (window.ADS_V3 || []).filter(x => x.id !== ad.id).slice(0, 4);

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(14,18,27,0.55)',
      zIndex: 100, display: 'grid', placeItems: 'center',
      backdropFilter: 'blur(8px)',
      padding: 24,
    }}>
      {/* Nav arrows outside */}
      {onPrev && (
        <button onClick={(e) => { e.stopPropagation(); onPrev(); }}
          style={{
            position: 'fixed', left: 24, top: '50%', transform: 'translateY(-50%)',
            width: 44, height: 44, borderRadius: 999,
            background: 'rgba(255,255,255,0.92)', border: 0,
            display: 'grid', placeItems: 'center', cursor: 'pointer',
            boxShadow: '0 8px 24px rgba(14,18,27,0.20)',
            color: 'var(--text)',
          }}><Icon name="arrow-left-s" size={20}/></button>
      )}
      {onNext && (
        <button onClick={(e) => { e.stopPropagation(); onNext(); }}
          style={{
            position: 'fixed', right: 24, top: '50%', transform: 'translateY(-50%)',
            width: 44, height: 44, borderRadius: 999,
            background: 'rgba(255,255,255,0.92)', border: 0,
            display: 'grid', placeItems: 'center', cursor: 'pointer',
            boxShadow: '0 8px 24px rgba(14,18,27,0.20)',
            color: 'var(--text)',
          }}><Icon name="arrow-right-s" size={20}/></button>
      )}

      <div onClick={(e) => e.stopPropagation()} style={{
        width: 1080, maxWidth: '100%', height: '92vh', maxHeight: 880,
        display: 'grid', gridTemplateColumns: '1.05fr 1fr',
        background: 'var(--bg-surface)',
        borderRadius: 18, overflow: 'hidden',
        boxShadow: '0 30px 80px rgba(14,18,27,0.30)',
        border: '1px solid var(--border)',
      }}>
        {/* LEFT: creative + meta */}
        <div style={{
          background: '#0a0c12',
          position: 'relative',
          display: 'flex', flexDirection: 'column',
        }}>
          {/* Creative */}
          <div style={{
            flex: 1, position: 'relative',
            background: ad.thumb,
            backgroundSize: 'cover', backgroundPosition: 'center',
          }}>
            <div style={{
              position: 'absolute', inset: 0,
              background: 'linear-gradient(180deg, rgba(0,0,0,0.35) 0%, rgba(0,0,0,0) 30%, rgba(0,0,0,0) 60%, rgba(0,0,0,0.55))',
            }}/>
            {/* Top chips */}
            <div style={{ position: 'absolute', top: 16, left: 16, display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              <span className="badge" style={{
                background: 'rgba(14,18,27,0.65)', color: '#fff', backdropFilter: 'blur(8px)',
              }}>
                <Icon name={ad.type === 'Video' ? 'play' : 'image-ai'} size={11}/>
                {ad.type}
              </span>
              <span className="badge" style={{
                background: 'rgba(14,18,27,0.65)', color: '#fff', backdropFilter: 'blur(8px)',
              }}>
                {ad.placement || (ad.type === 'Video' ? '9:16' : '4:5')}
              </span>
              {ad.daysActive > 60 && (
                <span className="badge" style={{
                  background: 'rgba(245,158,11,0.95)', color: '#fff',
                }}>
                  <Icon name="flame" size={11}/> Long-running
                </span>
              )}
            </div>
            {/* Type indicator center */}
            {ad.type === 'Video' && (
              <button style={{
                position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%,-50%)',
                width: 64, height: 64, borderRadius: 999,
                background: 'rgba(255,255,255,0.95)',
                display: 'grid', placeItems: 'center', color: 'var(--text)',
                border: 0, cursor: 'pointer',
                boxShadow: '0 12px 32px rgba(0,0,0,0.30)',
              }}><Icon name="play" size={22}/></button>
            )}
            {/* Bottom corner info */}
            <div style={{
              position: 'absolute', bottom: 16, left: 16, right: 16,
              display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between',
              color: '#fff',
            }}>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, opacity: 0.85 }}>
                Ad ID · {String(ad.id).padStart(4, '0')}-{ad.brand.slice(0,3).toUpperCase()}
              </div>
              {ad.type === 'Video' && (
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, opacity: 0.85 }}>
                  0:{String(28 + (ad.id % 30)).padStart(2,'0')}
                </div>
              )}
            </div>
          </div>

          {/* Variants strip */}
          <div style={{
            padding: '14px 18px',
            background: 'rgba(255,255,255,0.04)',
            borderTop: '1px solid rgba(255,255,255,0.08)',
            display: 'flex', alignItems: 'center', gap: 10,
          }}>
            <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.6)', textTransform: 'uppercase', letterSpacing: 0.05, fontWeight: 500 }}>
              {variants.length} variants
            </div>
            <div style={{ display: 'flex', gap: 6, flex: 1 }}>
              {variants.map((v, i) => (
                <button key={v.id} style={{
                  width: 36, height: 48, borderRadius: 6,
                  background: ad.thumb, backgroundSize: 'cover',
                  border: i === 0 ? '2px solid var(--accent)' : '2px solid transparent',
                  position: 'relative', cursor: 'pointer',
                  filter: v.status === 'paused' ? 'grayscale(0.6) opacity(0.55)' : 'none',
                }}>
                  <span style={{
                    position: 'absolute', top: 2, right: 2,
                    width: 14, height: 14, borderRadius: 4,
                    background: v.status === 'active' ? 'var(--accent)' : 'rgba(255,255,255,0.3)',
                    color: '#fff', fontSize: 9, fontWeight: 600,
                    display: 'grid', placeItems: 'center',
                  }}>{v.id}</span>
                </button>
              ))}
            </div>
            <div style={{ display: 'flex', gap: 6 }}>
              {platforms.map(p => (
                <span key={p.k} style={{
                  fontSize: 11, padding: '4px 8px', borderRadius: 6,
                  background: 'rgba(255,255,255,0.10)', color: 'rgba(255,255,255,0.85)',
                }}>{p.label}</span>
              ))}
            </div>
          </div>
        </div>

        {/* RIGHT: details */}
        <div style={{ display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
          {/* Header */}
          <div style={{
            padding: '18px 22px',
            borderBottom: '1px solid var(--border)',
            display: 'flex', alignItems: 'center', gap: 12,
          }}>
            <BrandChip name={ad.brand} size={36} square/>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <span style={{ fontWeight: 600, fontSize: 14 }}>{ad.brand}</span>
                <Icon name="check-circle" size={13} style={{ color: 'var(--accent)' }}/>
              </div>
              <div style={{ fontSize: 12, color: 'var(--text-faint)' }}>{ad.handle} · 1.2M followers</div>
            </div>
            <button className="btn btn-stroke btn-sm">
              <Icon name="bell" size={13}/> Track brand
            </button>
            <button onClick={onClose} className="btn btn-ghost btn-icon">
              <Icon name="close" size={16}/>
            </button>
          </div>

          {/* Tabs */}
          <div style={{
            padding: '0 22px',
            borderBottom: '1px solid var(--border)',
            display: 'flex', gap: 22,
          }}>
            {[
              { k: 'overview',   label: 'Overview' },
              { k: 'analytics',  label: 'Analytics' },
              { k: 'transcript', label: 'Transcript' },
              { k: 'similar',    label: 'Similar' },
            ].map(t => (
              <button key={t.k} onClick={() => setTab(t.k)}
                style={{
                  padding: '14px 0',
                  fontSize: 13, fontWeight: tab === t.k ? 600 : 500,
                  color: tab === t.k ? 'var(--text)' : 'var(--text-muted)',
                  borderBottom: tab === t.k ? '2px solid var(--accent)' : '2px solid transparent',
                  marginBottom: -1,
                  cursor: 'pointer', background: 'transparent', border: 'none', borderRadius: 0,
                }}>{t.label}</button>
            ))}
          </div>

          {/* Body */}
          <div className="scroll" style={{ flex: 1, overflowY: 'auto', padding: 22 }}>
            {tab === 'overview' && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
                <div>
                  <div className="font-display" style={{ fontWeight: 600, fontSize: 17, color: 'var(--text)', marginBottom: 6, lineHeight: 1.35 }}>
                    {ad.title}
                  </div>
                  <div style={{ fontSize: 13, color: 'var(--text-2)', lineHeight: 1.6 }}>
                    {ad.body} {ad.headline ? `${ad.headline}.` : ''} Built for daily wear, drawn from archive cuts and real-customer language.
                  </div>
                </div>

                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10 }}>
                  {[
                    { k: 'Est. spend',     v: '€' + spendK + 'k', sub: 'last 30d', accent: true },
                    { k: 'Reach',          v: reachK + 'k',       sub: 'unique users' },
                    { k: 'Days active',    v: ad.daysActive + 'd', sub: 'since launch' },
                    { k: 'Engagement',     v: ((0.4 + (ad.id % 30) / 100)).toFixed(1) + '%', sub: 'er median' },
                  ].map(s => (
                    <div key={s.k} style={{
                      padding: 14, borderRadius: 12,
                      background: s.accent ? 'var(--accent-soft)' : 'var(--bg-soft)',
                      border: s.accent ? '1px solid var(--accent-soft)' : '1px solid var(--border)',
                    }}>
                      <div style={{ fontSize: 11, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: 0.05, fontWeight: 500 }}>{s.k}</div>
                      <div style={{
                        fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 22, marginTop: 4,
                        color: s.accent ? 'var(--accent)' : 'var(--text)',
                      }}>{s.v}</div>
                      <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2 }}>{s.sub}</div>
                    </div>
                  ))}
                </div>

                <div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
                    <div style={{ fontSize: 11, fontWeight: 500, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: 0.05 }}>
                      Spend velocity · {ad.daysActive}d
                    </div>
                    <div style={{ fontSize: 12, color: 'var(--success)', fontWeight: 500 }}>
                      <Icon name="trend-up" size={11}/> +{14 + (ad.id % 18)}%
                    </div>
                  </div>
                  <Sparkline values={series}/>
                </div>

                <div>
                  <div style={{ fontSize: 11, fontWeight: 500, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: 0.05, marginBottom: 8 }}>
                    Targeting & meta
                  </div>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                    {[
                      ad.platform === 'meta' ? 'Meta' : 'TikTok',
                      ad.placement || 'Feed',
                      'US, UK, CA',
                      'Age 25–44',
                      'Mobile-first',
                      ad.type === 'Video' ? 'Sound on' : 'Static',
                      'Lookalike 1%',
                    ].map(t => <span key={t} className="chip" style={{ height: 26, fontSize: 12 }}>{t}</span>)}
                  </div>
                </div>

                <div style={{
                  padding: 14, borderRadius: 12,
                  background: 'var(--accent-soft)',
                  border: '1px solid var(--accent-soft)',
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6, color: 'var(--accent)', fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.04 }}>
                    <Icon name="sparkles" size={12}/> AI verdict
                  </div>
                  <div style={{ fontSize: 13, lineHeight: 1.55, color: 'var(--text-2)' }}>
                    Strong winner. Hook lands by 0:03 with a personal-streak claim, payoff arrives at 0:13 with the "afternoon crash gone" reframe. The {ad.daysActive}-day runway and {Math.round(ad.estSpend / 1000)}k spend put this in the top 8% of {ad.brand}'s active creatives.
                  </div>
                </div>
              </div>
            )}

            {tab === 'analytics' && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
                <div>
                  <div style={{ fontSize: 11, fontWeight: 500, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: 0.05, marginBottom: 10 }}>
                    Spend timeline
                  </div>
                  <div style={{
                    padding: 16, borderRadius: 12,
                    background: 'var(--bg-soft)', border: '1px solid var(--border)',
                  }}>
                    <Sparkline values={series} height={120}/>
                    <div style={{
                      display: 'flex', justifyContent: 'space-between',
                      fontSize: 11, color: 'var(--text-faint)', fontFamily: 'var(--font-mono)',
                      marginTop: 4,
                    }}>
                      <span>Day 1</span><span>Day {Math.floor(ad.daysActive / 2)}</span><span>Today</span>
                    </div>
                  </div>
                </div>

                <div>
                  <div style={{ fontSize: 11, fontWeight: 500, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: 0.05, marginBottom: 10 }}>
                    Platform breakdown
                  </div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                    {[
                      { p: 'Facebook',  pct: 48 },
                      { p: 'Instagram', pct: 39 },
                      { p: 'Messenger', pct:  9 },
                      { p: 'Audience Network', pct: 4 },
                    ].map(r => (
                      <div key={r.p} style={{ display: 'grid', gridTemplateColumns: '120px 1fr 40px', alignItems: 'center', gap: 10 }}>
                        <span style={{ fontSize: 12, color: 'var(--text-2)' }}>{r.p}</span>
                        <div style={{ height: 6, borderRadius: 999, background: 'var(--bg-soft)', overflow: 'hidden' }}>
                          <div style={{ width: r.pct + '%', height: '100%', background: 'var(--accent)' }}/>
                        </div>
                        <span style={{ fontSize: 12, fontFamily: 'var(--font-mono)', color: 'var(--text)', textAlign: 'right' }}>{r.pct}%</span>
                      </div>
                    ))}
                  </div>
                </div>

                <div>
                  <div style={{ fontSize: 11, fontWeight: 500, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: 0.05, marginBottom: 10 }}>
                    Variants performance
                  </div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                    {variants.map(v => (
                      <div key={v.id} style={{
                        padding: '10px 12px', borderRadius: 10,
                        border: '1px solid var(--border)',
                        background: v.id === 'A' ? 'var(--accent-soft)' : 'var(--bg-surface)',
                        display: 'grid', gridTemplateColumns: '24px 1fr auto auto', gap: 12, alignItems: 'center',
                      }}>
                        <span style={{
                          width: 24, height: 24, borderRadius: 6,
                          background: v.id === 'A' ? 'var(--accent)' : 'var(--bg-soft)',
                          color: v.id === 'A' ? '#fff' : 'var(--text-2)',
                          display: 'grid', placeItems: 'center', fontSize: 11, fontWeight: 600,
                        }}>{v.id}</span>
                        <span style={{ fontSize: 12, color: 'var(--text-2)' }}>
                          {v.status === 'active' ? <span style={{ color: 'var(--success)' }}>● </span> : <span style={{ color: 'var(--text-faint)' }}>● </span>}
                          {v.status}
                        </span>
                        <span style={{ fontSize: 12, fontFamily: 'var(--font-mono)', color: 'var(--text)' }}>€{(v.spend/1000).toFixed(1)}k</span>
                        <span style={{ fontSize: 12, fontFamily: 'var(--font-mono)', color: 'var(--text-muted)' }}>{v.days}d</span>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            )}

            {tab === 'transcript' && (
              <div>
                {ad.type !== 'Video' && (
                  <div style={{
                    padding: 16, borderRadius: 12, background: 'var(--bg-soft)',
                    border: '1px solid var(--border)', textAlign: 'center',
                    color: 'var(--text-muted)', fontSize: 13,
                  }}>
                    This ad is a static image. No transcript.
                  </div>
                )}
                {ad.type === 'Video' && (
                  <>
                    <div style={{
                      fontSize: 11, fontWeight: 500, color: 'var(--text-faint)',
                      textTransform: 'uppercase', letterSpacing: 0.05, marginBottom: 12,
                      display: 'flex', alignItems: 'center', gap: 8,
                    }}>
                      Transcript · {transcript.length} segments
                      <button className="btn btn-ghost btn-xs" style={{ marginLeft: 'auto' }}>
                        <Icon name="copy" size={11}/> Copy all
                      </button>
                    </div>
                    {transcript.map((line, i) => (
                      <div key={i} style={{
                        display: 'flex', gap: 12, padding: '10px 0',
                        borderBottom: i < transcript.length - 1 ? '1px solid var(--border-soft)' : 'none',
                      }}>
                        <span style={{
                          flexShrink: 0, fontSize: 11, fontFamily: 'var(--font-mono)',
                          color: 'var(--accent)', fontWeight: 500,
                          padding: '3px 8px', borderRadius: 6,
                          background: 'var(--accent-soft)', alignSelf: 'flex-start',
                        }}>{line.t}</span>
                        <div style={{ fontSize: 13, lineHeight: 1.6, color: 'var(--text)' }}>{line.text}</div>
                      </div>
                    ))}
                    <div style={{
                      marginTop: 16, padding: 14, borderRadius: 12,
                      background: 'var(--accent-soft)', border: '1px solid var(--accent-soft)',
                      fontSize: 13, lineHeight: 1.55, color: 'var(--text-2)',
                    }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6, color: 'var(--accent)', fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.04 }}>
                        <Icon name="sparkles" size={12}/> Hook breakdown
                      </div>
                      Opens with a personal-streak claim ("90 days"), pivots to outcome at 0:06 (afternoon crash gone), credentialed at 0:13 (75 ingredients), CTA at 0:21.
                    </div>
                  </>
                )}
              </div>
            )}

            {tab === 'similar' && (
              <div>
                <div style={{
                  fontSize: 11, fontWeight: 500, color: 'var(--text-faint)',
                  textTransform: 'uppercase', letterSpacing: 0.05, marginBottom: 12,
                }}>
                  Similar creatives · same hook structure
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                  {similar.map(s => (
                    <div key={s.id} style={{
                      borderRadius: 10, overflow: 'hidden',
                      border: '1px solid var(--border)', cursor: 'pointer',
                      background: 'var(--bg-surface)',
                    }}>
                      <div style={{ aspectRatio: '4/5', background: s.thumb }}/>
                      <div style={{ padding: 10 }}>
                        <div style={{ fontSize: 12, fontWeight: 500, color: 'var(--text)', marginBottom: 4, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.brand}</div>
                        <div style={{ fontSize: 11, color: 'var(--text-faint)', display: 'flex', justifyContent: 'space-between' }}>
                          <span>€{(s.estSpend/1000).toFixed(1)}k</span>
                          <span>{s.daysActive}d</span>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* Footer actions */}
          <div style={{
            padding: '14px 22px',
            borderTop: '1px solid var(--border)',
            display: 'flex', gap: 8,
          }}>
            <button onClick={onAskAI} className="btn btn-primary btn-sm" style={{ flex: 1, justifyContent: 'center' }}>
              <Icon name="sparkles" size={14}/> Ask AI about this ad
            </button>
            <button className="btn btn-night btn-sm">
              <Icon name="bookmark" size={14}/> Save
            </button>
            <button className="btn btn-stroke btn-sm">
              <Icon name="copy" size={14}/>
            </button>
            <button className="btn btn-stroke btn-sm">
              <Icon name="external" size={14}/>
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

window.AdDetailModal = AdDetailModal;
