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

/**
 * LangForge admin section tabs.
 *
 * refactor (2026-05-05): replaced the old flat 9-tab horizontal
 * nav with a hub-scoped one. Pages are grouped under three hubs
 * (Translations / Reports / Tools), each with its OWN top-tab strip
 * showing only that hub's siblings — never the global flat list.
 *
 * Hub | Sub-tabs
 * --------------+-----------------------------------------------
 * Translations | String Translation, Menu Translation, Visual Editor [PRO]
 * Reports | Translation Status, Analytics [PRO]
 * Tools | Glossary, Translation Memory [PRO], Import/Export [PRO]
 *
 * Pages outside any hub (Languages / Migration / Settings / License /
 * Contact Us) render NO top tabs — they're top-level destinations.
 *
 * The tester also flagged that Translation Memory was free in the
 * sidebar but [PRO] in the tabs (rassyhron). Now that the sub-tabs
 * are hidden from the sidebar entirely, the only place a TM badge
 * shows is inside the Tools-hub tab strip — and it correctly says
 * [PRO] there.
 */
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound -- LF_ is the established plugin class prefix
class LF_Admin_Tabs {

    private static $styles_printed = false;

    /**
 * Hub configuration. Keep in sync with add_admin_menu in
 * admin/class-admin.php — both files reference these slug strings.
 */
    public static function hubs() {
        return [
            'translations' => [
                'parent' => 'lf-translations-hub',
                'label'  => __('Translations', 'langforge'),
                'tabs'   => [
                    ['slug' => 'lf-strings', 'label' => __('String Translation', 'langforge'), 'pro' => false],
                    ['slug' => 'lf-menus',   'label' => __('Menu Translation', 'langforge'),   'pro' => false],
                    ['slug' => 'lf-editor',  'label' => __('Visual Editor', 'langforge'),      'pro' => true],
                ],
            ],
            'reports' => [
                'parent' => 'lf-reports-hub',
                'label'  => __('Reports', 'langforge'),
                'tabs'   => [
                    ['slug' => 'lf-status',    'label' => __('Translation Status', 'langforge'), 'pro' => false],
                    ['slug' => 'lf-analytics', 'label' => __('Analytics', 'langforge'),          'pro' => true],
                ],
            ],
            'tools' => [
                'parent' => 'lf-tools-hub',
                'label'  => __('Tools', 'langforge'),
                // Unlike Translations/Reports — whose parent slug merely
                // dispatches to the first sub-tab — the Tools parent page has
                // its OWN content (Flush Rewrite Rules / Populate Translation
                // Memory / One-Click Site Duplication). `self_tab` makes
                // render prepend a "Tools" tab for that landing page so the
                // strip owns the active state on lf-tools-hub instead of
                // falsely lighting up Glossary (the first sub-tab).
                'self_tab' => true,
                'tabs'   => [
                    ['slug' => 'lf-glossary',      'label' => __('Glossary', 'langforge'),           'pro' => false],
                    ['slug' => 'lf-tm',            'label' => __('Translation Memory', 'langforge'), 'pro' => true],
                    ['slug' => 'lf-import-export', 'label' => __('Import / Export', 'langforge'),    'pro' => true],
                    // v2 (2026-05-05): Migration moves INSIDE the
                    // Tools hub per spec. Was previously a stand-alone
                    // sidebar item; tester flagged it as "Migration
                    
                    
                    // Slug stays `lf-migration` (deep links survive)
                    // but it's hidden from the sidebar by
                    // `hide_grouped_sidebar_items` and shows up
                    // here as the 4th tab inside Tools.
                    ['slug' => 'lf-migration',     'label' => __('Migration', 'langforge'),          'pro' => false],
                ],
            ],
        ];
    }

    /**
 * Which hub does this slug live in? Returns hub key
 * ('translations' / 'reports' / 'tools') or null for stand-alone
 * pages (Languages, Migration, Settings, License, Contact Us).
 */
    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. Hub-parent renderers dispatch to
 * this when no `?tab=` is given.
 */
    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.
 * Stand-alone pages get an empty render (no tabs by design).
 */
    public static function render($current = null) {
        if ($current === null) {
            $current = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin tab routing from current page slug, no data mutation.
        }
        $hub_key = self::hub_for_slug($current);
        if (!$hub_key) return;

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

        self::print_styles();

        // Hubs flagged `self_tab` (their parent page has its own content) get a
        // leading tab pointing at that landing page. Dispatch hubs (Translations
        // / Reports), whose parent just shows the first sub-tab, get none — there
        // the parent slug is represented by the first sub-tab itself.
        $tabs         = $hub['tabs'];
        $has_self_tab = !empty($hub['self_tab']);
        if ($has_self_tab) {
            array_unshift($tabs, ['slug' => $hub['parent'], 'label' => $hub['label'], 'pro' => false]);
        }

        echo '<nav class="forge-tabs lf-forge-tabs forge-tabs--hub forge-tabs--hub-' . esc_attr($hub_key) . '" aria-label="' .
             /* translators: %s: the hub/section label (e.g. the plugin or settings group name). */
             esc_attr(sprintf(__('%s sections', 'langforge'), $hub['label'])) . '">';
        foreach ($tabs as $tab) {
            $url       = admin_url('admin.php?page=' . $tab['slug']);
            $is_active = ($tab['slug'] === $current);
            // Dispatch hubs only: on the parent slug, highlight the first
            // sub-tab (the content the parent renders). Skipped for self_tab
            // hubs, where the parent already has its own dedicated tab above.
            if (!$is_active && !$has_self_tab && $hub['parent'] === $current) {
                $is_active = ($tab['slug'] === self::first_tab_slug($hub_key));
            }
            $cls       = 'forge-tab' . ($is_active ? ' is-active' : '');
            $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
    }
}
