<?php
declare(strict_types=1);
/** @var string $pageTitle */
/** @var string $pageHeading */
/** @var string $activeNav dashboard|projects|settings|keywords|pages|opportunities|decay|cannibalization|quick_win|long_tail|question_queries */
/** @var string $content inner HTML */
/** @var array{ok:?string,err:?string} $flash */
/** @var ?bool $hideHero */
/** @var ?string $heroTitle */
/** @var ?string $heroSubtitle */
/** @var ?string $heroMeta */
/** @var ?array{start:string,end:string,prev_start:?string,prev_end:?string} $heroMetaData */
/** @var ?array{current_path:string,preset:string,compare:bool,device:string,country:string,prop_id:string,properties:list<array{id:int,site_url:string}>,countries:list<string>,settings_tab?:string} $globalFilters */

$t = static fn (string $k, array $p = []) => seoscope_h(__($k, $p));
$u = static fn (string $p) => seoscope_h(seoscope_url($p));
$gf = static function (string $path) use ($globalFilters): string {
    if (!isset($globalFilters) || !is_array($globalFilters)) {
        return seoscope_h(seoscope_url($path));
    }
    $qs = [
        'prop' => (string) ($globalFilters['prop_id'] ?? ''),
        'range' => (string) ($globalFilters['preset'] ?? ''),
    ];
    if (!empty($globalFilters['breakdowns_enabled'])) {
        $qs['device'] = (string) ($globalFilters['device'] ?? 'all');
        $qs['country'] = (string) ($globalFilters['country'] ?? 'all');
    }
    if (!empty($globalFilters['compare'])) {
        $qs['compare'] = '1';
    }
    if (!empty($globalFilters['settings_tab']) && $path === '/settings') {
        $qs['tab'] = (string) $globalFilters['settings_tab'];
    }
    // Drop empties.
    $qs = array_filter($qs, static fn ($v) => is_string($v) && $v !== '');
    $url = seoscope_url($path);
    if ($qs !== []) {
        $url .= (str_contains($url, '?') ? '&' : '?') . http_build_query($qs);
    }
    return seoscope_h($url);
};
$navDash = $activeNav === 'dashboard' ? 'nav-link active' : 'nav-link';
$navProj = $activeNav === 'projects' ? 'nav-link active' : 'nav-link';
$navSettings = $activeNav === 'settings' ? 'nav-link active' : 'nav-link';
$navKeywords = $activeNav === 'keywords' ? 'nav-link active' : 'nav-link';
$navPages = $activeNav === 'pages' ? 'nav-link active' : 'nav-link';
$navOpp = $activeNav === 'opportunities' ? 'nav-link active' : 'nav-link';
$navQw = $activeNav === 'quick_win' ? 'nav-link active' : 'nav-link';
$navLt = $activeNav === 'long_tail' ? 'nav-link active' : 'nav-link';
$navQq = $activeNav === 'question_queries' ? 'nav-link active' : 'nav-link';
$navDecay = $activeNav === 'decay' ? 'nav-link active' : 'nav-link';
$navCan = $activeNav === 'cannibalization' ? 'nav-link active' : 'nav-link';
$user = \SeoScope\Auth\SessionAuth::user();
$csrf = \SeoScope\Auth\AdminCsrf::token();
$heroTitle = isset($heroTitle) && is_string($heroTitle) ? $heroTitle : null;
$heroSubtitle = isset($heroSubtitle) && is_string($heroSubtitle) ? $heroSubtitle : null;
$heroMeta = isset($heroMeta) && is_string($heroMeta) ? $heroMeta : null;
$heroMetaData = isset($heroMetaData) && is_array($heroMetaData) ? $heroMetaData : null;
$hideHero = isset($hideHero) ? (bool) $hideHero : false;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= seoscope_h($pageTitle) ?> — <?= $t('app.name') ?></title>
    <link rel="icon" href="<?= $u('/assets/admin-template/images/favicon-seoscope.png') ?>" type="image/png">
    <link rel="shortcut icon" href="<?= $u('/assets/admin-template/images/favicon-seoscope.png') ?>" type="image/png">
    <link rel="stylesheet" href="<?= $u('/assets/fonts/inter/inter.css') ?>">
    <link rel="stylesheet" href="<?= $u('/assets/vendor/bootstrap/bootstrap.min.css') ?>">
    <link rel="stylesheet" href="<?= $u('/assets/vendor/fontawesome/css/all.min.css') ?>">
    <?php $cssPath = SEOSCOPE_ROOT . '/assets/admin-template/css/admin-template.css'; ?>
    <?php $cssVer = (string) SEOSCOPE_VERSION . '-' . (string) (@filemtime($cssPath) ?: time()); ?>
    <link rel="stylesheet" href="<?= $u('/assets/admin-template/css/admin-template.css?v=' . rawurlencode($cssVer)) ?>">
</head>
<body>
    <div class="app-shell">
        <div class="container-fluid p-0">
            <div class="row g-0 app-shell__main-row">
                <aside class="col-xxl-auto sidebar d-none d-xxl-block">
                    <div class="brand">
                        <img class="brand-logo" src="<?= $u('/assets/admin-template/images/logo-seoscope.png') ?>" alt="<?= $t('app.name') ?>">
                        <span><?= $t('app.name') ?></span>
                    </div>

                    <div class="nav-title"><?= $t('nav.section_main') ?></div>
                    <nav class="nav flex-column">
                        <a href="<?= $gf('/') ?>" class="<?= seoscope_h($navDash) ?>">
                            <span class="left"><i class="fa-solid fa-house"></i><span><?= $t('nav.dashboard') ?></span></span>
                        </a>
                        <a href="<?= $gf('/projects') ?>" class="<?= seoscope_h($navProj) ?>">
                            <span class="left"><i class="fa-solid fa-folder-open"></i><span><?= $t('nav.projects') ?></span></span>
                        </a>
                        <a href="<?= $gf('/settings') ?>" class="<?= seoscope_h($navSettings) ?>">
                            <span class="left"><i class="fa-solid fa-gear"></i><span><?= $t('nav.settings') ?></span></span>
                        </a>
                    </nav>

                    <div class="nav-title mt-3"><?= $t('nav.section_reports') ?></div>
                    <nav class="nav flex-column">
                        <a href="<?= $gf('/quick-win') ?>" class="<?= seoscope_h($navQw) ?>">
                            <span class="left"><i class="fa-solid fa-bolt"></i><span><?= $t('nav.quick_win') ?></span></span>
                        </a>
                        <a href="<?= $gf('/keywords') ?>" class="<?= seoscope_h($navKeywords) ?>">
                            <span class="left"><i class="fa-solid fa-magnifying-glass-chart"></i><span><?= $t('nav.keywords') ?></span></span>
                        </a>
                        <a href="<?= $gf('/pages') ?>" class="<?= seoscope_h($navPages) ?>">
                            <span class="left"><i class="fa-regular fa-file-lines"></i><span><?= $t('nav.pages') ?></span></span>
                        </a>
                        <a href="<?= $gf('/cannibalization') ?>" class="<?= seoscope_h($navCan) ?>">
                            <span class="left"><i class="fa-solid fa-code-branch"></i><span><?= $t('nav.cannibalization') ?></span></span>
                        </a>
                        <a href="<?= $gf('/long-tail') ?>" class="<?= seoscope_h($navLt) ?>">
                            <span class="left"><i class="fa-solid fa-list"></i><span><?= $t('nav.long_tail') ?></span></span>
                        </a>
                        <a href="<?= $gf('/question-queries') ?>" class="<?= seoscope_h($navQq) ?>">
                            <span class="left"><i class="fa-regular fa-circle-question"></i><span><?= $t('nav.question_queries') ?></span></span>
                        </a>
                        <a href="<?= $gf('/decay') ?>" class="<?= seoscope_h($navDecay) ?>">
                            <span class="left"><i class="fa-solid fa-arrow-trend-down"></i><span><?= $t('nav.decay') ?></span></span>
                        </a>
                    </nav>

                </aside>

                <div class="offcanvas offcanvas-start sidebar-offcanvas d-xxl-none" tabindex="-1" id="ss-mobile-nav" aria-labelledby="ss-mobile-nav-label">
                    <div class="offcanvas-header">
                        <div class="brand m-0" id="ss-mobile-nav-label">
                            <img class="brand-logo" src="<?= $u('/assets/admin-template/images/logo-seoscope.png') ?>" alt="<?= $t('app.name') ?>">
                            <span><?= $t('app.name') ?></span>
                        </div>
                        <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
                    </div>
                    <div class="offcanvas-body p-0">
                        <div class="sidebar sidebar--offcanvas">
                            <div class="nav-title"><?= $t('nav.section_main') ?></div>
                            <nav class="nav flex-column">
                                <a href="<?= $gf('/') ?>" class="<?= seoscope_h($navDash) ?>">
                                    <span class="left"><i class="fa-solid fa-house"></i><span><?= $t('nav.dashboard') ?></span></span>
                                </a>
                                <a href="<?= $gf('/projects') ?>" class="<?= seoscope_h($navProj) ?>">
                                    <span class="left"><i class="fa-solid fa-folder-open"></i><span><?= $t('nav.projects') ?></span></span>
                                </a>
                                <a href="<?= $gf('/settings') ?>" class="<?= seoscope_h($navSettings) ?>">
                                    <span class="left"><i class="fa-solid fa-gear"></i><span><?= $t('nav.settings') ?></span></span>
                                </a>
                            </nav>

                            <div class="nav-title mt-3"><?= $t('nav.section_reports') ?></div>
                            <nav class="nav flex-column">
                                <a href="<?= $gf('/quick-win') ?>" class="<?= seoscope_h($navQw) ?>">
                                    <span class="left"><i class="fa-solid fa-bolt"></i><span><?= $t('nav.quick_win') ?></span></span>
                                </a>
                                <a href="<?= $gf('/keywords') ?>" class="<?= seoscope_h($navKeywords) ?>">
                                    <span class="left"><i class="fa-solid fa-magnifying-glass-chart"></i><span><?= $t('nav.keywords') ?></span></span>
                                </a>
                                <a href="<?= $gf('/pages') ?>" class="<?= seoscope_h($navPages) ?>">
                                    <span class="left"><i class="fa-regular fa-file-lines"></i><span><?= $t('nav.pages') ?></span></span>
                                </a>
                                <a href="<?= $gf('/cannibalization') ?>" class="<?= seoscope_h($navCan) ?>">
                                    <span class="left"><i class="fa-solid fa-code-branch"></i><span><?= $t('nav.cannibalization') ?></span></span>
                                </a>
                                <a href="<?= $gf('/long-tail') ?>" class="<?= seoscope_h($navLt) ?>">
                                    <span class="left"><i class="fa-solid fa-list"></i><span><?= $t('nav.long_tail') ?></span></span>
                                </a>
                                <a href="<?= $gf('/question-queries') ?>" class="<?= seoscope_h($navQq) ?>">
                                    <span class="left"><i class="fa-regular fa-circle-question"></i><span><?= $t('nav.question_queries') ?></span></span>
                                </a>
                                <a href="<?= $gf('/decay') ?>" class="<?= seoscope_h($navDecay) ?>">
                                    <span class="left"><i class="fa-solid fa-arrow-trend-down"></i><span><?= $t('nav.decay') ?></span></span>
                                </a>
                            </nav>

                        </div>
                    </div>
                </div>

                <main class="col content-area">
                    <div class="topbar">
                        <button
                            type="button"
                            class="icon-pill d-xxl-none"
                            data-bs-toggle="offcanvas"
                            data-bs-target="#ss-mobile-nav"
                            aria-controls="ss-mobile-nav"
                            title="Menu"
                        >
                            <i class="fa-solid fa-bars"></i>
                        </button>
                        <?php if (isset($globalFilters) && is_array($globalFilters)): ?>
                            <form method="get" action="<?= $u((string) ($globalFilters['current_path'] ?? '/')) ?>" class="m-0 topbar-filters">
                                <select class="topbar-select" name="prop" onchange="this.form.submit()">
                                        <?php
                                            $curPropId = (string) ($globalFilters['prop_id'] ?? '');
                                            $uniqueProps = [];
                                            foreach (($globalFilters['properties'] ?? []) as $opt) {
                                                if (!is_array($opt)) {
                                                    continue;
                                                }
                                                $id = (int) ($opt['id'] ?? 0);
                                                $label = seoscope_prop_label((string) ($opt['site_url'] ?? ''));
                                                if ($label === '' || $id < 1) {
                                                    continue;
                                                }
                                                $key = strtolower($label);
                                                if (!isset($uniqueProps[$key])) {
                                                    $uniqueProps[$key] = ['opt' => $opt, 'label' => $label];
                                                } else {
                                                    // Preserve the currently selected property if it belongs to this normalized label.
                                                    if ($curPropId !== '' && $curPropId === (string) $id) {
                                                        $uniqueProps[$key] = ['opt' => $opt, 'label' => $label];
                                                    }
                                                }
                                            }
                                        ?>
                                        <?php foreach ($uniqueProps as $row): ?>
                                            <?php $opt = $row['opt']; ?>
                                            <?php $id = (int) ($opt['id'] ?? 0); ?>
                                            <option value="<?= (int) $id ?>" <?= ($curPropId !== '' && $curPropId === (string) $id) ? 'selected' : '' ?>>
                                                <?= seoscope_h((string) ($row['label'] ?? '')) ?>
                                            </option>
                                        <?php endforeach; ?>
                                </select>
                                <select class="topbar-select" name="range" onchange="this.form.submit()">
                                    <option value="last_7_days" <?= (($globalFilters['preset'] ?? '') === 'last_7_days') ? 'selected' : '' ?>><?= $t('global.range_last_7') ?></option>
                                    <option value="last_28_days" <?= (($globalFilters['preset'] ?? '') === 'last_28_days') ? 'selected' : '' ?>><?= $t('global.range_last_28') ?></option>
                                    <option value="last_3_months" <?= (($globalFilters['preset'] ?? '') === 'last_3_months') ? 'selected' : '' ?>><?= $t('global.range_last_3') ?></option>
                                    <option value="last_6_months" <?= (($globalFilters['preset'] ?? '') === 'last_6_months') ? 'selected' : '' ?>><?= $t('global.range_last_6') ?></option>
                                    <option value="last_12_months" <?= (($globalFilters['preset'] ?? '') === 'last_12_months') ? 'selected' : '' ?>><?= $t('global.range_last_12') ?></option>
                                    <option value="last_16_months" <?= (($globalFilters['preset'] ?? '') === 'last_16_months') ? 'selected' : '' ?>><?= $t('global.range_last_16') ?></option>
                                </select>
                                <?php /* Device/Country filters removed (property-level breakdowns only). */ ?>
                                <label class="d-flex align-items-center gap-2 small text-muted" style="user-select:none;">
                                    <input type="checkbox" class="form-check-input m-0" name="compare" value="1" <?= !empty($globalFilters['compare']) ? 'checked' : '' ?> onchange="this.form.submit()">
                                    <span><?= $t('global.compare') ?></span>
                                </label>
                                <?php if (!empty($globalFilters['settings_tab'])): ?>
                                    <input type="hidden" name="tab" value="<?= seoscope_h((string) $globalFilters['settings_tab']) ?>">
                                <?php endif; ?>
                                <input type="hidden" name="sort" value="<?= seoscope_h((string) ($_GET['sort'] ?? '')) ?>">
                                <input type="hidden" name="dir" value="<?= seoscope_h((string) ($_GET['dir'] ?? '')) ?>">
                                <input type="hidden" name="per_page" value="<?= seoscope_h((string) ($_GET['per_page'] ?? '')) ?>">
                            </form>
                        <?php else: ?>
                            <div></div>
                        <?php endif; ?>
                        <a class="icon-pill" href="<?= $u('/account') ?>" title="<?= seoscope_h($user['email'] ?? '') ?>">
                            <i class="fa-regular fa-user"></i>
                        </a>
                        <form method="post" action="<?= $u('/logout') ?>" class="d-inline">
                            <input type="hidden" name="_csrf" value="<?= seoscope_h($csrf) ?>">
                            <button type="submit" class="icon-pill" title="<?= $t('auth.logout') ?>" style="border:0;">
                                <i class="fa-solid fa-right-from-bracket"></i>
                            </button>
                        </form>
                    </div>

                    <?php if (!$hideHero): ?>
                        <section class="mb-4">
                            <h1 class="welcome-title mb-0"><?= seoscope_h($heroTitle ?? $pageHeading) ?></h1>
                            <p class="welcome-subtitle"><?= seoscope_h($heroSubtitle ?? $pageTitle) ?></p>
                            <?php if (is_array($heroMetaData) && !empty($heroMetaData['start']) && !empty($heroMetaData['end'])): ?>
                                <div class="alert alert-success mt-2 mb-0 py-2 px-3 small rounded-4 d-inline-block" role="status">
                                    <strong>Data range</strong>:
                                    <?= seoscope_h((string) $heroMetaData['start']) ?> to <?= seoscope_h((string) $heroMetaData['end']) ?>
                                    <?php if (!empty($heroMetaData['prev_start']) && !empty($heroMetaData['prev_end'])): ?>
                                        <strong>VS</strong>
                                        <?= seoscope_h((string) $heroMetaData['prev_start']) ?> to <?= seoscope_h((string) $heroMetaData['prev_end']) ?>
                                    <?php endif; ?>
                                </div>
                            <?php elseif ($heroMeta !== null && $heroMeta !== ''): ?>
                                <div class="alert alert-success mt-2 mb-0 py-2 px-3 small rounded-4 d-inline-block" role="status">
                                    <?= seoscope_h($heroMeta) ?>
                                </div>
                            <?php endif; ?>
                        </section>
                    <?php endif; ?>

                    <?php if (!empty($flash['ok'])): ?>
                        <div class="alert alert-success"><?= seoscope_h($flash['ok']) ?></div>
                    <?php endif; ?>
                    <?php if (!empty($flash['err'])): ?>
                        <div class="alert alert-danger"><?= seoscope_h($flash['err']) ?></div>
                    <?php endif; ?>

                    <?= $content ?>

                    <footer class="mt-4 pt-3">
                        <div class="text-muted small">
                            <?= $t('footer.copyright', ['year' => (string) date('Y'), 'version' => SEOSCOPE_VERSION]) ?>
                        </div>
                    </footer>
                </main>
            </div>
        </div>
    </div>
    <script src="<?= $u('/assets/vendor/bootstrap/bootstrap.bundle.min.js') ?>"></script>
    <script>
      (function () {
        if (!window.bootstrap || !window.bootstrap.Tooltip) return;
        var triggers = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        triggers.forEach(function (el) { new bootstrap.Tooltip(el); });
      })();
    </script>
    <?php if (in_array($activeNav ?? '', ['keywords', 'pages'], true)): ?>
    <?php
        $trackJsPath = SEOSCOPE_ROOT . '/assets/js/track-actions.js';
        $trackJsVer = (string) SEOSCOPE_VERSION . '-' . (string) (@filemtime($trackJsPath) ?: time());
    ?>
    <script src="<?= $u('/assets/js/track-actions.js?v=' . rawurlencode($trackJsVer)) ?>"></script>
    <?php endif; ?>
</body>
</html>
