<?php include('header.php'); ?>
<?php include('menu.php'); ?>
<?php
require_once __DIR__ . '/includes/nowplaying_lib.php';

$scheduleFile = __DIR__ . '/data/schedule.txt';
$schedule = [];
if (file_exists($scheduleFile)) {
  foreach (file($scheduleFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {
    $parts = array_map('trim', explode('|', $line));
    if (count($parts) === 3) {
      [$day, $hour, $dj] = $parts;
      $schedule[$day][$hour] = $dj;
    }
  }
}

date_default_timezone_set('America/New_York');
$currentDay = date('l');
$currentHour = date('H:00');
$todaySchedule = $schedule[$currentDay] ?? [];
$hours = array_keys($todaySchedule);
sort($hours);
$nowDJ = $todaySchedule[$currentHour] ?? 'No DJ scheduled';
$nextDJ = 'No DJ scheduled';
$comingDJ = 'No DJ scheduled';
$future = [];
foreach ($hours as $h) {
  if ($h > $currentHour) $future[] = $h;
}
if (isset($future[0])) $nextDJ = $todaySchedule[$future[0]] ?? $nextDJ;
if (isset($future[1])) $comingDJ = $todaySchedule[$future[1]] ?? $comingDJ;

$comments = file_exists(__DIR__ . '/data/comments.json') ? json_decode(file_get_contents(__DIR__ . '/data/comments.json'), true) : [];
if (!is_array($comments)) $comments = [];
$approvedComments = array_values(array_filter($comments, fn($c) => !empty($c['approved'])));
$approvedComments = array_slice(array_reverse($approvedComments), 0, 3);

$promo = file_exists(__DIR__ . '/data/promo.json') ? json_decode(file_get_contents(__DIR__ . '/data/promo.json'), true) : [];
if (!is_array($promo)) $promo = [];
$featuredEvent = !empty($promo['enabled']) && !empty($promo['title']);

$featuredNews = ['title' => '', 'body' => ''];
$newsDir = __DIR__ . '/data/news';
if (is_dir($newsDir)) {
  $newsFiles = glob($newsDir . '/*.json') ?: [];
  rsort($newsFiles);
  foreach ($newsFiles as $file) {
    $item = json_decode((string)file_get_contents($file), true);
    if (!is_array($item)) continue;
    if (!empty($item['featured']) || !empty($item['is_featured']) || !empty($item['pin_home'])) {
      $featuredNews = [
        'title' => trim((string)($item['title'] ?? 'Station Update')),
        'body' => trim((string)($item['body'] ?? $item['content'] ?? '')),
      ];
      break;
    }
  }
}
if ($featuredNews['title'] === '' && file_exists(__DIR__ . '/data/news.txt')) {
  $newsRaw = trim((string)file_get_contents(__DIR__ . '/data/news.txt'));
  $chunks = preg_split('/
---
/', $newsRaw);
  foreach ($chunks as $chunk) {
    $chunk = trim($chunk);
    if ($chunk === '') continue;
    $lines = preg_split('/\R+/', $chunk);
    $featuredNews['title'] = trim(strip_tags($lines[0] ?? 'Station Update'));
    $featuredNews['body'] = trim(strip_tags(implode(" ", array_slice($lines, 1))));
    if ($featuredNews['body'] !== '' || $featuredNews['title'] !== '') break;
  }
}
if ($featuredNews['body'] === '') $featuredNews['body'] = 'Fresh station updates will appear here when news is posted.';
if ($featuredNews['title'] === '') $featuredNews['title'] = 'Latest station news';

$directoryLinks = [
  ['key' => 'mytuner', 'label' => 'MyTuner', 'url' => '#', 'abbr' => 'MT'],
  ['key' => 'radiobox', 'label' => 'Online Radio Box', 'url' => '#', 'abbr' => 'ORB'],
  ['key' => 'spinner', 'label' => 'Radio Spinner', 'url' => '#', 'abbr' => 'RS'],
  ['key' => 'discord', 'label' => 'Discord', 'url' => '#', 'abbr' => 'D'],
];
?>
<main class="main-container home-main shell-wide">
  <section class="home-hero-panel ah-panel">
    <div class="hero-copy">
      <span class="eyebrow">Broadcasting from the heart of the hills</span>
      <h2>Almost Heaven lives here.</h2>
      <p class="hero-copy-text">Live radio, featured updates, station links, and the latest comments — all in one clean front page.</p>
      <div class="hero-actions">
        <button class="play-button" onclick="openPlayer()">▶ Play Now</button>
        <a class="hero-secondary-btn" href="/schedule.php">View Schedule</a>
      </div>
      <p class="live-status">Streaming live from the hills</p>
    </div>
    <div class="listen-platforms-wrap">
      <div class="platforms-header">
        <h3>Listen on…</h3>
        <p>Directory and community shortcuts</p>
      </div>
      <div class="listen-platforms">
        <?php foreach ($directoryLinks as $link): ?>
          <a class="platform-btn <?= htmlspecialchars($link['key']) ?>" href="<?= htmlspecialchars($link['url']) ?>" title="<?= htmlspecialchars($link['label']) ?>" data-placeholder="<?= $link['url'] === '#' ? '1' : '0' ?>">
            <span class="platform-icon"><?= htmlspecialchars($link['abbr']) ?></span>
            <span class="platform-label"><?= htmlspecialchars($link['label']) ?></span>
            <span class="platform-tip">Link coming soon</span>
          </a>
        <?php endforeach; ?>
      </div>
    </div>
  </section>

  <section class="home-feature-strip">
    <article class="ah-panel onair-horizontal">
      <div class="section-heading-row">
        <div>
          <h2 class="text-warning">On Air Right Now</h2>
          <p class="text-muted"><?= htmlspecialchars($currentDay) ?> schedule snapshot</p>
        </div>
      </div>
      <div class="onair-horizontal-grid">
        <div class="air-card now"><span class="air-label">Now</span><strong><?= htmlspecialchars($nowDJ) ?></strong></div>
        <div class="air-card next"><span class="air-label">Next</span><strong><?= htmlspecialchars($nextDJ) ?></strong></div>
        <div class="air-card later"><span class="air-label">Coming Up</span><strong><?= htmlspecialchars($comingDJ) ?></strong></div>
      </div>
    </article>

    <article class="ah-panel now-playing-panel">
      <div class="section-heading-row">
        <div>
          <h2 class="text-warning">♫ What’s Playing Now</h2>
          <p class="text-muted">Live track metadata from the stream</p>
        </div>
      </div>
      <div class="track-banner"><span class="track-prefix">Track</span> <span id="track-text">Loading…</span></div>
    </article>
  </section>

  <section class="home-grid-panels">
    <article class="ah-panel">
      <div class="section-heading-row">
        <div>
          <h2 class="text-warning">Featured on the Mountain</h2>
          <p class="text-muted">Pinned content from your admin side</p>
        </div>
      </div>
      <div class="feature-grid">
        <article class="feature-card">
          <h3>Featured News</h3>
          <p><strong><?= htmlspecialchars($featuredNews['title']) ?></strong></p>
          <p><?= htmlspecialchars(mb_strimwidth($featuredNews['body'], 0, 280, '…')) ?></p>
          <p class="feature-link-row"><a href="/news.php">Read more →</a></p>
        </article>
        <article class="feature-card">
          <h3>Featured Event</h3>
          <?php if ($featuredEvent): ?>
            <p><strong><?= htmlspecialchars((string)$promo['title']) ?></strong></p>
            <p><?= htmlspecialchars(mb_strimwidth((string)($promo['description'] ?? ''), 0, 220, '…')) ?></p>
          <?php else: ?>
            <p>No featured event is pinned right now.</p>
          <?php endif; ?>
          <p class="feature-link-row"><a href="/events.php">View events →</a></p>
        </article>
      </div>
    </article>

    <article class="ah-panel">
      <div class="section-heading-row">
        <div>
          <h2 class="text-warning">Leave a Comment</h2>
          <p class="text-muted">Say hello to the station</p>
        </div>
      </div>
      <form method="post" action="comments/submit_comment.php" class="comment-form-home">
        <input type="hidden" name="return_to" value="<?= htmlspecialchars($_SERVER['REQUEST_URI'] ?? '/index.php') ?>">
        <div class="comment-form-row">
          <label class="sr-only" for="comment-name">Your name</label>
          <input id="comment-name" type="text" name="name" placeholder="Your name" required>
          <label class="sr-only" for="comment-message">Your message</label>
          <textarea id="comment-message" name="message" placeholder="Your message" required></textarea>
          <button type="submit">Send</button>
        </div>
      </form>
    </article>
  </section>

  <section class="ah-panel recent-comments-panel">
    <div class="section-heading-row">
      <div>
        <h2 class="text-warning">Recent Comments</h2>
        <p class="text-muted">Latest approved messages from listeners</p>
      </div>
    </div>
    <div class="comments-list comments-list-grid">
      <?php if ($approvedComments): foreach ($approvedComments as $comment): ?>
        <div class="comment-item">
          <strong><?= htmlspecialchars($comment['name'] ?? 'Listener') ?></strong><br>
          <?= nl2br(htmlspecialchars($comment['message'] ?? '')) ?>
        </div>
      <?php endforeach; else: ?>
        <div class="comment-item">No approved comments are live yet.</div>
      <?php endif; ?>
    </div>
  </section>
</main>
<?php include('footer.php'); ?>
<script>
function openPlayer() {
  window.open('http://cr3.broadcasturself.com:6969/stream','streamPlayer','width=420,height=140,resizable=no,scrollbars=no');
}
async function updateTrack() {
  const target = document.getElementById('track-text');
  if (!target) return;
  try {
    const res = await fetch('/api/nowplaying.php', {cache: 'no-store'});
    const data = await res.json();
    target.textContent = (data && data.title ? data.title : 'Unable to fetch stream info.');
  } catch (e) {
    target.textContent = 'Unable to fetch stream info.';
  }
}
document.querySelectorAll('[data-placeholder="1"]').forEach(a => a.addEventListener('click', e => e.preventDefault()));
updateTrack();
setInterval(updateTrack, 30000);
</script>
