<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>EmbyToolkit</title>
<link rel="stylesheet" href="/static/app-theme.css">
<style>
  :root {
    --bg: #0d0f12;
    --surface: #13171f;
    --surface2: #1a2030;
    --surface3: #222840;
    --border: #252d3d;
    --border-active: #14b8a6;
    --text: #e8ecf4;
    --text-2: #8892a8;
    --text-3: #4e5a70;
    --accent: #14b8a6;
    --accent-h: #2dd4bf;
    --accent-glow: rgba(20,184,166,0.12);
    --green: #34d399;
    --green-bg: rgba(52,211,153,0.08);
    --red: #f87171;
    --r: 10px;
    --r-lg: 14px;
  }

  * { box-sizing: border-box; }
  html, body { height: 100%; }
  body {
    margin: 0;
    background: var(--bg);
    color: var(--text);
    font-family: 'Inter', system-ui, sans-serif;
    display: grid;
    grid-template-columns: 240px 1fr;
    height: 100vh;
    height: 100svh;
    overflow: hidden;
  }

  /* ── Mobile top bar (hidden on desktop) ── */
  .app-topbar {
    display: none;
    align-items: center;
    gap: 12px;
    padding: 10px 14px;
    background: var(--surface);
    border-bottom: 1px solid var(--border);
    position: sticky;
    top: 0;
    z-index: 30;
  }
  .app-topbar-brand {
    display: flex;
    align-items: center;
    gap: 10px;
    font-weight: 700;
    letter-spacing: -0.03em;
  }
  .icon-btn {
    width: 38px; height: 38px;
    display: inline-grid; place-items: center;
    border-radius: 10px;
    border: 1px solid var(--border);
    background: var(--surface2);
    color: var(--text);
    cursor: pointer;
  }
  .icon-btn:hover { background: var(--surface3); }

  .nav-scrim {
    display: none;
    position: fixed;
    inset: 0;
    background: rgba(0,0,0,0.55);
    z-index: 40;
    opacity: 0;
    transition: opacity 0.18s ease;
  }
  .nav-scrim.show { opacity: 1; }

  /* ── App Nav Sidebar ── */
  .app-nav {
    display: flex;
    flex-direction: column;
    background: var(--surface);
    border-right: 1px solid var(--border);
    overflow: hidden;
  }
  .app-nav-brand {
    padding: 18px 16px;
    display: flex;
    align-items: center;
    gap: 10px;
    border-bottom: 1px solid var(--border);
    flex-shrink: 0;
  }
  .app-nav-logo {
    width: 32px; height: 32px;
    background: var(--accent);
    border-radius: 8px;
    display: grid; place-items: center;
    color: #fff;
    flex-shrink: 0;
  }
  .app-nav-name {
    font-size: 15px;
    font-weight: 700;
    letter-spacing: -0.03em;
  }
  .app-nav-items {
    list-style: none;
    padding: 8px;
    flex: 1;
    overflow-y: auto;
    margin: 0;
  }
  .app-nav-item {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 9px 12px;
    border-radius: 8px;
    color: var(--text-2);
    text-decoration: none;
    font-size: 13px;
    font-weight: 500;
    transition: background 0.12s, color 0.12s;
    margin-bottom: 1px;
  }
  .app-nav-item:hover { background: var(--surface2); color: var(--text); }
  .app-nav-item.active { background: var(--accent); color: #fff; }
  .app-nav-footer {
    padding: 14px 16px;
    border-top: 1px solid var(--border);
    display: flex;
    align-items: center;
    gap: 7px;
    font-size: 12px;
    color: var(--text-2);
    flex-shrink: 0;
  }
  .dot {
    width: 7px; height: 7px; border-radius: 50%;
    background: var(--green); box-shadow: 0 0 6px var(--green);
  }
  .dot.off { background: var(--red); box-shadow: 0 0 6px var(--red); }

  .page {
    padding: 24px clamp(16px, 2.4vw, 36px) 32px;
    overflow-y: auto;
  }
  .page-inner {
    width: 100%;
    max-width: 1680px;
    margin: 0 auto;
  }
  .hero {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 18px;
    margin-bottom: 16px;
  }
  .hero-copy h2 {
    margin: 0 0 8px;
    font-size: clamp(24px, 3vw, 34px);
    line-height: 1;
    letter-spacing: -0.04em;
  }
  .hero-copy p {
    margin: 0;
    max-width: 820px;
    color: var(--text-2);
    font-size: 14px;
    line-height: 1.5;
  }

  .toolbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 14px;
    margin-bottom: 18px;
    padding: 14px 16px;
    border: 1px solid var(--border);
    border-radius: var(--r-lg);
    background: linear-gradient(180deg, rgba(26,32,48,0.95), rgba(19,23,31,0.95));
  }
  .toolbar-meta {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    color: var(--text-2);
    font-size: 12px;
  }
  .toolbar-meta strong {
    color: var(--text);
    font-weight: 700;
  }
  .toolbar-actions {
    display: flex;
    align-items: center;
    gap: 10px;
    flex-wrap: wrap;
  }
  .chip-toggle {
    min-height: 34px;
    padding: 0 12px;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    border-radius: 999px;
    border: 1px solid var(--border);
    background: var(--surface2);
    color: var(--text);
    cursor: pointer;
    user-select: none;
    font-size: 12px;
    font-weight: 600;
  }
  .chip-toggle input {
    margin: 0;
    accent-color: var(--accent);
  }

  .btn {
    min-height: 36px;
    padding: 0 14px;
    border-radius: 10px;
    border: 1px solid var(--border);
    background: var(--surface2);
    color: var(--text);
    font-family: inherit;
    font-size: 13px;
    font-weight: 600;
    cursor: pointer;
    transition: background 0.12s, border-color 0.12s, opacity 0.12s;
  }
  .btn:hover:not(:disabled) { background: var(--surface3); }
  .btn:disabled { opacity: 0.4; cursor: not-allowed; }
  .btn-green {
    background: var(--green);
    border-color: var(--green);
    color: #08120e;
  }

  .grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(min(100%, 340px), 1fr));
    gap: 16px;
  }
  @media (min-width: 1600px) {
    .grid { grid-template-columns: repeat(auto-fill, minmax(380px, 1fr)); gap: 18px; }
  }
  @media (min-width: 2200px) {
    .grid { grid-template-columns: repeat(auto-fill, minmax(420px, 1fr)); }
  }

  .card {
    display: grid;
    grid-template-columns: 108px minmax(0, 1fr);
    gap: 14px;
    padding: 14px;
    border: 1px solid var(--border);
    border-radius: var(--r-lg);
    background: linear-gradient(180deg, rgba(19,23,31,0.98), rgba(13,15,18,0.98));
    min-height: 190px;
  }
  .card-poster {
    width: 108px;
    aspect-ratio: 2 / 3;
    object-fit: cover;
    border-radius: 10px;
    background: var(--surface2);
  }
  .card-body {
    min-width: 0;
    display: flex;
    flex-direction: column;
    gap: 10px;
  }
  .card-top {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 10px;
  }
  .card-title {
    margin: 0;
    font-size: 18px;
    font-weight: 700;
    line-height: 1.1;
    letter-spacing: -0.03em;
  }
  .card-year {
    margin-top: 4px;
    color: var(--text-2);
    font-size: 12px;
  }
  .pill {
    padding: 4px 8px;
    border-radius: 999px;
    font-size: 10px;
    font-weight: 700;
    letter-spacing: 0.06em;
    text-transform: uppercase;
    border: 1px solid transparent;
    white-space: nowrap;
  }
  .pill-green {
    background: var(--green-bg);
    border-color: rgba(52,211,153,0.4);
    color: var(--green);
  }
  .pill-blue {
    background: rgba(74,111,255,0.12);
    border-color: rgba(74,111,255,0.35);
    color: #a9bbff;
  }
  .pill-muted {
    background: rgba(136,146,168,0.08);
    border-color: rgba(136,146,168,0.2);
    color: var(--text-2);
  }
  .meta-list {
    display: grid;
    gap: 8px;
  }
  .meta-row {
    display: grid;
    gap: 2px;
  }
  .meta-label {
    color: var(--text-3);
    font-size: 11px;
    text-transform: uppercase;
    letter-spacing: 0.08em;
  }
  .meta-value {
    color: var(--text);
    font-size: 13px;
    line-height: 1.35;
  }
  .meta-value.muted {
    color: var(--text-2);
  }
  .card-actions {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-top: auto;
  }
  .card-note {
    color: var(--text-3);
    font-size: 12px;
  }

  .empty {
    padding: 54px 20px;
    border: 1px dashed var(--border);
    border-radius: var(--r-lg);
    text-align: center;
    color: var(--text-3);
    font-size: 14px;
  }

  .pager {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    margin-top: 16px;
    padding-top: 4px;
  }
  .pager-meta {
    color: var(--text-2);
    font-size: 12px;
    font-family: inherit;
    font-variant-numeric: tabular-nums;
  }
  .pager-actions {
    display: flex;
    gap: 8px;
  }

  .toast {
    position: fixed;
    right: 20px;
    bottom: 20px;
    padding: 11px 18px;
    border-radius: 10px;
    font-size: 13px;
    font-weight: 500;
    transform: translateY(80px);
    opacity: 0;
    transition: all 0.25s cubic-bezier(0.4,0,0.2,1);
    pointer-events: none;
    z-index: 50;
  }
  .toast.show { transform: translateY(0); opacity: 1; }
  .toast.ok { background: var(--green-bg); border: 1px solid var(--green); color: var(--green); }
  .toast.err { background: rgba(248,113,113,.1); border: 1px solid var(--red); color: var(--red); }

  /* Ultra-wide tweak: widen the content cap a touch more on huge displays */
  @media (min-width: 2400px) {
    .page-inner { max-width: 1920px; }
  }

  @media (max-width: 1100px) {
    body { grid-template-columns: 200px 1fr; }
  }

  @media (max-width: 980px) {
    .hero, .toolbar, .pager {
      flex-direction: column;
      align-items: stretch;
    }
    .toolbar-actions, .pager-actions {
      justify-content: flex-start;
    }
  }

  /* ── Mobile: drawer nav ── */
  @media (max-width: 860px) {
    body {
      grid-template-columns: 1fr;
      grid-template-rows: auto 1fr;
    }
    .app-topbar { display: flex; }
    .app-nav {
      position: fixed;
      top: 0; left: 0; bottom: 0;
      width: min(82vw, 300px);
      z-index: 50;
      transform: translateX(-100%);
      transition: transform 0.22s cubic-bezier(0.4,0,0.2,1);
      box-shadow: 0 30px 60px rgba(0,0,0,0.4);
    }
    body.nav-open .app-nav { transform: translateX(0); }
    body.nav-open .nav-scrim { display: block; }
    .page { padding: 16px; }
  }

  @media (max-width: 720px) {
    .toolbar { padding: 12px; }
    .toolbar-actions { gap: 8px; }
    .toolbar-actions .btn,
    .toolbar-actions .chip-toggle { flex: 1 1 auto; justify-content: center; }
    .card {
      grid-template-columns: 92px minmax(0, 1fr);
      gap: 12px;
      padding: 12px;
      min-height: 0;
    }
    .card-poster { width: 92px; }
    .card-title { font-size: 16px; }
    .card-actions { flex-wrap: wrap; }
    .card-actions .btn { width: 100%; }
  }

  @media (max-width: 480px) {
    .card {
      grid-template-columns: 1fr;
    }
    .card-poster {
      width: 100%;
      aspect-ratio: 16 / 9;
      object-fit: cover;
    }
    .hero-copy h2 { font-size: 22px; }
  }
</style>
</head>
<body>

<header class="app-topbar">
  <button class="icon-btn" id="navToggle" aria-label="Open navigation">
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg>
  </button>
  <div class="app-topbar-brand">
    <span>EmbyToolkit</span>
  </div>
</header>

<div class="nav-scrim" id="navScrim"></div>

<nav class="app-nav">
  <div class="app-nav-brand">
    <div class="app-nav-logo">
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><polyline points="3.29 7 12 12 20.71 7"/><line x1="12" y1="22" x2="12" y2="12"/></svg>
    </div>
    <span class="app-nav-name">EmbyToolkit</span>
  </div>
  <ul class="app-nav-items">
    <li><a class="app-nav-item" href="/">
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="m21 15-5-5L5 21"/></svg>
      <span>Generator</span>
    </a></li>
    <li><a class="app-nav-item" href="/collections">
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/></svg>
      <span>Collections</span>
    </a></li>
    <li><a class="app-nav-item active" href="/airing">
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="7" width="20" height="15" rx="2"/><polyline points="17 2 12 7 7 2"/></svg>
      <span>Airing</span>
    </a></li>
    <li><a class="app-nav-item" href="/bulk-assign">
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"/></svg>
      <span>Bulk Assign</span>
    </a></li>
    <li><a class="app-nav-item" href="/favorites">
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 17.27 18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"/></svg>
      <span>User Favourites</span>
    </a></li>
  </ul>
  <div class="app-nav-foot">
    <div class="app-nav-status">
      <span class="dot" id="statusDot"></span>
      <span id="statusText">Checking…</span>
    </div>
    <div class="app-nav-version">EmbyToolkit · v1.0</div>
  </div>
</nav>

<main class="page">
 <div class="page-inner">
  <section class="hero">
    <div class="hero-copy">
      <h2>Current Airing Shows</h2>
      <p>
        This page uses Emby metadata to find continuing shows, upcoming airtimes, and season premieres.
        <strong>Apply New Season</strong> is available only when the show is in Emby and already has a logo.
      </p>
    </div>
  </section>

  <section class="toolbar">
    <div class="toolbar-meta">
      <div><strong id="countText">0</strong> shows</div>
      <div>Snapshot <strong id="generatedAt">—</strong></div>
      <div>Week <strong id="weekLabel">—</strong></div>
      <div>Window <strong id="windowText">7-21 days</strong></div>
    </div>
    <div class="toolbar-actions">
      <button class="btn" id="btnWeekPrev">Previous week</button>
      <button class="btn" id="btnWeekCurrent">This week</button>
      <button class="btn" id="btnWeekNext">Next week</button>
      <label class="chip-toggle" for="eligibleOnlyToggle">
        <input type="checkbox" id="eligibleOnlyToggle">
        <span>Eligible only</span>
      </label>
      <button class="btn" id="btnRefresh">Refresh</button>
    </div>
  </section>

  <section id="results">
    <div class="empty">Loading airing titles…</div>
  </section>

  <section class="pager">
    <div class="pager-meta" id="pagerMeta">Page 1</div>
    <div class="pager-actions">
      <button class="btn" id="btnPrev" disabled>Previous</button>
      <button class="btn" id="btnNext" disabled>Next</button>
    </div>
  </section>
 </div>
</main>

<div class="toast" id="toast"></div>

<script>
const state = {
  page: 1,
  limit: 12,
  total: 0,
  eligibleOnly: false,
  weekOffset: 0,
  windowMinDays: 7,
  windowMaxDays: 21,
  items: [],
  applyingId: null,
};
const MIN_WEEK_OFFSET = -8;
const MAX_WEEK_OFFSET = 4;

const $ = (selector) => document.querySelector(selector);
const results = $('#results');
const countText = $('#countText');
const generatedAt = $('#generatedAt');
const weekLabel = $('#weekLabel');
const windowText = $('#windowText');
const pagerMeta = $('#pagerMeta');
const btnWeekPrev = $('#btnWeekPrev');
const btnWeekCurrent = $('#btnWeekCurrent');
const btnWeekNext = $('#btnWeekNext');
const eligibleOnlyToggle = $('#eligibleOnlyToggle');
const btnRefresh = $('#btnRefresh');
const btnPrev = $('#btnPrev');
const btnNext = $('#btnNext');
const toast = $('#toast');

const navToggle = $('#navToggle');
const navScrim = $('#navScrim');
if (navToggle && navScrim) {
  const closeNav = () => document.body.classList.remove('nav-open');
  navToggle.addEventListener('click', () => document.body.classList.toggle('nav-open'));
  navScrim.addEventListener('click', closeNav);
  document.querySelectorAll('.app-nav-item').forEach((link) => link.addEventListener('click', closeNav));
  window.addEventListener('keydown', (e) => { if (e.key === 'Escape') closeNav(); });
}

function esc(value) {
  const div = document.createElement('div');
  div.textContent = value ?? '';
  return div.innerHTML;
}

function showToast(message, type) {
  toast.textContent = message;
  toast.className = `toast ${type} show`;
  setTimeout(() => toast.classList.remove('show'), 2800);
}

function formatDateTime(value) {
  if (!value) return '—';
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return '—';
  return new Intl.DateTimeFormat(undefined, {
    weekday: 'short',
    month: 'short',
    day: 'numeric',
    hour: 'numeric',
    minute: '2-digit',
  }).format(date);
}

function formatDateOnly(value) {
  if (!value) return '—';
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return '—';
  return new Intl.DateTimeFormat(undefined, {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
  }).format(date);
}

function formatWeekRange(startValue, endValue) {
  if (!startValue || !endValue) return '—';
  const start = new Date(startValue);
  const end = new Date(endValue);
  if (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime())) return '—';
  const endDisplay = new Date(end.getTime() - 1000);
  const fmt = new Intl.DateTimeFormat(undefined, { month: 'short', day: 'numeric' });
  return `${fmt.format(start)} - ${fmt.format(endDisplay)}`;
}

function canApplyNewSeason(item) {
  return Boolean(
    item.has_logo && (
      item.eligible_new_season ||
      ((item.status || '').toLowerCase() === 'continuing' && (item.selected_week_air_at || item.next_air_at))
    )
  );
}

function renderCards(items) {
  if (!items.length) {
    results.innerHTML = '<div class="empty">No airing shows matched this week. Try Previous week or turn off Eligible only.</div>';
    return;
  }

  results.innerHTML = `
    <div class="grid">
      ${items.map((item) => `
        ${(() => {
          const applyAllowed = canApplyNewSeason(item);
          const note = !item.has_logo
            ? 'Requires an Emby logo before New Season artwork can be applied.'
            : applyAllowed
              ? (item.eligibility_reason === 'current_airing' || (!item.eligibility_reason && ((item.status || '').toLowerCase() === 'continuing') && (item.selected_week_air_at || item.next_air_at))
                  ? 'Applies thumb + primary. Eligible because the show is continuing and has a current or upcoming airing.'
                  : (item.season_premiere_inferred
                      ? 'Applies thumb + primary. Season start was inferred from current season activity.'
                      : 'Applies thumb + primary with default artwork settings.'))
              : `Available when Emby finds a current or upcoming airing, or a recent season start in the ${esc(String(state.windowMinDays))}-${esc(String(state.windowMaxDays))} day window.`;
          return `
        <article class="card">
          <img class="card-poster" src="${esc(item.poster_url)}" alt="" loading="lazy" decoding="async">
          <div class="card-body">
            <div class="card-top">
              <div>
                <h3 class="card-title">${esc(item.name)}</h3>
                <div class="card-year">${item.year ? esc(String(item.year)) : '—'}</div>
              </div>
              <span class="pill ${item.eligible_new_season ? 'pill-green' : (item.status === 'Continuing' ? 'pill-blue' : 'pill-muted')}">
                ${item.eligible_new_season ? 'Eligible' : esc(item.status || 'Airing')}
              </span>
            </div>

            <div class="meta-list">
              <div class="meta-row">
                <div class="meta-label">Air Days</div>
                <div class="meta-value ${item.air_days?.length ? '' : 'muted'}">${item.air_days?.length ? esc(item.air_days.join(', ')) : 'No recurring air day metadata'}</div>
              </div>
              <div class="meta-row">
                <div class="meta-label">Selected Week Airtime</div>
                <div class="meta-value ${item.selected_week_air_at ? '' : 'muted'}">${item.selected_week_air_at ? `${esc(formatDateTime(item.selected_week_air_at))}${item.selected_week_episode_label ? ` · ${esc(item.selected_week_episode_label)}` : ''}` : 'No episode found in the selected week'}</div>
              </div>
              <div class="meta-row">
                <div class="meta-label">Next Known Airtime</div>
                <div class="meta-value ${item.next_air_at ? '' : 'muted'}">${item.next_air_at ? `${esc(formatDateTime(item.next_air_at))}${item.next_episode_label ? ` · ${esc(item.next_episode_label)}` : ''}` : 'No upcoming episode found in Emby'}</div>
              </div>
              <div class="meta-row">
                <div class="meta-label">Latest Season Premiere</div>
                <div class="meta-value ${item.season_premiere_at ? '' : 'muted'}">${item.season_premiere_at ? `Season ${esc(String(item.season_number))} · ${esc(formatDateOnly(item.season_premiere_at))} · ${esc(String(item.days_since_season_premiere))} days ago${item.season_premiere_inferred ? ' · inferred from recent season activity' : ''}` : `No recent season start in the ${esc(String(state.windowMinDays))}-${esc(String(state.windowMaxDays))} day window`}</div>
              </div>
            </div>

            <div class="card-actions">
              <button
                class="btn btn-green"
                data-apply-id="${esc(item.id)}"
                data-apply-title="${esc(item.name)}"
                ${applyAllowed ? '' : 'disabled'}
              >
                ${state.applyingId === item.id ? 'Applying…' : 'Apply New Season'}
              </button>
              <span class="card-note">${note}</span>
            </div>
          </div>
        </article>
      `;
        })()}
      `).join('')}
    </div>
  `;
}

function updatePager() {
  const start = state.total === 0 ? 0 : ((state.page - 1) * state.limit) + 1;
  const end = Math.min(state.page * state.limit, state.total);
  pagerMeta.textContent = state.total ? `${start}-${end} of ${state.total} · Page ${state.page}` : 'No results';
  btnPrev.disabled = state.page <= 1;
  btnNext.disabled = state.page * state.limit >= state.total;
  btnWeekPrev.disabled = state.weekOffset <= MIN_WEEK_OFFSET;
  btnWeekCurrent.disabled = state.weekOffset === 0;
  btnWeekNext.disabled = state.weekOffset >= MAX_WEEK_OFFSET;
}

async function loadAiring(refresh = false) {
  results.innerHTML = '<div class="empty">Loading airing titles…</div>';
  btnRefresh.disabled = true;
  try {
    const response = await fetch(`/api/airing?page=${state.page}&limit=${state.limit}&eligible_only=${state.eligibleOnly}&refresh=${refresh}&week_offset=${state.weekOffset}`);
    const data = await response.json();
    if (!response.ok) throw new Error(data.detail || `${response.status}`);
    state.items = data.items;
    state.total = data.total;
    state.windowMinDays = data.new_season_min_days;
    state.windowMaxDays = data.new_season_max_days;
    countText.textContent = data.total;
    generatedAt.textContent = data.generated_at ? formatDateTime(data.generated_at) : '—';
    weekLabel.textContent = formatWeekRange(data.week_start, data.week_end);
    windowText.textContent = `${data.new_season_min_days}-${data.new_season_max_days} days`;
    renderCards(data.items);
    updatePager();
  } catch (error) {
    results.innerHTML = `<div class="empty">Failed to load airing data: ${esc(error.message)}</div>`;
    state.total = 0;
    updatePager();
  } finally {
    btnRefresh.disabled = false;
  }
}

results.addEventListener('click', async (event) => {
  const button = event.target.closest('[data-apply-id]');
  if (!button || button.disabled) return;

  const itemId = button.dataset.applyId;
  const title = button.dataset.applyTitle;
  state.applyingId = itemId;
  renderCards(state.items);

  try {
    const response = await fetch('/api/airing/apply-new-season', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        item_id: itemId,
        title,
        generate_primary: true,
        week_offset: state.weekOffset,
      }),
    });
    const data = await response.json();
    if (!response.ok) throw new Error(data.detail || `${response.status}`);
    if (data.primary_attempted && data.primary_code) {
      showToast('Applied New Season thumb + primary', 'ok');
    } else if (data.primary_attempted && data.primary_error) {
      showToast('Applied New Season thumb only', 'ok');
    } else {
      showToast('Applied New Season artwork', 'ok');
    }
  } catch (error) {
    showToast(error.message, 'err');
  } finally {
    state.applyingId = null;
    renderCards(state.items);
  }
});

eligibleOnlyToggle.addEventListener('change', () => {
  state.eligibleOnly = eligibleOnlyToggle.checked;
  state.page = 1;
  loadAiring(false);
});

btnRefresh.addEventListener('click', () => {
  state.page = 1;
  loadAiring(true);
});

btnWeekPrev.addEventListener('click', () => {
  if (state.weekOffset <= MIN_WEEK_OFFSET) return;
  state.weekOffset -= 1;
  state.page = 1;
  loadAiring(true);
});

btnWeekCurrent.addEventListener('click', () => {
  if (state.weekOffset === 0) return;
  state.weekOffset = 0;
  state.page = 1;
  loadAiring(true);
});

btnWeekNext.addEventListener('click', () => {
  if (state.weekOffset >= MAX_WEEK_OFFSET) return;
  state.weekOffset += 1;
  state.page = 1;
  loadAiring(true);
});

btnPrev.addEventListener('click', () => {
  if (state.page <= 1) return;
  state.page -= 1;
  loadAiring(false);
});

btnNext.addEventListener('click', () => {
  if (state.page * state.limit >= state.total) return;
  state.page += 1;
  loadAiring(false);
});

(async () => {
  try {
    const config = await (await fetch('/api/config')).json();
    if (config.connected) {
      $('#statusText').textContent = 'Connected to Emby';
    } else {
      $('#statusDot').classList.add('off');
      $('#statusText').textContent = 'No API key';
    }
  } catch {
    $('#statusDot').classList.add('off');
    $('#statusText').textContent = 'Connection error';
  }
})();

loadAiring(false);
</script>

</body>
</html>
