/* ── Shared UI components + Nav + Subscribe Modal ── */

const C = {
  black: '#0a0a0a', dark2: '#111', dark3: '#1a1a1a',
  border: '#2a2a2a', borderMid: '#444',
  text: '#e0e0e0', muted: '#777', mutedMid: '#999',
  blue: '#00a8e6', rust: '#643b35',
};

/* ── Btn ── */
function Btn({ children, variant = 'primary', small, onClick, href, style = {}, target }) {
  const [hov, setHov] = React.useState(false);
  const base = {
    padding: small ? '9px 22px' : '13px 32px',
    fontFamily: 'Inter, sans-serif', fontWeight: 700,
    fontSize: small ? '10px' : '11px', letterSpacing: '2.5px',
    textTransform: 'uppercase', cursor: 'pointer',
    border: '2px solid #e0e0e0', transition: 'all 0.3s ease',
    display: 'inline-flex', alignItems: 'center', gap: 8,
    textDecoration: 'none', borderRadius: 0,
  };
  const variants = {
    primary: { ...base, background: hov ? C.black : C.text, color: hov ? C.text : C.black },
    secondary: { ...base, background: hov ? C.text : 'transparent', color: hov ? C.black : C.text },
    blue: { ...base, border: `2px solid ${C.blue}`, background: hov ? C.blue : 'transparent', color: hov ? '#fff' : C.blue },
    ghost: { ...base, border: `1px solid #333`, background: hov ? '#1a1a1a' : 'transparent', color: hov ? C.text : C.muted },
  };
  const p = { style: { ...variants[variant], ...style }, onMouseEnter: () => setHov(true), onMouseLeave: () => setHov(false), onClick };
  return href
    ? <a href={href} target={target || '_blank'} rel="noreferrer" {...p}>{children}</a>
    : <button {...p}>{children}</button>;
}

/* ── Section header with number ── */
function SectionHeader({ num, title }) {
  return (
    <div style={{ marginBottom: 56 }}>
      <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '3px', textTransform: 'uppercase', color: C.muted, marginBottom: 14 }}>
        {String(num).padStart(2, '0')} &mdash; {title}
      </div>
      <h2 style={{ fontSize: 'clamp(2rem, 4.5vw, 3rem)', fontWeight: 900, letterSpacing: '4px', textTransform: 'uppercase', color: C.text, lineHeight: 1, animation: 'tb-flicker 2.5s infinite' }}>{title}</h2>
    </div>
  );
}

/* ── Platform link pill ── */
function PlatformLink({ icon, label, href = '#' }) {
  const [hov, setHov] = React.useState(false);
  return (
    <a href={href} target="_blank" rel="noreferrer"
      style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '7px 14px', border: `1px solid ${hov ? '#e0e0e0' : '#333'}`, background: hov ? '#e0e0e0' : 'transparent', color: hov ? '#0a0a0a' : '#bbb', fontSize: 9, fontWeight: 700, letterSpacing: '1.5px', textTransform: 'uppercase', textDecoration: 'none', transition: 'all 0.25s' }}
      onMouseEnter={() => setHov(true)} onMouseLeave={() => setHov(false)}>
      <i className={icon} style={{ fontSize: 12 }}></i>{label}
    </a>
  );
}

/* ── Ticker tape ── */
function Ticker() {
  const items = TICKER_ITEMS;
  const text = items.join('  ·  ') + '  ·  ' + items.join('  ·  ') + '  ·  ';
  return (
    <div style={{ background: C.blue, overflow: 'hidden', height: 32, display: 'flex', alignItems: 'center' }}>
      <div style={{ display: 'flex', whiteSpace: 'nowrap', animation: 'ticker 28s linear infinite' }}>
        <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: '2px', textTransform: 'uppercase', color: '#fff', paddingRight: 40 }}>{text}</span>
        <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: '2px', textTransform: 'uppercase', color: '#fff', paddingRight: 40 }}>{text}</span>
      </div>
    </div>
  );
}

/* ── Subscribe Modal ── */
function SubscribeModal({ onClose }) {
  const [status, setStatus] = React.useState('idle'); // idle | submitting | done | error

  const handleSubmit = async (e) => {
    e.preventDefault();
    setStatus('submitting');
    try {
      const data = new FormData(e.target);
      const res = await fetch('https://api.web3forms.com/submit', { method: 'POST', body: data });
      const json = await res.json();
      setStatus(json.success ? 'done' : 'error');
    } catch {
      setStatus('error');
    }
  };

  return (
    <div onClick={e => { if (e.target === e.currentTarget) onClose(); }}
      style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.92)', backdropFilter: 'blur(12px)', zIndex: 9000, display: 'flex', alignItems: 'center', justifyContent: 'center', animation: 'fadeIn 0.2s ease' }}>
      <div style={{ background: '#0f0f0f', border: '1px solid #2a2a2a', padding: '56px 48px', maxWidth: 480, width: '90%', position: 'relative' }}>
        <button onClick={onClose} style={{ position: 'absolute', top: 20, right: 22, background: 'none', border: 'none', color: '#555', fontSize: 22, cursor: 'pointer', lineHeight: 1 }}>×</button>

        {status === 'done' ? (
          <div style={{ textAlign: 'center' }}>
            <div style={{ width: 48, height: 48, border: '2px solid #e0e0e0', borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 24px', animation: 'tb-flicker 2s infinite' }}>
              <i className="fas fa-check" style={{ fontSize: 18, color: '#e0e0e0' }}/>
            </div>
            <h3 style={{ fontSize: '1.4rem', fontWeight: 900, letterSpacing: '3px', textTransform: 'uppercase', marginBottom: 12, animation: 'tb-flicker 2.5s infinite' }}>YOU'RE IN</h3>
            <p style={{ color: C.muted, fontSize: 13, lineHeight: 1.7 }}>We'll be in touch with news, shows, and releases. No noise — just signal.</p>
            <div style={{ marginTop: 28 }}><Btn small onClick={onClose}>CLOSE</Btn></div>
          </div>
        ) : (
          <>
            <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '3px', textTransform: 'uppercase', color: C.muted, marginBottom: 14 }}>MAILING LIST</div>
            <h3 style={{ fontSize: '1.6rem', fontWeight: 900, letterSpacing: '3px', textTransform: 'uppercase', marginBottom: 10, animation: 'tb-flicker 2.5s infinite' }}>STAY CLOSE</h3>
            <p style={{ color: C.muted, fontSize: 13, lineHeight: 1.7, marginBottom: 36 }}>First access to shows, new music, and whatever else we're up to.</p>
            <form onSubmit={handleSubmit}>
              <input type="hidden" name="access_key" value="28ca3711-de15-40d7-b368-f2b9c5fa939e"/>
              <input type="hidden" name="subject" value="New subscriber — The Breakdown"/>
              <input type="hidden" name="from_name" value="The Breakdown Website"/>
              <div style={{ position: 'relative', marginBottom: 24 }}>
                <input
                  type="email" name="email" placeholder="YOUR EMAIL ADDRESS" required
                  style={{ width: '100%', background: 'transparent', border: 'none', borderBottom: '1px solid #444', padding: '14px 0', color: '#e0e0e0', fontSize: 12, fontFamily: 'Inter', letterSpacing: '1px', outline: 'none', transition: 'border-color 0.3s' }}
                  onFocus={e => e.target.style.borderBottomColor = '#e0e0e0'}
                  onBlur={e => e.target.style.borderBottomColor = '#444'}
                />
              </div>
              {status === 'error' && (
                <div style={{ color: '#e05555', fontSize: 11, marginBottom: 16, letterSpacing: '1px' }}>Something went wrong — please try again.</div>
              )}
              <button type="submit" disabled={status === 'submitting'}
                style={{ width: '100%', padding: '14px', background: status === 'submitting' ? 'transparent' : '#e0e0e0', border: '2px solid #e0e0e0', color: status === 'submitting' ? '#e0e0e0' : '#0a0a0a', fontFamily: 'Inter', fontWeight: 700, fontSize: 11, letterSpacing: '2.5px', textTransform: 'uppercase', cursor: status === 'submitting' ? 'wait' : 'pointer', transition: 'all 0.3s' }}>
                {status === 'submitting' ? 'SENDING...' : 'SUBSCRIBE'}
              </button>
            </form>
          </>
        )}
      </div>
    </div>
  );
}

/* ── Navigation ── */
const NAV_LINKS = [
  { label: 'NEWS', id: 'news' }, { label: 'LIVE', id: 'live' },
  { label: 'MUSIC', id: 'music' }, { label: 'VIDEO', id: 'video' }, { label: 'DISCOGRAPHY', id: 'discography' },
  { label: 'PHOTOS', id: 'photos' }, { label: 'MERCH', id: 'merch' },
  { label: 'EPK', id: 'epk', href: 'https://thinkable-arthropod-0ec.notion.site/The-Breakdown-EPK' },
  { label: 'CONTACT', id: 'contact' },
];

function SiteNav({ active, onNav, onSubscribe }) {
  const [scrolled, setScrolled] = React.useState(false);
  const [menuOpen, setMenuOpen] = React.useState(false);

  React.useEffect(() => {
    const handler = () => setScrolled(window.scrollY > 40);
    window.addEventListener('scroll', handler, { passive: true });
    return () => window.removeEventListener('scroll', handler);
  }, []);

  const navStyle = {
    position: 'fixed', top: 0, left: 0, right: 0, zIndex: 5000,
    background: scrolled ? 'rgba(10,10,10,0.97)' : 'rgba(10,10,10,0.85)',
    backdropFilter: 'blur(14px)',
    borderBottom: `1px solid ${scrolled ? '#222' : 'transparent'}`,
    transition: 'all 0.4s ease',
  };

  return (
    <nav style={navStyle}>
      <div style={{ maxWidth: 1280, margin: '0 auto', padding: '0 28px', height: 68, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        {/* Logo */}
        <button onClick={() => onNav('hero')} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 0, display: 'flex', alignItems: 'center' }}>
          <img src="assets/icon.png" alt="The Breakdown" style={{ height: 42, animation: 'tb-flicker-logo 4s infinite' }}/>
        </button>

        {/* Desktop nav */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 26 }}>
          {NAV_LINKS.map(({ label, id, href }) => {
            const isActive = active === id;
            const [hov, setHov] = React.useState(false);
            return href ? (
              <a key={id} href={href} target="_blank" rel="noreferrer"
                style={{ color: '#e0e0e0', fontSize: 10, fontWeight: 700, letterSpacing: '2px', textTransform: 'uppercase', textDecoration: 'none', opacity: hov ? 0.5 : isActive ? 1 : 0.75, transition: 'opacity 0.3s', animation: 'tb-flicker 3s infinite' }}
                onMouseEnter={() => setHov(true)} onMouseLeave={() => setHov(false)}>
                {label}
              </a>
            ) : (
              <button key={id} onClick={() => onNav(id)}
                style={{ background: 'none', border: 'none', color: '#e0e0e0', fontSize: 10, fontWeight: 700, letterSpacing: '2px', textTransform: 'uppercase', cursor: 'pointer', padding: 0, opacity: hov ? 0.5 : isActive ? 1 : 0.75, borderBottom: isActive ? '1px solid #e0e0e0' : '1px solid transparent', paddingBottom: 2, transition: 'all 0.3s', animation: 'tb-flicker 3s infinite' }}
                onMouseEnter={() => setHov(true)} onMouseLeave={() => setHov(false)}>
                {label}
              </button>
            );
          })}
          <button onClick={onSubscribe}
            style={{ background: 'transparent', border: '1px solid #444', color: '#bbb', fontSize: 9, fontWeight: 700, letterSpacing: '2px', textTransform: 'uppercase', cursor: 'pointer', padding: '7px 16px', transition: 'all 0.3s', fontFamily: 'Inter' }}
            onMouseEnter={e => { e.currentTarget.style.borderColor = '#e0e0e0'; e.currentTarget.style.color = '#e0e0e0'; }}
            onMouseLeave={e => { e.currentTarget.style.borderColor = '#444'; e.currentTarget.style.color = '#bbb'; }}>
            SUBSCRIBE
          </button>
        </div>
      </div>
    </nav>
  );
}

Object.assign(window, { C, Btn, SectionHeader, PlatformLink, Ticker, SubscribeModal, SiteNav, NAV_LINKS });
