
const { useState, useEffect, useRef } = React;

// ── Route hook ──────────────────────────────────────────────────────────────
function useRoute() {
  const [route, setRoute] = useState(window.location.hash || '#/');
  useEffect(() => {
    const handler = () => setRoute(window.location.hash || '#/');
    window.addEventListener('hashchange', handler);
    return () => window.removeEventListener('hashchange', handler);
  }, []);
  return route;
}

// ── Scroll reveal hook ──────────────────────────────────────────────────────
function useScrollReveal(dep) {
  useEffect(() => {
    const els = document.querySelectorAll('.reveal');
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) e.target.classList.add('revealed'); });
    }, { threshold: 0.08 });
    els.forEach(el => observer.observe(el));
    return () => observer.disconnect();
  }, [dep]);
}

// ── Nav ─────────────────────────────────────────────────────────────────────
function Nav({ route }) {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);

  useEffect(() => {
    const h = () => setScrolled(window.scrollY > 60);
    window.addEventListener('scroll', h);
    return () => window.removeEventListener('scroll', h);
  }, []);

  useEffect(() => { setOpen(false); }, [route]);

  const links = [
    { href: '#/', label: 'Home' },
    { href: '#/watch', label: 'Watch' },
    { href: '#/music', label: 'Music' },
    { href: '#/merch', label: 'Merch' },
    { href: '#/resources', label: 'Resources' },
    { href: '#/about', label: 'About' },
    { href: '#/contact', label: 'Contact' },
  ];

  return (
    <nav className={`ik-nav${scrolled ? ' scrolled' : ''}`}>
      <a href="#/" className="ik-logo">
        <div className="logo-icon"><img src="uploads/Untitled design (2).png" alt="Idol Killer logo" /></div>
        <span className="logo-text">IDOL<span className="logo-accent">KILLER</span></span>
      </a>
      <div className={`ik-nav-links${open ? ' open' : ''}`}>
        {links.map(l => (
          <a key={l.href} href={l.href} className={`ik-nav-link${route === l.href ? ' active' : ''}`}>
            {l.label}
          </a>
        ))}
        <a href="https://youtube.com/@idolkiller" target="_blank" rel="noopener noreferrer" className="ik-nav-cta">
          Subscribe
        </a>
      </div>
      <button className="ik-burger" onClick={() => setOpen(o => !o)} aria-label="Menu">
        <span></span><span></span><span></span>
      </button>
    </nav>
  );
}

// ── Social icons ─────────────────────────────────────────────────────────────
function SocialLinks() {
  const socials = [
    {
      label: 'X', href: 'https://x.com/The_Idol_Killer',
      icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-4.714-6.231-5.401 6.231H2.744l7.73-8.835L1.254 2.25H8.08l4.259 5.63L18.244 2.25zm-1.161 17.52h1.833L7.084 4.126H5.117L17.083 19.77z"/></svg>
    },
    {
      label: 'Facebook', href: 'https://www.facebook.com/IdolKiller',
      icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/></svg>
    },
    {
      label: 'Kick', href: 'https://kick.com/idolkiller',
      icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M2 2h4v8l4-4h4l-5 6 5 6h-4l-4-4v4H2V2zm14 0h4v20h-4V2z"/></svg>
    },
    {
      label: 'Patreon', href: 'https://www.patreon.com/IdolKiller',
      icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M14.82 2.41C11.58 2.41 8.96 5.03 8.96 8.27c0 3.23 2.62 5.85 5.86 5.85 3.23 0 5.85-2.62 5.85-5.85 0-3.24-2.62-5.86-5.85-5.86zM3.19 21.59h3.44V2.41H3.19v19.18z"/></svg>
    },
  ];
  return (
    <div className="social-links">
      {socials.map(s => (
        <a key={s.label} href={s.href} target="_blank" rel="noreferrer" className="social-link" aria-label={s.label} title={s.label}>
          {s.icon}
        </a>
      ))}
    </div>
  );
}

// ── Footer ──────────────────────────────────────────────────────────────────
function Footer() {
  return (
    <footer className="ik-footer">
      <div className="footer-inner">
        <div className="footer-brand">
          <div className="ik-logo" style={{marginBottom:'4px'}}>
            <div className="logo-icon"><img src="uploads/Untitled design (2).png" alt="Idol Killer logo" /></div>
            <span className="logo-text">IDOL<span className="logo-accent">KILLER</span></span>
          </div>
          <p>Destroying Sacred Cows for the Cause of Christ</p>
        </div>
        <div className="footer-links">
          <a href="#/">Home</a>
          <a href="#/watch">Watch</a>
          <a href="#/music">Music</a>
          <a href="#/merch">Merch</a>
          <a href="#/resources">Resources</a>
          <a href="#/about">About</a>
          <a href="#/contact">Contact</a>
          <a href="https://youtube.com/@idolkiller" target="_blank" rel="noopener noreferrer">YouTube ↗</a>
        </div>
      </div>
      <div className="footer-bottom">
        <span>© 2025 Idol Killer · Warren McGrew</span>
        <SocialLinks />
        <span>Introducing you to the Holy and living God of Scripture</span>
      </div>
    </footer>
  );
}

// ── Category badge ───────────────────────────────────────────────────────────
function CategoryBadge({ label }) {
  const colors = {
    'Calvinism': '#8855cc',
    'Original Sin': '#cc5511',
    'Atonement': '#cc1111',
    'Molinism': '#1155cc',
    'Dynamic Omniscience': '#117755',
    'Debates & Responses': '#cc9911',
    'Church History': '#667788',
    'Theology': '#444',
  };
  const bg = colors[label] || '#444';
  return (
    <span className="cat-badge" style={{ background: bg + '33', borderColor: bg + '88', color: bg === '#444' ? '#aaa' : bg }}>
      {label}
    </span>
  );
}

// ── Video card ────────────────────────────────────────────────────────────────
function VideoCard({ video, onClick }) {
  const thumb = video.thumb || `https://i.ytimg.com/vi/${video.id}/hqdefault.jpg`;
  const dateStr = video.date ? new Date(video.date).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }) : '';
  return (
    <div className="video-card reveal" onClick={() => onClick && onClick(video)}>
      <div className="video-thumb">
        <img src={thumb} alt={video.title} loading="lazy" onError={e => { e.target.style.display = 'none'; }} />
        <div className="thumb-overlay">
          <div className="play-btn">▶</div>
        </div>
        {video.duration && <span className="video-duration">{video.duration}</span>}
      </div>
      <div className="video-info">
        {video.category && <CategoryBadge label={video.category} />}
        <h3 className="video-title">{video.title}</h3>
        <div className="video-meta">
          {dateStr && <span>{dateStr}</span>}
          {video.views && <span>{video.views} views</span>}
        </div>
      </div>
    </div>
  );
}

// ── Video modal ────────────────────────────────────────────────────────────────
function VideoModal({ video, onClose }) {
  useEffect(() => {
    const handler = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', handler);
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', handler);
      document.body.style.overflow = '';
    };
  }, [onClose]);

  if (!video) return null;
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal-inner" onClick={e => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose}>✕</button>
        <div className="modal-player">
          <iframe
            src={`https://www.youtube.com/embed/${video.id}?autoplay=1`}
            title={video.title}
            frameBorder="0"
            allow="autoplay; encrypted-media"
            allowFullScreen
          ></iframe>
        </div>
        <div className="modal-meta">
          {video.category && <CategoryBadge label={video.category} />}
          <h2>{video.title}</h2>
          {video.date && <p className="modal-date">{new Date(video.date).toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' })}</p>}
          {video.description && <p className="modal-desc">{video.description.slice(0, 300)}{video.description.length > 300 ? '…' : ''}</p>}
          <a href={`https://www.youtube.com/watch?v=${video.id}`} target="_blank" rel="noreferrer" className="ik-btn-outline">
            Watch on YouTube ↗
          </a>
        </div>
      </div>
    </div>
  );
}

// ── Section divider ──────────────────────────────────────────────────────────
function RedLine() {
  return <div className="red-line"></div>;
}

Object.assign(window, { Nav, Footer, VideoCard, VideoModal, CategoryBadge, RedLine, SocialLinks, useRoute, useScrollReveal });
