<?php include 'includes/header.php';
function ht_asset_url(string $path, string $fallbackDir = ''): string {
  $path = trim($path);
  if ($path === '') return '';
  if (preg_match('#^(https?:)?//#i', $path) || str_starts_with($path, 'data:')) return $path;
  $path = str_replace('\\', '/', $path);
  $path = ltrim($path, '/');
  if ($fallbackDir !== '' && strpos($path, '/') === false) $path = trim($fallbackDir, '/') . '/' . $path;
  return '/' . $path;
}
$friends=[];
$dataFile=__DIR__.'/data/friends.json';
$legacyFile=__DIR__.'/friends-data.json';
if (file_exists($dataFile)) { $friends=json_decode((string)file_get_contents($dataFile), true); }
if (!is_array($friends) || !$friends) { if (file_exists($legacyFile)) { $friends=json_decode((string)file_get_contents($legacyFile), true); } }
if (!is_array($friends)) $friends=[];
?>
<div class="container ugfx-page-shell">
  <section class="ugfx-page-hero-card mb-4">
    <div class="kicker">Extended broadcast family</div>
    <h1 class="section-title">Our Radio Friends</h1>
    <p class="section-subtitle text-start ms-0">Explore other stations and projects connected to the broader community around Underground FX.</p>
  </section>
  <div class="row g-4">
    <?php foreach ($friends as $station): $link=$station['url'] ?? ($station['link'] ?? '#'); $img=ht_asset_url((string)($station['image'] ?? ''),'img/friends'); ?>
      <div class="col-md-6 col-xl-4"><div class="ugfx-card h-100 ugfx-photo-card contain">
        <?php if ($img): ?><img src="<?= htmlspecialchars($img, ENT_QUOTES, 'UTF-8') ?>" alt="<?= htmlspecialchars((string)($station['name'] ?? ''), ENT_QUOTES, 'UTF-8') ?>"><?php endif; ?>
        <h4 class="mt-3"><?= htmlspecialchars((string)($station['name'] ?? ''), ENT_QUOTES, 'UTF-8') ?></h4>
        <?php if (!empty($station['description'])): ?><p><?= nl2br(htmlspecialchars((string)$station['description'], ENT_QUOTES, 'UTF-8')) ?></p><?php else: ?><p>Visit one of our broadcast friends and check out what they are playing.</p><?php endif; ?>
        <?php if ($link && $link !== '#'): ?><div class="mt-3"><a href="<?= htmlspecialchars((string)$link, ENT_QUOTES, 'UTF-8') ?>" class="btn btn-outline-light" target="_blank" rel="noopener">Visit Station</a></div><?php endif; ?>
      </div></div>
    <?php endforeach; ?>
    <?php if (empty($friends)): ?><div class="col-12"><div class="ugfx-empty-state">No friends added yet.</div></div><?php endif; ?>
  </div>
</div>
<?php include 'includes/footer.php'; ?>