<?php
use App\Core\Auth;
use App\Core\Lang;
use App\Models\Page;
use function App\Core\{e, logo_asset, site_setting, t, url};

$user = Auth::user();
$logoAsset = logo_asset('main');
$headerMenuEnabled = site_setting('header_menu_enabled', '1') !== '0';
$currentPath = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';
$currentPath = rtrim($currentPath, '/') ?: '/';
$currentQuery = $_GET;
$searchHref = static fn (string $term): string => '/arama?q=' . rawurlencode($term);

$categoryLinks = [
    ['label' => 'Animal Trailers', 'href' => $searchHref('Animal Trailers'), 'icon' => 'AT'],
    ['label' => 'Asian Maps', 'href' => $searchHref('Asian Maps'), 'icon' => 'AM'],
    ['label' => 'Auger Wagons', 'href' => $searchHref('Auger Wagons'), 'icon' => 'AW'],
    ['label' => 'Bale Flatbed Trailers', 'href' => $searchHref('Bale Flatbed Trailers'), 'icon' => 'BF'],
    ['label' => 'Bale Wrappers', 'href' => $searchHref('Bale Wrappers'), 'icon' => 'BW'],
    ['label' => 'Tum Kategorileri Gor', 'href' => '/arama', 'icon' => 'K'],
];

$brandLinks = [
    ['label' => 'John Deere', 'href' => $searchHref('John Deere'), 'icon' => 'JD'],
    ['label' => 'CLAAS', 'href' => $searchHref('CLAAS'), 'icon' => 'CL'],
    ['label' => 'New Holland', 'href' => $searchHref('New Holland'), 'icon' => 'NH'],
    ['label' => 'Fendt', 'href' => $searchHref('Fendt'), 'icon' => 'FE'],
    ['label' => 'Case IH', 'href' => $searchHref('Case IH'), 'icon' => 'CI'],
    ['label' => 'Tum Markalari Gor', 'href' => $searchHref('brands'), 'icon' => 'M'],
];

$buildMega = static function (string $gameLabel, string $gameHref, string $short) use ($categoryLinks, $brandLinks): array {
    return [
        [
            'title' => 'Hizli baglantilar',
            'links' => [
                ['label' => 'New Mods', 'href' => $gameHref . (str_contains($gameHref, '?') ? '&sirala=newest' : '?sirala=newest'), 'icon' => 'N'],
                ['label' => 'Trending Mods', 'href' => '/arama?sirala=populer&q=' . rawurlencode($gameLabel), 'icon' => 'T'],
                ['label' => 'Categories', 'href' => '/arama', 'icon' => 'C'],
                ['label' => 'Brands', 'href' => '/arama?q=brands', 'icon' => 'B'],
                ['label' => 'Game page', 'href' => $gameHref, 'icon' => $short],
            ],
        ],
        ['title' => 'Kategoriler', 'links' => $categoryLinks],
        ['title' => 'Markalar', 'links' => $brandLinks],
    ];
};

$menuItems = [
    ['label' => t('home'), 'href' => '/', 'active' => ['/']],
    ['label' => 'FS25 Mods', 'href' => '/kategori/fs25-mods', 'active' => ['/kategori/fs25-mods'], 'mega' => $buildMega('FS25', '/kategori/fs25-mods', '25')],
    ['label' => 'FS22 Mods', 'href' => '/kategori/fs22-mods', 'active' => ['/kategori/fs22-mods'], 'mega' => $buildMega('FS22', '/kategori/fs22-mods', '22')],
    ['label' => 'FS17 Mods', 'href' => '/arama?q=FS17', 'active' => ['/kategori/fs17-mods'], 'activeQuery' => ['q' => 'FS17'], 'mega' => $buildMega('FS17', '/arama?q=FS17', '17')],
    ['label' => 'Work-In-Progress', 'href' => '/kategori/work-in-progress', 'active' => ['/kategori/work-in-progress'], 'mega' => $buildMega('Work-In-Progress', '/kategori/work-in-progress', 'WP')],
    ['label' => 'Packs', 'href' => '/kategori/packs', 'active' => ['/kategori/packs'], 'dropdown' => [
        ['label' => 'Paketler', 'href' => '/kategori/packs'],
        ['label' => 'Abonelik', 'href' => '/checkout'],
    ]],
    ['label' => 'Music', 'href' => '/music', 'activePrefix' => ['/music'], 'dropdown' => [
        ['label' => 'Kesfet', 'href' => '/music'],
        ['label' => 'Muzik Yukle', 'href' => '/studyo/muzik-yukle'],
    ]],
    ['label' => 'Weekly Choice', 'href' => '/kategori/weekly-choice', 'active' => ['/kategori/weekly-choice'], 'dropdown' => [
        ['label' => 'Haftanin secimi', 'href' => '/kategori/weekly-choice'],
        ['label' => 'FS25', 'href' => '/kategori/fs25-mods'],
    ]],
];

try {
    foreach ((new Page())->menuLinks(Lang::current(), 6) as $pageLink) {
        $menuItems[] = [
            'label' => (string) $pageLink['title'],
            'href' => '/sayfa/' . (string) $pageLink['slug'],
            'active' => ['/sayfa/' . (string) $pageLink['slug']],
        ];
    }
} catch (Throwable) {
}

$isMenuActive = static function (array $item) use ($currentPath, $currentQuery): bool {
    foreach (($item['active'] ?? []) as $path) {
        if ($currentPath === $path) {
            return true;
        }
    }

    foreach (($item['activePrefix'] ?? []) as $prefix) {
        if ($currentPath === $prefix || str_starts_with($currentPath, $prefix . '/')) {
            return true;
        }
    }

    foreach (($item['activeQuery'] ?? []) as $key => $value) {
        if (($currentQuery[$key] ?? null) !== $value) {
            return false;
        }

        return $currentPath === '/arama';
    }

    return false;
};
?>
<header class="site-header">
    <div class="topbar container">
        <a class="brand <?= $logoAsset ? 'has-logo' : 'has-fallback' ?>" href="<?= url('/') ?>">
            <?php if ($logoAsset): ?>
                <img src="<?= url($logoAsset) ?>" alt="Zalorox" loading="eager">
            <?php else: ?>
                <span class="brand-text">Zalorox</span>
            <?php endif; ?>
        </a>
        <form class="search header-search" action="<?= url('/arama') ?>" method="get" data-site-search-form>
            <span class="search-leading" aria-hidden="true">/</span>
            <input name="q" data-live-search autocomplete="off" placeholder="Mod veya icerik ara...">
            <button class="search-submit" type="submit" aria-label="Ara"><span aria-hidden="true">&#128269;</span></button>
            <div class="search-results" data-live-search-results hidden></div>
        </form>
        <div class="account">
            <?php if (!$user): ?>
                <div class="guest-actions" aria-label="Hesap">
                    <span class="account-icon" aria-hidden="true"></span>
                    <a class="pill" href="<?= url('/giris-yap') ?>"><?= e(t('login')) ?></a>
                    <a class="pill primary" href="<?= url('/kayit') ?>"><?= e(t('register')) ?></a>
                </div>
                <?php require BASE_PATH . '/app/Views/partials/guest-dropdown.php'; ?>
            <?php else: ?>
                <div class="notification-center" data-notification-center>
                    <button class="notification-trigger" type="button" data-notification-toggle aria-label="Bildirimler" aria-expanded="false">
                        <span aria-hidden="true">&#128276;</span>
                        <i data-notification-count hidden>0</i>
                    </button>
                    <div class="notification-dropdown" data-notification-dropdown hidden>
                        <div class="notification-head">
                            <strong>Bildirimler</strong>
                            <span>
                                <button type="button" data-notification-read-all>Tumunu okundu yap</button>
                                <button type="button" data-notification-clear>Temizle</button>
                            </span>
                        </div>
                        <div class="notification-list" data-notification-list>
                            <div class="notification-empty">Bildirimler yukleniyor.</div>
                        </div>
                    </div>
                </div>
                <?php require BASE_PATH . '/app/Views/partials/user-dropdown.php'; ?>
            <?php endif; ?>
        </div>
        <button class="hamburger" type="button" data-menu aria-label="Menu" aria-expanded="false">
            <span></span><span></span><span></span>
        </button>
    </div>
    <?php if ($headerMenuEnabled): ?>
    <nav class="menubar">
        <div class="container menu">
            <?php foreach ($menuItems as $item): ?>
                <?php $active = $isMenuActive($item); $hasPanel = !empty($item['mega']) || !empty($item['dropdown']); ?>
                <div class="menu-item<?= !empty($item['mega']) ? ' has-mega' : '' ?><?= $active ? ' is-active' : '' ?>">
                    <a
                        class="menu-link<?= $active ? ' is-active' : '' ?>"
                        href="<?= url($item['href']) ?>"
                        <?= $hasPanel ? 'aria-haspopup="true" aria-expanded="false"' : '' ?>
                    >
                        <?= e($item['label']) ?>
                        <?php if ($hasPanel): ?><span class="menu-caret" aria-hidden="true">v</span><?php endif; ?>
                    </a>

                    <?php if (!empty($item['mega'])): ?>
                        <div class="mega-menu" role="menu">
                            <?php foreach ($item['mega'] as $column): ?>
                                <div class="mega-column">
                                    <h3><?= e($column['title']) ?></h3>
                                    <div class="mega-links">
                                        <?php foreach ($column['links'] as $link): ?>
                                            <a class="mega-link" role="menuitem" href="<?= url($link['href']) ?>">
                                                <span class="mega-icon" aria-hidden="true"><?= e($link['icon']) ?></span>
                                                <span><?= e($link['label']) ?></span>
                                            </a>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php elseif (!empty($item['dropdown'])): ?>
                        <div class="menu-dropdown" role="menu">
                            <?php foreach ($item['dropdown'] as $link): ?>
                                <a role="menuitem" href="<?= url($link['href']) ?>"><?= e($link['label']) ?></a>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
        </div>
    </nav>
    <?php endif; ?>
</header>
