<?php
$pageTitle = 'Almost Heaven Radio';
$metaDescription = 'Live radio, requests, featured news and community from Almost Heaven Radio.';
include __DIR__ . '/header.php';
include __DIR__ . '/menu.php';
require_once __DIR__ . '/includes/schedule_lib.php';
require_once __DIR__ . '/includes/stream_lib.php';
$daysOrder = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];
$schedule = smurf_load_schedule_hourmap(__DIR__ . '/data/schedule.json', __DIR__ . '/data/schedule.txt', $daysOrder);
$nn = smurf_schedule_now_next($schedule, 'America/New_York');
$nowDJ = $nn['now'] ?: 'DJ Eagle';
$nextDJ = $nn['next'] ?: 'DJ Eagle';
$comingDJ = $nn['after'] ?: 'DJ Eagle';
$comments = file_exists(__DIR__ . '/data/comments.json') ? json_decode((string)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, 4);
$promo = file_exists(__DIR__ . '/data/promo.json') ? json_decode((string)file_get_contents(__DIR__ . '/data/promo.json'), true) : [];
if (!is_array($promo)) $promo = [];
$featuredEvent = !empty($promo['enabled']) && !empty($promo['title']);
$featuredNews = ['title' => 'Latest station news', 'body' => 'Fresh station updates will appear here when news is posted.'];
$newsRawFile = __DIR__ . '/data/news.txt';
if (file_exists($newsRawFile)) {
  $newsRaw = trim((string)file_get_contents($newsRawFile));
  if ($newsRaw !== '') {
    $chunks = preg_split('/
\s*---\s*
/', $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;
    }
  }
}
$directoryLinks = [
  ['label' => 'MyTuner', 'url' => '#', 'abbr' => 'MT'],
  ['label' => 'Online Radio Box', 'url' => '#', 'abbr' => 'ORB'],
  ['label' => 'Radio Spinner', 'url' => '#', 'abbr' => 'RS'],
  ['label' => 'Discord', 'url' => '#', 'abbr' => 'D'],
];
?>
<main class="main-container home-main">
  <section class="content-card hero-grid">
    <div class="hero-copy">
      <span class="eyebrow">Broadcasting from the heart of the hills</span>
      <h2>Professional radio layout. Heaven branding.</h2>
      <p class="hero-copy-text">Live radio, requests, featured updates, comments, and directory links — rebuilt into one clean station front page.</p>
      <div class="hero-actions">
        <button class="play-button" onclick="openPlayer()"><i class="fa-solid fa-play"></i> Play Now</button>
        <a class="hero-secondary-btn" href="/schedule.php">View Schedule</a>
        <a class="hero-secondary-btn" href="/requests.php">Make a Request</a>
      </div>
      <p class="live-status">Streaming live from the hills</p>
      <div class="listen-platforms-wrap" style="margin-top:24px;">
        <div class="section-heading-row" style="margin-bottom:12px;"><div><h2 class="text-warning" style="font-size:1.35rem;margin-bottom:4px;">Listen on…</h2><p class="text-muted">Directory and community shortcuts</p></div></div>
        <div class="listen-platforms">
          <?php foreach ($directoryLinks as $link): ?>
          <a class="platform-btn" href="<?= htmlspecialchars($link['url']) ?>" 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</span>
          </a>
          <?php endforeach; ?>
        </div>
      </div>
    </div>
    <div class="home-side-visual">
      <div class="visual-poster"><img src="/assets/logo.png" alt="Almost Heaven Radio"></div>
    </div>
  </section>

  <div class="smurf-divider"></div>

  <section class="home-feature-strip">
    <article class="content-card onair-horizontal">
      <div class="section-heading-row"><div><h2 class="text-warning">On Air Right Now</h2><p class="text-muted">Current schedule snapshot</p></div></div>
      <div class="onair-horizontal-grid">
        <div class="air-card"><span class="air-label">Now</span><strong><?= htmlspecialchars($nowDJ) ?></strong></div>
        <div class="air-card"><span class="air-label">Next</span><strong><?= htmlspecialchars($nextDJ) ?></strong></div>
        <div class="air-card"><span class="air-label">Coming Up</span><strong><?= htmlspecialchars($comingDJ) ?></strong></div>
      </div>
    </article>
    <article class="content-card now-playing-panel">
      <div class="section-heading-row"><div><h2 class="text-warning"><i class="fa-solid fa-music"></i> 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>
      <div class="button-row" style="margin-top:18px;"><a class="hero-secondary-btn" href="/top50.php">Top 50</a><a class="hero-secondary-btn" href="/news.php">Station News</a></div>
    </article>
  </section>

  <div class="smurf-divider"></div>

  <section class="home-grid-panels">
    <article class="content-card">
      <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, 250, '…')) ?></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>
        <article class="feature-card">
          <h3>Listener Hub</h3>
          <p>Requests, comments, and community links are all connected from one clean station shell.</p>
          <p class="feature-link-row"><a href="/contact.php">Contact the station →</a></p>
        </article>
      </div>
    </article>
    <article class="content-card">
      <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">
          <input id="comment-name" type="text" name="name" placeholder="Your name" required>
          <textarea id="comment-message" name="message" placeholder="Your message" required></textarea>
          <button type="submit" class="play-button">Send</button>
        </div>
      </form>
      <div class="comments-list comments-list-grid" style="margin-top:18px;display:grid;gap:12px;">
      <?php if ($approvedComments): foreach ($approvedComments as $comment): ?>
        <div class="comment-item"><strong><?= htmlspecialchars($comment['name'] ?? 'Listener') ?></strong><?= nl2br(htmlspecialchars($comment['message'] ?? '')) ?></div>
      <?php endforeach; else: ?>
        <div class="comment-item">No approved comments are live yet.</div>
      <?php endif; ?>
      </div>
    </article>
  </section>
</main>
<?php include __DIR__ . '/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>
