<?php
declare(strict_types=1);

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

use LolaCore\Admin\Settings;
use WordPress\AiClient\AiClient;

// Fetch current configurations
$lolacore_selected_model        = Settings::getConfig('selected_model', 'auto');
$lolacore_tech_level            = Settings::getConfig('technical_level', 'Professional');
$lolacore_decay_rate            = Settings::getConfig('memory_decay_rate', '0.02');
$lolacore_archive_threshold     = Settings::getConfig('memory_archive_threshold', '0.10');
$lolacore_max_context_entries   = Settings::getConfig('memory_max_context_entries', '20');
$lolacore_log_retention_days    = Settings::getConfig('log_retention_days', '90');

$lolacore_safety_confirm_writes = Settings::getConfig('safety_confirm_writes', '1') === '1';
$lolacore_safety_require_backup = Settings::getConfig('safety_require_backup', '0') === '1';
$lolacore_safety_learning_mode  = Settings::getConfig('safety_learning_mode', '0')  === '1';
$lolacore_last_maintenance_at   = Settings::getConfig('last_maintenance_at', '');

// Fetch real memory stats
$lolacore_memory_manager = new \LolaCore\Memory\MemoryManager();
$lolacore_active_facts = $lolacore_memory_manager->getActiveFactCount();
$lolacore_maintenance_text = __('Never', 'lolacore');
$lolacore_maintenance_color = 'red'; // Default: never maintained
if (!empty($lolacore_last_maintenance_at)) {
    $lolacore_maintenance_text = human_time_diff(strtotime($lolacore_last_maintenance_at), current_time('timestamp')) . ' ago';
    $lolacore_hours_since = (current_time('timestamp') - strtotime($lolacore_last_maintenance_at)) / 3600;
    if ($lolacore_hours_since < 24) {
        $lolacore_maintenance_color = 'green';
    } elseif ($lolacore_hours_since > 168) { // 7 days
        $lolacore_maintenance_color = 'amber';
    } else {
        $lolacore_maintenance_color = 'green';
    }
}

// Fetch scan data for header pills
$lolacore_scan_json   = Settings::getConfig('last_scan_data', '{}');
$lolacore_scan_data   = json_decode($lolacore_scan_json, true) ?: [];
$lolacore_plugin_count  = isset($lolacore_scan_data['plugins_total']) ? (int) $lolacore_scan_data['plugins_total'] : count(get_plugins());
$lolacore_updates_count = 0;
$lolacore_update_plugins = get_site_transient('update_plugins');
if (!empty($lolacore_update_plugins->response)) {
    $lolacore_updates_count = count($lolacore_update_plugins->response);
}

$lolacore_avatar_attachment_id  = Settings::getConfig('lola_avatar_attachment_id', 0);
$lolacore_avatar_url            = '';
if ($lolacore_avatar_attachment_id > 0) {
    $lolacore_avatar_url = \wp_get_attachment_image_url((int) $lolacore_avatar_attachment_id, 'thumbnail');
}
if (!$lolacore_avatar_url) {
    $lolacore_avatar_url = \plugin_dir_url(LOLACORE_PLUGIN_FILE) . 'assets/img/lola-default.png';
}

// Retrieve available AI models from the WP 7.0 Connectors registry
$lolacore_wp_models = [];
if (class_exists(AiClient::class)) {
    try {
        $lolacore_registry = AiClient::defaultRegistry();
        $lolacore_provider_ids = $lolacore_registry->getRegisteredProviderIds();
        
        foreach ($lolacore_provider_ids as $lolacore_provider_id) {
            try {
                $lolacore_provider_class = $lolacore_registry->getProviderClassName($lolacore_provider_id);
                $lolacore_metadata = $lolacore_provider_class::metadata();
                $lolacore_provider_name = $lolacore_metadata->getName();
                
                $lolacore_model_dir = $lolacore_provider_class::modelMetadataDirectory();
                $lolacore_models = $lolacore_model_dir->listModelMetadata();
                
                foreach ($lolacore_models as $lolacore_model) {
                    $lolacore_caps = $lolacore_model->getSupportedCapabilities();
                    $lolacore_has_text = empty($lolacore_caps); // If empty, assume it's valid to avoid filtering out everything
                    
                    foreach ($lolacore_caps as $lolacore_cap) {
                        if (((string) $lolacore_cap) === 'text_generation') {
                            $lolacore_has_text = true;
                            break;
                        }
                    }
                    
                    if ($lolacore_has_text) {
                        $lolacore_key = $lolacore_provider_id . '|' . $lolacore_model->getId();
                        $lolacore_wp_models[$lolacore_key] = $lolacore_provider_name . ' - ' . $lolacore_model->getName();
                    }
                }
            } catch (\Throwable $e) {
                // Skip provider if it throws an exception (e.g. auth interface not set)
                continue;
            }
        }
    } catch (\Throwable $e) {
        // Fallback quietly if the API structure changes
    }
}
?>

<div class="lc-settings-container">

    <div class="lc-settings-header">
        <img src="<?php echo esc_url($lolacore_avatar_url); ?>" alt="<?php echo esc_attr__('Lola Avatar', 'lolacore'); ?>" class="lc-avatar header-avatar">
        <div class="lc-settings-header-text">
            <span class="lc-eyebrow"><?php echo esc_html__('Lola', 'lolacore'); ?> &middot; V<?php echo esc_html(LOLACORE_VERSION); ?></span>
            <h2><?php echo esc_html__('Lola Configuration', 'lolacore'); ?></h2>
            <span class="lc-header-subtitle"><?php echo esc_html__('Your AI admin agent. Configure once and forget — Lola remembers the rest.', 'lolacore'); ?></span>
        </div>
        <div class="lc-header-status">
            <?php if ($lolacore_active_facts > 0) : ?>
                <span class="lc-pill mint"><?php echo esc_html__('MEMORY ACTIVE', 'lolacore'); ?></span>
            <?php else : ?>
                <span class="lc-pill gray"><?php echo esc_html__('NO MEMORY', 'lolacore'); ?></span>
            <?php endif; ?>
            <span class="lc-pill plum"><?php echo esc_html($lolacore_plugin_count); ?> <?php echo esc_html__('PLUGINS', 'lolacore'); ?></span>
            <?php if ($lolacore_updates_count > 0) : ?>
                <span class="lc-pill amber"><?php echo esc_html($lolacore_updates_count); ?> <?php echo esc_html__('UPDATES', 'lolacore'); ?></span>
            <?php endif; ?>
        </div>
    </div>

    <div id="lolacore-settings-messages"></div>

    <form id="lolacore-settings-form" method="post">

        <!-- Section 1: Lola's Brain (BYOM) -->
        <div class="lc-card">
            <div class="lc-card-header">
                <span class="lc-section-number">1</span>
                <h3><?php echo esc_html__("Lola's Brain (AI Model)", 'lolacore'); ?></h3>
            </div>
            <p class="description"><?php
                echo wp_kses_post(
                    sprintf(
                        /* translators: %s: link to Settings > Connectors */
                        __('Lola uses the AI model configured in your WordPress installation. You can add or change providers in %s.', 'lolacore'),
                        '<a href="' . esc_url(admin_url('options-connectors.php')) . '">' . esc_html__('Settings › Connectors', 'lolacore') . '</a>'
                    )
                );
            ?></p>

            <div style="margin-top: 16px;">
                <label for="lolacore-model" style="display:block; font-weight:600; margin-bottom:8px;"><?php echo esc_html__('Preferred model for Lola:', 'lolacore'); ?></label>
                <select id="lolacore-model" name="selected_model" class="lc-select">
                    <option value="auto" <?php selected($lolacore_selected_model, 'auto'); ?>>
                        <?php echo esc_html__('Automatic (use WordPress default)', 'lolacore'); ?>
                    </option>
                    <?php if (!empty($lolacore_wp_models)) : ?>
                        <?php foreach ($lolacore_wp_models as $lolacore_model_id => $lolacore_model_label) : ?>
                            <option value="<?php echo esc_attr($lolacore_model_id); ?>" <?php selected($lolacore_selected_model, $lolacore_model_id); ?>>
                                <?php echo esc_html($lolacore_model_label); ?>
                            </option>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </select>
                <p class="description" style="margin-top:8px;">
                    <?php if (empty($lolacore_wp_models)) : ?>
                        <?php echo esc_html__('No AI providers connected yet.', 'lolacore'); ?>
                        <a href="<?php echo esc_url(admin_url('options-connectors.php')); ?>"><?php echo esc_html__('Connect one now →', 'lolacore'); ?></a>
                    <?php else : ?>
                        <?php echo esc_html__('Select which model Lola will use. "Automatic" uses the first available text generation model.', 'lolacore'); ?>
                    <?php endif; ?>
                </p>
            </div>
        </div>

        <!-- Section 2: Communication Style -->
        <div class="lc-card">
            <div class="lc-card-header">
                <span class="lc-section-number">2</span>
                <h3><?php echo esc_html__('Communication Style', 'lolacore'); ?></h3>
            </div>
            <p class="description"><?php echo esc_html__('How do you prefer Lola to talk to you?', 'lolacore'); ?></p>

            <div class="lc-radio-grid">
                <label class="lc-radio-card">
                    <input type="radio" name="technical_level" value="Technical" <?php checked($lolacore_tech_level, 'Technical'); ?>>
                    <div class="lc-radio-content">
                        <strong><?php echo esc_html__('Technical', 'lolacore'); ?></strong>
                        <span><?php echo esc_html__('Development terminology, shows code, doesn\'t explain basics.', 'lolacore'); ?></span>
                    </div>
                </label>
                <label class="lc-radio-card">
                    <input type="radio" name="technical_level" value="Professional" <?php checked($lolacore_tech_level, 'Professional'); ?>>
                    <div class="lc-radio-content">
                        <strong><?php echo esc_html__('Professional', 'lolacore'); ?></strong>
                        <span><?php echo esc_html__('Clear language, explains technical decisions without jargon.', 'lolacore'); ?></span>
                    </div>
                </label>
                <label class="lc-radio-card">
                    <input type="radio" name="technical_level" value="Direct" <?php checked($lolacore_tech_level, 'Direct'); ?>>
                    <div class="lc-radio-content">
                        <strong><?php echo esc_html__('Direct', 'lolacore'); ?></strong>
                        <span><?php echo esc_html__('Minimal explanations, maximum action.', 'lolacore'); ?></span>
                    </div>
                </label>
            </div>
        </div>

        <!-- Section 3: Lola's Avatar -->
        <div class="lc-card">
            <div class="lc-card-header">
                <span class="lc-section-number">3</span>
                <h3><?php echo esc_html__("Lola's Avatar", 'lolacore'); ?></h3>
            </div>
            
            <div class="lc-avatar-group">
                <img src="<?php echo esc_url($lolacore_avatar_url); ?>" id="current-lola-avatar" class="lc-avatar-preview" alt="<?php echo esc_attr__('Lola Avatar', 'lolacore'); ?>">
                <div>
                    <div style="display:flex; gap:8px; margin-bottom:8px;">
                        <button type="button" id="btn-change-avatar" class="lc-action-btn ghost"><?php echo esc_html__('Change Avatar', 'lolacore'); ?></button>
                        <button type="button" id="btn-restore-avatar" class="lc-action-btn ghost"><?php echo esc_html__('Restore Default', 'lolacore'); ?></button>
                        <input type="hidden" id="lola_avatar_attachment_id" name="lola_avatar_attachment_id" value="<?php echo esc_attr($lolacore_avatar_attachment_id); ?>">
                    </div>
                    <p class="description"><?php echo esc_html__('Formats: JPG, PNG, WebP. Recommended: 128×128px.', 'lolacore'); ?></p>
                </div>
            </div>
        </div>

        <!-- Section 4: Memory Settings -->
        <div class="lc-card">
            <div class="lc-card-header">
                <span class="lc-section-number">4</span>
                <h3><?php echo esc_html__('Memory Settings', 'lolacore'); ?></h3>
            </div>
            <p class="description"><?php echo esc_html__('Configure how Lola stores and forgets information about your site.', 'lolacore'); ?></p>

            <table class="lc-form-table">
                <tr>
                    <th scope="row"><label for="memory_decay_rate"><?php echo esc_html__('Decay Rate', 'lolacore'); ?></label></th>
                    <td>
                        <input type="number" id="memory_decay_rate" name="memory_decay_rate" class="lc-input"
                               value="<?php echo esc_attr($lolacore_decay_rate); ?>"
                               step="0.01" min="0" max="0.10">
                        <p class="description"><?php echo esc_html__('How fast old facts are forgotten. Default 0.02.', 'lolacore'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="memory_archive_threshold"><?php echo esc_html__('Archive Threshold', 'lolacore'); ?></label></th>
                    <td>
                        <input type="number" id="memory_archive_threshold" name="memory_archive_threshold" class="lc-input"
                               value="<?php echo esc_attr($lolacore_archive_threshold); ?>"
                               step="0.05" min="0" max="0.50">
                        <p class="description"><?php echo esc_html__('Score below which a fact is archived. Default 0.10.', 'lolacore'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="memory_max_context_entries"><?php echo esc_html__('Max Context Entries', 'lolacore'); ?></label></th>
                    <td>
                        <input type="number" id="memory_max_context_entries" name="memory_max_context_entries" class="lc-input"
                               value="<?php echo esc_attr($lolacore_max_context_entries); ?>"
                               step="5" min="5" max="50">
                        <p class="description"><?php echo esc_html__('Maximum memory facts injected into the system prompt. Default 20.', 'lolacore'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="log_retention_days"><?php echo esc_html__('Log Retention Days', 'lolacore'); ?></label></th>
                    <td>
                        <input type="number" id="log_retention_days" name="log_retention_days" class="lc-input"
                               value="<?php echo esc_attr($lolacore_log_retention_days); ?>"
                               step="1" min="30" max="365">
                        <p class="description"><?php echo esc_html__('How long to keep action logs. Default 90.', 'lolacore'); ?></p>
                    </td>
                </tr>
            </table>

            <div style="margin-top: 16px;">
                <button type="button" id="btn-restore-memory-defaults" class="lc-action-btn ghost"><?php echo esc_html__('Restore Memory Defaults', 'lolacore'); ?></button>
            </div>

            <div class="lc-status-bar lc-status-bar--<?php echo esc_attr($lolacore_maintenance_color); ?>">
                <span class="lc-status-dot lc-status-dot--<?php echo esc_attr($lolacore_maintenance_color); ?>"></span>
                <span class="lc-status-text" id="memory-status-text"><?php
                    printf(
                        /* translators: 1: fact count, 2: last maintenance time */
                        esc_html__('%1$s facts in memory. Last maintenance: %2$s.', 'lolacore'),
                        esc_html((string) $lolacore_active_facts),
                        esc_html($lolacore_maintenance_text)
                    );
                ?></span>
            </div>
        </div>

        <!-- Section 5: What Lola Can Do + Expansions -->
        <?php
        $lolacore_settings_inst = new \LolaCore\Admin\Settings();
        $lolacore_domain_summary = $lolacore_settings_inst->getAbilityDomainSummary('disabled_domains', true);
        $lolacore_expansion_cards = \LolaCore\Marketing\AddonCatalog::getSortedForExpansionsPanel();
        $lolacore_total_abilities = 0;
        foreach ($lolacore_domain_summary as $lolacore_dom) { $lolacore_total_abilities += $lolacore_dom['count']; }
        $lolacore_total_domains = count($lolacore_domain_summary);
        ?>
        <div class="lc-card">
            <div class="lc-card-header">
                <span class="lc-section-number">5</span>
                <h3><?php echo esc_html__('What Lola Can Do', 'lolacore'); ?></h3>
            </div>
            <p class="description"><?php
                printf(
                    /* translators: 1: ability count, 2: domain count */
                    esc_html__('%1$s abilities across %2$s domains. Enable or disable categories based on your needs.', 'lolacore'),
                    esc_html((string) $lolacore_total_abilities),
                    esc_html((string) $lolacore_total_domains)
                );
            ?></p>

            <div class="lc-grid-2">
                <?php foreach ($lolacore_domain_summary as $lolacore_slug => $lolacore_data): ?>
                <div class="lc-toggle-wrapper">
                    <div class="lc-toggle-label">
                        <strong><?php echo esc_html($lolacore_data['label']); ?></strong>
                        <span><?php
                            printf(
                                /* translators: %s: ability count */
                                esc_html__('%s abilities', 'lolacore'),
                                esc_html((string) $lolacore_data['count'])
                            );
                        ?></span>
                        <?php if (!empty($lolacore_data['is_addon'])): ?>
                            <div style="margin-top: 4px;">
                                <?php if (!empty($lolacore_data['badge'])): ?>
                                    <span class="lc-pill amber" style="font-size: 10px; padding: 2px 6px;"><?php echo esc_html(mb_strtoupper($lolacore_data['badge'])); ?></span>
                                <?php elseif (!empty($lolacore_data['is_premium'])): ?>
                                    <span class="lc-pill amber" style="font-size: 10px; padding: 2px 6px;"><?php echo esc_html__('PREMIUM ADDON', 'lolacore'); ?></span>
                                <?php else: ?>
                                    <span class="lc-pill mint" style="font-size: 10px; padding: 2px 6px;"><?php echo esc_html__('FREE ADDON', 'lolacore'); ?></span>
                                <?php endif; ?>
                            </div>
                            <?php if (!empty($lolacore_data['license_url'])): ?>
                                <a href="<?php echo esc_url($lolacore_data['license_url']); ?>" style="display: inline-block; font-size: 11px; margin-top: 4px; color: var(--lc-plum); text-decoration: none;">
                                    <?php echo esc_html__('Manage license →', 'lolacore'); ?>
                                </a>
                            <?php elseif (!empty($lolacore_data['settings_url'])): ?>
                                <a href="<?php echo esc_url($lolacore_data['settings_url']); ?>" style="display: inline-block; font-size: 11px; margin-top: 4px; color: var(--lc-plum); text-decoration: none;">
                                    <?php echo esc_html__('Configure →', 'lolacore'); ?>
                                </a>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                    <label class="lc-toggle">
                        <input type="checkbox" class="lc-domain-toggle" data-domain="<?php echo esc_attr($lolacore_slug); ?>" <?php checked($lolacore_data['enabled']); ?>>
                        <span class="lc-toggle-slider"></span>
                    </label>
                </div>
                <?php endforeach; ?>
            </div>

            <div style="margin-top: 16px; font-size: 13px;">
                <a href="#" id="lc-toggle-abilities-list" style="text-decoration: none; color: var(--lc-plum); font-weight: 500;"><?php
                    printf(
                        /* translators: %s: ability count */
                        esc_html__('View all %s abilities ↓', 'lolacore'),
                        esc_html((string) $lolacore_total_abilities)
                    );
                ?></a>
                <div id="lc-abilities-list" style="display: none; margin-top: 12px; padding: 16px; background: #fff; border: 1px solid var(--lc-border); border-radius: 8px; max-height: 300px; overflow-y: auto;">
                    <?php
                    $lolacore_ab_registry = new \LolaCore\Actions\AbilitiesRegistry();
                    $lolacore_all_abilities = $lolacore_ab_registry->getRegisteredAbilities();
                    foreach ($lolacore_domain_summary as $lolacore_slug => $lolacore_data):
                        $lolacore_domain_abilities = [];
                        $lolacore_categories = \LolaCore\Admin\Settings::getAbilityCategoriesForDomain($lolacore_data, $lolacore_slug);
                        foreach ($lolacore_all_abilities as $lolacore_ability_name => $lolacore_ability) {
                            if (in_array($lolacore_ability['category'] ?? 'uncategorized', $lolacore_categories, true)) {
                                $lolacore_domain_abilities[] = $lolacore_ability_name;
                            }
                        }
                        if (!empty($lolacore_domain_abilities)):
                    ?>
                        <div style="margin-bottom: 12px;">
                            <strong style="color: var(--lc-text-primary);"><?php echo esc_html($lolacore_data['label']); ?></strong>
                            <ul style="margin: 4px 0 0 16px; color: var(--lc-text-secondary); list-style-type: disc; font-size: 12px; font-family: var(--lc-font-mono);">
                                <?php foreach ($lolacore_domain_abilities as $lolacore_ab): ?>
                                    <li><?php echo esc_html($lolacore_ab); ?></li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                    <?php endif; endforeach; ?>
                </div>
            </div>
        </div>

        <?php if (!empty($lolacore_expansion_cards)) : ?>
        <div class="lc-card lc-expansions-panel">
            <div class="lc-card-header">
                <h3><?php echo esc_html__('Expansions', 'lolacore'); ?></h3>
            </div>
            <p class="description"><?php echo esc_html__(
                'Addons that teach Lola new domains. Each one is built for a specific plugin on your site.',
                'lolacore'
            ); ?></p>
            <div class="lc-addon-grid">
                <?php foreach ($lolacore_expansion_cards as $lolacore_addon_card) : ?>
                    <?php
                    $lolacore_addon_card_context = 'expansion';
                    require __DIR__ . '/partials/addon-catalog-card.php';
                    ?>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- Section 6: Safety & Confirmations -->
        <div class="lc-card">
            <div class="lc-card-header">
                <span class="lc-section-number">6</span>
                <h3><?php echo esc_html__('Safety & Confirmations', 'lolacore'); ?></h3>
            </div>
            <p class="description"><?php echo esc_html__('Configure when Lola requires your explicit approval to act.', 'lolacore'); ?></p>

            <div class="lc-toggle-wrapper">
                <div class="lc-toggle-label">
                    <strong><?php echo esc_html__('Confirm before every write action', 'lolacore'); ?></strong>
                    <span><?php echo esc_html__('Recommended. If disabled, Lola will execute actions without asking.', 'lolacore'); ?><br><span style="color: var(--lc-salmon); font-style: italic;"><?php echo esc_html__('Disclaimer: Lola is an AI and can make mistakes.', 'lolacore'); ?></span></span>
                </div>
                <label class="lc-toggle">
                    <input type="checkbox" class="lc-safety-toggle" id="safety_confirm_writes" <?php checked($lolacore_safety_confirm_writes); ?>>
                    <span class="lc-toggle-slider"></span>
                </label>
            </div>
            <div class="lc-toggle-wrapper">
                <div class="lc-toggle-label">
                    <strong><?php echo esc_html__('Block destructive actions without verified backup', 'lolacore'); ?></strong>
                    <span><?php echo esc_html__('Lola checks for a recent backup before deleting content.', 'lolacore'); ?></span>
                </div>
                <label class="lc-toggle">
                    <input type="checkbox" class="lc-safety-toggle" id="safety_require_backup" <?php checked($lolacore_safety_require_backup); ?>>
                    <span class="lc-toggle-slider"></span>
                </label>
            </div>
            <div class="lc-toggle-wrapper">
                <div class="lc-toggle-label">
                    <strong><?php echo esc_html__('Learning mode', 'lolacore'); ?></strong>
                    <span><?php echo esc_html__('Lola explains what she\'s about to do before showing the preview, so you understand each action.', 'lolacore'); ?></span>
                </div>
                <label class="lc-toggle">
                    <input type="checkbox" class="lc-safety-toggle" id="safety_learning_mode" <?php checked($lolacore_safety_learning_mode); ?>>
                    <span class="lc-toggle-slider"></span>
                </label>
            </div>

            <div style="margin-top: 16px;">
                <button type="button" id="btn-save-safety" class="lc-action-btn primary"><?php echo esc_html__('Save Safety Settings', 'lolacore'); ?></button>
                <span class="spinner" id="safety-spinner" style="float:none; vertical-align:middle;"></span>
            </div>
        </div>

        <!-- Section 7: Maintenance -->
        <div class="lc-card">
            <div class="lc-card-header">
                <span class="lc-section-number">7</span>
                <h3><?php echo esc_html__('Maintenance', 'lolacore'); ?></h3>
            </div>
            <p class="description"><?php echo esc_html__('Manual controls for database and memory health.', 'lolacore'); ?></p>

            <div style="display:flex; flex-wrap:wrap; gap:12px;">
                <button type="button" id="btn-maint-rescan" class="lc-action-btn ghost"><?php echo esc_html__('Re-scan site', 'lolacore'); ?></button>
                <button type="button" id="btn-maint-export" class="lc-action-btn ghost"><?php echo esc_html__('Export memory', 'lolacore'); ?></button>
                <button type="button" id="btn-maint-import" class="lc-action-btn ghost"><?php echo esc_html__('Import memory', 'lolacore'); ?></button>
                <button type="button" id="btn-maint-compact" class="lc-action-btn ghost"><?php echo esc_html__('Compact memory', 'lolacore'); ?></button>
                <button type="button" id="btn-maint-wipe" class="lc-action-btn danger"><?php echo esc_html__('Wipe all memory', 'lolacore'); ?></button>
            </div>

            <?php if (!empty($lolacore_last_maintenance_at)) : ?>
                <div class="lc-status-bar" style="margin-top: 16px;">
                    <span class="lc-pill mint"><?php echo esc_html__('OK', 'lolacore'); ?></span>
                    <span class="lc-status-text"><?php
                        printf(
                            /* translators: %s: human-readable time */
                            esc_html__('Last maintenance: %s', 'lolacore'),
                            esc_html($lolacore_maintenance_text)
                        );
                    ?></span>
                </div>
            <?php endif; ?>
        </div>

        <div class="lc-sticky-footer" id="lc-sticky-footer" style="display: none;">
            <span class="lc-dirty-label" id="lc-dirty-label"></span>
            <span class="spinner" id="save-spinner"></span>
            <button type="button" class="lc-action-btn ghost" id="btn-discard-settings"><?php echo esc_html__('Discard', 'lolacore'); ?></button>
            <button type="submit" class="lc-action-btn primary" id="btn-save-settings"><?php echo esc_html__('Save Changes', 'lolacore'); ?></button>
        </div>

    </form>

    <!-- Wipe Memory Modal -->
    <div id="lc-wipe-modal" class="lc-modal-overlay" style="display: none;">
        <div class="lc-modal-card">
            <div class="lc-modal-header">
                <h3><?php echo esc_html__('⚠️ Wipe All Memory', 'lolacore'); ?></h3>
            </div>
            <div class="lc-modal-body">
                <p><?php echo esc_html__('Are you sure you want to wipe ALL of Lola\'s memory? This cannot be undone.', 'lolacore'); ?></p>
                <p style="margin-top: 16px; font-weight: 600;"><?php echo esc_html__('Type WIPE to confirm:', 'lolacore'); ?></p>
                <input type="text" id="lc-wipe-token" class="lc-input" autocomplete="off" placeholder="<?php echo esc_attr__('WIPE', 'lolacore'); ?>">
            </div>
            <div class="lc-modal-footer">
                <button type="button" class="lc-action-btn ghost" id="btn-wipe-cancel"><?php echo esc_html__('Cancel', 'lolacore'); ?></button>
                <button type="button" class="lc-action-btn danger" id="btn-wipe-confirm"><?php echo esc_html__('Wipe Memory', 'lolacore'); ?></button>
            </div>
        </div>
    </div>

    <!-- Generic Confirmation Modal -->
    <div id="lc-confirm-modal" class="lc-modal-overlay" style="display: none;">
        <div class="lc-modal-card">
            <div class="lc-modal-header" style="background: var(--lc-paper); border-bottom-color: var(--lc-border);">
                <h3 id="lc-confirm-title" style="color: var(--lc-text-primary);"><?php echo esc_html__('Confirm Action', 'lolacore'); ?></h3>
            </div>
            <div class="lc-modal-body">
                <p id="lc-confirm-message"><?php echo esc_html__('Are you sure?', 'lolacore'); ?></p>
            </div>
            <div class="lc-modal-footer">
                <button type="button" class="lc-action-btn ghost" id="btn-confirm-cancel"><?php echo esc_html__('Cancel', 'lolacore'); ?></button>
                <button type="button" class="lc-action-btn primary" id="btn-confirm-ok"><?php echo esc_html__('Confirm', 'lolacore'); ?></button>
            </div>
        </div>
    </div>

    <!-- Hidden File Input for Memory Import (Outside the Form to avoid F5 caching) -->
    <input type="file" id="maint-import-file" accept="application/json,.json" style="display:none;" autocomplete="off">

</div>
