<?php

require_once __DIR__ . '/config.php';

function escapeHtml($value)
{
    return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function safeExternalUrl($value)
{
    $value = trim((string) $value);
    if ($value === '') {
        return '';
    }

    if (strpos($value, '//') === 0) {
        return $value;
    }

    $scheme = parse_url($value, PHP_URL_SCHEME);
    return in_array(strtolower((string) $scheme), ['http', 'https'], true) ? $value : '';
}

$siteName = defined('SITE_NAME') ? SITE_NAME : 'Easy Radio';
// Default to the current outage notice; set RADIO_MAINTENANCE_MODE to false in config.php after recovery.
$maintenanceMode = defined('RADIO_MAINTENANCE_MODE') ? (bool) RADIO_MAINTENANCE_MODE : true;
$siteUrl = defined('SITE_URL') ? safeExternalUrl(SITE_URL) : '/';
$siteUrl = $siteUrl !== '' ? $siteUrl : '/';
$streams = defined('STREAMS') && is_array(STREAMS) ? STREAMS : [];
$streamOptions = [];

foreach ($streams as $name => $stream) {
    if (!is_array($stream) || empty($stream['url'])) {
        continue;
    }

    $format = !empty($stream['format']) ? $stream['format'] : preg_replace('/\s+Stream.*$/i', '', (string) $name);
    $bitrate = !empty($stream['bitrate']) ? $stream['bitrate'] : '';
    if ($bitrate === '' && preg_match('/\(([^)]+)\)/', (string) $name, $matches)) {
        $bitrate = $matches[1];
    }

    $streamOptions[] = [
        'name' => (string) $name,
        'url' => (string) $stream['url'],
        'm3u' => !empty($stream['m3u']) ? 'm3u/' . ltrim((string) $stream['m3u'], '/') : '',
        'format' => (string) $format,
        'bitrate' => (string) $bitrate,
        'description' => !empty($stream['description']) ? (string) $stream['description'] : 'High quality radio stream',
        'mime' => !empty($stream['mime']) ? (string) $stream['mime'] : 'audio/mpeg',
    ];
}

?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="<?= escapeHtml($siteName) ?> - your relaxing music mix.">
    <meta name="theme-color" content="#0c1220">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-title" content="<?= escapeHtml($siteName) ?>">
    <title><?= escapeHtml($siteName) ?></title>
    <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
    <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
    <link rel="manifest" href="/site.webmanifest?ver=<?= escapeHtml(filemtime(__DIR__ . '/site.webmanifest')) ?>">
    <link href="css/main.css?ver=<?= escapeHtml(filemtime(__DIR__ . '/css/main.css')) ?>" rel="stylesheet">
</head>
<body data-site-name="<?= escapeHtml($siteName) ?>" data-service-worker="/service-worker.js?ver=<?= escapeHtml(filemtime(__DIR__ . '/service-worker.js')) ?>">
<a class="skip-link" href="#main-content">Skip to content</a>

<header class="site-header">
    <div class="shell header-inner">
        <a class="brand" href="/" aria-label="<?= escapeHtml($siteName) ?> home">
            <img src="/static/radio-l.png" alt="<?= escapeHtml($siteName) ?>">
        </a>
        <nav class="site-nav" aria-label="Main navigation">
            <a class="active" href="#home">Home</a>
            <a href="#">Contact</a>
        </nav>
        <button class="install-button" id="js-install-app" type="button" hidden>
            <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3v12m0 0 4-4m-4 4-4-4M5 17v3h14v-3"/></svg>
            <span>Install App</span>
        </button>
        <span class="header-signal" aria-hidden="true">
            <svg viewBox="0 0 24 24"><path d="M4 9v6M8 6v12M12 3v18M16 7v10M20 9v6"/></svg>
        </span>
    </div>
</header>

<main id="main-content">
    <section class="hero shell" id="home" aria-labelledby="hero-title">
        <div class="hero-mark" aria-hidden="true">
            <span></span><span></span><span></span><span></span><span></span>
        </div>
        <p class="eyebrow"><?= $maintenanceMode ? 'Back soon. Always easy.' : 'Always on. Always easy.' ?></p>
        <h1 id="hero-title">Your Relaxing Music Mix</h1>
        <p class="hero-copy"><?= $maintenanceMode ? 'Your relaxing music mix will be back soon.' : 'Sit back, slow down and enjoy the perfect soundtrack for your day.' ?></p>
    </section>

    <div class="shell content-stack">
        <?php if ($maintenanceMode): ?>
        <section class="offline-notice" aria-labelledby="offline-heading">
            <img class="offline-logo" src="static/radio-l.png" alt="<?= escapeHtml($siteName) ?>">
            <div>
                <p class="offline-kicker"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3 2 21h20L12 3Z"/><path d="M12 9v5m0 3v1"/></svg>Service update</p>
                <h2 id="offline-heading">Temporarily offline</h2>
                <p>Easy Radio will be offline until <time datetime="2026-09-15">15 September 2026</time> due to technical difficulties.</p>
                <p>We’re sorry for the interruption and thank you for your patience.</p>
            </div>
        </section>
        <?php else: ?>
        <section class="player-card" aria-labelledby="now-playing-label">
            <div class="artwork-wrap fallback-artwork-wrap">
                <img class="fallback-artwork" id="js-artwork" src="static/radio-l.png" alt="Current track artwork">
                <span class="artwork-glow" aria-hidden="true"></span>
            </div>

            <div class="player-content">
                <div class="player-heading">
                    <div>
                        <p class="section-kicker" id="now-playing-label"><span></span>Now playing</p>
                        <p class="artist" id="js-artist">Easy Radio</p>
                        <div class="track-title-row">
                            <h2 id="js-track">Loading the current track...</h2>
                            <span class="release-year" id="js-release-year" hidden></span>
                        </div>
                    </div>
                    <div class="live-status">
                        <span class="live-badge" id="js-live-badge"><i></i>Live</span>
                    </div>
                </div>

                <div class="meter-wrap" id="js-meter-wrap">
                    <div class="wave-meter" id="js-wave-meter" role="progressbar" aria-label="Track elapsed" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">
                        <span class="wave-fill" id="js-wave-fill"></span>
                        <span class="jingle-bars" aria-hidden="true">
                            <?php for ($bar = 0; $bar < 24; $bar++): ?><i></i><?php endfor; ?>
                        </span>
                    </div>
                    <div class="time-row" aria-hidden="true">
                        <span id="js-elapsed">0:00</span>
                        <span id="js-duration">--:--</span>
                    </div>
                </div>

                <div class="transport">
                    <button class="play-button" id="js-play" type="button" aria-label="Play live radio" aria-pressed="false"<?= empty($streamOptions) ? ' disabled' : '' ?>>
                        <svg class="icon-play" viewBox="0 0 24 24" aria-hidden="true"><path d="M8 5v14l11-7z"/></svg>
                        <svg class="icon-pause" viewBox="0 0 24 24" aria-hidden="true"><path d="M7 5h4v14H7zM14 5h4v14h-4z"/></svg>
                    </button>
                    <div class="volume-control">
                        <button class="icon-button" id="js-mute" type="button" aria-label="Mute radio" aria-pressed="false">
                            <svg class="volume-on" viewBox="0 0 24 24" aria-hidden="true"><path d="M4 9v6h4l5 4V5L8 9H4zm12.5 3a4.5 4.5 0 0 0-2-4v8a4.5 4.5 0 0 0 2-4zm-2.5-8.5v2.1a7 7 0 0 1 0 12.8v2.1a9 9 0 0 0 0-17z"/></svg>
                            <svg class="volume-off" viewBox="0 0 24 24" aria-hidden="true"><path d="M4 9v6h4l5 4V5L8 9H4zm12.6 3 2.7-2.7-1.4-1.4-2.7 2.7-2.7-2.7-1.4 1.4 2.7 2.7-2.7 2.7 1.4 1.4 2.7-2.7 2.7 2.7 1.4-1.4z"/></svg>
                        </button>
                        <label class="sr-only" for="js-volume">Volume</label>
                        <input id="js-volume" type="range" min="0" max="100" value="75" aria-valuetext="75 percent">
                        <output id="js-volume-output" for="js-volume">75%</output>
                    </div>
                </div>

                <div class="player-footer">
                    <p><span>Selected stream</span><strong id="js-selected-stream"><?= !empty($streamOptions) ? escapeHtml($streamOptions[0]['name']) : 'No stream configured' ?></strong></p>
                    <a class="external-link" id="js-external-player" href="<?= !empty($streamOptions) ? escapeHtml($streamOptions[0]['m3u']) : '#' ?>" target="_blank" rel="noopener noreferrer"<?= empty($streamOptions) || $streamOptions[0]['m3u'] === '' ? ' hidden' : '' ?>>
                        <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M14 4h6v6M20 4l-9 9M18 13v6H5V6h6"/></svg>
                        Open in external player
                    </a>
                </div>
            </div>

            <audio class="native-audio" id="js-audio" controls preload="none"<?= !empty($streamOptions) ? ' src="' . escapeHtml($streamOptions[0]['url']) . '"' : '' ?>>Your browser does not support audio playback.</audio>
        </section>
        <?php endif; ?>

        <div class="dashboard-grid<?= $maintenanceMode ? ' dashboard-grid-offline' : '' ?>">
            <section class="panel history-panel" aria-labelledby="history-heading">
                <div class="panel-heading">
                    <div>
                        <span class="panel-icon" aria-hidden="true">
                            <svg viewBox="0 0 24 24"><path d="M4 12a8 8 0 1 0 2.3-5.7L4 8.6M4 4v4.6h4.6M12 7v5l3 2"/></svg>
                        </span>
                        <h2 id="history-heading">Recently Played</h2>
                    </div>
                    <button class="small-button" id="js-history-toggle" type="button" aria-haspopup="dialog">View full history</button>
                </div>
                <div class="history-list" id="js-history-list" aria-live="polite" aria-busy="true">
                    <p class="panel-status">Loading recent tracks...</p>
                </div>
            </section>

            <?php if (!$maintenanceMode): ?>
            <section class="panel quality-panel" aria-labelledby="quality-heading">
                <div class="panel-heading quality-title">
                    <div>
                        <span class="panel-icon" aria-hidden="true">
                            <svg viewBox="0 0 24 24"><path d="M4 14v-4a8 8 0 0 1 16 0v4M4 13H2v6h5v-6H4zm16 0h-3v6h5v-6h-2z"/></svg>
                        </span>
                        <span><h2 id="quality-heading">Listen Your Way</h2><p>Choose the stream quality that suits you best.</p></span>
                    </div>
                </div>
                <div class="quality-list" role="radiogroup" aria-labelledby="quality-heading">
                    <?php foreach ($streamOptions as $index => $stream): ?>
                        <button class="quality-option<?= $index === 0 ? ' selected' : '' ?>" type="button" role="radio" aria-checked="<?= $index === 0 ? 'true' : 'false' ?>" tabindex="<?= $index === 0 ? '0' : '-1' ?>"
                                data-index="<?= $index ?>" data-url="<?= escapeHtml($stream['url']) ?>" data-m3u="<?= escapeHtml($stream['m3u']) ?>" data-mime="<?= escapeHtml($stream['mime']) ?>" data-name="<?= escapeHtml($stream['name']) ?>">
                            <span class="quality-signal" aria-hidden="true"><i></i><i></i><i></i><i></i></span>
                            <span class="quality-copy"><strong><?= escapeHtml(trim($stream['format'] . ' ' . $stream['bitrate'])) ?></strong><small><?= escapeHtml($stream['description']) ?></small></span>
                            <span class="radio-mark" aria-hidden="true"></span>
                        </button>
                    <?php endforeach; ?>
                    <?php if (empty($streamOptions)): ?>
                        <p class="panel-status">No streams are currently configured.</p>
                    <?php endif; ?>
                </div>
            </section>
            <?php endif; ?>
        </div>
    </div>

</main>

<dialog class="history-dialog" id="js-history-dialog" aria-labelledby="history-dialog-heading">
    <div class="history-dialog-header">
        <div>
            <p class="section-kicker"><span></span>Recently played</p>
            <h2 id="history-dialog-heading">Full History</h2>
            <p>Up to the 100 most recent tracks.</p>
        </div>
        <button class="history-dialog-close" id="js-history-close" type="button" aria-label="Close full history">
            <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M6 6l12 12M18 6 6 18"/></svg>
        </button>
    </div>
    <div class="history-list history-dialog-list" id="js-full-history-list" aria-live="polite" aria-busy="true">
        <p class="panel-status">Loading full history...</p>
    </div>
</dialog>

<footer class="site-footer">
    <div class="shell footer-inner">
        <a class="footer-brand" href="<?= escapeHtml($siteUrl) ?>"><img src="/static/radio-l.png" alt=""><span><?= escapeHtml($siteName) ?><small>Your Relaxing Music Mix</small></span></a>
        <div class="footer-copy">
            <p>&copy; <?= date('Y') ?> <?= escapeHtml($siteName) ?>. All rights reserved.</p>
            <small>dev by .donchev</small>
        </div>
    </div>
</footer>

<script src="js/main.js?ver=<?= escapeHtml(filemtime(__DIR__ . '/js/main.js')) ?>"></script>
</body>
</html>
