<?php
declare(strict_types=1);

require __DIR__ . '/_app/autoload.php';

use Nav\Config;
use Nav\I18n;

// === HTTP cache headers (CDN-safe: never cache HTML) ===
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');
header('CDN-Cache-Control: no-store');
header('Cloudflare-CDN-Cache-Control: no-store');
header('Surrogate-Control: no-store');
header('Vary: Accept-Encoding, Accept-Language, Cookie');
header('X-Content-Type-Options: nosniff');
header('Referrer-Policy: strict-origin-when-cross-origin');

$config = Config::load(data_path('config.json'));

// === language: admin sets default; no frontend switcher ===
$defaultLang = (string)Config::get($config, 'i18n.default', 'en');
$lang = $defaultLang;
$i18n = new I18n(data_path('i18n'), $lang, $defaultLang);

// === ETag ===
$version = (string)Config::get($config, 'version', 'v0');
$etag = '"' . md5($version . ':' . $lang) . '"';
header("ETag: $etag");
if (($_SERVER['HTTP_IF_NONE_MATCH'] ?? '') === $etag) {
    http_response_code(304);
    exit;
}

// === extract values ===
$site = Config::get($config, 'site', []);
$htmlLang   = (string)($site['lang_attr'] ?? 'en');
$title      = (string)($site['title'] ?? '');
$desc       = (string)($site['description'] ?? '');
$keywords   = (string)($site['keywords'] ?? '');
$favicon    = (string)($site['favicon'] ?? './img/icon-512px-3.png');
$logo       = (string)($site['logo'] ?? './img/p666.cc.png');
$cpPrefix   = (string)($site['copyright_prefix'] ?? '');
$cpStart    = (int)($site['copyright_start_year'] ?? date('Y'));

$theme = (string)Config::get($config, 'theme.active', 'classic');

$carousel = array_values(array_filter(
    (array)Config::get($config, 'carousel', []),
    fn($s) => !empty($s['enabled'])
));
usort($carousel, fn($a, $b) => ($a['order'] ?? 0) <=> ($b['order'] ?? 0));

$primaryLinks = array_values(array_filter(
    (array)Config::get($config, 'primary_links', []),
    fn($l) => !empty($l['enabled'])
));

$downloads = array_values(array_filter(
    (array)Config::get($config, 'download_links', []),
    fn($d) => !empty($d['enabled'])
));

$socials = array_values(array_filter(
    (array)Config::get($config, 'social_links', []),
    fn($s) => !empty($s['enabled']) && !empty($s['url'])
));
usort($socials, fn($a, $b) => ($a['order'] ?? 0) <=> ($b['order'] ?? 0));

$pool = array_values((array)Config::get($config, 'redirect_pool', []));
$marqueeEnabled = (bool)Config::get($config, 'marquee.enabled', true);
$marqueeText = pick_lang(Config::get($config, 'marquee.text', ''), $lang, $defaultLang);
$popupEnabled = (bool)Config::get($config, 'popup.enabled', false);
$popupImg = (string)Config::get($config, 'popup.image', './index_files/VPN-AZ.jpg');

$year = (int)date('Y');

// === asset versioning: per-file mtime hash (cache-bust on change) ===
$assetV = function (string $rel) {
    $abs = public_path(ltrim(str_replace('./', '', $rel), '/'));
    return is_file($abs) ? substr((string)filemtime($abs), -8) : '0';
};

// === Performance hints: preload LCP banner + DNS prefetch redirect pool hosts ===
$firstBanner = null;
foreach ($carousel as $slide) {
    if (!empty($slide['enabled'])) { $firstBanner = $slide['image'] ?? null; break; }
}
$dnsPrefetchHosts = [];
foreach ($pool as $url) {
    $h = parse_url($url, PHP_URL_HOST);
    if ($h && !in_array($h, $dnsPrefetchHosts, true)) $dnsPrefetchHosts[] = $h;
}
?><!DOCTYPE html>
<html lang="<?= e($htmlLang) ?>" ng-app="website" data-theme="<?= e($theme) ?>" style="font-size: 100px;"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

     <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="mobile-web-app-status-bar-style" content="black">
    <meta name="format-detection" content="telephone=no">
    <link rel="icon" href="<?= e($favicon) ?>" type="image/x-icon">
     <title><?= e($title) ?></title>
    <meta name="Description" content="<?= e($desc) ?>">
    <meta name="keywords" content="<?= e($keywords) ?>">
    <?php if ($firstBanner): ?><link rel="preload" as="image" href="<?= e($firstBanner) ?>" fetchpriority="high"><?php endif; ?>
    <?php if ($logo): ?><link rel="preload" as="image" href="<?= e($logo) ?>"><?php endif; ?>
    <?php foreach ($dnsPrefetchHosts as $h): ?><link rel="dns-prefetch" href="//<?= e($h) ?>"><?php endforeach; ?>
    <link rel="stylesheet" href="./index_files/style.css?v=<?= $assetV('index_files/style.css') ?>">
    <link rel="stylesheet" href="./index_files/swiper.css?v=<?= $assetV('index_files/swiper.css') ?>">
    <link rel="stylesheet" href="./index_files/theme-overrides.css?v=<?= $assetV('index_files/theme-overrides.css') ?>">
    <link rel="stylesheet" href="./index_files/animations.css?v=<?= $assetV('index_files/animations.css') ?>">
       <script src="./index_files/rem.js?v=<?= $assetV('index_files/rem.js') ?>"></script>
    <!--设置字体大小-->
</head>

<body data-theme="<?= e($theme) ?>" data-lang="<?= e($lang) ?>">
    <div class="wraper">
<style>
.header {
  margin-top: 0.2em;
  margin-bottom: 0.2em;
}
</style>
        <!--logo-->
        <div class="header">
            <img class="logo" src="<?= e($logo) ?>">
        </div>

        <div class="swiper-container swiper-banner">
            <div class="swiper-wrapper">
<?php foreach ($carousel as $i => $slide):
    $loading = $i === 0 ? 'eager' : 'lazy';
    $fetch   = $i === 0 ? ' fetchpriority="high"' : '';
?>
                <div class="swiper-slide"<?php if (!empty($slide['link'])): ?> data-src="<?= e($slide['link']) ?>"<?php endif; ?>><img src="<?= e($slide['image']) ?>" loading="<?= $loading ?>" decoding="async"<?= $fetch ?>></div>
<?php endforeach; ?>
            </div>
<style>
.spacer {
  margin-top: 0.2em;
  margin-bottom: 0.2em;
}
</style>
<div class="spacer"></div>


        <div class="main-content">
<?php if ($marqueeEnabled): ?>
            <div class="notice">
                <img class="gg" src="./index_files/gonggao1.png">
                <div class="marquee-wrap">
                    <p><?= e($marqueeText) ?></p>
                </div>
            </div>
<?php endif; ?>

            <div class="net-wrapper number">
                <ul>
<?php
// ── 老虎机中奖配置：每个按钮一个不同中奖符号 + 3 列错落 sprite 顺序 ──
$winSymbols = ['7', 'diamond', 'cherry', 'bell'];          // LINK1-4 各自的中奖图标
$orderA = ['7','bar','apple','cherry','bell','coin','diamond'];
$orderB = ['cherry','coin','7','bell','apple','diamond','bar'];
$orderC = ['diamond','apple','bell','7','bar','cherry','coin'];
// strip 高度 1400%（2 张 sprite repeat-y），每个符号占 strip 的 100/14% = 7.143%
$yOf = fn(array $arr, string $sym) => round(-array_search($sym, $arr) * 100 / 14, 3);
?>
<?php foreach ($primaryLinks as $idx => $link): $n = $idx + 1; $win = $winSymbols[$idx % 4];
    $ya = $yOf($orderA, $win); $yb = $yOf($orderB, $win); $yc = $yOf($orderC, $win); ?>
                    <li style="--idx:<?= $idx ?>;">
                        <div class="flex">
                            <img class="img1" src="./index_files/link_icon_gif.gif">
                            <p style="color: #20E133;"> <i id="number-<?= $n ?>" data-sum></i> ms</p>
                        </div>
                        <span class="slot-reel" aria-hidden="true" style="--ya:<?= $ya ?>%;--yb:<?= $yb ?>%;--yc:<?= $yc ?>%;">
                            <i class="slot-col col-a"></i>
                            <i class="slot-col col-b"></i>
                            <i class="slot-col col-c"></i>
                        </span>
                        <a onclick="changeurl();" rel="nofollow" target="_blank">
                            <span><?= e(pick_lang($link['label'] ?? '', $lang, $defaultLang)) ?></span>
                            <img class="button" src="./index_files/game3.png">
                        </a>
                    </li>
<?php endforeach; ?>
                </ul>
                <p><?= e(pick_lang(Config::get($config, 'site.footer_save_text', ''), $lang, $defaultLang)) ?></p>
            </div>
            <br />
            <div class="links"  style="margin-top: -40px;">
<?php foreach ($downloads as $d): ?>
                <a href="<?= e($d['url']) ?>" target="_blank">
                    <img src="<?= e($d['image']) ?>">
                </a>
<?php endforeach; ?>
            </div>

            <div class="links">
<?php foreach ($socials as $s): ?>
                <a href="<?= e($s['url']) ?>" target="_blank">
                    <img src="<?= e($s['image']) ?>">
                </a>
<?php endforeach; ?>
            </div>
        </div>
    </div>

<?php if ($popupEnabled): ?>
    <!--弹框-->
    <div class="popup" id="popup">
        <div class="popup-body">
            <img class="popup-img" src="<?= e($popupImg) ?>">
        </div>
    </div>
<?php endif; ?>

    <script src="./index_files/jquery-2.2.4.min.js?v=<?= $assetV('index_files/jquery-2.2.4.min.js') ?>"></script>
    <script src="./index_files/swiper.js?v=<?= $assetV('index_files/swiper.js') ?>"></script>
    <script>

     var doMainArr = <?= json_encode($pool, JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP) ?>;

        var swiper = new Swiper('.swiper-banner', {
            slidesPerView: 1,
            slidesPerColumn: 1,
            spaceBetween: <?= (int)Config::get($config, 'carousel_settings.space_between_px', 30) ?>,
            autoplay: {
                delay: <?= (int)Config::get($config, 'carousel_settings.autoplay_ms', 3000) ?>,
                autoplayDisableOnInteraction: false,
                disableOnInteraction: false,
            },
            loop: <?= Config::get($config, 'carousel_settings.loop', true) ? 'true' : 'false' ?>,
            navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
            },
            pagination: {
                el: '.swiper-pagination',
            },
        });

        function getMobileOperatingSystem() {
            const userAgent = navigator.userAgent || navigator.vendor || window.opera;

            if (/android/i.test(userAgent)) {
                return 'Android';
            } else if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
                return 'iOS';
            } else {
                return 'unknown';
            }
        }

        const os = getMobileOperatingSystem();
        const goAPP = $('#go_app');
        if (os === 'Android') {
            goAPP.attr('href', doMainArr[Math.floor(Math.random() * doMainArr.length)]);
        } else if (os === 'iOS') {
            goAPP.attr('href',  doMainArr[Math.floor(Math.random() * doMainArr.length)]);
        } else {
            goAPP.attr('href',  doMainArr[Math.floor(Math.random() * doMainArr.length)]);
        }

        $('.swiper-slide').on('click', function () {
            const src = $(this).attr('data-src');
            if (src) {
                if (src == 'app') {
                    if (os === 'iOS') {
                        window.open( doMainArr[Math.floor(Math.random() * doMainArr.length)]);
                    } else {
                        location.href =  doMainArr[Math.floor(Math.random() * doMainArr.length)];
                    }
                } else {
                    window.open(src);
                }
            }
        });

        // popup
        $('#go_vpn').click(function () {
            $('#popup').show();
        })
        $('#popup').click(function () {
            $('#popup').hide();
        });
        $('#popup .popup-body').click(function (e) {
            e.stopPropagation();
        })

        function changeurl(){
            window.location.href = doMainArr[Math.floor(Math.random() * doMainArr.length)];
        }

<?php $cnt = count($primaryLinks); for ($i = 1; $i <= $cnt; $i++):
    $min = (int)($primaryLinks[$i-1]['ping_min'] ?? 10);
    $max = (int)($primaryLinks[$i-1]['ping_max'] ?? 150);
?>
        let ram<?= $i ?> = Math.floor(Math.random() * (<?= $max ?> - <?= $min ?> + 1) + <?= $min ?>);
        document.querySelectorAll('i')[<?= $i-1 ?>].setAttribute('data-sum',ram<?= $i ?>);
<?php endfor; ?>

    </script>
        <div class="net-wrapper">
                <p><?= e($cpPrefix) ?>      <?= e(pick_lang(Config::get($config, 'site.footer_copyright_suffix', '@Copyright'), $lang, $defaultLang)) ?> <?= $cpStart ?>-<?= $year ?></p>
            </div>

</div>


    <script src="./num.js?v=<?= $assetV('num.js') ?>"></script>
    <script defer src="./index_files/animations.js?v=<?= $assetV('index_files/animations.js') ?>"></script>
    </body></html>
