const BROADCAST_LOADING = {
  status: 'loading',
  label: 'THE BROADCAST',
  message: 'Checking broadcast status...',
  channelUrl: 'https://www.youtube.com/@therightsidemedia',
};

const BROADCAST_FALLBACK = {
  status: 'offline',
  label: 'THE BROADCAST',
  message: 'We\'ll be back live at 10A CT. Catch the latest from Rightside on YouTube.',
  channelUrl: 'https://www.youtube.com/@therightsidemedia',
};

const getBroadcastHref = (broadcast) =>
  broadcast?.watchUrl || broadcast?.channelUrl || 'https://www.youtube.com/@therightsidemedia';

const getBroadcastCta = (broadcast) => {
  if (broadcast?.status === 'live') return 'WATCH LIVE';
  if (broadcast?.status === 'replay') return 'WATCH REPLAY';
  if (broadcast?.status === 'upcoming') return 'NEXT LIVE';
  return 'WATCH YOUTUBE';
};

const getBroadcastTag = (broadcast) => {
  if (broadcast?.status === 'live') return 'LIVE NOW';
  if (broadcast?.status === 'replay') return 'LATEST BROADCAST';
  if (broadcast?.status === 'upcoming') return 'NEXT LIVE';
  return 'THE BROADCAST';
};

const setBroadcastSnapshot = (broadcast) => {
  window.__rightsideBroadcast = broadcast;
  (window.__rightsideBroadcastListeners || []).forEach((listener) => listener(broadcast));
};

const useRightsideBroadcast = () => {
  const [broadcast, setBroadcast] = React.useState(window.__rightsideBroadcast || BROADCAST_LOADING);

  React.useEffect(() => {
    window.__rightsideBroadcastListeners = window.__rightsideBroadcastListeners || [];
    window.__rightsideBroadcastListeners.push(setBroadcast);

    if (!window.__rightsideBroadcastPromise) {
      window.__rightsideBroadcastPromise = fetch('/api/youtube-live')
        .then((res) => res.ok ? res.json() : Promise.reject(new Error('Broadcast unavailable')))
        .then((data) => {
          setBroadcastSnapshot(data);
          return data;
        })
        .catch(() => {
          setBroadcastSnapshot(BROADCAST_FALLBACK);
          return BROADCAST_FALLBACK;
        });
    }

    return () => {
      window.__rightsideBroadcastListeners = (window.__rightsideBroadcastListeners || []).filter((listener) => listener !== setBroadcast);
    };
  }, []);

  return broadcast;
};

window.useRightsideBroadcast = useRightsideBroadcast;
window.getBroadcastHref = getBroadcastHref;
window.getBroadcastCta = getBroadcastCta;
window.getBroadcastTag = getBroadcastTag;

// ============ Top Bar with auto-populating ticker =================
const TopBar = () => {
  const broadcast = useRightsideBroadcast();
  const cta = getBroadcastCta(broadcast);
  const href = getBroadcastHref(broadcast);
  const [time, setTime] = React.useState(new Date());
  const [items, setItems] = React.useState([
    'Allison & Amie Beth go live at 10A CT',
    'Subscribe to The Rightside Dispatch',
    'Listen on Apple, Spotify & YouTube',
    'Watch the latest broadcast — @therightsidemedia',
    'Text the show: 833.687.4448',
  ]);
  React.useEffect(() => {
    const t = setInterval(() => setTime(new Date()), 1000);
    return () => clearInterval(t);
  }, []);
  React.useEffect(() => {
    // Auto-populate ticker via Claude with today's headlines
    let cancelled = false;
    (async () => {
      try {
        const today = new Date().toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' });
        const txt = await window.claude.complete(
          `It is ${today}. List 6 short, punchy news/culture/political tickers (max 8 words each) for a conservative Alabama-based talk show called The Rightside (with hosts Allison & Amie Beth). Cover Alabama news, national politics, and culture. Return ONLY the 6 items separated by " // " — no numbering, no quotes, no extra text.`
        );
        if (cancelled) return;
        const parts = txt.split('//').map(s => s.trim()).filter(s => s && s.length < 80);
        if (parts.length >= 3) setItems(parts.slice(0, 8));
      } catch (e) { /* keep fallback */ }
    })();
    return () => { cancelled = true; };
  }, []);
  const fmt = time.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', timeZone: 'America/Chicago' });
  return (
    <div className="topbar topbar-with-ticker">
      <div className="topbar-inner">
        <div className="topbar-left">
          <span className="live-dot" aria-hidden />
          <span className="topbar-label">DAILY TICKER</span>
          <span className="topbar-sep">/</span>
          <span className="topbar-show">{fmt} CT · BIRMINGHAM, AL</span>
        </div>
        <div className="topbar-right">
          <a className="topbar-btn" href={href} target="_blank" rel="noopener">
            <Icon.Play size={10} /> {cta}
          </a>
        </div>
      </div>
      <div className="topbar-ticker">
        <div className="topbar-ticker-track">
          {[...items, ...items].map((t, i) => (
            <span className="topbar-ticker-item" key={i}>
              <Icon.Dot size={5} /> {t}
            </span>
          ))}
        </div>
      </div>
    </div>
  );
};

// ============ Nav =================
const Nav = () => {
  const links = [
    { label: 'The Show', href: '#live' },
    { label: 'Hosts', href: '#hosts' },
    { label: 'Op-Eds', href: '#opeds' },
    { label: 'Newsletter', href: '#newsletter' },
    { label: 'Contact', href: '#contact' },
  ];
  return (
    <nav className="nav">
      <div className="nav-inner">
        <a href="#top" className="nav-logo">
          <RightsideLogo size={0.42} showTagline={false} />
        </a>
        <ul className="nav-links">
          {links.map((l) => (
            <li key={l.label}>
              <a href={l.href}>{l.label}</a>
            </li>
          ))}
        </ul>
        <div className="nav-right">
          <a className="nav-sub" href="https://www.youtube.com/@therightsidemedia" target="_blank" rel="noopener">
            Subscribe <Icon.Arrow size={14} />
          </a>
        </div>
      </div>
    </nav>
  );
};

// Auto-formatted today date e.g. "APR 30, 2026"
const formatToday = () => {
  const d = new Date();
  return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }).toUpperCase();
};

// ============ Hero =================
const HeroEditorial = () => {
  const broadcast = useRightsideBroadcast();
  const isLive = broadcast.status === 'live';
  const cta = getBroadcastCta(broadcast);
  const href = getBroadcastHref(broadcast);

  return (
    <section className="hero hero-editorial" id="top">
      <div className="hero-grid">
        <div className="hero-meta">
          <div className="hero-tag">
            {isLive && <Icon.Dot size={6} />} {getBroadcastTag(broadcast)}
          </div>
          <div className="hero-date">{formatToday()} · 10A–12P CT</div>
        </div>

      <h1 className="hero-headline">
        <span className="hl-line">THE RIGHT PLACE.</span>
        <span className="hl-line">THE RIGHT TIME.</span>
        <span className="hl-line hl-accent">
          THE RIGHTSIDE.
        </span>
      </h1>

      <div className="hero-sub">
        <p>
          Because you can't influence conversations you aren't in.
        </p>
        <div className="hero-ctas">
          <a href={href} target="_blank" rel="noopener" className="btn btn-primary">
            {isLive && <span className="btn-pulse" />} {cta}
            <Icon.Arrow size={14} />
          </a>
          <a href="https://www.youtube.com/@therightsidemedia" target="_blank" rel="noopener" className="btn btn-ghost">
            SUBSCRIBE <Icon.ArrowUpRight size={14} />
          </a>
        </div>
      </div>

      <div className="hero-hosts">
        <div className="host-card">
          <div className="host-photo">
            <img src="assets/allison.jpeg" alt="Allison Sinclair" />
          </div>
          <div className="host-name">ALLISON</div>
          <div className="host-role">HOST / OWNER</div>
        </div>
        <div className="host-card">
          <div className="host-photo">
            <img src="assets/amiebeth.jpeg" alt="Amie Beth Shaver" />
          </div>
          <div className="host-name">AMIE BETH</div>
          <div className="host-role">HOST / OWNER</div>
        </div>
        <div className="host-card">
          <div className="host-photo">
            <img src="assets/jp.jpeg" alt="JP Plott" />
          </div>
          <div className="host-name">JP</div>
          <div className="host-role">CO-HOST / PRODUCER</div>
        </div>
      </div>
    </div>
  </section>
  );
};

// Alt hero: full-bleed studio poster
const HeroPoster = () => {
  const broadcast = useRightsideBroadcast();
  const isLive = broadcast.status === 'live';
  const cta = getBroadcastCta(broadcast);
  const href = getBroadcastHref(broadcast);

  return (
    <section className="hero hero-poster" id="top">
    <div className="poster-frame">
      <div className="poster-tag">
        {isLive && <span className="live-dot" />} {getBroadcastTag(broadcast)} FROM BIRMINGHAM
      </div>
      <div className="poster-stack">
        <div className="poster-word">WE</div>
        <div className="poster-word poster-word-red">SPEAK</div>
        <div className="poster-word">TRUTH</div>
        <div className="poster-word poster-word-italic">to power.</div>
      </div>
      <div className="poster-footer">
        <div>
          <div className="poster-footer-lbl">PRESENTED BY</div>
          <div className="poster-footer-val">YELLOWHAMMER NEWS</div>
        </div>
        <div>
          <div className="poster-footer-lbl">TODAY</div>
          <div className="poster-footer-val">{formatToday()}</div>
        </div>
        <div>
          <div className="poster-footer-lbl">NEXT LIVE</div>
          <div className="poster-footer-val">TODAY 10:00A CT</div>
        </div>
      </div>
      <a href={href} target="_blank" rel="noopener" className="poster-cta">
        {isLive && <span className="btn-pulse" />} {cta} <Icon.Arrow size={14} />
      </a>
    </div>
  </section>
  );
};

window.TopBar = TopBar;
window.Nav = Nav;
window.HeroEditorial = HeroEditorial;
window.HeroPoster = HeroPoster;
