<?php

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

class AIEO_IAPI_Admin {

    const MENU_SLUG     = 'aieo-iapi';
    const NONCE_ACTION  = 'aieo_iapi_save';
    const FORM_ACTION   = 'aieo_iapi_save_settings';
    const CAPABILITY    = 'manage_options';

    
    private static $instance = null;

    public static function instance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        add_action('admin_menu',                          array($this, 'register_menu'), 25);
        add_action('admin_post_' . self::FORM_ACTION,     array($this, 'handle_save'));
        add_action('admin_enqueue_scripts',               array($this, 'enqueue_assets'));
    }

    public function register_menu() {
        add_submenu_page(
            'ai-eshop-optimizer',
            __('Interactivity (IAPI)', 'ai-eshop-optimizer'),
            '🔌 ' . __('Interactivity (IAPI)', 'ai-eshop-optimizer'),
            self::CAPABILITY,
            self::MENU_SLUG,
            array($this, 'render_page')
        );
    }

    public function enqueue_assets($hook_suffix) {
        if (strpos((string) $hook_suffix, self::MENU_SLUG) === false) { return; }
        
        
        wp_enqueue_style(
            'ai-eshop-optimizer-admin',
            AIEO_URI . 'assets/css/aieo-admin-panel.css',
            array(),
            AIEO_VERSION . '.iapi'
        );
        wp_add_inline_style('ai-eshop-optimizer-admin', $this->inline_css());
    }

    private function inline_css() {
        return '.aieo-iapi-grid{display:grid;gap:14px;grid-template-columns:repeat(auto-fill,minmax(320px,1fr));margin-top:16px}'
            . '.aieo-iapi-card{border:1px solid #e1e1e1;border-radius:8px;background:#fff;padding:16px}'
            . '.aieo-iapi-card h3{margin:0 0 4px;font-size:14px;font-weight:600}'
            . '.aieo-iapi-card .desc{color:#646970;font-size:12px;margin:0 0 12px}'
            . '.aieo-iapi-card .opts{display:flex;gap:14px;flex-wrap:wrap;margin:0}'
            . '.aieo-iapi-card label{display:inline-flex;align-items:center;gap:5px;font-size:13px;cursor:pointer}'
            . '.aieo-iapi-badge{display:inline-block;padding:2px 8px;border-radius:11px;font-size:11px;font-weight:600;letter-spacing:.02em;text-transform:uppercase;margin-left:6px;vertical-align:middle}'
            . '.aieo-iapi-badge--production{background:#dcfce7;color:#15803d}'
            . '.aieo-iapi-badge--scaffold{background:#fef3c7;color:#92400e}'
            . '.aieo-iapi-badge--unknown{background:#f3f4f6;color:#374151}'
            . '.aieo-iapi-master{display:flex;align-items:center;gap:14px;padding:14px 16px;border:1px solid #c3c4c7;border-radius:6px;background:#f8fafc;margin:16px 0}'
            . '.aieo-iapi-master .state{font-weight:600}'
            . '.aieo-iapi-master .state.on{color:#15803d}'
            . '.aieo-iapi-master .state.off{color:#b32d2e}'
            . '.aieo-iapi-toolrow{display:flex;flex-wrap:wrap;gap:10px;margin:14px 0 0}'
            . '.aieo-iapi-tool{display:inline-flex;align-items:center;gap:6px;padding:6px 12px;border:1px solid #c3c4c7;border-radius:4px;background:#fff;font-size:13px;text-decoration:none}'
            . '.aieo-iapi-tool:hover{background:#f0f0f1}'
            . '.aieo-iapi-note{padding:10px 14px;border-left:4px solid #2271b1;background:#f0f6fc;margin:8px 0;font-size:13px}'
            . '.aieo-iapi-note.warn{border-color:#dba617;background:#fcf9e8}'
            . '.aieo-iapi-flagstate{font-size:11px;color:#646970;margin-top:8px}'
            . '.aieo-iapi-flagstate code{background:#f0f0f1;padding:1px 5px;border-radius:3px;font-size:11px}';
    }

    
    private function modules() {
        return array(
            'pricing' => array(
                'label' => __('Pricing batch (REST)', 'ai-eshop-optimizer'),
                'desc'  => __('Batch effective-price lookup via /aieo/v1/pricing/batch. Read-only; safe to leave on.', 'ai-eshop-optimizer'),
            ),
            'wishlist' => array(
                'label' => __('Wishlist heart', 'ai-eshop-optimizer'),
                'desc'  => __('Heart toggle, optimistic paint with rollback, cookie sync, multi-heart sync, "See your favourites" label.', 'ai-eshop-optimizer'),
            ),
            'waitlist' => array(
                'label' => __('Waitlist', 'ai-eshop-optimizer'),
                'desc'  => __('"Notify me when back in stock" form: email validation, loading overlay, WC variation integration.', 'ai-eshop-optimizer'),
            ),
            'complementary' => array(
                'label' => __('Complementary products', 'ai-eshop-optimizer'),
                'desc'  => __('Multi-checkbox batch add-to-cart. Routes fragments through the IAPI cart store.', 'ai-eshop-optimizer'),
            ),
            'reco' => array(
                'label' => __('Recommendations (events only)', 'ai-eshop-optimizer'),
                'desc'  => __('No standalone shim — emits aieo:reco:rendered after each section mounts. Per-card UI lives in the wishlist/swatches modules.', 'ai-eshop-optimizer'),
            ),
            'ratings' => array(
                'label' => __('Star ratings', 'ai-eshop-optimizer'),
                'desc'  => __('5-star product rating widget with per-product aggregate. Optimistic paint + rollback, batch REST hydration on archives, anonymous-cookie scoping.', 'ai-eshop-optimizer'),
            ),
            'swatches' => array(
                'label' => __('Swatches', 'ai-eshop-optimizer'),
                'desc'  => __('Single-select hydration only. Multi-select / quick-view modal / cart-sync markers NOT IMPLEMENTED — see ROADMAP.md, Phase C-θ.', 'ai-eshop-optimizer'),
            ),
            'sticky_atc' => array(
                'label' => __('Sticky add-to-cart', 'ai-eshop-optimizer'),
                'desc'  => __('IO-based visibility + cart-store add. Multi-select sticky / persistent sticky / smart auto-pick NOT IMPLEMENTED — Phase C-ι.', 'ai-eshop-optimizer'),
            ),
            'side_cart' => array(
                'label' => __('Side cart', 'ai-eshop-optimizer'),
                'desc'  => __('Qty/remove/close handlers. Drawer rendering still legacy. Coupons / RV+Favorites tabs NOT IMPLEMENTED — Phase C-κ.', 'ai-eshop-optimizer'),
            ),
        );
    }

    private function module_statuses() {
        if (method_exists('AIEO_DMM', 'get_iapi_module_statuses')) {
            return AIEO_DMM::get_iapi_module_statuses();
        }
        return array();
    }

    public function render_page() {
        if (!current_user_can(self::CAPABILITY)) {
            wp_die(esc_html__('You do not have permission to access this page.', 'ai-eshop-optimizer'));
        }

        $master_on = (bool) get_option('roosterx_iapi_enabled', false);
        $modules   = $this->modules();
        $statuses  = $this->module_statuses();
        $saved     = isset($_GET['aieo_iapi_saved']) && $_GET['aieo_iapi_saved'] === '1';

        $theme_settings_url = admin_url('themes.php?page=roosterx-settings');
        
        
        $rest_url = esc_url(rest_url('aieo/v1/pricing/batch'));
        ?>
        <div class="wrap aieo-admin">
            <h1>🔌 <?php esc_html_e('Interactivity (IAPI)', 'ai-eshop-optimizer'); ?></h1>
            <p class="description"><?php esc_html_e('Roll out the WordPress Interactivity API to AIEO frontend modules. Master switch is owned by the Rooster X theme; per-module cutover happens here.', 'ai-eshop-optimizer'); ?></p>

            <?php if ($saved): ?>
                <div class="notice notice-success is-dismissible"><p><?php esc_html_e('IAPI settings saved.', 'ai-eshop-optimizer'); ?></p></div>
            <?php endif; ?>

            <div class="aieo-iapi-master">
                <div>
                    <strong><?php esc_html_e('Master switch (foundation):', 'ai-eshop-optimizer'); ?></strong>
                    <span class="state <?php echo $master_on ? 'on' : 'off'; ?>">
                        <?php echo $master_on ? esc_html__('ON', 'ai-eshop-optimizer') : esc_html__('OFF', 'ai-eshop-optimizer'); ?>
                    </span>
                </div>
                <div style="flex:1">
                    <p style="margin:0;font-size:12px;color:#646970">
                        <?php
                        printf(
                            
                            esc_html__('Reads %s. Loads the IAPI bootstrap (stores, REST endpoint, public CustomEvents) regardless of per-module flags. Owned by the Rooster X theme.', 'ai-eshop-optimizer'),
                            '<code>roosterx_iapi_enabled</code>'
                        );
                        ?>
                    </p>
                </div>
                <a class="button button-secondary" href="<?php echo esc_url($theme_settings_url); ?>">
                    <?php esc_html_e('Open theme settings', 'ai-eshop-optimizer'); ?> →
                </a>
            </div>

            <h2 style="margin-top:24px"><?php esc_html_e('Per-module cutover', 'ai-eshop-optimizer'); ?></h2>
            <p class="description">
                <?php esc_html_e('Each module has three states: Inherit (= Off — explicit cutover required), On (use the IAPI shim when production-ready), Off (force legacy jQuery). Scaffold modules are blocked by a safety gate even when set to On.', 'ai-eshop-optimizer'); ?>
            </p>

            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                <input type="hidden" name="action" value="<?php echo esc_attr(self::FORM_ACTION); ?>">
                <?php wp_nonce_field(self::NONCE_ACTION); ?>

                <div class="aieo-iapi-grid">
                    <?php foreach ($modules as $slug => $info): ?>
                        <?php
                        $opt_key = 'aieo_dmm_' . $slug . '_iapi_enabled';
                        $current = (string) get_option($opt_key, 'inherit');
                        $status  = isset($statuses[$slug]) ? $statuses[$slug] : 'unknown';
                        $is_active = method_exists('AIEO_DMM', 'is_iapi_enabled')
                            ? AIEO_DMM::is_iapi_enabled($slug)
                            : false;
                        ?>
                        <div class="aieo-iapi-card">
                            <h3>
                                <?php echo esc_html($info['label']); ?>
                                <span class="aieo-iapi-badge aieo-iapi-badge--<?php echo esc_attr($status); ?>">
                                    <?php echo esc_html($status); ?>
                                </span>
                            </h3>
                            <p class="desc"><?php echo esc_html($info['desc']); ?></p>

                            <div class="opts">
                                <label>
                                    <input type="radio" name="aieo_iapi[<?php echo esc_attr($slug); ?>]" value="inherit" <?php checked($current, 'inherit'); ?>>
                                    <?php esc_html_e('Inherit', 'ai-eshop-optimizer'); ?>
                                </label>
                                <label>
                                    <input type="radio" name="aieo_iapi[<?php echo esc_attr($slug); ?>]" value="yes" <?php checked($current, 'yes'); ?>>
                                    <?php esc_html_e('On', 'ai-eshop-optimizer'); ?>
                                </label>
                                <label>
                                    <input type="radio" name="aieo_iapi[<?php echo esc_attr($slug); ?>]" value="no" <?php checked($current, 'no'); ?>>
                                    <?php esc_html_e('Off', 'ai-eshop-optimizer'); ?>
                                </label>
                            </div>

                            <p class="aieo-iapi-flagstate">
                                <?php
                                printf(
                                    
                                    esc_html__('option %1$s = %2$s · resolves: %3$s', 'ai-eshop-optimizer'),
                                    '<code>' . esc_html($opt_key) . '</code>',
                                    '<code>' . esc_html($current) . '</code>',
                                    $is_active
                                        ? '<strong style="color:#15803d">' . esc_html(_x('IAPI', 'IAPI branch label', 'ai-eshop-optimizer')) . '</strong>'
                                        : '<strong style="color:#646970">' . esc_html(_x('legacy', 'legacy branch label', 'ai-eshop-optimizer')) . '</strong>'
                                );
                                ?>
                                <?php if ($status === 'scaffold' && $current === 'yes'): ?>
                                    <br>
                                    <span style="color:#92400e">
                                        ⚠ <?php esc_html_e('Scaffold gate active — flag is ignored. Override with the aieo/iapi/allow_scaffold filter for dev only.', 'ai-eshop-optimizer'); ?>
                                    </span>
                                <?php endif; ?>
                            </p>
                        </div>
                    <?php endforeach; ?>
                </div>

                <p class="submit">
                    <button type="submit" class="button button-primary"><?php esc_html_e('Save Changes', 'ai-eshop-optimizer'); ?></button>
                </p>
            </form>

            <h2 style="margin-top:32px"><?php esc_html_e('Smoke tests & inspection', 'ai-eshop-optimizer'); ?></h2>
            <div class="aieo-iapi-toolrow">
                <a class="aieo-iapi-tool" href="<?php echo esc_url(home_url('/')); ?>" target="_blank" rel="noopener">
                    🌐 <?php esc_html_e('Open frontend', 'ai-eshop-optimizer'); ?>
                </a>
                <a class="aieo-iapi-tool" href="<?php echo esc_url($rest_url); ?>" target="_blank" rel="noopener">
                    🔍 <?php esc_html_e('Pricing batch endpoint', 'ai-eshop-optimizer'); ?>
                </a>
            </div>
            <div class="aieo-iapi-note">
                <strong><?php esc_html_e('DevTools console one-liners:', 'ai-eshop-optimizer'); ?></strong>
                <pre style="margin:6px 0 0;font-size:12px;background:#fff;padding:8px;border:1px solid #e1e1e1;border-radius:4px;white-space:pre-wrap">// after adding to cart on the frontend:
aieo.iapi.stores.cart.state.fragments

// pricing batch round-trip:
aieo.iapi.stores.pricing.actions.prefetch([487390])
  .then(() =&gt; aieo.iapi.stores.pricing.state.effectivePrice)

// wishlist state:
aieo.iapi.stores.wishlist.state.productIds</pre>
            </div>

            <h2 style="margin-top:32px"><?php esc_html_e('Docs', 'ai-eshop-optimizer'); ?></h2>
            <p>
                <?php
                $runtime_dir = defined('AIEO_RUNTIME_DIR') ? AIEO_RUNTIME_DIR : '';
                if ($runtime_dir) {
                    echo wp_kses_post(sprintf(
                        
                        __('Companion docs live in the runtime plugin: %s', 'ai-eshop-optimizer'),
                        '<code>' . esc_html($runtime_dir) . '</code>'
                    ));
                    echo '<ul style="margin-top:8px"><li><code>CONTRACT.md</code> — ' . esc_html__('public DOM/JS surface', 'ai-eshop-optimizer') . '</li>'
                       . '<li><code>STATUS.md</code> — ' . esc_html__('what\'s done + open TODOs (incl. multi-select swatches)', 'ai-eshop-optimizer') . '</li>'
                       . '<li><code>ROADMAP.md</code> — ' . esc_html__('sequenced next phases', 'ai-eshop-optimizer') . '</li></ul>';
                }
                ?>
            </p>
        </div>
        <?php
    }

    public function handle_save() {
        if (!current_user_can(self::CAPABILITY)) {
            wp_die(esc_html__('Insufficient permissions.', 'ai-eshop-optimizer'));
        }
        check_admin_referer(self::NONCE_ACTION);

        $allowed_slugs = array_keys($this->modules());
        $allowed_vals  = array('inherit', 'yes', 'no');

        $submitted = isset($_POST['aieo_iapi']) && is_array($_POST['aieo_iapi'])
            ? wp_unslash($_POST['aieo_iapi'])
            : array();

        foreach ($allowed_slugs as $slug) {
            $value = isset($submitted[$slug]) ? sanitize_key($submitted[$slug]) : 'inherit';
            if (!in_array($value, $allowed_vals, true)) { $value = 'inherit'; }
            update_option('aieo_dmm_' . $slug . '_iapi_enabled', $value, false);
        }

        wp_safe_redirect(add_query_arg(
            array('page' => self::MENU_SLUG, 'aieo_iapi_saved' => '1'),
            admin_url('admin.php')
        ));
        exit;
    }
}
