<?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'],
    Skill::STATUS_INACTIVE           => ['class' => 'lc-skill-badge--inactive',  'label' => 'Inactive'],
    Skill::STATUS_NO_TRIGGERS        => ['class' => 'lc-skill-badge--inactive',  'label' => 'No triggers — add rules to activate'],
    Skill::STATUS_INCOMPATIBLE       => ['class' => 'lc-skill-badge--warn',      'label' => 'Requires newer LolaCore'],
    Skill::STATUS_UNMET_DEPENDENCIES => ['class' => 'lc-skill-badge--error',     'label' => 'Missing dependencies'],
];
?>

<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>Enable the Skills system</strong>
                <span>Activates the entire Skills layer. When on, all built-in skills load together.</span>
            </div>
        </div>
        <div class="lc-skills-beta-notice">
            <span class="lc-pill amber">Beta</span>
            <p>
                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.
            </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">
                <strong><?php echo esc_html((string) $activeCount); ?></strong> / <?php echo esc_html((string) $maxActive); ?> active
            </span>
            <div class="lc-skills-counter-actions">
                <button type="button" class="lc-action-btn ghost" id="lolacore-import-skill-btn">Import skill</button>
                <button type="button" class="lc-action-btn ghost" id="lolacore-reload-skills">Reload skills</button>
            </div>
        </div>
        <p class="lc-skills-author-hint">
            Want a new skill written for you? Ask Lola directly in the chat — she'll guide you through it.
        </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">— managed by the master toggle</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">priority: <?php echo esc_html((string) $lolacore_skill->getPriority()); ?></span>
                        </div>
                        <p class="lc-skill-desc"><?php echo esc_html($lolacore_skill->getDescription()); ?></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); ?>">View source</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); ?>">Delete</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">
                            Read-only source. To modify this skill, ask Lola in the chat — e.g. <em>"mejora la skill <?php echo esc_html($lolacore_name); ?> para que…"</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">
                Broken skills (<?php echo esc_html((string) count($errors)); ?>)
            </h4>
            <?php foreach ($errors as $error) : ?>
                <div class="lc-skill-error-row">
                    <span class="lc-skill-badge lc-skill-badge--error">Parse Error</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>Import Skill</h3>

            <div class="lc-skill-import-tabs">
                <button type="button" class="lc-skill-import-tab active" data-tab="paste">Paste markdown</button>
                <button type="button" class="lc-skill-import-tab" data-tab="upload">Upload .md file</button>
            </div>

            <div class="lc-skill-import-panel" data-panel="paste" style="display:block;">
                <textarea id="lolacore-import-paste" rows="15" placeholder="Paste skill markdown here...&#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">
                    Choose .md file (max 100 KB)
                </label>
                <input type="file" id="lolacore-import-file" accept=".md" />
                <span class="lc-file-name" id="lolacore-import-file-name">No file selected</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">Import</span>
                    <span class="lc-btn-spinner" style="display:none;">⏳</span>
                </button>
                <button type="button" class="lc-action-btn ghost" id="lolacore-import-cancel">Cancel</button>
            </div>
        </div>
    </dialog>

    <!-- =============================================================== -->
    <!-- Advanced Parameters Panel -->
    <!-- =============================================================== -->
    <details class="lolacore-advanced-panel" id="lolacore-skills-advanced">
        <summary>Advanced parameters ▼</summary>

        <div class="lolacore-warning">
            <strong>Warning:</strong> These parameters fine-tune how Lola loads and applies skills. Setting them outside the recommended range can lead to:
            <ul>
                <li>slower responses (added latency on every turn)</li>
                <li>unpredictable or inconsistent behavior</li>
                <li>instability if limits are pushed too high</li>
                <li>higher token consumption per request</li>
            </ul>
            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.
        </div>

        <div class="lolacore-field">
            <label for="lolacore-param-max-active">Max active skills (5–100)</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">Max skills per prompt (1–15)</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">Skill character budget (1500–15000)</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">Skill registry cache (5–1440 min)</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'])); ?>>
                Require manual approval for Lola-generated skills
            </label>
        </div>

        <div class="lolacore-field-actions">
            <button type="button" class="lc-action-btn primary" id="lolacore-save-skill-params">Save</button>
            <button type="button" class="lc-action-btn ghost" id="lolacore-restore-skill-defaults">Restore defaults</button>
        </div>
    </details>

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

</div>
