<?php
$PAGE_TITLE = 'Home';
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/includes/site-data.php';

$news_posts  = get_news_posts(4);
$on_air_now  = get_on_air_now();
$top10       = get_top10();
$contests    = get_active_contests(1); // just teaser
?>

<!-- ══ HERO ══════════════════════════════════════════════════════════════ -->
<section class="home-hero" style="margin:0 -20px">
  <div class="hero-inner">

    <!-- Left: Branding + Actions -->
    <div class="hero-copy">

      <!-- On Air Now — compact card in hero -->
      <?php if ($on_air_now):
        $oa_name   = $on_air_now['air_name'] ?: $on_air_now['name'] ?: 'On Air';
        $oa_show   = $on_air_now['show_name'] ?? '';
        $oa_photo  = $on_air_now['photo_url'] ?? '';
        $oa_days   = json_decode($on_air_now['days_of_week']??'', true) ?: [(int)($on_air_now['day_of_week']??-1)];
        $oa_dnames = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
        $oa_dlist  = implode('–', array_map(fn($d)=>$oa_dnames[$d]??'', array_filter($oa_days,fn($d)=>$d>=0&&$d<=6)));
        $oa_start  = !empty($on_air_now['start_time']) ? date('g:ia', strtotime($on_air_now['start_time'])) : '';
        $oa_end    = !empty($on_air_now['end_time'])   ? date('g:ia', strtotime($on_air_now['end_time']))   : '';
      ?>
      <div style="display:flex;align-items:center;gap:12px;margin-bottom:20px;background:rgba(6,22,28,.8);border:1px solid rgba(198,50,144,.35);border-radius:10px;padding:10px 14px;max-width:340px">
        <?php if ($oa_photo): ?>
        <div style="width:50px;height:50px;border-radius:8px;overflow:hidden;flex-shrink:0;border:2px solid var(--pink)">
          <img src="<?= h($oa_photo) ?>" style="width:100%;height:100%;object-fit:cover" alt="<?= h($oa_name) ?>">
        </div>
        <?php else: ?>
        <div style="width:50px;height:50px;border-radius:8px;background:var(--bg3);border:2px solid var(--pink);display:flex;align-items:center;justify-content:center;font-size:24px;flex-shrink:0">🎙️</div>
        <?php endif; ?>
        <div style="flex:1;min-width:0">
          <div style="display:flex;align-items:center;gap:6px;margin-bottom:3px">
            <span class="live-dot"></span>
            <span style="font-size:10px;color:var(--text-dim);letter-spacing:1px;text-transform:uppercase;font-family:var(--font-head)">On Air Now</span>
          </div>
          <div style="font-weight:700;font-size:14px;color:var(--cream);overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><?= h($oa_name) ?></div>
          <?php if ($oa_show): ?><div style="font-size:11px;color:var(--gold);overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><?= h($oa_show) ?></div><?php endif; ?>
          <?php if ($oa_dlist && $oa_start): ?>
          <div style="font-size:10px;color:var(--text-dim);margin-top:2px"><?= h($oa_dlist) ?> · <?= h($oa_start) ?><?= $oa_end ? " – {$oa_end}" : '' ?></div>
          <?php endif; ?>
        </div>
        <a href="<?= $ROOT_PATH ?>onair.php" style="font-size:10px;color:var(--teal);flex-shrink:0;white-space:nowrap">All Staff →</a>
      </div>
      <?php endif; ?>

      <!-- Frequency — large (hidden for HD/internet stations) -->
      <?php $is_hd = site_setting('is_hd_subchannel','0') === '1'; ?>
      <?php if (!$is_hd): ?><div class="hero-freq"><?= h(STATION_FREQ) ?></div><?php endif; ?>
      <div class="hero-name"><?= h($is_hd ? STATION_FULLNAME : STATION_NAME) ?></div>
      <p class="hero-tagline"><?= h(STATION_TAGLINE) ?></p>
      <?php if (!$is_hd): ?><p style="font-size:12px;color:var(--text-dim);margin-top:6px"><?= h(STATION_MARKET) ?></p><?php endif; ?>

      <div class="hero-actions">
        <button class="rfm-btn" style="font-size:13px;padding:12px 24px" id="heroPlayBtn">▶ Listen Live</button>
        <a href="<?= $ROOT_PATH ?>request.php" class="rfm-btn outline" style="font-size:13px;padding:12px 24px">🎵 Request a Song</a>
      </div>
      <p style="margin-top:12px;font-size:12px;color:var(--text-dim)">
        Request line: <a href="tel:<?= h(STATION_PHONE) ?>" style="color:var(--teal)"><?= h(STATION_PHONE) ?></a>
      </p>
    </div>

    <!-- Right: Now Playing card -->
    <div class="hero-np">
      <div class="hero-np-card">
        <div class="hnp-label"><span class="live-dot"></span> NOW PLAYING</div>
        <div class="hnp-art" id="cardArt">🎵</div>
        <p class="hnp-artist" id="cardArtist">Loading…</p>
        <p class="hnp-title"  id="cardTitle"></p>
        <p class="hnp-album"  id="cardAlbum"></p>
        <div class="hnp-bar-wrap"><div class="hnp-bar" id="cardBar" style="width:0%"></div></div>
        <div class="hnp-time-row"><span id="cardElapsed">0:00</span><span id="cardTotal">0:00</span></div>
        <p class="hnp-listeners" id="cardListens"></p>
        <div style="display:flex;gap:8px;margin-top:8px;align-items:center"><a href="<?= $ROOT_PATH ?>request.php" class="hnp-request-link" style="flex:1;font-size:12px">🎵 Request a Song</a><button id="shareNowPlaying" type="button" style="background:none;border:1px solid rgba(17,162,162,.3);color:var(--teal);border-radius:6px;padding:6px 10px;cursor:pointer;font-size:12px;white-space:nowrap;display:none" title="Share what's playing">📤</button></div>
      </div>
    </div>

  </div>
</section>

<!-- ══ CTA STRIP ════════════════════════════════════════════════════════ -->
<div class="cta-strip">
  <a href="javascript:void(0)" onclick="document.getElementById('heroPlayBtn').click()" class="cta-card">
    <span class="cta-icon">📻</span>
    <div class="cta-text"><span class="cta-label">Listen Online</span><span class="cta-sub">Stream 24/7, anywhere</span></div>
  </a>
  <a href="<?= $ROOT_PATH ?>request.php" class="cta-card">
    <span class="cta-icon">🎵</span>
    <div class="cta-text"><span class="cta-label">Request a Song</span><span class="cta-sub">Or call <?= h(STATION_PHONE) ?></span></div>
  </a>
  <a href="<?= $ROOT_PATH ?>members.php" class="cta-card">
    <span class="cta-icon">⭐</span>
    <div class="cta-text"><span class="cta-label">Join Y2Krew</span><span class="cta-sub">Free listener club</span></div>
  </a>
  <?php if ($contests): ?>
  <a href="<?= $ROOT_PATH ?>contests.php" class="cta-card">
    <span class="cta-icon">🏆</span>
    <div class="cta-text"><span class="cta-label">Contest Active!</span><span class="cta-sub"><?= h($contests[0]['prize'] ?? 'Win prizes') ?></span></div>
  </a>
  <?php endif; ?>
</div>

<!-- ══ DEDICATIONS TICKER ═══════════════════════════════════════════════ -->
<div id="dedicationTicker" style="display:none;background:rgba(198,50,144,.08);border:1px solid rgba(198,50,144,.25);border-radius:8px;padding:10px 16px;margin-bottom:16px;overflow:hidden">
  <div style="display:flex;align-items:center;gap:10px">
    <span style="font-size:12px;font-weight:700;color:var(--pink);letter-spacing:1px;text-transform:uppercase;white-space:nowrap">💌 Dedication</span>
    <div id="dedicationText" style="font-size:13px;color:var(--cream-dim);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:1"></div>
    <a href="<?= $ROOT_PATH ?>request.php" style="font-size:11px;color:var(--teal);white-space:nowrap;flex-shrink:0">Send one →</a>
  </div>
</div>

<!-- ══ RECENTLY PLAYED + TOP 10 ════════════════════════════════════════════ -->
<div style="display:grid;grid-template-columns:1fr 1fr;gap:24px;margin-bottom:32px">
  <div>
    <h3 class="section-head">Recently Played</h3>
    <ul class="recent-list" id="recentList">
      <li class="loading-state"><div class="spinner"></div></li>
    </ul>
  </div>
  <div>
    <h3 class="section-head">This Week's Top 10 <span style="font-size:10px;font-weight:400;color:var(--text-dim)">Most Requested</span></h3>
    <div class="card" style="padding:0">
      <?php if ($top10): foreach ($top10 as $i => $t): $pos=$i+1;
        $col=$pos===1?'var(--gold)':($pos===2?'#aaa':($pos===3?'#cd7f32':'var(--text-dim))'));
      ?>
      <div style="display:flex;align-items:center;gap:12px;padding:9px 16px;border-bottom:1px solid var(--border)">
        <span style="font-family:var(--font-vt);font-size:24px;color:<?= $col ?>;min-width:30px;text-align:right"><?= $pos ?></span>
        <div style="flex:1;min-width:0">
          <div style="font-weight:700;font-size:13px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><?= h($t['artist']) ?></div>
          <div style="font-size:12px;color:var(--text-dim);overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><?= h($t['title']) ?></div>
        </div>
        <?php if (!empty($t['cnt'])): ?><span style="font-size:11px;color:var(--teal);flex-shrink:0"><?= (int)$t['cnt'] ?>×</span><?php endif; ?>
        <?php if ($pos<=3): ?><span><?= $pos===1?'🥇':($pos===2?'🥈':'🥉') ?></span><?php endif; ?>
      </div>
      <?php endforeach; else: ?>
      <div style="padding:24px;text-align:center;color:var(--text-dim);font-size:13px">No requests yet — <a href="<?= $ROOT_PATH ?>request.php">be the first!</a></div>
      <?php endif; ?>
    </div>
  </div>
</div>

<!-- ══ NEWSLETTER ════════════════════════════════════════════════════════ -->
<div class="newsletter-banner" style="margin-bottom:32px">
  <div class="newsletter-copy">
    <h3>Stay Connected</h3>
    <p>Contest alerts, station news, and throwback highlights — straight to your inbox.</p>
  </div>
  <div class="newsletter-form">
    <input type="email" id="nlEmail" placeholder="your@email.com" autocomplete="email">
    <button class="rfm-btn" onclick="submitNewsletter()">Subscribe</button>
  </div>
</div>

<!-- ══ NEWS ══════════════════════════════════════════════════════════════ -->
<?php if ($news_posts): ?>
<h3 class="section-head">Station News</h3>
<div class="card-grid" style="margin-bottom:40px">
  <?php foreach ($news_posts as $n): ?>
  <div class="news-card">
    <div class="news-date"><?= h(isset($n['published_at']) ? date('F j, Y', strtotime($n['published_at'])) : '') ?></div>
    <div class="news-title"><?= h($n['title']) ?></div>
    <div class="news-body"><?= h(mb_substr($n['body']??'',0,200)) ?><?= mb_strlen($n['body']??'')>200?'…':'' ?></div>
  </div>
  <?php endforeach; ?>
</div>
<?php endif; ?>

<div class="ad-slot leaderboard"><span>Advertisement</span></div>

<script>
// Dedication ticker
(function loadDedications(){
  fetch('<?= $ROOT_PATH ?>api/request.php?dedications=1&limit=10')
    .then(function(r){return r.json();})
    .then(function(d){
      if(!d.dedications||!d.dedications.length)return;
      var ticker=document.getElementById('dedicationTicker');
      var text=document.getElementById('dedicationText');
      if(!ticker||!text)return;
      ticker.style.display='';
      var items=d.dedications; var idx=0;
      function show(){
        var r=items[idx%items.length]; idx++;
        var msg='"'+r.title+'" by '+r.artist;
        if(r.dedicated_to)msg+=' — dedicated to '+r.dedicated_to;
        if(r.dedication)msg+=' · "'+r.dedication+'"';
        text.style.opacity=0;
        setTimeout(function(){text.textContent=msg;text.style.opacity=1;},300);
      }
      text.style.transition='opacity .3s';
      show(); setInterval(show,6000);
    }).catch(function(){});
})();

function submitNewsletter(){
  var email=document.getElementById('nlEmail')?.value.trim();
  if(!email||!email.includes('@')){window.rfmToast?.('Enter a valid email.','error');return;}
  window.rfmToast?.('Thanks for subscribing! 🎵','success');
  document.getElementById('nlEmail').value='';
}
</script>

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