<?php

/**
 * Sandbox View
 *
 * Test interface for AI configurations with persistent sessions,
 * rendered prompt display and configuration export.
 *
 * @package SlideMind
 * @since 2.0.0
 */
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
if ( !current_user_can( 'manage_slidemind_configs' ) ) {
    wp_die( esc_html__( 'You do not have permission to access this page.', 'slidemind' ) );
}
$plugin = \SlideMind\Plugin::instance();
$config_repo = $plugin->get_config_repository();
$llm_proxy = $plugin->get_llm_proxy();
// Defaults from settings
$sm_settings = wp_parse_args( get_option( 'slidemind_settings', [] ), [
    'default_model'       => 'anthropic/claude-3.5-sonnet',
    'default_temperature' => 0.7,
    'default_max_tokens'  => 1024,
] );
// Pre-selected configuration (read-only navigation params; capability checked above; values cast to int).
// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only navigation params; capability checked above; values cast to int.
$config_id = ( isset( $_GET['config_id'] ) ? (int) $_GET['config_id'] : 0 );
if ( !$config_id && isset( $_GET['slide_id'] ) ) {
    $config_id = (int) $_GET['slide_id'];
}
// phpcs:enable WordPress.Security.NonceVerification.Recommended
$selected_config = ( $config_id ? $config_repo->get_by_id( $config_id ) : null );
// Only published slides (only ones with config_uid, model, prompt)
$configs = $config_repo->get_all_slides( 'publish' );
// Pre-compute inherited values for each slide
$configs_inherited = [];
foreach ( $configs as $config ) {
    $inherited = $config_repo->get_inherited_content( $config['id'] );
    $var_values = [];
    if ( $inherited['course'] ) {
        if ( !empty( $inherited['course']['theme'] ) ) {
            $var_values['course_theme'] = $inherited['course']['theme'];
        }
        if ( !empty( $inherited['course']['content'] ) ) {
            $var_values['course_content'] = $inherited['course']['content'];
        }
        if ( !empty( $inherited['course']['objectives'] ) ) {
            $var_values['course_objectives'] = $inherited['course']['objectives'];
        }
    }
    if ( $inherited['module'] ) {
        if ( !empty( $inherited['module']['theme'] ) ) {
            $var_values['module_theme'] = $inherited['module']['theme'];
        }
        if ( !empty( $inherited['module']['objectives'] ) ) {
            $var_values['module_objectives'] = $inherited['module']['objectives'];
        }
        if ( !empty( $inherited['module']['content'] ) ) {
            $var_values['module_content'] = $inherited['module']['content'];
        }
        if ( !empty( $inherited['module']['response_example'] ) ) {
            $var_values['module_response_example'] = $inherited['module']['response_example'];
        }
    }
    if ( $inherited['course'] ) {
        if ( !empty( $inherited['course']['response_example'] ) ) {
            $var_values['course_response_example'] = $inherited['course']['response_example'];
        }
    }
    $configs_inherited[$config['id']] = $var_values;
}
// Available models
$models = $llm_proxy->get_models();
?>

<div class="sm-wrap">
    <div class="sm-header">
        <h1><?php 
esc_html_e( 'Sandbox', 'slidemind' );
?></h1>
        <span class="sm-badge sm-badge-info"><?php 
esc_html_e( 'Test mode', 'slidemind' );
?></span>
    </div>

    <div style="display: grid; grid-template-columns: 1fr 400px; gap: 24px;" class="sm-sandbox-layout">
        <!-- Prompt + chat area -->
        <div>
            <!-- System prompt -->
            <div class="sm-card sm-sandbox-prompt-card" id="sm-sandbox-prompt-card">
                <div class="sm-card-header">
                    <h2 class="sm-card-title"><?php 
esc_html_e( 'System prompt', 'slidemind' );
?></h2>
                </div>

                <!-- Config mode: read-only display -->
                <div id="sm-sandbox-prompt-display">
                    <div id="sm-sandbox-prompt-info" class="sm-sandbox-prompt-info" style="display: none;">
                        <span class="sm-prompt-badge" id="sm-sandbox-info-model">
                            <span class="dashicons dashicons-cloud"></span>
                            <span class="sm-prompt-badge-text">—</span>
                        </span>
                        <span class="sm-prompt-badge" id="sm-sandbox-info-temp">
                            <span class="dashicons dashicons-controls-volumeon"></span>
                            <span class="sm-prompt-badge-text">—</span>
                        </span>
                        <span class="sm-prompt-badge" id="sm-sandbox-info-tokens">
                            <span class="dashicons dashicons-editor-textcolor"></span>
                            <span class="sm-prompt-badge-text">—</span>
                        </span>
                    </div>
                    <pre id="sm-sandbox-prompt-display-content" class="sm-sandbox-prompt-pre"><?php 
esc_html_e( 'Select a slide to view the prompt.', 'slidemind' );
?></pre>
                </div>

                <!-- Manual mode: editable textarea -->
                <div id="sm-sandbox-prompt-editor" style="display: none;">
                    <textarea id="sm-sandbox-prompt"
                              class="sm-form-textarea"
                              rows="8"
                              placeholder="<?php 
esc_attr_e( 'You are a pedagogical assistant...', 'slidemind' );
?>"></textarea>
                    <div style="display: flex; gap: 8px; margin-top: 6px;">
                        <button type="button" class="sm-btn sm-btn-sm sm-btn-secondary sm-insert-variable-btn" data-target="sm-sandbox-prompt">
                            <span class="dashicons dashicons-editor-code"></span>
                            <?php 
esc_html_e( 'Insert a variable', 'slidemind' );
?>
                        </button>
                        <button type="button" class="sm-btn sm-btn-sm sm-btn-secondary" id="sm-sandbox-generate-prompt-btn">
                            <span class="dashicons dashicons-admin-generic"></span>
                            <?php 
esc_html_e( 'Generate with AI', 'slidemind' );
?>
                        </button>
                    </div>
                </div>
            </div>

            <!-- Conversation -->
            <div class="sm-card sm-sandbox-conversation-card" style="margin-top: 16px;">
                <div class="sm-card-header">
                    <h2 class="sm-card-title"><?php 
esc_html_e( 'Conversation', 'slidemind' );
?></h2>
                    <div class="sm-header-buttons">
                        <button type="button" id="sm-sandbox-export" class="sm-export-btn">
                            <span class="dashicons dashicons-download"></span>
                            <?php 
esc_html_e( 'Export', 'slidemind' );
?>
                        </button>
                        <button type="button" id="sm-sandbox-reset" class="sm-btn sm-btn-sm sm-btn-secondary">
                            <span class="dashicons dashicons-update"></span>
                            <?php 
esc_html_e( 'Reset', 'slidemind' );
?>
                        </button>
                    </div>
                </div>

                <div id="sm-sandbox-messages" class="sm-sandbox-messages">
                    <div class="sm-sandbox-empty" style="text-align: center; padding: 20px 40px; color: #6b7280;">
                        <span class="dashicons dashicons-format-chat" style="font-size: 36px; margin-bottom: 12px; display: block;"></span>
                        <p><?php 
esc_html_e( 'Select a slide and send a message to get started.', 'slidemind' );
?></p>
                    </div>
                </div>

                <form id="sm-sandbox-form" style="display: flex; gap: 12px;">
                    <input type="text"
                           id="sm-sandbox-input"
                           class="sm-form-input"
                           placeholder="<?php 
esc_attr_e( 'Type your message...', 'slidemind' );
?>"
                           style="flex: 1;"
                           disabled>
                    <button type="submit" id="sm-sandbox-send" class="sm-btn sm-btn-primary" disabled>
                        <?php 
esc_html_e( 'Send', 'slidemind' );
?>
                    </button>
                </form>
            </div>

            <?php 
?>
            <div class="sm-card" style="margin-top: 16px;">
                <?php 
$required_plan = 'dialogue';
$feature_label = __( 'Debug panel', 'slidemind' );
include SLIDEMIND_PLUGIN_PATH . 'admin/views/partials/upsell-notice.php';
?>
            </div>
            <?php 
?>
        </div>

        <!-- Configuration panel -->
        <div class="sm-sandbox-sidebar">
            <div class="sm-card">
                <div class="sm-card-header">
                    <h2 class="sm-card-title"><?php 
esc_html_e( 'Slide', 'slidemind' );
?></h2>
                </div>

                <!-- Session indicator -->
                <div class="sm-session-indicator" id="sm-session-status">
                    <span class="sm-session-dot"></span>
                    <span><?php 
esc_html_e( 'Connecting...', 'slidemind' );
?></span>
                </div>

                <div class="sm-form-group">
                    <label class="sm-form-label"><?php 
esc_html_e( 'Mode', 'slidemind' );
?></label>
                    <div style="display: flex; gap: 8px;">
                        <button type="button" class="sm-btn sm-btn-sm sm-sandbox-mode active" data-mode="config">
                            <?php 
esc_html_e( 'Existing slide', 'slidemind' );
?>
                        </button>
                        <button type="button" class="sm-btn sm-btn-sm sm-btn-secondary sm-sandbox-mode" data-mode="manual">
                            <?php 
esc_html_e( 'Manual', 'slidemind' );
?>
                        </button>
                    </div>
                </div>

                <!-- Mode: Existing configuration -->
                <div id="sm-sandbox-mode-config">
                    <div class="sm-form-group">
                        <label class="sm-form-label" for="sm-sandbox-config">
                            <?php 
esc_html_e( 'Slide', 'slidemind' );
?>
                        </label>
                        <select id="sm-sandbox-config" class="sm-form-select">
                            <option value=""><?php 
esc_html_e( 'Select...', 'slidemind' );
?></option>
                            <?php 
foreach ( $configs as $config ) {
    // Extract variables from prompt
    $prompt_vars = [];
    if ( !empty( $config['system_prompt'] ) ) {
        preg_match_all( '/\\{\\{([\\p{L}_][\\p{L}0-9_]*(?:\\.[\\p{L}_][\\p{L}0-9_]*){0,2})\\}\\}/u', $config['system_prompt'], $matches );
        if ( !empty( $matches[1] ) ) {
            $prompt_vars = array_unique( $matches[1] );
        }
    }
    $output_vars = ( isset( $config['output_variables'] ) ? $config['output_variables'] : [] );
    ?>
                                <option value="<?php 
    echo esc_attr( $config['config_uid'] );
    ?>"
                                        <?php 
    selected( $selected_config && $selected_config['id'] === $config['id'] );
    ?>
                                        data-post-id="<?php 
    echo esc_attr( $config['id'] );
    ?>"
                                        data-prompt="<?php 
    echo esc_attr( $config['system_prompt'] );
    ?>"
                                        data-model="<?php 
    echo esc_attr( $config['model_id'] );
    ?>"
                                        data-temperature="<?php 
    echo esc_attr( $config['temperature'] );
    ?>"
                                        data-max-tokens="<?php 
    echo esc_attr( $config['max_tokens'] ?? $sm_settings['default_max_tokens'] );
    ?>"
                                        data-variables='<?php 
    echo esc_attr( wp_json_encode( array_values( $prompt_vars ) ) );
    ?>'
                                        data-variable-values='<?php 
    echo esc_attr( wp_json_encode( $configs_inherited[$config['id']] ?? new \stdClass(), JSON_UNESCAPED_UNICODE ) );
    ?>'
                                        data-output-variables='<?php 
    echo esc_attr( wp_json_encode( $output_vars, JSON_UNESCAPED_UNICODE ) );
    ?>'
                                        data-response-example="<?php 
    echo esc_attr( $config['response_example'] ?? '' );
    ?>">
                                    <?php 
    echo esc_html( $config['title'] );
    ?>
                                </option>
                            <?php 
}
?>
                        </select>
                    </div>
                </div>

                <!-- Mode: Manual -->
                <div id="sm-sandbox-mode-manual" style="display: none;">
                    <?php 
$sandbox_global_provider = get_option( 'slidemind_global_provider', 'openrouter' );
$sandbox_providers = \SlideMind\Core\LLMProxy::get_providers();
?>
                    <div class="sm-form-group">
                        <label class="sm-form-label" for="sm-sandbox-provider"><?php 
esc_html_e( 'LLM Provider', 'slidemind' );
?></label>
                        <select id="sm-sandbox-provider" class="sm-form-select sm-provider-select">
                            <?php 
foreach ( $sandbox_providers as $slug => $info ) {
    ?>
                                <option value="<?php 
    echo esc_attr( $slug );
    ?>" <?php 
    selected( $sandbox_global_provider, $slug );
    ?>>
                                    <?php 
    echo esc_html( $info['label'] );
    ?>
                                </option>
                            <?php 
}
?>
                        </select>
                    </div>

                    <?php 
?>

                    <?php 
?>
                        <div class="sm-form-group">
                            <?php 
$required_plan = 'pro';
$feature_label = __( 'Model comparison', 'slidemind' );
include SLIDEMIND_PLUGIN_PATH . 'admin/views/partials/upsell-notice.php';
?>
                        </div>
                    <?php 
?>

                    <div class="sm-form-group">
                        <label class="sm-form-label" for="sm-sandbox-model">
                            <?php 
esc_html_e( 'Model', 'slidemind' );
?>
                        </label>
                        <select id="sm-sandbox-model" class="sm-form-select sm-model-select" data-current-provider="<?php 
echo esc_attr( $sandbox_global_provider );
?>">
                            <?php 
$grouped = [];
foreach ( $models as $model ) {
    $parts = explode( '/', $model['id'] );
    $model_provider_label = ucfirst( $parts[0] );
    $grouped[$model_provider_label][] = $model;
}
foreach ( $grouped as $model_provider_label => $provider_models ) {
    ?>
                                <optgroup label="<?php 
    echo esc_attr( $model_provider_label );
    ?>">
                                    <?php 
    foreach ( $provider_models as $model ) {
        ?>
                                        <option value="<?php 
        echo esc_attr( $model['id'] );
        ?>"
                                                <?php 
        selected( $sm_settings['default_model'], $model['id'] );
        ?>>
                                            <?php 
        echo esc_html( $model['name'] );
        ?>
                                        </option>
                                    <?php 
    }
    ?>
                                </optgroup>
                            <?php 
}
?>
                        </select>
                    </div>

                    <div class="sm-form-group">
                        <label class="sm-form-label" for="sm-sandbox-temperature">
                            <?php 
esc_html_e( 'Temperature:', 'slidemind' );
?> <span id="sm-sandbox-temp-value"><?php 
echo esc_attr( $sm_settings['default_temperature'] );
?></span>
                        </label>
                        <input type="range"
                               id="sm-sandbox-temperature"
                               min="0"
                               max="2"
                               step="0.1"
                               value="<?php 
echo esc_attr( $sm_settings['default_temperature'] );
?>"
                               style="width: 100%;">
                    </div>

                    <div class="sm-form-group">
                        <label class="sm-form-label" for="sm-sandbox-max-tokens">
                            <?php 
esc_html_e( 'Max tokens', 'slidemind' );
?>
                        </label>
                        <input type="number"
                               id="sm-sandbox-max-tokens"
                               class="sm-form-input"
                               value="<?php 
echo esc_attr( $sm_settings['default_max_tokens'] );
?>"
                               min="1"
                               max="128000">
                    </div>

                    <div class="sm-form-group">
                        <label class="sm-form-label" for="sm-sandbox-response-example">
                            <?php 
esc_html_e( 'Response example', 'slidemind' );
?>
                        </label>
                        <textarea id="sm-sandbox-response-example"
                                  class="sm-form-textarea"
                                  rows="4"
                                  placeholder="<?php 
esc_attr_e( 'Optional: example of the expected response format...', 'slidemind' );
?>"></textarea>
                        <p class="sm-form-help"><?php 
esc_html_e( 'If provided, this example will be appended to the system prompt.', 'slidemind' );
?></p>
                    </div>
                </div>

                <div id="sm-sandbox-config-actions" class="sm-sandbox-config-actions" style="display: none;">
                    <a href="#" id="sm-sandbox-edit-slide" class="sm-btn sm-btn-sm sm-btn-secondary" target="_blank">
                        <span class="dashicons dashicons-edit"></span>
                        <?php 
esc_html_e( 'Edit slide', 'slidemind' );
?>
                    </a>
                    <button type="button" id="sm-sandbox-apply-changes" class="sm-btn sm-btn-sm sm-btn-success" style="display: none;">
                        <span class="dashicons dashicons-saved"></span>
                        <?php 
esc_html_e( 'Apply changes', 'slidemind' );
?>
                    </button>
                </div>
            </div>

            <!-- Response format (output variables) -->
            <div class="sm-card">
                <div class="sm-card-header">
                    <h2 class="sm-card-title"><?php 
esc_html_e( 'Response format', 'slidemind' );
?></h2>
                    <span class="sm-badge sm-badge-secondary"><?php 
esc_html_e( 'Optional', 'slidemind' );
?></span>
                </div>

                <p class="sm-form-help" style="margin-bottom: 12px;">
                    <?php 
esc_html_e( 'Without variables, the response remains free text.', 'slidemind' );
?>
                </p>

                <div id="sm-sandbox-output-vars-list">
                    <!-- Populated dynamically -->
                </div>

                <button type="button" id="sm-sandbox-add-output-var" class="sm-btn sm-btn-secondary sm-btn-sm" style="margin-top: 8px;">
                    <span class="dashicons dashicons-plus-alt2"></span>
                    <?php 
esc_html_e( 'Add a return variable', 'slidemind' );
?>
                </button>
            </div>

            <div class="sm-card">
                <div class="sm-card-header">
                    <h2 class="sm-card-title"><?php 
esc_html_e( 'Test variables', 'slidemind' );
?></h2>
                </div>

                <div id="sm-sandbox-variables">
                    <p class="sm-form-help" style="color: #9ca3af;">
                    <?php 
/* translators: %s: variable syntax */
printf( esc_html__( 'No %s variable detected in the prompt.', 'slidemind' ), '<code>{{name}}</code>' );
?>
                    </p>
                </div>

                <p class="sm-form-help" style="margin-top: 8px;">
                    <?php 
/* translators: %s: variable syntax */
printf( esc_html__( 'Variables are automatically detected from the prompt %s.', 'slidemind' ), '<code>{{name}}</code>' );
?>
                </p>
            </div>

        </div>
    </div>
</div>

