<?php
/**
 * LolaCore — Skills Section Template (Section 8)
 *
 * Renders the skill inventory grouped by origin with status badges,
 * a single on/off toggle per skill, delete, import modal, and the
 * advanced parameters panel.
 *
 * Variables provided by Settings::renderSkillsSection():
 *
 * @var array<string, \LolaCore\Skills\Skill> $skills
 * @var array<int, \Throwable>                $errors
 * @var int                                   $activeCount
 * @var int                                   $maxActive
 * @var bool                                  $sectionEnabled
 * @var array<int, string>                    $disabledFs
 * @var array<string, int>                    $paramValues
 * @var array<string, array>                  $paramDefaults
 *
 * @package LolaCore
 * @license GPL-2.0-or-later
 */

declare(strict_types=1);

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

use LolaCore\Skills\Skill;
use LolaCore\Admin\Settings;

$lolacore_origin_order = [
    Skill::ORIGIN_BUILT_IN,
    Skill::ORIGIN_ADDON,
    Skill::ORIGIN_FILESYSTEM,
    Skill::ORIGIN_DB,
];

// Origin groups managed centrally by the master toggle (no individual checkboxes).
$lolacore_bundled_origins = [Skill::ORIGIN_BUILT_IN, Skill::ORIGIN_ADDON];

// Badge config: CSS class + label.
// 'active' / 'inactive' are persisted states the user controls via the toggle.
// 'no-triggers' / 'incompatible' / 'unmet-dependencies' are runtime diagnoses
// the SkillRegistry computes; the user does not set them directly.
$lolacore_badge_map = [
    Skill::STATUS_ACTIVE             => ['class' => 'lc-skill-badge--active',    'label' => __('Active', 'lolacore')],
    Skill::STATUS_INACTIVE           => ['class' => 'lc-skill-badge--inactive',  'label' => __('Inactive', 'lolacore')],
    Skill::STATUS_NO_TRIGGERS        => ['class' => 'lc-skill-badge--inactive',  'label' => __('No triggers — add rules to activate', 'lolacore')],
    Skill::STATUS_INCOMPATIBLE       => ['class' => 'lc-skill-badge--warn',      'label' => __('Requires newer LolaCore', 'lolacore')],
    Skill::STATUS_UNMET_DEPENDENCIES => ['class' => 'lc-skill-badge--error',     'label' => __('Missing dependencies', 'lolacore')],
];

// Translations for built-in skill descriptions. Skill metadata lives in the
// .md frontmatter (English source of truth); this map localizes the copy at
// render time. Unknown descriptions (addon/user skills) fall back unchanged.
$lolacore_skill_desc_i18n = [
    'Guides Lola when building WordPress Playground blueprint JSON to test a plugin in a safe disposable environment.' => __('Guides Lola when building WordPress Playground blueprint JSON to test a plugin in a safe disposable environment.', 'lolacore'),
    'Enforces WordPress data conventions when manipulating slugs, meta keys, options, taxonomies, and post statuses.' => __('Enforces WordPress data conventions when manipulating slugs, meta keys, options, taxonomies, and post statuses.', 'lolacore'),
    'Enables Lola to create, enrich, and refine LolaCore skill files.' => __('Enables Lola to create, enrich, and refine LolaCore skill files.', 'lolacore'),
    'Non-negotiable security rules when generating or reviewing plugin code that handles input, output, forms, AJAX, or the database.' => __('Non-negotiable security rules when generating or reviewing plugin code that handles input, output, forms, AJAX, or the database.', 'lolacore'),
    'Methodology for auditing any existing plugin\'s functional and runtime correctness before iterating, catching behavior bugs the linter and reviewer miss.' => __('Methodology for auditing any existing plugin\'s functional and runtime correctness before iterating, catching behavior bugs the linter and reviewer miss.', 'lolacore'),
    'Guides Lola when creating or iterating 3-file mini-plugins (PHP, JS, CSS) with correct structure and lifecycle.' => __('Guides Lola when creating or iterating 3-file mini-plugins (PHP, JS, CSS) with correct structure and lifecycle.', 'lolacore'),
    'Guides Lola to update, archive, or consolidate existing memory facts instead of accumulating contradictions.' => __('Guides Lola to update, archive, or consolidate existing memory facts instead of accumulating contradictions.', 'lolacore'),
    'Gives Lola a coherent structured response when users ask about LolaCore as a product.' => __('Gives Lola a coherent structured response when users ask about LolaCore as a product.', 'lolacore'),
    'Enforces a 4-step protocol before executing any destructive bulk operation on WordPress data.' => __('Enforces a 4-step protocol before executing any destructive bulk operation on WordPress data.', 'lolacore'),
    'Applies CRO analytical lenses to commercial copy review and generation.' => __('Applies CRO analytical lenses to commercial copy review and generation.', 'lolacore'),
    'Defines anti-AI prose discipline for content generated to be published on the user\'s site.' => __('Defines anti-AI prose discipline for content generated to be published on the user\'s site.', 'lolacore'),
    'Structures every code delivery with context, placement location, risks, and a minimal test.' => __('Structures every code delivery with context, placement location, risks, and a minimal test.', 'lolacore'),
    'Ensures post_content is written in Gutenberg block format, not raw HTML.' => __('Ensures post_content is written in Gutenberg block format, not raw HTML.', 'lolacore'),
    'Structures action log presentation by domain and offers revert when a snapshot exists.' => __('Structures action log presentation by domain and offers revert when a snapshot exists.', 'lolacore'),
];
?>

<div class="lc-skills-section <?php echo $sectionEnabled ? '' : 'lc-skills-section--off'; ?>" id="lolacore-skills">

    <!-- Master toggle + Beta notice -->
    <div class="lc-skills-master">
        <div class="lc-skills-master-toggle">
            <label class="lc-toggle">
                <input type="checkbox"
                       id="lolacore-skills-section-toggle"
                       data-no-dirty="1"
                       <?php checked($sectionEnabled); ?>>
                <span class="lc-toggle-slider"></span>
            </label>
            <div class="lc-skills-master-text">
                <strong><?php echo esc_html__('Enable the Skills system', 'lolacore'); ?></strong>
                <span><?php echo esc_html__('Activates the entire Skills layer. When on, all built-in skills load together.', 'lolacore'); ?></span>
            </div>
        </div>
        <div class="lc-skills-beta-notice">
            <span class="lc-pill amber"><?php echo esc_html__('Beta', 'lolacore'); ?></span>
            <p>
                <?php echo esc_html__('This section noticeably improves Lola\'s performance, but it\'s currently under development and ships as an opt-in beta. You can turn it on or off at any time.', 'lolacore'); ?>
            </p>
        </div>
    </div>

    <div class="lc-skills-content<?php echo $sectionEnabled ? '' : ' lc-skills-content--disabled'; ?>">

    <!-- Toolbar: counter, actions, author hint (single card) -->
    <div class="lc-skills-counter">
        <div class="lc-skills-counter-row">
            <span class="lc-skills-counter-text">
                <?php
                printf(
                    /* translators: 1: number of active skills (bold), 2: maximum allowed active skills. */
                    esc_html__('%1$s / %2$s active', 'lolacore'),
                    '<strong>' . esc_html((string) $activeCount) . '</strong>',
                    esc_html((string) $maxActive)
                );
                ?>
            </span>
            <div class="lc-skills-counter-actions">
                <button type="button" class="lc-action-btn ghost" id="lolacore-import-skill-btn"><?php echo esc_html__('Import skill', 'lolacore'); ?></button>
                <button type="button" class="lc-action-btn ghost" id="lolacore-reload-skills"><?php echo esc_html__('Reload skills', 'lolacore'); ?></button>
            </div>
        </div>
        <p class="lc-skills-author-hint">
            <?php echo esc_html__('Want a new skill written for you? Ask Lola directly in the chat — she\'ll guide you through it.', 'lolacore'); ?>
        </p>
    </div>

    <!-- Groups by origin -->
    <?php foreach ($lolacore_origin_order as $lolacore_origin) : ?>
        <?php
        $lolacore_group = array_filter($skills, static fn(Skill $s) => $s->getOrigin() === $lolacore_origin);
        if (empty($lolacore_group)) {
            continue;
        }
        $lolacore_is_bundled  = in_array($lolacore_origin, $lolacore_bundled_origins, true);
        $lolacore_group_count = count($lolacore_group);
        // Auto-open the user/lola-generated group: that's where the user's own
        // skills live, and the ones most likely to be edited.
        $lolacore_open_default = ($lolacore_origin === Skill::ORIGIN_DB);
        ?>
        <details class="lc-skills-group" data-origin="<?php echo esc_attr($lolacore_origin); ?>" <?php echo $lolacore_open_default ? 'open' : ''; ?>>
            <summary class="lc-skills-group-title">
                <span class="lc-skills-group-chevron" aria-hidden="true">▸</span>
                <span class="lc-skills-group-label"><?php echo esc_html(Settings::originLabel($lolacore_origin)); ?></span>
                <span class="lc-skills-group-count"><?php echo esc_html((string) $lolacore_group_count); ?></span>
                <?php if ($lolacore_is_bundled) : ?>
                    <span class="lc-skills-group-hint"><?php echo esc_html__('— managed by the master toggle', 'lolacore'); ?></span>
                <?php endif; ?>
            </summary>
            <div class="lc-skills-group-body">

            <?php foreach ($lolacore_group as $lolacore_skill) : ?>
                <?php
                $lolacore_name   = $lolacore_skill->getName();
                $lolacore_status = $lolacore_skill->getStatus();

                // The toggle reflects whether the skill is currently firing.
                // For DB skills the source of truth is `status` (active/inactive).
                // For filesystem skills the source of truth is the disabled list
                // in skills.disabled_filesystem, because their .md files cannot
                // be mutated from the UI.
                if ($lolacore_origin === Skill::ORIGIN_FILESYSTEM) {
                    $lolacore_is_on = !in_array($lolacore_name, $disabledFs, true);
                } else {
                    $lolacore_is_on = ($lolacore_status === Skill::STATUS_ACTIVE);
                }

                $lolacore_can_toggle = in_array($lolacore_origin, [Skill::ORIGIN_FILESYSTEM, Skill::ORIGIN_DB], true);
                $lolacore_can_delete = ($lolacore_origin === Skill::ORIGIN_DB);
                $lolacore_can_edit   = ($lolacore_origin === Skill::ORIGIN_DB);

                $lolacore_badge = $lolacore_badge_map[$lolacore_status] ?? $lolacore_badge_map[Skill::STATUS_ACTIVE];
                ?>
                <div class="lc-skill-row <?php echo $lolacore_is_bundled ? 'lc-skill-row--bundled' : ''; ?>"
                     data-skill-name="<?php echo esc_attr($lolacore_name); ?>"
                     data-origin="<?php echo esc_attr($lolacore_origin); ?>">
                    <?php if ($lolacore_can_toggle) : ?>
                        <div class="lc-skill-toggle-col">
                            <label class="lc-toggle lc-toggle--sm">
                                <input type="checkbox"
                                       class="lolacore-skill-toggle"
                                       data-skill-name="<?php echo esc_attr($lolacore_name); ?>"
                                       <?php checked($lolacore_is_on); ?>>
                                <span class="lc-toggle-slider"></span>
                            </label>
                        </div>
                    <?php endif; ?>

                    <div class="lc-skill-info">
                        <div class="lc-skill-header-row">
                            <span class="lc-skill-name"><?php echo esc_html($lolacore_name); ?></span>
                            <span class="lc-skill-priority"><?php echo esc_html__('priority:', 'lolacore'); ?> <?php echo esc_html((string) $lolacore_skill->getPriority()); ?></span>
                        </div>
                        <?php $lolacore_desc = $lolacore_skill->getDescription(); ?>
                        <p class="lc-skill-desc"><?php echo esc_html($lolacore_skill_desc_i18n[$lolacore_desc] ?? $lolacore_desc); ?></p>
                        <span class="lc-skill-badge <?php echo esc_attr($lolacore_badge['class']); ?>">
                            <?php echo esc_html($lolacore_badge['label']); ?>
                        </span>
                    </div>

                    <div class="lc-skill-actions">
                        <?php if ($lolacore_can_edit) : ?>
                            <button type="button"
                                    class="lc-action-btn ghost lc-skill-view-btn"
                                    data-skill-name="<?php echo esc_attr($lolacore_name); ?>"><?php echo esc_html__('View source', 'lolacore'); ?></button>
                        <?php endif; ?>
                        <?php if ($lolacore_can_delete) : ?>
                            <button type="button"
                                    class="lc-action-btn ghost lc-skill-delete-btn"
                                    data-skill-name="<?php echo esc_attr($lolacore_name); ?>"><?php echo esc_html__('Delete', 'lolacore'); ?></button>
                        <?php endif; ?>
                    </div>

                    <!-- Read-only source viewer (hidden by default, expanded by JS) -->
                    <?php
                    if ($lolacore_can_edit) :
                        // Prefer the raw DB content (preserves frontmatter); fall back to body if missing.
                        $lolacore_raw_content = $dbSkillSource[$lolacore_name] ?? $lolacore_skill->getBody();
                    ?>
                    <div class="lc-skill-viewer" style="display:none;">
                        <p class="lc-skill-viewer-hint">
                            <?php
                            printf(
                                /* translators: %s: skill name inside an example chat request. */
                                esc_html__('Read-only source. To modify this skill, ask Lola in the chat — e.g. "improve the skill %s so that…".', 'lolacore'),
                                '<em>' . esc_html($lolacore_name) . '</em>'
                            );
                            ?>
                        </p>
                        <pre class="lc-skill-viewer-source"><?php echo esc_html($lolacore_raw_content); ?></pre>
                    </div>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
            </div><!-- /.lc-skills-group-body -->
        </details>
    <?php endforeach; ?>

    <!-- Broken skills -->
    <?php if (!empty($errors)) : ?>
        <div class="lc-skills-broken">
            <h4 class="lc-skills-group-title lc-skills-group-title--error">
                <?php
                printf(
                    /* translators: %d: number of skills that failed to parse. */
                    esc_html__('Broken skills (%d)', 'lolacore'),
                    (int) count($errors)
                );
                ?>
            </h4>
            <?php foreach ($errors as $error) : ?>
                <div class="lc-skill-error-row">
                    <span class="lc-skill-badge lc-skill-badge--error"><?php echo esc_html__('Parse Error', 'lolacore'); ?></span>
                    <span class="lc-skill-error-msg">
                        <?php echo esc_html(method_exists($error, 'getUserMessage') ? $error->getUserMessage() : $error->getMessage()); ?>
                    </span>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <!-- =============================================================== -->
    <!-- Import Skill Modal -->
    <!-- =============================================================== -->
    <dialog class="lc-skill-import-modal" id="lolacore-import-modal">
        <div class="lc-skill-import-modal-inner">
            <h3><?php echo esc_html__('Import Skill', 'lolacore'); ?></h3>

            <div class="lc-skill-import-tabs">
                <button type="button" class="lc-skill-import-tab active" data-tab="paste"><?php echo esc_html__('Paste markdown', 'lolacore'); ?></button>
                <button type="button" class="lc-skill-import-tab" data-tab="upload"><?php echo esc_html__('Upload .md file', 'lolacore'); ?></button>
            </div>

            <div class="lc-skill-import-panel" data-panel="paste" style="display:block;">
                <textarea id="lolacore-import-paste" rows="15" placeholder="<?php echo esc_attr__('Paste skill markdown here...', 'lolacore'); ?>&#10;---&#10;name: my-skill&#10;description: What this skill does&#10;---&#10;Body instructions..."></textarea>
            </div>

            <div class="lc-skill-import-panel" data-panel="upload" style="display:none;">
                <label class="lc-file-upload-label" for="lolacore-import-file">
                    <?php echo esc_html__('Choose .md file (max 100 KB)', 'lolacore'); ?>
                </label>
                <input type="file" id="lolacore-import-file" accept=".md" />
                <span class="lc-file-name" id="lolacore-import-file-name"><?php echo esc_html__('No file selected', 'lolacore'); ?></span>
            </div>

            <div class="lc-skill-import-error" id="lolacore-import-error" style="display:none;"></div>

            <div class="lc-skill-import-actions">
                <button type="button" class="lc-action-btn primary" id="lolacore-import-submit">
                    <span class="lc-btn-label"><?php echo esc_html__('Import', 'lolacore'); ?></span>
                    <span class="lc-btn-spinner" style="display:none;">⏳</span>
                </button>
                <button type="button" class="lc-action-btn ghost" id="lolacore-import-cancel"><?php echo esc_html__('Cancel', 'lolacore'); ?></button>
            </div>
        </div>
    </dialog>

    <!-- =============================================================== -->
    <!-- Advanced Parameters Panel -->
    <!-- =============================================================== -->
    <details class="lolacore-advanced-panel" id="lolacore-skills-advanced">
        <summary><?php echo esc_html__('Advanced parameters ▼', 'lolacore'); ?></summary>

        <div class="lolacore-warning">
            <strong><?php echo esc_html__('Warning:', 'lolacore'); ?></strong> <?php echo esc_html__('These parameters fine-tune how Lola loads and applies skills. Setting them outside the recommended range can lead to:', 'lolacore'); ?>
            <ul>
                <li><?php echo esc_html__('slower responses (added latency on every turn)', 'lolacore'); ?></li>
                <li><?php echo esc_html__('unpredictable or inconsistent behavior', 'lolacore'); ?></li>
                <li><?php echo esc_html__('instability if limits are pushed too high', 'lolacore'); ?></li>
                <li><?php echo esc_html__('higher token consumption per request', 'lolacore'); ?></li>
            </ul>
            <?php echo esc_html__('The "Skill character budget" is a token approximation based on characters (≈ chars/3, conservative estimate). Actual consumption may vary ±20% depending on the LLM provider (Anthropic, OpenAI, DeepSeek tokenize differently). Default values are calibrated for 95% of use cases.', 'lolacore'); ?>
        </div>

        <div class="lolacore-field">
            <label for="lolacore-param-max-active"><?php echo esc_html__('Max active skills (5–100)', 'lolacore'); ?></label>
            <input type="number" id="lolacore-param-max-active" name="max_active"
                   value="<?php echo esc_attr((string) ($paramValues['max_active'] ?? 30)); ?>"
                   min="5" max="100">
        </div>
        <div class="lolacore-field">
            <label for="lolacore-param-max-per-prompt"><?php echo esc_html__('Max skills per prompt (1–15)', 'lolacore'); ?></label>
            <input type="number" id="lolacore-param-max-per-prompt" name="max_per_prompt"
                   value="<?php echo esc_attr((string) ($paramValues['max_per_prompt'] ?? 5)); ?>"
                   min="1" max="15">
        </div>
        <div class="lolacore-field">
            <label for="lolacore-param-char-budget"><?php echo esc_html__('Skill character budget (1500–15000)', 'lolacore'); ?></label>
            <input type="number" id="lolacore-param-char-budget" name="char_budget"
                   value="<?php echo esc_attr((string) ($paramValues['char_budget'] ?? 6000)); ?>"
                   min="1500" max="15000">
        </div>
        <div class="lolacore-field">
            <label for="lolacore-param-cache-ttl"><?php echo esc_html__('Skill registry cache (5–1440 min)', 'lolacore'); ?></label>
            <input type="number" id="lolacore-param-cache-ttl" name="cache_ttl_min"
                   value="<?php echo esc_attr((string) ($paramValues['cache_ttl_min'] ?? 60)); ?>"
                   min="5" max="1440">
        </div>
        <div class="lolacore-field">
            <label>
                <input type="checkbox" id="lolacore-param-require-approval" name="require_approval" value="1"
                       <?php checked(!empty($paramValues['require_approval'])); ?>>
                <?php echo esc_html__('Require manual approval for Lola-generated skills', 'lolacore'); ?>
            </label>
        </div>

        <div class="lolacore-field-actions">
            <button type="button" class="lc-action-btn primary" id="lolacore-save-skill-params"><?php echo esc_html__('Save', 'lolacore'); ?></button>
            <button type="button" class="lc-action-btn ghost" id="lolacore-restore-skill-defaults"><?php echo esc_html__('Restore defaults', 'lolacore'); ?></button>
        </div>
    </details>

    </div><!-- /.lc-skills-content -->

</div>
