<?php
error_reporting(E_ALL);
ini_set('display_errors', 0);
set_time_limit(0);
ini_set('memory_limit', '1G');

$cacheFile = 'stars_country_data.json';
$cacheTime = 86400; 
$stars = [];
$countryCounts = [];

if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < $cacheTime)) {
    $stars = json_decode(file_get_contents($cacheFile), true);
} else {
    $directory = new RecursiveDirectoryIterator('profiles');
    $iterator = new RecursiveIteratorIterator($directory);
    foreach ($iterator as $file) {
        if ($file->isFile() && $file->getExtension() === 'php' && $file->getFilename() !== 'index.php') {
            $content = file_get_contents($file->getPathname());

            if (preg_match('/<span class="stat-label">Country<\/span>\s*<span class="stat-value">(.*?)<\/span>/is', $content, $countryMatch)) {
                
                $country = trim(strip_tags($countryMatch[1]));

                $isCode = (strpos($country, '${') !== false || strpos($country, 'd.stats') !== false);
                $isValid = (!empty($country) && !$isCode && $country !== '&nbsp;' && strlen($country) < 60);

                if ($isValid) {
                    preg_match('/<!-- TITRE -->(.*?)<!-- \/TITRE -->/s', $content, $nameMatch);
                    $name = isset($nameMatch[1]) ? trim(strip_tags($nameMatch[1])) : ucwords(str_replace(['-', '.php'], [' ', ''], $file->getBasename('.php')));

                    preg_match('/<img[^>]+src=["\']([^"\']+)["\']/i', $content, $imgMatch);
                    $photo = isset($imgMatch[1]) ? $imgMatch[1] : '/default-avatar.png';
                    
                    $stars[] = [
                        'name' => $name,
                        'country' => $country,
                        'photo' => $photo,
                        'url' => "/" . str_replace('\\', '/', $file->getPathname())
                    ];
                }
            }
        }
    }
    file_put_contents($cacheFile, json_encode($stars));
}

foreach ($stars as $s) {
    $c = $s['country'];
    $countryCounts[$c] = ($countryCounts[$c] ?? 0) + 1;
}
ksort($countryCounts);

$countryFilter = isset($_GET['country']) ? trim($_GET['country']) : '';
$filteredStars = array_filter($stars, function($s) use ($countryFilter) {
    if ($countryFilter === '') return true;
    return ($s['country'] === $countryFilter);
});

usort($filteredStars, function($a, $b) {
    return strcmp($a['name'], $b['name']);
});

$currentPage = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$itemsPerPage = 60;
$totalItems = count($filteredStars);
$totalPages = ceil($totalItems / $itemsPerPage);
$pagedStars = array_slice($filteredStars, ($currentPage - 1) * $itemsPerPage, $itemsPerPage);

$metaDesc = $countryFilter !== '' ? "List of $totalItems celebrities from $countryFilter." : "Browse celebrities by their country of origin.";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $countryFilter !== '' ? htmlspecialchars($countryFilter) . " ($totalItems)" : "Celebrities by Country" ?> - Became.info</title>
    <meta name="description" content="<?= htmlspecialchars($metaDesc) ?>">
    <link rel="stylesheet" href="/style.css">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;700;900&display=swap');
        :root { --primary: #2563eb; --gradient: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%); --bg: #f1f5f9; --text: #0f172a; }
        body { font-family: 'Inter', sans-serif; background: var(--bg); color: var(--text); padding: 15px; margin: 0; }
        .container { max-width: 1100px; margin: auto; width: 100%; }
        .logo { display: inline-block; background: var(--gradient); -webkit-background-clip: text; -webkit-text-fill-color: transparent; text-align: center; font-size: 2.2rem; font-weight: 900; margin: 10px auto; width: 100%; cursor: pointer; }
        
        .search-wrapper { display: flex; gap: 10px; justify-content: center; margin-bottom: 30px; flex-wrap: wrap; }
        .country-select { 
            padding: 15px; 
            border-radius: 12px; 
            border: 2px solid #e2e8f0; 
            width: 100%; 
            max-width: 350px !important; 
            font-size: 1rem; 
            cursor: pointer; 
            background: white;
            text-overflow: ellipsis;
            white-space: nowrap;
            overflow: hidden;
        }

        .loading-overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255,255,255,0.9); z-index: 2000; justify-content: center; align-items: center; flex-direction: column; font-weight: bold; color: var(--primary); }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
        
        .stars-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 15px; margin-top: 30px; }
        .star-item { background: white; padding: 20px 10px; border-radius: 16px; border: 1px solid #e2e8f0; text-decoration: none; color: #334155; font-weight: 700; text-align: center; display: flex; flex-direction: column; align-items: center; gap: 10px; transition: 0.2s; }
        .star-item:hover { transform: translateY(-5px); border-color: var(--primary); box-shadow: 0 4px 12px rgba(0,0,0,0.05); }
        .star-thumb { width: 80px; height: 80px; border-radius: 50%; object-fit: cover; border: 3px solid #f1f5f9; }
        .country-tag { background: #eff6ff; color: var(--primary); padding: 4px 12px; border-radius: 20px; font-size: 0.75rem; font-weight: 800; border: 1px solid #e2e8f0; }
        
        .pagination { margin: 40px 0; display: flex; justify-content: center; align-items: center; gap: 8px; flex-wrap: wrap; }
        .page-btn { padding: 8px 14px; background: white; border: 1px solid #e2e8f0; border-radius: 8px; text-decoration: none; color: var(--text); font-weight: 700; }
        .active-page { background: var(--gradient); color: white; border: none; }

        @media (max-width: 480px) { .country-select { max-width: 100% !important; } }
    </style>
    <?php include_once("analyticstracking.php") ?>
    <link rel="canonical" href="https://www.became.info/celebrity-country.php">
<meta name="google-adsense-account" content="ca-pub-9068036362020026"><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-9068036362020026" crossorigin="anonymous"></script></head>
<body>

<div id="loader" class="loading-overlay">
    <div style="border: 4px solid #f3f3f3; border-top: 4px solid #6366f1; border-radius: 50%; width: 40px; height: 40px; animation: spin 1s linear infinite; margin-bottom: 15px;"></div>
    <span>Loading...</span>
</div>

<div class="container">
    <header style="text-align: center;"><div class="logo" onclick="location.href='/'">Became.info</div></header>

    <h2 style="text-align:center; font-size: 1.2rem; color: #64748b; margin-bottom: 20px;">
        <?= $countryFilter !== '' ? "Celebrities from " . htmlspecialchars($countryFilter) : "Find celebrities by country" ?>
    </h2>

    <form method="GET" class="search-wrapper">
        <select name="country" class="country-select" onchange="document.getElementById('loader').style.display='flex'; this.form.submit()">
            <option value="">— Select a country —</option>
            <?php foreach ($countryCounts as $name => $count): ?>
                <option value="<?= htmlspecialchars($name) ?>" <?= $countryFilter === $name ? 'selected' : '' ?>>
                    <?= htmlspecialchars($name) ?> (<?= $count ?>)
                </option>
            <?php endforeach; ?>
        </select>
        <?php if($countryFilter !== ''): ?>
            <a href="?" style="padding:15px; text-decoration:none; color:#64748b; font-weight:bold;">Reset</a>
        <?php endif; ?>
    </form>

    <div class="stars-grid">
        <?php if (empty($pagedStars)): ?>
            <p style="grid-column: 1/-1; text-align: center; padding: 50px; color: #64748b;">No results found. Please select a country.</p>
        <?php else: ?>
            <?php foreach ($pagedStars as $star): ?>
                <a href="<?= $star['url'] ?>" class="star-item">
                    <img src="<?= htmlspecialchars($star['photo']) ?>" alt="<?= htmlspecialchars($star['name']) ?>" class="star-thumb" loading="lazy">
                    <span style="font-size: 0.9rem;"><?= htmlspecialchars($star['name']) ?></span>
                    <span class="country-tag">🌍 <?= htmlspecialchars($star['country']) ?></span>
                </a>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>

    <?php if ($totalPages > 1): ?>
    <div class="pagination">
        <?php $q = "&country=" . urlencode($countryFilter); ?>
        <?php if ($currentPage > 1): ?>
            <a href="?page=1<?= $q ?>" class="page-btn">First</a>
            <a href="?page=<?= $currentPage - 1 ?><?= $q ?>" class="page-btn">←</a>
        <?php endif; ?>
        <span class="page-btn active-page"><?= $currentPage ?> / <?= $totalPages ?></span>
        <?php if ($currentPage < $totalPages): ?>
            <a href="?page=<?= $currentPage + 1 ?><?= $q ?>" class="page-btn">→</a>
            <a href="?page=<?= $totalPages ?><?= $q ?>" class="page-btn">Last</a>
        <?php endif; ?>
    </div>
    <?php endif; ?>
</div>

<footer style="text-align: center; padding: 40px; border-top: 1px solid #e2e8f0; margin-top: 50px;">
    <?php include("footer.php"); ?>
</footer>

<script>
window.addEventListener('pageshow', (event) => {
    const globalLoader = document.getElementById('loader');
    if (globalLoader) { globalLoader.style.display = 'none'; }
    if (event.persisted) { window.location.reload(); }
});
</script>

</body>
</html>
