<?php

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

/**
 * MCP Server admin settings page.
 *
 * Provides token generation, active token management, and connection
 * instructions for Claude Desktop and Claude Code.
 *
 * @since 0.10.69
 */
class Niwa_AI_Admin_MCP_Settings {

    /**
     * Register WordPress hooks.
     */
    public function register_hooks() {
        add_action( 'admin_menu', array( $this, 'add_submenu' ) );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
    }

    /**
     * Add MCP submenu page under Niwa AI.
     */
    public function add_submenu() {
        add_submenu_page(
            'niwa-ai',
            __( 'Niwa MCP', 'niwa-ai' ),
            __( 'Niwa MCP', 'niwa-ai' ),
            'manage_options',
            'niwa-ai-mcp',
            array( $this, 'render_page' )
        );
    }

    /**
     * Enqueue MCP admin JS and pass localized data.
     *
     * @param string $hook The current admin page hook suffix.
     */
    public function enqueue_scripts( $hook ) {
        if ( 'niwa-ai_page_niwa-ai-mcp' !== $hook ) {
            return;
        }

        $js_path    = dirname( dirname( __FILE__ ) ) . '/assets/js/niwa-admin-mcp.js';
        $js_version = file_exists( $js_path ) ? (string) filemtime( $js_path ) : NIWA_AI_VERSION;

        wp_enqueue_script(
            'niwa-admin-mcp',
            plugin_dir_url( dirname( __FILE__ ) ) . 'assets/js/niwa-admin-mcp.js',
            array(),
            $js_version,
            true
        );

        wp_localize_script( 'niwa-admin-mcp', 'niwaMcpAdmin', array(
            'restUrl'   => esc_url_raw( rest_url( 'niwa-ai/v1' ) ),
            'nonce'     => wp_create_nonce( 'wp_rest' ),
            'serverUrl' => esc_url_raw( rest_url( 'niwa-ai/v1/mcp' ) ),
        ) );
    }

    /**
     * Render the MCP settings page with all 5 sections.
     */
    public function render_page() {
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'Insufficient permissions.', 'niwa-ai' ) );
        }

        $server_url = rest_url( 'niwa-ai/v1/mcp' );

        // ── MCP-specific inline styles ──
        ?>
        <style>
            .niwa-mcp-endpoint {
                background: var(--niwa-surface-2, #1e1e2e);
                border: 1px solid var(--niwa-border, rgba(255,255,255,0.08));
                border-radius: 8px;
                padding: 14px 18px;
                font-family: 'SF Mono', 'Fira Code', 'Cascadia Code', monospace;
                font-size: 13px;
                color: var(--niwa-ink-1, #e2e8f0);
                word-break: break-all;
                line-height: 1.6;
            }
            .niwa-mcp-code-block {
                position: relative;
                background: var(--niwa-surface-2, #1e1e2e);
                border: 1px solid var(--niwa-border, rgba(255,255,255,0.08));
                border-radius: 8px;
                padding: 16px 18px;
                font-family: 'SF Mono', 'Fira Code', 'Cascadia Code', monospace;
                font-size: 12.5px;
                color: var(--niwa-ink-1, #e2e8f0);
                white-space: pre-wrap;
                word-break: break-all;
                line-height: 1.7;
                overflow-x: auto;
            }
            .niwa-mcp-code-block .niwa-mcp-copy-btn {
                position: absolute;
                top: 8px;
                right: 8px;
            }
            .niwa-mcp-copy-btn {
                display: inline-flex;
                align-items: center;
                gap: 5px;
                padding: 5px 12px;
                font-size: 12px;
                font-weight: 500;
                border: 1px solid var(--niwa-border, rgba(255,255,255,0.12));
                border-radius: 6px;
                background: var(--niwa-surface-3, #2a2a3e);
                color: var(--niwa-ink-2, #94a3b8);
                cursor: pointer;
                transition: all 0.15s ease;
            }
            .niwa-mcp-copy-btn:hover {
                background: var(--niwa-accent, #6366f1);
                color: #fff;
                border-color: var(--niwa-accent, #6366f1);
            }
            .niwa-mcp-copy-btn.copied {
                background: var(--niwa-success, #22c55e);
                color: #fff;
                border-color: var(--niwa-success, #22c55e);
            }
            .niwa-mcp-token-result {
                display: none;
                margin-top: 16px;
                padding: 16px;
                background: var(--niwa-surface-2, #1e1e2e);
                border: 1px solid var(--niwa-success, #22c55e);
                border-radius: 8px;
            }
            .niwa-mcp-token-result.visible {
                display: block;
            }
            .niwa-mcp-token-value {
                display: flex;
                align-items: center;
                gap: 10px;
                margin-top: 8px;
            }
            .niwa-mcp-token-value code {
                flex: 1;
                display: block;
                padding: 10px 14px;
                background: var(--niwa-surface-1, #111827);
                border: 1px solid var(--niwa-border, rgba(255,255,255,0.08));
                border-radius: 6px;
                font-family: 'SF Mono', 'Fira Code', 'Cascadia Code', monospace;
                font-size: 13px;
                color: var(--niwa-accent, #6366f1);
                word-break: break-all;
                line-height: 1.5;
            }
            .niwa-mcp-token-warning {
                display: flex;
                align-items: center;
                gap: 8px;
                margin-top: 10px;
                padding: 10px 14px;
                background: rgba(234, 179, 8, 0.08);
                border: 1px solid rgba(234, 179, 8, 0.25);
                border-radius: 6px;
                font-size: 12.5px;
                color: var(--niwa-warning, #eab308);
            }
            .niwa-mcp-generate-row {
                display: flex;
                align-items: center;
                gap: 12px;
                flex-wrap: wrap;
            }
            .niwa-mcp-generate-row select {
                padding: 8px 12px;
                border: 1px solid var(--niwa-border, rgba(255,255,255,0.12));
                border-radius: 6px;
                background: var(--niwa-surface-2, #1e1e2e);
                color: var(--niwa-ink-1, #e2e8f0);
                font-size: 13px;
                min-width: 160px;
            }
            .niwa-mcp-table-wrap {
                overflow-x: auto;
            }
            .niwa-mcp-status-dot {
                display: inline-block;
                width: 8px;
                height: 8px;
                border-radius: 50%;
                margin-right: 6px;
            }
            .niwa-mcp-status-dot--active {
                background: var(--niwa-success, #22c55e);
                box-shadow: 0 0 6px rgba(34, 197, 94, 0.4);
            }
            #niwa-mcp-tokens-loading {
                text-align: center;
                padding: 20px;
                color: var(--niwa-ink-3, #64748b);
                font-size: 13px;
            }
        </style>
        <?php

        // ── Page wrapper ──
        echo '<div class="wrap niwa-wrap">';

        // ── Page header ──
        echo '<div class="niwa-page-header">';
        echo '<div class="niwa-page-header__icon">';
        echo '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="20" height="14" rx="2" ry="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg>';
        echo '</div>';
        echo '<div class="niwa-page-header__text">';
        echo '<h1 class="niwa-page-header__title">' . esc_html__( 'Niwa MCP', 'niwa-ai' ) . '</h1>';
        echo '<p class="niwa-page-header__subtitle">' . esc_html__( 'Model Context Protocol server — connect Claude Desktop, Claude Code, or any MCP-compatible client to your WordPress site.', 'niwa-ai' ) . '</p>';
        echo '</div>';
        echo '</div>';

        // ─────────────────────────────────────────
        // Card 1: MCP Server Info
        // ─────────────────────────────────────────
        echo '<div class="niwa-card">';
        echo '<div class="niwa-card__header">';
        echo '<div class="niwa-card__icon"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="20" height="8" rx="2" ry="2"/><rect x="2" y="14" width="20" height="8" rx="2" ry="2"/><line x1="6" y1="6" x2="6.01" y2="6"/><line x1="6" y1="18" x2="6.01" y2="18"/></svg></div>';
        echo '<h2 class="niwa-card__title">' . esc_html__( 'MCP Server Info', 'niwa-ai' ) . '</h2>';
        echo '</div>';
        echo '<div class="niwa-card__body">';

        echo '<div class="niwa-stats">';

        // Endpoint URL.
        echo '<div class="niwa-stat" style="grid-column: 1 / -1;">';
        echo '<div class="niwa-stat__label">' . esc_html__( 'MCP Endpoint URL', 'niwa-ai' ) . '</div>';
        echo '<div class="niwa-mcp-endpoint">' . esc_url( $server_url ) . '</div>';
        echo '</div>';

        echo '</div>'; // .niwa-stats

        echo '<div class="niwa-stats" style="margin-top: 16px;">';

        // Auth Header.
        echo '<div class="niwa-stat">';
        echo '<div class="niwa-stat__label">' . esc_html__( 'Auth Header', 'niwa-ai' ) . '</div>';
        echo '<div class="niwa-stat__value"><code>X-Niwa-MCP-Token</code></div>';
        echo '</div>';

        // Protocol.
        echo '<div class="niwa-stat">';
        echo '<div class="niwa-stat__label">' . esc_html__( 'Protocol', 'niwa-ai' ) . '</div>';
        echo '<div class="niwa-stat__value">' . esc_html__( 'MCP 2024-11-05 (Streamable HTTP)', 'niwa-ai' ) . '</div>';
        echo '</div>';

        // Status.
        echo '<div class="niwa-stat">';
        echo '<div class="niwa-stat__label">' . esc_html__( 'Status', 'niwa-ai' ) . '</div>';
        echo '<div class="niwa-stat__value"><span class="niwa-mcp-status-dot niwa-mcp-status-dot--active"></span>' . esc_html__( 'Active', 'niwa-ai' ) . '</div>';
        echo '</div>';

        echo '</div>'; // .niwa-stats

        echo '</div>'; // .niwa-card__body
        echo '</div>'; // .niwa-card

        // ─────────────────────────────────────────
        // Card 2: Generate Token
        // ─────────────────────────────────────────
        echo '<div class="niwa-card">';
        echo '<div class="niwa-card__header">';
        echo '<div class="niwa-card__icon"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg></div>';
        echo '<h2 class="niwa-card__title">' . esc_html__( 'Generate Token', 'niwa-ai' ) . '</h2>';
        echo '</div>';
        echo '<div class="niwa-card__body">';

        echo '<div class="niwa-field">';
        echo '<span class="niwa-field__hint">' . esc_html__( 'Create a new MCP authentication token. Choose how long it should remain valid.', 'niwa-ai' ) . '</span>';
        echo '</div>';

        echo '<div class="niwa-mcp-generate-row">';
        echo '<select id="niwa-mcp-duration">';
        echo '<option value="1_day">' . esc_html__( '1 Day', 'niwa-ai' ) . '</option>';
        echo '<option value="1_month">' . esc_html__( '1 Month', 'niwa-ai' ) . '</option>';
        echo '<option value="1_year" selected>' . esc_html__( '1 Year', 'niwa-ai' ) . '</option>';
        echo '<option value="never">' . esc_html__( 'No Expiration', 'niwa-ai' ) . '</option>';
        echo '</select>';
        echo '<button type="button" class="button niwa-btn niwa-btn--primary" id="niwa-mcp-generate-btn">';
        echo '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-right:4px;vertical-align:-2px;"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>';
        echo esc_html__( 'Generate Token', 'niwa-ai' );
        echo '</button>';
        echo '</div>';
		echo '<label style="display:block;margin-top:12px;"><input type="checkbox" id="niwa-mcp-read-options" value="1" /> ';
		echo esc_html__( 'Allow this external token to use wp_option_get (may expose sensitive WordPress configuration).', 'niwa-ai' );
		echo '</label>';

        // Token result area (hidden until generated).
        echo '<div id="niwa-mcp-token-result" class="niwa-mcp-token-result">';
        echo '<strong>' . esc_html__( 'Your new token:', 'niwa-ai' ) . '</strong>';
        echo '<div class="niwa-mcp-token-value">';
        echo '<code id="niwa-mcp-token-value"></code>';
        echo '<button type="button" class="niwa-mcp-copy-btn" data-copy-target="niwa-mcp-token-value">';
        echo '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>';
        echo esc_html__( 'Copy', 'niwa-ai' );
        echo '</button>';
        echo '</div>';
        echo '<div class="niwa-mcp-token-warning">';
        echo '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>';
        echo esc_html__( 'Copy this token now. It will not be shown again.', 'niwa-ai' );
        echo '</div>';
        echo '</div>';

        echo '</div>'; // .niwa-card__body
        echo '</div>'; // .niwa-card

        // ─────────────────────────────────────────
        // Card 3: Active Tokens
        // ─────────────────────────────────────────
        echo '<div class="niwa-card">';
        echo '<div class="niwa-card__header">';
        echo '<div class="niwa-card__icon"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg></div>';
        echo '<h2 class="niwa-card__title">' . esc_html__( 'Active Tokens', 'niwa-ai' ) . '</h2>';
        echo '</div>';
        echo '<div class="niwa-card__body" style="padding:0;overflow-x:auto;">';

        echo '<div id="niwa-mcp-tokens-loading">' . esc_html__( 'Loading tokens...', 'niwa-ai' ) . '</div>';

        echo '<table class="niwa-table" id="niwa-mcp-tokens-table" style="display:none;">';
        echo '<thead><tr>';
        echo '<th>' . esc_html__( 'Token ID', 'niwa-ai' ) . '</th>';
        echo '<th>' . esc_html__( 'User', 'niwa-ai' ) . '</th>';
        echo '<th>' . esc_html__( 'Created', 'niwa-ai' ) . '</th>';
        echo '<th>' . esc_html__( 'Expires', 'niwa-ai' ) . '</th>';
        echo '<th>' . esc_html__( 'Duration', 'niwa-ai' ) . '</th>';
		echo '<th>' . esc_html__( 'Scopes', 'niwa-ai' ) . '</th>';
        echo '<th>' . esc_html__( 'Actions', 'niwa-ai' ) . '</th>';
        echo '</tr></thead>';
        echo '<tbody id="niwa-mcp-tokens-body"></tbody>';
        echo '</table>';

        echo '<div id="niwa-mcp-tokens-empty" style="display:none;text-align:center;padding:24px;color:var(--niwa-ink-3,#64748b);font-size:13px;">';
        echo esc_html__( 'No active tokens. Generate one above to get started.', 'niwa-ai' );
        echo '</div>';

        echo '</div>'; // .niwa-card__body
        echo '</div>'; // .niwa-card

        // ─────────────────────────────────────────
        // Card 4: Claude Desktop Configuration
        // ─────────────────────────────────────────
        $claude_desktop_json = wp_json_encode(
            array(
                'mcpServers' => array(
                    'niwa-ai' => array(
                        'url'     => $server_url,
                        'headers' => array(
                            'X-Niwa-MCP-Token' => 'YOUR_TOKEN_HERE',
                        ),
                    ),
                ),
            ),
            JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES
        );

        echo '<div class="niwa-card">';
        echo '<div class="niwa-card__header">';
        echo '<div class="niwa-card__icon"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="20" height="14" rx="2" ry="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg></div>';
        echo '<h2 class="niwa-card__title">' . esc_html__( 'Claude Desktop Configuration', 'niwa-ai' ) . '</h2>';
        echo '</div>';
        echo '<div class="niwa-card__body">';

        echo '<div class="niwa-field">';
        echo '<span class="niwa-field__hint">' . esc_html__( 'Add this configuration to your Claude Desktop settings file. On macOS: ~/Library/Application Support/Claude/claude_desktop_config.json. On Windows: %APPDATA%\\Claude\\claude_desktop_config.json. Replace YOUR_TOKEN_HERE with the token generated above.', 'niwa-ai' ) . '</span>';
        echo '</div>';

        echo '<div class="niwa-mcp-code-block" id="niwa-mcp-claude-desktop-config">';
        echo '<button type="button" class="niwa-mcp-copy-btn" data-copy-target="niwa-mcp-claude-desktop-config-text">';
        echo '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>';
        echo esc_html__( 'Copy', 'niwa-ai' );
        echo '</button>';
        echo '<span id="niwa-mcp-claude-desktop-config-text">' . esc_html( $claude_desktop_json ) . '</span>';
        echo '</div>';

        echo '</div>'; // .niwa-card__body
        echo '</div>'; // .niwa-card

        // ─────────────────────────────────────────
        // Card 5: Claude Code Configuration
        // ─────────────────────────────────────────
        $claude_code_cmd = 'claude mcp add niwa-ai --transport http --url ' . esc_url( $server_url ) . ' --header "X-Niwa-MCP-Token: YOUR_TOKEN_HERE"';

        echo '<div class="niwa-card">';
        echo '<div class="niwa-card__header">';
        echo '<div class="niwa-card__icon"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="4 17 10 11 4 5"/><line x1="12" y1="19" x2="20" y2="19"/></svg></div>';
        echo '<h2 class="niwa-card__title">' . esc_html__( 'Claude Code Configuration', 'niwa-ai' ) . '</h2>';
        echo '</div>';
        echo '<div class="niwa-card__body">';

        echo '<div class="niwa-field">';
        echo '<span class="niwa-field__hint">' . esc_html__( 'Run this command in your terminal to register the Niwa AI MCP server with Claude Code. Replace YOUR_TOKEN_HERE with the token generated above.', 'niwa-ai' ) . '</span>';
        echo '</div>';

        echo '<div class="niwa-mcp-code-block" id="niwa-mcp-claude-code-config">';
        echo '<button type="button" class="niwa-mcp-copy-btn" data-copy-target="niwa-mcp-claude-code-config-text">';
        echo '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>';
        echo esc_html__( 'Copy', 'niwa-ai' );
        echo '</button>';
        echo '<span id="niwa-mcp-claude-code-config-text">' . esc_html( $claude_code_cmd ) . '</span>';
        echo '</div>';

        echo '</div>'; // .niwa-card__body
        echo '</div>'; // .niwa-card

        echo '</div>'; // .wrap .niwa-wrap
    }
}
