<?php

namespace SoftminalB2B;

if (!defined('ABSPATH')) {
    exit;
}

use SoftminalB2B\Models\Conversation;
use SoftminalB2B\Support\Tier;

class Menu {
    private const SLUG = 'softminal-b2b-wholesale-for-woocommerce';

    public function init() {
        add_action('admin_menu', [$this, 'add_admin_menu']);
        add_action('admin_footer', [$this, 'print_submenu_highlighter']);
    }

    public function add_admin_menu() {
        $isPro = Tier::isPro();

        $title = $isPro
            ? __('B2B Suite Pro', 'softminal-b2b-wholesale-for-woocommerce')
            : __('B2B Suite', 'softminal-b2b-wholesale-for-woocommerce');

        add_menu_page(
            __('Softminal B2B Suite for WooCommerce', 'softminal-b2b-wholesale-for-woocommerce'),
            $title . $this->unreadBubble(),
            'manage_options',
            self::SLUG,
            [$this, 'render_dashboard'],
            $this->menuIcon(),
            58
        );

        // Rename the auto-created first submenu (which duplicates the menu title)
        // to "Dashboard" by registering it explicitly against the same slug.
        add_submenu_page(
            self::SLUG,
            __('Dashboard', 'softminal-b2b-wholesale-for-woocommerce'),
            __('Dashboard', 'softminal-b2b-wholesale-for-woocommerce'),
            'manage_options',
            self::SLUG,
            [$this, 'render_dashboard']
        );

        $this->add_deep_link_submenus();
    }

    /**
     * The SPA is a single admin page with hash routing, so its screens have no
     * distinct `page` slug of their own. We surface the most-used destinations
     * as native WordPress submenu items by pushing hash-deep-links straight into
     * the $submenu global — the one reliable way to get `admin.php?page=…#/route`
     * links that WordPress won't URL-encode the `#` out of.
     */
    private function add_deep_link_submenus(): void {
        global $submenu;

        foreach ($this->deep_links() as $item) {
            $submenu[self::SLUG][] = [
                $item['label'],
                'manage_options',
                'admin.php?page=' . self::SLUG . '#' . $item['route'],
            ];
        }
    }

    /**
     * Curated WordPress submenu — the daily destinations, not the full nav.
     * Labels mirror the in-app menu; Pro-only screens appear only on Pro.
     *
     * @return array<int, array{label: string, route: string}>
     */
    private function deep_links(): array {
        $isPro = Tier::isPro();

        $links = [
            ['label' => __('Customer Groups', 'softminal-b2b-wholesale-for-woocommerce'), 'route' => '/groups'],
            ['label' => __('Price Rules', 'softminal-b2b-wholesale-for-woocommerce'),     'route' => '/price-rules'],
            ['label' => __('Customers', 'softminal-b2b-wholesale-for-woocommerce'),        'route' => '/customers'],
            ['label' => __('Registrations', 'softminal-b2b-wholesale-for-woocommerce'),    'route' => '/registrations'],
            ['label' => __('Messages', 'softminal-b2b-wholesale-for-woocommerce'),         'route' => '/messages'],
        ];

        if ($isPro) {
            $links[] = ['label' => __('Companies', 'softminal-b2b-wholesale-for-woocommerce'), 'route' => '/companies'];
            $links[] = ['label' => __('Quotes', 'softminal-b2b-wholesale-for-woocommerce'),    'route' => '/quotes'];
        }

        $links[] = ['label' => __('Migration', 'softminal-b2b-wholesale-for-woocommerce'), 'route' => '/settings/import'];
        $links[] = ['label' => __('Settings', 'softminal-b2b-wholesale-for-woocommerce'),  'route' => '/settings/general'];

        return $links;
    }

    /**
     * WordPress highlights submenu items by their `page` query arg, which is the
     * same for every hash route here, so it would always mark "Dashboard" active.
     * This small script (only on our page) syncs the `.current` class to the
     * live hash instead, keeping the WP submenu in step with the SPA.
     */
    public function print_submenu_highlighter(): void {
        $screen = function_exists('get_current_screen') ? get_current_screen() : null;

        if (!$screen || strpos((string) $screen->id, self::SLUG) === false) {
            return;
        }

        ?>
        <script>
        (function () {
            var slug = '<?php echo esc_js(self::SLUG); ?>';
            var menu = document.querySelector('#toplevel_page_' + slug);
            if (!menu) { return; }
            var links = menu.querySelectorAll('ul.wp-submenu a');

            function sync() {
                var hash = window.location.hash || '#/';
                var active = null;
                links.forEach(function (a) {
                    var li = a.parentNode;
                    var href = a.getAttribute('href') || '';
                    var idx = href.indexOf('#');
                    var route = idx === -1 ? '#/' : href.slice(idx);
                    var isMatch = route === '#/'
                        ? (hash === '#/' || hash === '' || hash === '#')
                        : hash.indexOf(route) === 0;
                    li.classList.remove('current');
                    a.classList.remove('current');
                    if (isMatch && (!active || route.length > active.route.length)) {
                        active = { li: li, a: a, route: route };
                    }
                });
                if (active) {
                    active.li.classList.add('current');
                    active.a.classList.add('current');
                }
            }

            sync();
            window.addEventListener('hashchange', sync);
        })();
        </script>
        <?php
    }

    /**
     * A WooCommerce-style count bubble on the menu item for unread buyer
     * messages, so a merchant who lives in wp-admin (not the SPA) still sees a
     * thread is waiting. Empty when nothing is unread. Server-rendered per page
     * load — the SPA bell covers live updates while the app is open.
     */
    private function unreadBubble(): string {
        $count = Conversation::unreadThreadCountForShop();

        if ($count < 1) {
            return '';
        }

        return sprintf(
            ' <span class="awaiting-mod update-plugins count-%1$d"><span class="pending-count">%2$s</span></span>',
            (int) $count,
            esc_html(number_format_i18n($count))
        );
    }

    private function menuIcon(): string {
        $svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">'
            . '<rect x="3" y="5" width="9" height="4" rx="2"/>'
            . '<rect x="3" y="10" width="14" height="4" rx="2"/>'
            . '<rect x="3" y="15" width="18" height="4" rx="2"/>'
            . '</svg>';

        // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- Required for a WordPress SVG menu icon
        return 'data:image/svg+xml;base64,' . base64_encode($svg);
    }

    public function render_dashboard() {
        wp_enqueue_media();
        echo '<div id="softminal-b2b-wholesale-for-woocommerce-app"></div>';
    }
}
