<?php
if (!defined('ABSPATH')) exit;

/**
 * SEOForge admin section tabs.
 *
 * refactor: replaced the old flat 10-tab horizontal nav with a
 * hub-scoped one. Pages are now grouped under three hubs (Analytics /
 * Content / Tools), each with its OWN top-tab strip showing only that
 * hub's siblings — never the global flat list.
 *
 * Hub | Sub-tabs (in display order)
 * -----------+--------------------------------------------------
 * Analytics | Performance, Analytics & Traffic, Indexing
 * Content | Optimizer (was "Content"/audit), Content Brief, Content Decay
 * Tools | Redirects, Broken Links, Local SEO
 *
 * Pages outside any hub (Dashboard / Settings / Migration / License /
 * Contact Us) render NO top tabs — they are top-level destinations in
 * their own right.
 *
 * Public API:
 * - hubs — full hub config (parent slug + sub-tab list).
 * - hub_for_slug($slug) — returns the hub key the slug belongs to,
 * or null for non-hub pages.
 * - render($slug = null) — renders the tab strip for the slug's hub.
 * If the slug is not part of any hub, renders nothing (back-compat:
 * old callers that always called render now silently no-op on
 * pages that shouldn't have tabs at all).
 * - first_tab_slug($hub_key) — first sub-tab of a hub; the hub
 * parent slug routes here so clicks on the WP sidebar land on a
 * real renderable page.
 */
class SEOFORGE_Admin_Tabs {

    private static $styles_printed = false;

    /**
 * Hub configuration. Keep in sync with admin_menu in
 * class-core.php — both files reference these slug strings.
 */
    public static function hubs() {
        return [
            // 'feature' maps each tab to its SEOFORGE_License::can slug so the
            // PRO badge is driven by the real capability gate, not a static
            // flag. Tabs whose feature is in FREE_FEATURES (redirects, local_seo)
            // therefore render with NO badge on a Free-only site. (2026-05-29
            // Free/Pro rebalance.)
            'analytics' => [
                'parent' => 'seoforge-analytics-hub',
                'label'  => __('Analytics', 'seoforge'),
                'tabs'   => [
                    ['slug' => 'seoforge-rankings',  'label' => __('Performance', 'seoforge'),         'feature' => 'gsc'],
                    ['slug' => 'seoforge-analytics', 'label' => __('Analytics & Traffic', 'seoforge'), 'feature' => 'gsc'],
                    ['slug' => 'seoforge-indexing',  'label' => __('Indexing', 'seoforge'),            'feature' => 'gsc'],
                ],
            ],
            'content' => [
                'parent' => 'seoforge-content-hub',
                'label'  => __('Content', 'seoforge'),
                'tabs'   => [
                    // tester wanted the existing "Content" page
                    // renamed to "Optimizer" so the hub itself can keep
                    // the broader "Content" label.
                    ['slug' => 'seoforge-audit', 'label' => __('Optimizer', 'seoforge'),     'feature' => 'site_audit'],
                    ['slug' => 'seoforge-brief', 'label' => __('Content Brief', 'seoforge'), 'feature' => 'content_brief'],
                    ['slug' => 'seoforge-decay', 'label' => __('Content Decay', 'seoforge'), 'feature' => 'gsc'],
                ],
            ],
            'tools' => [
                'parent' => 'seoforge-tools-hub',
                'label'  => __('Tools', 'seoforge'),
                'tabs'   => [
                    ['slug' => 'seoforge-redirects', 'label' => __('Redirects', 'seoforge'),    'feature' => 'redirects'],
                    ['slug' => 'seoforge-broken',    'label' => __('Broken Links', 'seoforge'), 'feature' => 'internal_links'],
                    ['slug' => 'seoforge-local',     'label' => __('Local SEO', 'seoforge'),    'feature' => 'local_seo'],
                ],
            ],
        ];
    }

    /**
 * Which hub does this slug live in? Returns hub key
 * ('analytics' / 'content' / 'tools') or null if the slug is a
 * standalone page (Dashboard, Settings, Migration, License,
 * Contact Us — all hubless). Indexing lives under Analytics.
 *
 * The hub parent slug itself maps to its own hub so the parent
 * page can render tabs identical to any of its sub-tabs.
 */
    public static function hub_for_slug($slug) {
        if (!$slug) return null;
        $slug = (string) $slug;
        foreach (self::hubs() as $key => $hub) {
            if ($hub['parent'] === $slug) return $key;
            foreach ($hub['tabs'] as $tab) {
                if ($tab['slug'] === $slug) return $key;
            }
        }
        return null;
    }

    /**
 * First sub-tab slug of a hub. Used by the hub-parent renderer to
 * dispatch when the user clicks the WP sidebar entry directly
 * (no `?tab=` parameter).
 */
    public static function first_tab_slug($hub_key) {
        $hubs = self::hubs();
        if (empty($hubs[$hub_key]['tabs'])) return '';
        return $hubs[$hub_key]['tabs'][0]['slug'];
    }

    /**
 * Render the tab strip for whichever hub $current belongs to.
 * Non-hub pages get an empty render (no tabs by design — Dashboard,
 * Settings etc. are stand-alone destinations).
 */
    public static function render($current = null) {
        if ($current === null) {
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin UI state, no data mutation.
            $current = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : '';
        }
        $hub_key = self::hub_for_slug($current);
        if (!$hub_key) {
            // Stand-alone page — no top tabs.
            return;
        }

        $hubs    = self::hubs();
        $hub     = $hubs[$hub_key];
        $is_pro  = class_exists('SEOFORGE_License') ? SEOFORGE_License::instance()->is_pro() : false;

        self::print_styles();

        echo '<nav class="forge-tabs sf-forge-tabs forge-tabs--hub forge-tabs--hub-' . esc_attr($hub_key) . '" aria-label="' .
             esc_attr(sprintf( /* translators: %s: hub label (admin section name) */ __('%s sections', 'seoforge'), $hub['label'])) . '">';
        foreach ($hub['tabs'] as $tab) {
            // Sub-tabs link to the existing slugs (back-compat with deep
            // links). Hub parent slug acts as the same as the first
            // sub-tab visually — both render the same content.
            $url       = admin_url('admin.php?page=' . $tab['slug']);
            $is_active = ($tab['slug'] === $current) || ($hub['parent'] === $current && $tab['slug'] === self::first_tab_slug($hub_key));
            $cls       = 'forge-tab' . ($is_active ? ' is-active' : '');
            // Per-capability badge: show PRO only when this tab's feature is
            // NOT available to the current site. Free-core features
            // (redirects, local_seo) resolve can=true → no badge. Legacy
            // 'pro' flag still honored as a fallback.
            if (isset($tab['feature']) && class_exists('SEOFORGE_License')) {
                $show_pro = !SEOFORGE_License::can($tab['feature']);
            } else {
                $show_pro = !empty($tab['pro']) && !$is_pro;
            }
            printf(
                '<a href="%s" class="%s"%s><span class="forge-tab__label" data-label="%s"><span>%s</span></span>%s</a>',
                esc_url($url),
                esc_attr($cls),
                $is_active ? ' aria-current="page"' : '',
                esc_attr($tab['label']),
                esc_html($tab['label']),
                $show_pro ? '<span class="forge-tab-pro">PRO</span>' : ''
            );
        }
        echo '</nav>';
    }

    private static function print_styles() {
        if (self::$styles_printed) return;
        self::$styles_printed = true;
        ?>
        <style id="forge-tabs-css">
            .fs-notice .fs-plugin-title { display: none !important; }
            .fs-notice.fs-has-title    { margin-bottom: 0 !important; }
            .forge-tabs {
                display: flex;
                gap: 2px;
                margin: 6px 0 20px;
                font-size: 14px;
                flex-wrap: nowrap;
                background: #fff;
                padding: 4px 6px 0;
                align-items: flex-end;
                border: 1px solid #e5e7eb;
                border-radius: 8px;
                box-shadow: 0 1px 2px rgba(15,23,42,.04);
            }
            .forge-tabs .forge-tab {
                padding: 9px 14px;
                text-decoration: none !important;
                color: #50575e;
                border: 0;
                box-shadow: inset 0 -2px 0 transparent;
                transition: color .12s ease, box-shadow .12s ease, background .12s ease;
                display: inline-flex;
                align-items: center;
                gap: 6px;
                line-height: 1.3;
                white-space: nowrap;
                border-radius: 6px 6px 0 0;
            }
            .forge-tabs .forge-tab:hover,
            .forge-tabs .forge-tab:focus {
                color: #1d2327;
                background: #f3f4f6;
                text-decoration: none !important;
                outline: none;
            }
            .forge-tabs .forge-tab.is-active {
                color: var(--forge-tab-accent, #2271b1);
                box-shadow: inset 0 -2px 0 var(--forge-tab-accent, #2271b1);
                background: transparent;
            }
            .forge-tabs .forge-tab__label { display: inline-grid; grid-template-areas: 'stack'; }
            .forge-tabs .forge-tab__label > span,
            .forge-tabs .forge-tab__label::before { grid-area: stack; }
            .forge-tabs .forge-tab__label::before { content: attr(data-label); font-weight: 600; visibility: hidden; pointer-events: none; }
            .forge-tabs .forge-tab.is-active .forge-tab__label > span { font-weight: 600; }
            .forge-tabs .forge-tab-pro {
                font-size: 14px;
                padding: 2px 5px;
                background: #fff4e5;
                color: #b45309;
                border: 1px solid #fcd9a8;
                border-radius: 3px;
                letter-spacing: .4px;
                font-weight: 700;
                text-transform: uppercase;
                line-height: 1;
            }
            .lf-forge-tabs  { --forge-tab-accent: #0e8a7a; }
            .sf-forge-tabs  { --forge-tab-accent: #e67e22; }
            .ff-forge-tabs  { --forge-tab-accent: #2271b1; }
            .fdf-forge-tabs { --forge-tab-accent: #d14578; }
            .wrap:has(> .forge-tabs) { min-width: min-content; }
        </style>
        <?php
    }
}
