// Creative Examples — components

const { useState, useEffect, useRef, useMemo } = React;

// --- Beehiiv ---
const BEEHIIV_PUB_ID = 'pub_71d19aae-7467-46af-a607-0fe078358d93';
// Add your Beehiiv API key from Settings → API Keys in your Beehiiv dashboard
const BEEHIIV_API_KEY = 'l727CkarsuUck4N8ez75LkInvuRckSm8zAs62jXTisCETYx7UfYcV7bDIHZCDBCn';

async function subscribe(email) {
  const res = await fetch(
    `https://api.beehiiv.com/v2/publications/${BEEHIIV_PUB_ID}/subscriptions`,
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${BEEHIIV_API_KEY}`,
      },
      body: JSON.stringify({ email, reactivate_existing: false, send_welcome_email: true }),
    }
  );
  if (!res.ok) throw new Error('Subscription failed');
}

// --- Palette ---
const C = {
  cream: '#f7f4ef',
  creamDeep: '#ede7dc',
  charcoal: '#03443e',
  coral: '#ea553c',
  sky: '#c3cebe',
  sand: '#dd9550',
};

// --- Abstract thumbnail placeholders in brand palette ---
// Generate SVG compositions. Each variant is deterministic per id.
function Thumb({ variant = 0, seed = 0 }) {
  const variants = [
    // Wavy gradient blobs (echoes the brand sheet sample)
    <svg key="a" viewBox="0 0 400 260" preserveAspectRatio="none" style={{ width: '100%', height: '100%', display: 'block' }}>
      <defs>
        <filter id={`blur-${seed}`} x="-20%" y="-20%" width="140%" height="140%">
          <feGaussianBlur stdDeviation="22" />
        </filter>
      </defs>
      <rect width="400" height="260" fill={C.cream} />
      <g filter={`url(#blur-${seed})`}>
        <ellipse cx="80" cy="90" rx="120" ry="80" fill={C.coral} opacity="0.9" />
        <ellipse cx="280" cy="60" rx="110" ry="70" fill={C.sky} opacity="0.95" />
        <ellipse cx="320" cy="210" rx="140" ry="90" fill={C.sand} opacity="0.85" />
        <ellipse cx="120" cy="220" rx="100" ry="60" fill={C.coral} opacity="0.7" />
      </g>
    </svg>,
    // Bold stripes
    <svg key="b" viewBox="0 0 400 260" preserveAspectRatio="none" style={{ width: '100%', height: '100%', display: 'block' }}>
      <rect width="400" height="260" fill={C.charcoal} />
      <rect x="0" y="40" width="400" height="28" fill={C.coral} />
      <rect x="0" y="90" width="400" height="14" fill={C.sand} />
      <rect x="0" y="120" width="400" height="44" fill={C.sky} />
      <rect x="0" y="180" width="400" height="20" fill={C.cream} />
      <rect x="0" y="215" width="400" height="10" fill={C.coral} />
    </svg>,
    // Big type placeholder
    <svg key="c" viewBox="0 0 400 260" preserveAspectRatio="none" style={{ width: '100%', height: '100%', display: 'block' }}>
      <rect width="400" height="260" fill={C.coral} />
      <text x="200" y="155" textAnchor="middle" fontFamily="Instrument Serif, serif" fontSize="130" fill={C.cream} fontStyle="italic">ad</text>
      <circle cx="320" cy="60" r="28" fill={C.sky} />
    </svg>,
    // Dotted grid
    <svg key="d" viewBox="0 0 400 260" preserveAspectRatio="none" style={{ width: '100%', height: '100%', display: 'block' }}>
      <rect width="400" height="260" fill={C.sky} />
      {[...Array(7)].map((_, y) => [...Array(11)].map((_, x) => (
        <circle key={`${x}-${y}`} cx={30 + x * 35} cy={30 + y * 35} r={(x + y) % 3 === 0 ? 10 : 5} fill={(x + y) % 4 === 0 ? C.coral : C.charcoal} />
      )))}
    </svg>,
    // Phone mockup
    <svg key="e" viewBox="0 0 400 260" preserveAspectRatio="none" style={{ width: '100%', height: '100%', display: 'block' }}>
      <rect width="400" height="260" fill={C.sand} />
      <rect x="155" y="30" width="90" height="200" rx="12" fill={C.charcoal} />
      <rect x="163" y="45" width="74" height="165" rx="4" fill={C.cream} />
      <rect x="170" y="55" width="60" height="8" rx="2" fill={C.coral} />
      <rect x="170" y="70" width="40" height="6" rx="2" fill={C.charcoal} opacity="0.4" />
      <circle cx="200" cy="130" r="22" fill={C.coral} />
      <polygon points="194,120 214,130 194,140" fill={C.cream} />
    </svg>,
    // Big quote
    <svg key="f" viewBox="0 0 400 260" preserveAspectRatio="none" style={{ width: '100%', height: '100%', display: 'block' }}>
      <rect width="400" height="260" fill={C.cream} />
      <text x="40" y="180" fontFamily="Instrument Serif, serif" fontSize="240" fill={C.coral}>"</text>
      <rect x="150" y="90" width="220" height="10" rx="2" fill={C.charcoal} />
      <rect x="150" y="115" width="180" height="10" rx="2" fill={C.charcoal} />
      <rect x="150" y="140" width="140" height="10" rx="2" fill={C.sand} />
    </svg>,
    // TikTok-style vertical frames
    <svg key="g" viewBox="0 0 400 260" preserveAspectRatio="none" style={{ width: '100%', height: '100%', display: 'block' }}>
      <rect width="400" height="260" fill={C.charcoal} />
      {[0, 1, 2].map(i => (
        <g key={i}>
          <rect x={40 + i * 115} y="30" width="95" height="200" rx="8" fill={i === 1 ? C.coral : C.sky} />
          <circle cx={87 + i * 115} cy="130" r="18" fill={C.cream} opacity="0.9" />
          <polygon points={`${82 + i * 115},122 ${96 + i * 115},130 ${82 + i * 115},138`} fill={C.charcoal} />
        </g>
      ))}
    </svg>,
    // Concentric circles
    <svg key="h" viewBox="0 0 400 260" preserveAspectRatio="none" style={{ width: '100%', height: '100%', display: 'block' }}>
      <rect width="400" height="260" fill={C.cream} />
      <circle cx="200" cy="130" r="110" fill={C.sand} />
      <circle cx="200" cy="130" r="78" fill={C.coral} />
      <circle cx="200" cy="130" r="46" fill={C.sky} />
      <circle cx="200" cy="130" r="18" fill={C.charcoal} />
    </svg>,
    // Chart bars
    <svg key="i" viewBox="0 0 400 260" preserveAspectRatio="none" style={{ width: '100%', height: '100%', display: 'block' }}>
      <rect width="400" height="260" fill={C.sky} />
      <rect x="40" y="180" width="40" height="50" fill={C.charcoal} />
      <rect x="100" y="140" width="40" height="90" fill={C.coral} />
      <rect x="160" y="100" width="40" height="130" fill={C.sand} />
      <rect x="220" y="60" width="40" height="170" fill={C.coral} />
      <rect x="280" y="30" width="40" height="200" fill={C.charcoal} />
      <path d="M 40 70 Q 180 200 320 30" fill="none" stroke={C.cream} strokeWidth="4" />
    </svg>,
    // Overlapping rectangles
    <svg key="j" viewBox="0 0 400 260" preserveAspectRatio="none" style={{ width: '100%', height: '100%', display: 'block' }}>
      <rect width="400" height="260" fill={C.charcoal} />
      <rect x="40" y="50" width="180" height="120" fill={C.sand} transform="rotate(-6 130 110)" />
      <rect x="140" y="80" width="180" height="130" fill={C.coral} transform="rotate(8 230 145)" />
      <rect x="90" y="140" width="140" height="90" fill={C.sky} transform="rotate(-3 160 185)" />
    </svg>,
    // Handwritten scribble
    <svg key="k" viewBox="0 0 400 260" preserveAspectRatio="none" style={{ width: '100%', height: '100%', display: 'block' }}>
      <rect width="400" height="260" fill={C.cream} />
      <path d="M 30 80 C 100 40, 200 140, 370 60" fill="none" stroke={C.coral} strokeWidth="6" strokeLinecap="round" />
      <path d="M 30 140 C 120 100, 220 200, 370 120" fill="none" stroke={C.charcoal} strokeWidth="6" strokeLinecap="round" />
      <path d="M 30 200 C 100 160, 250 240, 370 180" fill="none" stroke={C.sand} strokeWidth="6" strokeLinecap="round" />
    </svg>,
    // Big number
    <svg key="l" viewBox="0 0 400 260" preserveAspectRatio="none" style={{ width: '100%', height: '100%', display: 'block' }}>
      <rect width="400" height="260" fill={C.sand} />
      <text x="200" y="195" textAnchor="middle" fontFamily="Instrument Serif, serif" fontSize="200" fill={C.charcoal} fontWeight="400">18M</text>
    </svg>,
  ];
  return variants[variant % variants.length];
}

// --- Category pill ---
function Pill({ children, tone = 'sky', size = 'sm', active = false, onClick, style }) {
  const tones = {
    coral: { bg: '#fcd9d1', fg: C.charcoal, active: C.coral, activeFg: C.cream },
    sky:   { bg: '#e0e7e1', fg: C.charcoal, active: C.sky, activeFg: C.charcoal },
    sand:  { bg: '#f3dfc5', fg: C.charcoal, active: C.sand, activeFg: C.cream },
    cream: { bg: '#f0e3c9', fg: C.charcoal, active: C.charcoal, activeFg: C.cream },
    charcoal: { bg: '#d9e0dc', fg: C.charcoal, active: C.charcoal, activeFg: C.cream },
  };
  const t = tones[tone] || tones.sky;
  const bg = active ? t.active : t.bg;
  const fg = active ? t.activeFg : t.fg;
  const padding = size === 'sm' ? '5px 11px' : '7px 14px';
  const fs = size === 'sm' ? 12.5 : 13.5;
  return (
    <button
      onClick={onClick}
      style={{
        background: bg, color: fg, border: 'none',
        borderRadius: 999, padding, fontSize: fs, fontWeight: 500,
        fontFamily: 'Inter, system-ui, sans-serif',
        cursor: onClick ? 'pointer' : 'default',
        letterSpacing: 0.1,
        transition: 'background 160ms ease, color 160ms ease',
        ...style,
      }}
    >
      {children}
    </button>
  );
}

// --- Clock icon ---
function ClockIcon({ size = 13, color = C.charcoal }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" style={{ display: 'inline-block', verticalAlign: '-2px' }}>
      <circle cx="12" cy="12" r="9" stroke={color} strokeWidth="2" />
      <path d="M12 7v5l3 2" stroke={color} strokeWidth="2" strokeLinecap="round" />
    </svg>
  );
}

// --- Lightbulb icon (read time on cards) ---
function BulbIcon({ size = 13, color = C.charcoal }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" style={{ display: 'inline-block', verticalAlign: '-2px' }}>
      <path d="M9 18h6M10 21h4M12 3a6 6 0 0 0-4 10.5c.7.8 1.2 1.5 1.5 2.5h5c.3-1 .8-1.7 1.5-2.5A6 6 0 0 0 12 3z" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

// --- Star icon ---
function Star({ size = 12, color = C.coral, filled = true }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill={filled ? color : 'none'} stroke={color} strokeWidth="1.5" style={{ display: 'inline-block' }}>
      <polygon points="12,2 15,9 22,9.5 17,14 18.5,21 12,17.5 5.5,21 7,14 2,9.5 9,9" />
    </svg>
  );
}

// --- Card ---
function Card({ item, onClick }) {
  const [hover, setHover] = useState(false);
  return (
    <article
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      onClick={onClick}
      style={{
        background: '#ffffff',
        borderRadius: 14,
        overflow: 'hidden',
        cursor: 'pointer',
        border: `1px solid ${hover ? 'rgba(3,68,62,0.2)' : 'rgba(3,68,62,0.08)'}`,
        boxShadow: hover ? '0 8px 24px -10px rgba(3,68,62,0.18)' : '0 1px 0 rgba(3,68,62,0.04)',
        transition: 'all 180ms ease',
        transform: hover ? 'translateY(-2px)' : 'none',
        breakInside: 'avoid',
        marginBottom: 18,
        display: 'block',
      }}
    >
      <div style={{ aspectRatio: '16 / 10', background: C.cream, position: 'relative', overflow: 'hidden' }}>
        {item.headerImage?.asset?.url
          ? <img src={item.headerImage.asset.url} alt={item.headerImage.alt || item.title}
              style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
          : <Thumb variant={item.thumb} seed={item.id} />
        }
        {/* Read time chip on thumbnail */}
        <div style={{
          position: 'absolute', bottom: 10, left: 10,
          background: 'rgba(3,68,62,0.85)', color: C.cream,
          borderRadius: 999, padding: '4px 9px 4px 7px',
          fontSize: 11, fontWeight: 600,
          fontFamily: 'Inter, system-ui, sans-serif',
          display: 'inline-flex', alignItems: 'center', gap: 4,
          backdropFilter: 'blur(4px)',
        }}>
          <BulbIcon size={12} color={C.cream} /> {item.readTime}
        </div>
      </div>
      <div style={{ padding: '16px 18px 18px' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, marginBottom: 10 }}>
          <Pill tone={item.tone} size="sm">{item.category}</Pill>
          <span style={{ fontSize: 12, color: 'rgba(3,68,62,0.6)', fontFamily: 'Inter, system-ui, sans-serif', display: 'inline-flex', alignItems: 'center', gap: 5 }}>
            <BulbIcon color="rgba(3,68,62,0.55)" /> {item.readTime}
          </span>
        </div>
        <h3 style={{
          fontFamily: 'Lora, Georgia, serif',
          fontSize: item.big ? 24 : 20,
          lineHeight: 1.3,
          color: C.charcoal,
          margin: 0,
          fontWeight: 500,
          letterSpacing: -0.1,
        }}>
          {item.title}
        </h3>
      </div>
    </article>
  );
}

// --- Sidebar ---
function Sidebar({ active, setActive, mobileOpen, setMobileOpen, openPopup }) {
  const groups = [
    { label: 'Genre', items: [
      { key: 'Ecom', tone: 'coral' },
      { key: 'Apps', tone: 'sky' },
      { key: 'Games', tone: 'sand' },
      { key: 'Services', tone: 'cream' },
      { key: 'Local', tone: 'coral' },
    ]},
    { label: 'Format', items: [
      { key: 'Ads', tone: 'coral' },
      { key: 'Organic', tone: 'sky' },
      { key: 'UGC', tone: 'sand' },
    ]},
    { label: 'Angle', items: [
      { key: 'Brand', tone: 'cream' },
      { key: 'Hook', tone: 'coral' },
      { key: 'Viral', tone: 'sky' },
    ]},
  ];

  return (
    <aside style={{
      padding: '0 4px',
    }}>
      {/* Filter groups */}
      <div style={{ marginBottom: 28 }}>
        <button
          onClick={() => setActive('All')}
          style={{
            background: active === 'All' ? C.charcoal : 'transparent',
            color: active === 'All' ? C.cream : C.charcoal,
            border: `1.5px solid ${C.charcoal}`,
            borderRadius: 999,
            padding: '6px 14px',
            fontSize: 13,
            fontWeight: 500,
            fontFamily: 'Inter, system-ui, sans-serif',
            cursor: 'pointer',
            marginBottom: 4,
          }}
        >
          All examples
        </button>
      </div>

      {groups.map(group => (
        <div key={group.label} style={{ marginBottom: 24 }}>
          <div style={{
            fontSize: 11,
            fontWeight: 600,
            letterSpacing: 1.4,
            color: 'rgba(3,68,62,0.55)',
            textTransform: 'uppercase',
            fontFamily: 'Inter, system-ui, sans-serif',
            marginBottom: 10,
          }}>
            {group.label}
          </div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7 }}>
            {group.items.map(item => (
              <Pill
                key={item.key}
                tone={item.tone}
                active={active === item.key}
                onClick={() => setActive(item.key)}
              >
                {item.key}
              </Pill>
            ))}
          </div>
        </div>
      ))}

      {/* Newsletter mini-card */}
      <div style={{
        marginTop: 8,
        padding: 18,
        background: C.charcoal,
        borderRadius: 14,
        color: C.cream,
        position: 'relative',
        overflow: 'hidden',
      }}>
        {/* Danny photo + stars */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
          <div style={{
            width: 56, height: 56, borderRadius: '50%',
            background: C.coral,
            padding: 3,
            flexShrink: 0,
            boxShadow: '0 4px 12px -4px rgba(234,85,60,0.5)',
          }}>
            <div style={{
              width: '100%', height: '100%', borderRadius: '50%',
              background: `${C.creamDeep} url('danny.png') center 20% / 130% no-repeat`,
              border: `2px solid ${C.cream}`,
            }} />
          </div>
          <div>
            <div style={{ display: 'flex', gap: 1.5, marginBottom: 4 }}>
              {[0,1,2,3,4].map(i => <Star key={i} size={11} color={C.coral} />)}
            </div>
            <div style={{ fontSize: 11, color: 'rgba(255,243,220,0.7)', fontFamily: 'Inter, system-ui, sans-serif' }}>
              42k readers
            </div>
          </div>
        </div>
        <div style={{
          fontFamily: 'Instrument Serif, serif',
          fontSize: 21,
          lineHeight: 1.1,
          color: C.cream,
          marginBottom: 8,
          letterSpacing: -0.3,
        }}>
          The best 5 minutes in your inbox.
        </div>
        <div style={{
          fontSize: 12.5,
          color: 'rgba(255,243,220,0.75)',
          marginBottom: 14,
          fontFamily: 'Inter, system-ui, sans-serif',
          lineHeight: 1.4,
        }}>
          3 brilliant ads, 2 hooks, 1 lesson — every Tuesday.
        </div>
        <button
          onClick={openPopup}
          style={{
            width: '100%',
            background: C.coral, color: C.cream,
            border: 'none', borderRadius: 8,
            padding: '10px 14px',
            fontSize: 13, fontWeight: 600,
            fontFamily: 'Inter, system-ui, sans-serif',
            cursor: 'pointer',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
          }}
        >
          Tell me more
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none"><path d="M5 12h14M13 6l6 6-6 6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </button>
      </div>
    </aside>
  );
}

// --- Top nav ---
function TopNav({ onOpenMenu }) {
  const IG = () => (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><rect x="3" y="3" width="18" height="18" rx="5" stroke="currentColor" strokeWidth="1.8"/><circle cx="12" cy="12" r="4" stroke="currentColor" strokeWidth="1.8"/><circle cx="17.5" cy="6.5" r="1.2" fill="currentColor"/></svg>
  );
  const TT = () => (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M14 4v9.5a3.5 3.5 0 1 1-3.5-3.5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/><path d="M14 4c.5 2.5 2.5 4 5 4" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/></svg>
  );
  const X = () => (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M4 4l16 16M20 4L4 20" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/></svg>
  );
  const LI = () => (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><rect x="3" y="3" width="18" height="18" rx="3" stroke="currentColor" strokeWidth="1.8"/><path d="M7 10v7M7 7.5v.01M11 17v-4.5a2.5 2.5 0 0 1 5 0V17M11 10v7" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/></svg>
  );

  return (
    <header style={{
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'space-between',
      padding: '22px 40px 18px',
      borderBottom: '1px solid rgba(3,68,62,0.08)',
    }} className="ce-topnav">
      <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
        <button
          className="ce-menu-btn"
          onClick={onOpenMenu}
          aria-label="Open menu"
          style={{
            display: 'none',
            background: 'transparent', border: 'none', cursor: 'pointer',
            padding: 4,
          }}
        >
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none"><path d="M4 7h16M4 12h16M4 17h16" stroke={C.charcoal} strokeWidth="2" strokeLinecap="round"/></svg>
        </button>
        <a href="#" style={{
          fontFamily: 'Instrument Serif, serif',
          fontSize: 28,
          color: C.charcoal,
          textDecoration: 'none',
          lineHeight: 1,
          letterSpacing: -0.3,
        }}>
          Creative Examples
        </a>
      </div>
      <nav style={{ display: 'flex', alignItems: 'center', gap: 22 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16, color: C.charcoal }}>
          <a href="https://www.tiktok.com/@dannyhayder" target="_blank" rel="noopener noreferrer" aria-label="TikTok" style={{ color: 'inherit', display: 'inline-flex' }}><TT/></a>
          <a href="https://x.com/dannyhayder" target="_blank" rel="noopener noreferrer" aria-label="X" style={{ color: 'inherit', display: 'inline-flex' }}><X/></a>
          <a href="https://www.instagram.com/dannyhayder" target="_blank" rel="noopener noreferrer" aria-label="Instagram" style={{ color: 'inherit', display: 'inline-flex' }}><IG/></a>
          <a href="https://www.linkedin.com/in/danialali007/" target="_blank" rel="noopener noreferrer" aria-label="LinkedIn" style={{ color: 'inherit', display: 'inline-flex' }}><LI/></a>
        </div>
      </nav>
    </header>
  );
}

// --- Email capture popup ---
function EmailPopup({ open, onClose }) {
  const [email, setEmail] = useState('');
  // 'idle' | 'loading' | 'success' | 'error'
  const [status, setStatus] = useState('idle');

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!email) return;
    setStatus('loading');
    try {
      await subscribe(email);
      setStatus('success');
    } catch {
      setStatus('error');
    }
  };

  if (!open) return null;

  const testimonials = [
    { bg: '#fcd9d1', fg: C.charcoal, text: '"My favourite newsletter on the web"', author: 'M. Patel' },
    { bg: C.coral, fg: C.cream, text: '"The breakdowns are so good it hurts"', author: 'J. Okafor' },
    { bg: '#f3dfc5', fg: C.charcoal, text: '"Better than my marketing degree"', author: 'L. Chen' },
    { bg: C.sky, fg: C.charcoal, text: '"Actually changed how I write ads"', author: 'R. Silva' },
    { bg: C.sand, fg: C.charcoal, text: '"Stop what you\'re doing and subscribe"', author: 'T. Nowak' },
  ];

  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0,
        background: 'rgba(3,68,62,0.35)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        zIndex: 1000,
        padding: 20,
        animation: 'cePopupFade 240ms ease',
      }}
    >
      <div
        onClick={e => e.stopPropagation()}
        style={{
          background: C.cream,
          borderRadius: 18,
          maxWidth: 440,
          width: '100%',
          maxHeight: '92vh',
          overflow: 'auto',
          position: 'relative',
          boxShadow: '0 24px 60px -20px rgba(3,68,62,0.4)',
          animation: 'cePopupRise 320ms cubic-bezier(.2,.8,.2,1)',
        }}
      >
        <button
          onClick={onClose}
          aria-label="Close"
          style={{
            position: 'absolute', top: 14, right: 14,
            background: 'transparent', border: 'none', cursor: 'pointer',
            color: C.charcoal, padding: 6, zIndex: 2,
          }}
        >
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M6 6l12 12M18 6L6 18" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/></svg>
        </button>

        <div style={{ padding: '28px 28px 20px' }}>
          {/* Avatar header */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 18 }}>
          <div style={{
            width: 48, height: 48, borderRadius: '50%',
            background: `${C.coral} url('danny.png') center 20% / 140% no-repeat`,
            flexShrink: 0,
            border: `2px solid ${C.coral}`,
          }}>
          </div>
            <div>
              <div style={{
                fontFamily: 'Instrument Serif, serif', fontSize: 22, color: C.charcoal,
                lineHeight: 1.25,
              }}>
                Hey, I'm Danny.
              </div>
              <div style={{ fontSize: 13, color: 'rgba(3,68,62,0.65)', fontFamily: 'Inter, system-ui, sans-serif', marginTop: 2 }}>
                Every week I share:
              </div>
            </div>
          </div>

          {status !== 'success' ? (
            <>
              <ul style={{
                listStyle: 'none', padding: 0, margin: '0 0 18px',
                fontFamily: 'Inter, system-ui, sans-serif',
                fontSize: 14.5, color: C.charcoal,
              }}>
                {[
                  { icon: (<svg width="14" height="14" viewBox="0 0 24 24" fill="none"><polygon points="6,4 20,12 6,20" fill={C.coral}/></svg>), num: '3', emph: 'brilliant', tail: ' ad breakdowns' },
                  { icon: (<svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M3 6h18M3 12h18M3 18h12" stroke={C.coral} strokeWidth="2.5" strokeLinecap="round"/></svg>), num: '2', emph: 'short-form', tail: ' video tips' },
                  { icon: (<svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M5 12c4 0 4-6 8-6s4 12 8 6" stroke={C.coral} strokeWidth="2.5" strokeLinecap="round" fill="none"/></svg>), num: '1', emph: 'hook', tail: ' worth stealing' },
                ].map((row, i) => (
                  <li key={i} style={{
                    display: 'flex', gap: 12, alignItems: 'center',
                    padding: '9px 12px',
                    background: i % 2 === 0 ? 'rgba(234,85,60,0.06)' : 'transparent',
                    borderRadius: 8,
                  }}>
                    <span style={{
                      width: 26, height: 26, borderRadius: 7,
                      background: '#ffffff',
                      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                      flexShrink: 0,
                      border: `1px solid rgba(234,85,60,0.2)`,
                    }}>{row.icon}</span>
                    <span>
                      <b style={{ fontWeight: 700 }}>{row.num} </b>
                      <span style={{ borderBottom: `2px solid ${C.coral}`, paddingBottom: 1 }}>{row.emph}</span>
                      {row.tail}
                    </span>
                  </li>
                ))}
              </ul>

              <div style={{
                display: 'flex', alignItems: 'center', gap: 10,
                padding: '10px 12px',
                background: C.creamDeep,
                borderRadius: 10,
                margin: '0 0 16px',
              }}>
                <div style={{ display: 'flex', gap: 1 }}>
                  {[0,1,2,3,4].map(i => <Star key={i} size={13} color={C.coral} />)}
                </div>
                <div style={{
                  fontFamily: 'Inter, system-ui, sans-serif', fontSize: 13,
                  color: C.charcoal, lineHeight: 1.4,
                }}>
                  Voted{' '}
                  <span style={{ borderBottom: `2px solid ${C.coral}`, paddingBottom: 1, fontWeight: 600 }}>
                    “#1 creative newsletter”
                  </span>
                  {' '}by <b>42,000</b> marketers.
                </div>
              </div>

              <form
                onSubmit={handleSubmit}
                style={{ display: 'flex', gap: 8, marginBottom: 18 }}
              >
                <input
                  type="email"
                  required
                  value={email}
                  onChange={e => setEmail(e.target.value)}
                  placeholder="Your email"
                  style={{
                    flex: 1, padding: '11px 14px',
                    border: `1px solid rgba(3,68,62,0.2)`,
                    borderRadius: 8,
                    fontSize: 14,
                    fontFamily: 'Inter, system-ui, sans-serif',
                    background: '#ffffff',
                    color: C.charcoal,
                    outline: 'none',
                  }}
                />
                <button
                  type="submit"
                  disabled={status === 'loading'}
                  style={{
                    background: C.charcoal, color: C.cream,
                    border: 'none', borderRadius: 8,
                    padding: '11px 20px', fontSize: 14, fontWeight: 600,
                    fontFamily: 'Inter, system-ui, sans-serif',
                    cursor: status === 'loading' ? 'default' : 'pointer',
                    opacity: status === 'loading' ? 0.7 : 1,
                  }}
                >
                  {status === 'loading' ? '…' : 'Try it'}
                </button>
              </form>
              {status === 'error' && (
                <div style={{
                  fontFamily: 'Inter, system-ui, sans-serif', fontSize: 13,
                  color: C.coral, marginBottom: 8,
                }}>
                  Something went wrong — try again.
                </div>
              )}
            </>
          ) : (
            <div style={{ padding: '18px 0 24px', textAlign: 'center' }}>
              <div style={{
                fontFamily: 'Inter, system-ui, sans-serif', fontSize: 14,
                color: C.coral, fontWeight: 500,
              }}>
                Double opt in required — Check your inbox (may take 2 mins) :)
              </div>
            </div>
          )}
        </div>

        {/* Testimonial strips */}
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          {testimonials.map((t, i) => (
            <div key={i} style={{
              background: t.bg, color: t.fg,
              padding: '12px 22px',
              display: 'flex', alignItems: 'center', gap: 12,
            }}>
              <div style={{
                width: 28, height: 28, borderRadius: '50%',
                background: 'rgba(255,255,255,0.5)',
                flexShrink: 0,
                border: `1px solid rgba(0,0,0,0.08)`,
              }} />
              <div style={{
                fontFamily: 'Instrument Serif, serif',
                fontSize: 17,
                lineHeight: 1.2,
                flex: 1,
              }}>
                {t.text}
              </div>
              <div style={{
                fontFamily: 'Inter, system-ui, sans-serif',
                fontSize: 11,
                opacity: 0.75,
                whiteSpace: 'nowrap',
              }}>
                {t.author}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// --- Content data ---
// Optional richer content that the article popup can use

const CONTENT = [
  { id: 1, title: "How Liquid Death turned water into rebellion", category: 'Brand', tone: 'cream', readTime: '4 min', thumb: 0, big: true },
  { id: 2, title: "The 3-second hook that made this ad go viral", category: 'Hook', tone: 'coral', readTime: '2 min', thumb: 2 },
  { id: 3, title: "Why this founder's TikTok got 18M views", category: 'Viral', tone: 'sky', readTime: '3 min', thumb: 11, big: true },
  { id: 4, title: "UGC that doesn't look like UGC", category: 'UGC', tone: 'sand', readTime: '5 min', thumb: 1 },
  { id: 5, title: "Duolingo's unhinged strategy, broken down", category: 'Organic', tone: 'sky', readTime: '6 min', thumb: 6, big: true },
  { id: 6, title: "The one frame that sells the entire product", category: 'Ads', tone: 'coral', readTime: '2 min', thumb: 4 },
  { id: 7, title: "Poppi's Super Bowl spot, shot by shot", category: 'Ads', tone: 'coral', readTime: '4 min', thumb: 9 },
  { id: 8, title: "Writing copy that sounds like a person", category: 'Brand', tone: 'cream', readTime: '3 min', thumb: 5 },
  { id: 9, title: "Ryan Reynolds' fast-turnaround formula", category: 'Ads', tone: 'coral', readTime: '5 min', thumb: 8, big: true },
  { id: 10, title: "Why founders make the best on-camera talent", category: 'UGC', tone: 'sand', readTime: '3 min', thumb: 7 },
  { id: 11, title: "This skincare brand's hook is a masterclass", category: 'Hook', tone: 'coral', readTime: '2 min', thumb: 10 },
  { id: 12, title: "The anatomy of a $4 CPM TikTok ad", category: 'Ads', tone: 'coral', readTime: '6 min', thumb: 3, big: true },
  { id: 13, title: "Patagonia's organic content playbook", category: 'Organic', tone: 'sky', readTime: '4 min', thumb: 0 },
  { id: 14, title: "A hook that breaks every rule and works", category: 'Hook', tone: 'coral', readTime: '2 min', thumb: 5 },
  { id: 15, title: "Creator-led ads that beat studio production", category: 'UGC', tone: 'sand', readTime: '4 min', thumb: 6 },
  { id: 16, title: "The Stanley Cup phenomenon, explained", category: 'Viral', tone: 'sky', readTime: '5 min', thumb: 2 },
  { id: 17, title: "What a great brand voice actually sounds like", category: 'Brand', tone: 'cream', readTime: '3 min', thumb: 10 },
  { id: 18, title: "30-second ad structures that convert", category: 'Ads', tone: 'coral', readTime: '4 min', thumb: 8 },
];

// --- Minimal Portable Text renderer (no build step required) ---
function toEmbedUrl(url) {
  if (!url) return '';
  // YouTube
  const yt = url.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([^&?/]+)/);
  if (yt) return `https://www.youtube.com/embed/${yt[1]}`;
  // TikTok — use oEmbed iframe src pattern
  const tt = url.match(/tiktok\.com\/@[^/]+\/video\/(\d+)/);
  if (tt) return `https://www.tiktok.com/embed/v2/${tt[1]}`;
  return url;
}

function renderSpan(span) {
  let node = span.text || '';
  if (!node) return null;
  if (span.marks && span.marks.includes('strong')) node = <strong>{node}</strong>;
  if (span.marks && span.marks.includes('em')) node = <em>{node}</em>;
  return node;
}

function renderPTBlock(block, i) {
  if (block._type === 'block') {
    const children = (block.children || []).map((s, j) => (
      <React.Fragment key={j}>{renderSpan(s)}</React.Fragment>
    ));
    const key = block._key || i;
    if (block.style === 'h2') {
      return <h2 key={key} style={{ fontFamily: 'Instrument Serif, serif', fontSize: 26, fontWeight: 400, color: C.charcoal, margin: '24px 0 10px', letterSpacing: -0.3 }}>{children}</h2>;
    }
    if (block.style === 'h3') {
      return <h3 key={key} style={{ fontFamily: 'Lora, Georgia, serif', fontSize: 20, fontWeight: 500, color: C.charcoal, margin: '20px 0 8px' }}>{children}</h3>;
    }
    return <p key={key} style={{ margin: '0 0 14px' }}>{children}</p>;
  }
  if (block._type === 'videoEmbed') {
    const src = toEmbedUrl(block.url);
    return (
      <div key={block._key || i} style={{ margin: '20px 0', aspectRatio: '16/9', borderRadius: 10, overflow: 'hidden' }}>
        <iframe src={src} style={{ width: '100%', height: '100%', border: 'none' }} allowFullScreen allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" />
      </div>
    );
  }
  if (block._type === 'image' && block.asset) {
    return (
      <img key={block._key || i} src={`https://cdn.sanity.io/images/prwe0dj2/production/${block.asset._ref.replace('image-', '').replace(/-(\w+)$/, '.$1')}`}
        alt={block.alt || ''} style={{ width: '100%', borderRadius: 8, margin: '16px 0', display: 'block' }} />
    );
  }
  return null;
}

// --- Article Popup (CMS-ready) ---
function ArticlePopup({ article, onClose }) {
  const [email, setEmail] = useState('');
  // 'idle' | 'loading' | 'success' | 'error'
  const [status, setStatus] = useState('idle');

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!email) return;
    setStatus('loading');
    try {
      await subscribe(email);
      setStatus('success');
    } catch {
      setStatus('error');
    }
  };
  if (!article) return null;

  const body = Array.isArray(article.body) ? article.body : [];

  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, background: 'rgba(3,68,62,0.45)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        zIndex: 1100, padding: 20, animation: 'cePopupFade 240ms ease',
      }}
    >
      <div
        onClick={e => e.stopPropagation()}
        style={{
          background: C.cream, borderRadius: 18,
          maxWidth: 640, width: '100%', maxHeight: '92vh',
          overflow: 'auto', position: 'relative',
          boxShadow: '0 24px 60px -20px rgba(3,68,62,0.45)',
          animation: 'cePopupRise 320ms cubic-bezier(.2,.8,.2,1)',
        }}
      >
        <button
          onClick={onClose}
          aria-label="Close"
          style={{
            position: 'absolute', top: 14, right: 14, zIndex: 3,
            background: 'rgba(255,243,220,0.9)', border: 'none', cursor: 'pointer',
            color: C.charcoal, padding: 8, borderRadius: '50%',
            width: 34, height: 34,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}
        >
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M6 6l12 12M18 6L6 18" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/></svg>
        </button>

        {/* Header image */}
        <div style={{ aspectRatio: '16 / 8', background: C.cream, overflow: 'hidden' }}>
          {article.headerImage?.asset?.url
            ? <img src={article.headerImage.asset.url} alt={article.headerImage.alt || article.title}
                style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
            : <Thumb variant={article.thumb} seed={article.id + 100} />
          }
        </div>

        <div style={{ padding: '28px 36px 32px' }}>
          {/* Meta row */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
            <Pill tone={article.tone} size="md">{article.category}</Pill>
            <span style={{
              fontSize: 12.5, color: 'rgba(3,68,62,0.65)',
              fontFamily: 'Inter, system-ui, sans-serif',
              display: 'inline-flex', alignItems: 'center', gap: 5,
            }}>
              <BulbIcon color="rgba(3,68,62,0.6)" /> {article.readTime} read
            </span>
            <span style={{ fontSize: 12.5, color: 'rgba(3,68,62,0.5)', fontFamily: 'Inter, system-ui, sans-serif' }}>
              · Issue #42 · Apr 12, 2026
            </span>
          </div>

          {/* Title */}
          <h2 style={{
            fontFamily: 'Instrument Serif, serif',
            fontSize: 'clamp(28px, 4vw, 38px)',
            lineHeight: 1.05,
            color: C.charcoal, margin: '0 0 14px',
            fontWeight: 400, letterSpacing: -0.6,
          }}>
            {article.title}
          </h2>

          {/* Body */}
          <div style={{
            fontFamily: 'Inter, system-ui, sans-serif',
            fontSize: 15.5, lineHeight: 1.65, color: C.charcoal,
            marginBottom: 26,
          }}>
            {body.map((block, i) => renderPTBlock(block, i))}
          </div>

          {/* Email capture footer */}
          <div style={{
            borderTop: '1px solid rgba(3,68,62,0.12)',
            paddingTop: 22,
          }}>
            <div style={{
              fontFamily: 'Instrument Serif, serif', fontSize: 20,
              color: C.charcoal, marginBottom: 4, letterSpacing: -0.2,
            }}>
              Want the next one in your inbox?
            </div>
            <div style={{
              fontSize: 13, color: 'rgba(3,68,62,0.65)',
              fontFamily: 'Inter, system-ui, sans-serif',
              marginBottom: 12,
            }}>
              One breakdown like this every Tuesday. Free.
            </div>
            {status !== 'success' ? (
              <>
                <form
                  onSubmit={handleSubmit}
                  style={{ display: 'flex', gap: 8 }}
                >
                  <input
                    type="email" required value={email}
                    onChange={e => setEmail(e.target.value)}
                    placeholder="you@work.com"
                    style={{
                      flex: 1, padding: '11px 14px',
                      border: `1px solid rgba(3,68,62,0.2)`,
                      borderRadius: 8, fontSize: 14,
                      fontFamily: 'Inter, system-ui, sans-serif',
                      background: '#ffffff', color: C.charcoal, outline: 'none',
                    }}
                  />
                  <button
                    type="submit"
                    disabled={status === 'loading'}
                    style={{
                      background: C.charcoal, color: C.cream,
                      border: 'none', borderRadius: 8,
                      padding: '11px 22px', fontSize: 14, fontWeight: 600,
                      fontFamily: 'Inter, system-ui, sans-serif',
                      cursor: status === 'loading' ? 'default' : 'pointer',
                      opacity: status === 'loading' ? 0.7 : 1,
                    }}
                  >
                    {status === 'loading' ? '…' : 'Subscribe'}
                  </button>
                </form>
                {status === 'error' && (
                  <div style={{
                    fontFamily: 'Inter, system-ui, sans-serif', fontSize: 13,
                    color: C.coral, marginTop: 8,
                  }}>
                    Something went wrong — try again.
                  </div>
                )}
              </>
            ) : (
              <div style={{
                fontFamily: 'Inter, system-ui, sans-serif', fontSize: 14,
                color: C.coral, fontWeight: 500, padding: '10px 0',
              }}>
                Double opt in required — Check your inbox (may take 2 mins) :)
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { C, Thumb, Pill, ClockIcon, BulbIcon, Star, Card, Sidebar, TopNav, EmailPopup, ArticlePopup, CONTENT });
