<?php require_once __DIR__ . '/includes/bootstrap.php';
$pageTitle = 'Schedule | Underground FX Radio';
$currentPage = basename(__FILE__);
include __DIR__ . '/includes/header.php';

function ugfx_schedule_blocks(array $slots): array {
    $blocks = [];
    $currentShow = null;
    $startHour = 0;
    for ($hour = 0; $hour < 24; $hour++) {
        $show = trim((string)($slots[$hour] ?? 'Underground FX AutoDJ'));
        if ($currentShow === null) {
            $currentShow = $show;
            $startHour = $hour;
            continue;
        }
        if ($show !== $currentShow) {
            $blocks[] = [
                'show' => $currentShow,
                'start' => $startHour,
                'end' => $hour,
            ];
            $currentShow = $show;
            $startHour = $hour;
        }
    }
    if ($currentShow !== null) {
        $blocks[] = [
            'show' => $currentShow,
            'start' => $startHour,
            'end' => 24,
        ];
    }
    return $blocks;
}

function ugfx_format_hour_label(int $hour): string {
    return date('g:i A', strtotime(sprintf('%02d:00', $hour % 24)));
}

function ugfx_schedule_time_range(int $start, int $end): string {
    $startLabel = ugfx_format_hour_label($start);
    $endLabel = $end >= 24 ? '12:00 AM' : ugfx_format_hour_label($end);
    return $startLabel . ' - ' . $endLabel;
}

function ugfx_schedule_periods(array $blocks): array {
    $periods = [
        'Morning' => ['start' => 0, 'end' => 12, 'rows' => []],
        'Afternoon' => ['start' => 12, 'end' => 18, 'rows' => []],
        'Evening' => ['start' => 18, 'end' => 24, 'rows' => []],
    ];

    foreach ($blocks as $block) {
        foreach ($periods as $label => $period) {
            $overlapStart = max($block['start'], $period['start']);
            $overlapEnd = min($block['end'], $period['end']);
            if ($overlapStart < $overlapEnd) {
                $periods[$label]['rows'][] = [
                    'show' => $block['show'],
                    'start' => $overlapStart,
                    'end' => $overlapEnd,
                    'full_start' => $block['start'],
                    'full_end' => $block['end'],
                ];
            }
        }
    }

    return $periods;
}

$schedule = ugfx_get_schedule();
$today = ugfx_day_name();
$today = isset($schedule[$today]) ? $today : array_key_first($schedule);
$currentHour = (int) date('G');
$currentShow = $schedule[$today][$currentHour] ?? 'Underground FX AutoDJ';
$nextHour = ($currentHour + 1) % 24;
$nextShow = $schedule[$today][$nextHour] ?? 'Underground FX AutoDJ';
?>
<section class="ugfx-page-hero">
  <div class="container-xxl">
    <div class="ugfx-kicker"><i class="bi bi-calendar2-week-fill"></i> Underground FX Radio</div>
    <h1 class="page-title">On-air schedule</h1>
    <p class="page-copy">Choose a day and view the full station clock with the AutoDJ slots kept in place for easy swaps later.</p>
  </div>
</section>

<section class="section-pad pt-3">
  <div class="container-xxl">
    <div class="ugfx-card ugfx-schedule-shell p-3 p-lg-4">
      <div class="ugfx-schedule-miniwrap">
        <div class="ugfx-schedule-mini">
          <span class="ugfx-schedule-mini-label"><i class="bi bi-broadcast-pin"></i> Live right now</span>
          <strong><?= htmlspecialchars($currentShow) ?></strong>
          <small><?= htmlspecialchars($today) ?> · <?= date('g:i A') ?></small>
        </div>
        <div class="ugfx-schedule-mini alt">
          <span class="ugfx-schedule-mini-label"><i class="bi bi-clock-history"></i> Up next</span>
          <strong><?= htmlspecialchars($nextShow) ?></strong>
          <small>Starts <?= date('g:i A', strtotime(sprintf('%02d:00', $nextHour))) ?></small>
        </div>
      </div>

      <div class="ugfx-schedule-tabs mt-3" role="tablist" aria-label="Schedule days">
        <?php $dayIndex = 0; foreach ($schedule as $day => $slots): ?>
          <?php $isActive = ($day === $today) || ($today === '' && $dayIndex === 0); ?>
          <button
            class="ugfx-schedule-tab <?= $isActive ? 'is-active' : '' ?>"
            type="button"
            data-schedule-day="<?= htmlspecialchars($day) ?>"
            aria-pressed="<?= $isActive ? 'true' : 'false' ?>"
          >
            <span><?= htmlspecialchars(substr($day, 0, 3)) ?></span>
            <small><?= htmlspecialchars($day) ?></small>
          </button>
        <?php $dayIndex++; endforeach; ?>
      </div>

      <?php $dayIndex = 0; foreach ($schedule as $day => $slots): ?>
        <?php
          $isActive = ($day === $today) || ($today === '' && $dayIndex === 0);
          $blocks = ugfx_schedule_blocks($slots);
          $periods = ugfx_schedule_periods($blocks);
        ?>
        <div class="ugfx-schedule-panel <?= $isActive ? 'is-active' : '' ?>" data-schedule-panel="<?= htmlspecialchars($day) ?>">
          <div class="ugfx-schedule-panel-head">
            <div>
              <div class="ugfx-kicker"><i class="bi bi-stars"></i> <?= htmlspecialchars($day) ?></div>
              <h3 class="mt-3 mb-2"><?= htmlspecialchars($day) ?> lineup</h3>
              <p class="text-secondary mb-0">Morning, afternoon, and evening blocks in one cleaner day view.</p>
            </div>
          </div>

          <div class="ugfx-schedule-period-grid mt-4">
            <?php foreach ($periods as $periodLabel => $period): ?>
              <section class="ugfx-schedule-period-card">
                <div class="ugfx-schedule-period-head">
                  <div>
                    <div class="ugfx-schedule-period-title"><?= htmlspecialchars($periodLabel) ?></div>
                    <div class="ugfx-schedule-period-range"><?= htmlspecialchars(ugfx_schedule_time_range($period['start'], $period['end'])) ?></div>
                  </div>
                </div>
                <div class="table-responsive">
                  <table class="ugfx-schedule-table">
                    <thead>
                      <tr>
                        <th>Time</th>
                        <th>Show</th>
                        <th>Type</th>
                      </tr>
                    </thead>
                    <tbody>
                      <?php if (empty($period['rows'])): ?>
                        <tr>
                          <td colspan="3" class="ugfx-schedule-empty">No shows in this block.</td>
                        </tr>
                      <?php else: ?>
                        <?php foreach ($period['rows'] as $row): ?>
                          <?php
                            $isLive = ($day === $today && $currentHour >= $row['start'] && $currentHour < $row['end']);
                            $isAuto = stripos($row['show'], 'autodj') !== false;
                          ?>
                          <tr class="<?= $isLive ? 'is-live' : '' ?>">
                            <td class="ugfx-schedule-table-time"><?= htmlspecialchars(ugfx_schedule_time_range($row['start'], $row['end'])) ?></td>
                            <td>
                              <div class="ugfx-schedule-show-title"><?= htmlspecialchars($row['show']) ?></div>
                              <?php if ($isLive): ?><span class="ugfx-live-pill mt-2">LIVE NOW</span><?php endif; ?>
                            </td>
                            <td>
                              <span class="ugfx-chip"><i class="bi bi-mic-fill"></i> <?= $isAuto ? 'AutoDJ slot' : 'DJ show' ?></span>
                            </td>
                          </tr>
                        <?php endforeach; ?>
                      <?php endif; ?>
                    </tbody>
                  </table>
                </div>
              </section>
            <?php endforeach; ?>
          </div>
        </div>
      <?php $dayIndex++; endforeach; ?>
    </div>
  </div>
</section>

<script>
document.addEventListener('DOMContentLoaded', function () {
  const tabs = Array.from(document.querySelectorAll('[data-schedule-day]'));
  const panels = Array.from(document.querySelectorAll('[data-schedule-panel]'));
  if (!tabs.length || !panels.length) return;

  function activate(day) {
    tabs.forEach((tab) => {
      const active = tab.getAttribute('data-schedule-day') === day;
      tab.classList.toggle('is-active', active);
      tab.setAttribute('aria-pressed', active ? 'true' : 'false');
    });
    panels.forEach((panel) => {
      const active = panel.getAttribute('data-schedule-panel') === day;
      panel.classList.toggle('is-active', active);
    });
  }

  tabs.forEach((tab) => {
    tab.addEventListener('click', () => activate(tab.getAttribute('data-schedule-day')));
  });
});
</script>

<?php include __DIR__ . '/includes/footer.php'; ?>
