<?php
/**
 * Playbooks management section — list inventory or manual markdown editor.
 *
 * @var string                                           $view
 * @var string                                           $editSlug
 * @var array<string, \LolaCore\Playbooks\Playbook>      $playbooks
 * @var array<int, \Throwable>                           $errors
 * @var array<string, string>                             $dbPlaybookSource
 * @var array<string, int>                               $dbPlaybookIds
 * @var array<string, string>                            $allRawContent
 * @var string                                           $editContent
 * @var int                                              $editPlaybookId
 * @var bool                                             $isNewPlaybook
 * @var string                                           $listUrl
 *
 * @package LolaCore
 * @license GPL-2.0-or-later
 */

declare(strict_types=1);

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

use LolaCore\Admin\Settings;
use LolaCore\Playbooks\PlaybookDocumentReader;
use LolaCore\Playbooks\Playbook;

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

$lolacore_badge_map = [
    Playbook::STATUS_ACTIVE   => ['class' => 'lc-skill-badge--active',   'label' => __('Active', 'lolacore')],
    Playbook::STATUS_INACTIVE => ['class' => 'lc-skill-badge--inactive', 'label' => __('Inactive', 'lolacore')],
    Playbook::STATUS_ARCHIVED => ['class' => 'lc-skill-badge--warn',     'label' => __('Archived', 'lolacore')],
];

if ($view === 'edit' || $isNewPlaybook) :
    $lolacore_edit_title = $isNewPlaybook
        ? __('New playbook', 'lolacore')
        : sprintf(
            /* translators: %s: playbook slug */
            __('Edit playbook: %s', 'lolacore'),
            $editSlug
        );
    ?>
    <div class="lc-card lc-playbooks-editor">
        <div class="lc-card-header">
            <h3><?php echo esc_html($lolacore_edit_title); ?></h3>
        </div>
        <p class="description">
            <?php echo esc_html__('Full markdown with YAML frontmatter. The name: field in frontmatter is the canonical slug. See the built-in playbook-format manual for the contract.', 'lolacore'); ?>
        </p>
        <?php
        Settings::echoPlaybooksDocParagraph(
            /* translators: %s: linked "playbooks guide" label */
            __('Frontmatter reference and save-error fixes: %s.', 'lolacore')
        );
        ?>

        <?php if ($isNewPlaybook) : ?>
            <div class="lolacore-field">
                <label for="lolacore-playbook-slug"><?php echo esc_html__('Slug (from frontmatter name)', 'lolacore'); ?></label>
                <input type="text" id="lolacore-playbook-slug" class="lc-input" value="my-playbook" readonly autocomplete="off">
            </div>
        <?php endif; ?>

        <div class="lolacore-field">
            <label for="lolacore-playbook-content"><?php echo esc_html__('Content', 'lolacore'); ?></label>
            <textarea id="lolacore-playbook-content" class="lc-input" rows="24" style="font-family: var(--lc-font-mono, monospace); width:100%;"><?php echo esc_textarea($editContent); ?></textarea>
        </div>

        <div class="lc-playbooks-editor-actions">
            <button type="button"
                    class="lc-action-btn primary"
                    id="lolacore-playbook-save"
                    data-playbook-id="<?php echo esc_attr((string) $editPlaybookId); ?>"
                    data-playbook-slug="<?php echo esc_attr($editSlug); ?>"
                    data-is-new="<?php echo $isNewPlaybook ? '1' : '0'; ?>">
                <?php echo esc_html__('Save playbook', 'lolacore'); ?>
            </button>
            <a class="lc-action-btn ghost" href="<?php echo esc_url($listUrl); ?>"><?php echo esc_html__('Back to list', 'lolacore'); ?></a>
        </div>
    </div>
    <?php
    return;
endif;
?>

<div id="lolacore-playbook-distill-review" class="lc-card lc-playbooks-editor" style="display:none;">
    <div class="lc-card-header">
        <h3><?php echo esc_html__('Review distilled playbook', 'lolacore'); ?></h3>
    </div>
    <p class="description">
        <?php echo esc_html__('Edit the draft below, then save it to your database playbooks (inactive until you activate it). Distillation uses your configured AI provider.', 'lolacore'); ?>
    </p>
    <div id="lolacore-playbook-distill-validation" class="notice notice-warning inline" style="display:none;margin:0 0 12px;"></div>
    <div class="lolacore-field">
        <label for="lolacore-playbook-distill-slug"><?php echo esc_html__('Slug (from frontmatter name)', 'lolacore'); ?></label>
        <input type="text" id="lolacore-playbook-distill-slug" class="lc-input" value="" readonly autocomplete="off">
    </div>
    <div class="lolacore-field">
        <label for="lolacore-playbook-distill-content"><?php echo esc_html__('Draft content', 'lolacore'); ?></label>
        <textarea id="lolacore-playbook-distill-content" class="lc-input" rows="24" style="font-family: var(--lc-font-mono, monospace); width:100%;"></textarea>
    </div>
    <div class="lolacore-field">
        <label for="lolacore-playbook-distill-instructions"><?php echo esc_html__('Regeneration instructions (optional)', 'lolacore'); ?></label>
        <textarea id="lolacore-playbook-distill-instructions" class="lc-input" rows="3" placeholder="<?php echo esc_attr__('e.g. Shorten the body, add more examples, use domain woocommerce…', 'lolacore'); ?>"></textarea>
    </div>
    <div class="lc-playbooks-editor-actions">
        <button type="button" class="lc-action-btn primary" id="lolacore-playbook-distill-save" data-playbook-id="0" data-playbook-slug="" data-is-new="1">
            <?php echo esc_html__('Save playbook', 'lolacore'); ?>
        </button>
        <button type="button" class="lc-action-btn ghost" id="lolacore-playbook-distill-regenerate">
            <?php echo esc_html__('Regenerate', 'lolacore'); ?>
        </button>
        <button type="button" class="lc-action-btn ghost" id="lolacore-playbook-distill-cancel">
            <?php echo esc_html__('Cancel', 'lolacore'); ?>
        </button>
    </div>
</div>

<div class="lc-skills-section" id="lolacore-playbooks-list">

    <div class="lc-skills-counter">
        <div class="lc-skills-counter-row">
            <span class="lc-skills-counter-text">
                <?php
                printf(
                    /* translators: %d: total playbook count */
                    esc_html(_n('%d playbook', '%d playbooks', count($playbooks), 'lolacore')),
                    (int) count($playbooks)
                );
                ?>
            </span>
            <div class="lc-skills-counter-actions">
                <a class="lc-action-btn primary" href="<?php echo esc_url(add_query_arg('view', 'new', $listUrl)); ?>"><?php echo esc_html__('New playbook', 'lolacore'); ?></a>
                <button type="button" class="lc-action-btn primary" id="lolacore-playbook-upload-btn"><?php echo esc_html__('Upload playbook', 'lolacore'); ?></button>
                <input type="file" id="lolacore-playbook-upload-input" accept=".txt,.md,.markdown,.docx,.html,.htm" hidden>
                <button type="button" class="lc-action-btn ghost" id="lolacore-reload-playbooks"><?php echo esc_html__('Reload playbooks', 'lolacore'); ?></button>
            </div>
        </div>
        <p class="lc-skills-author-hint">
            <?php
            printf(
                /* translators: 1: max extracted characters (number), 2: approximate page count */
                esc_html__(
                    'Accepted formats: TXT, MD, DOCX, HTML. After extraction, the document must be %1$s characters or less (roughly 10–15 pages of dense text). Lola will distill it into a playbook you can review before saving. For longer manuals, upload one section at a time or ask Lola in the chat.',
                    'lolacore'
                ),
                esc_html(number_format(PlaybookDocumentReader::MAX_EXTRACTED_CHARS))
            );
            ?>
        </p>
    </div>

    <?php foreach ($lolacore_origin_order as $lolacore_origin) : ?>
        <?php
        $lolacore_group = array_filter($playbooks, static fn(Playbook $p) => $p->getOrigin() === $lolacore_origin);
        if ($lolacore_group === []) {
            continue;
        }
        $lolacore_open_default = ($lolacore_origin === Playbook::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::playbookOriginLabel($lolacore_origin)); ?></span>
                <span class="lc-skills-group-count"><?php echo esc_html((string) count($lolacore_group)); ?></span>
            </summary>
            <div class="lc-skills-group-body">
                <?php foreach ($lolacore_group as $lolacore_playbook) : ?>
                    <?php
                    $lolacore_slug   = $lolacore_playbook->getSlug();
                    $lolacore_status = $lolacore_playbook->getStatus();
                    $lolacore_origin = $lolacore_playbook->getOrigin();
                    $lolacore_is_on  = ($lolacore_status === Playbook::STATUS_ACTIVE);
                    $lolacore_can_toggle = ($lolacore_origin === Playbook::ORIGIN_DB);
                    $lolacore_can_delete = ($lolacore_origin === Playbook::ORIGIN_DB);
                    $lolacore_can_edit   = ($lolacore_origin === Playbook::ORIGIN_DB);
                    $lolacore_badge      = $lolacore_badge_map[$lolacore_status] ?? $lolacore_badge_map[Playbook::STATUS_ACTIVE];
                    $lolacore_raw        = $allRawContent[$lolacore_slug] ?? $lolacore_playbook->getBody();
                    ?>
                    <div class="lc-skill-row"
                         data-playbook-slug="<?php echo esc_attr($lolacore_slug); ?>"
                         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-playbook-toggle"
                                           data-playbook-slug="<?php echo esc_attr($lolacore_slug); ?>"
                                           <?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_slug); ?></span>
                                <span class="lc-skill-priority"><?php echo esc_html($lolacore_playbook->getDomain()); ?> · <?php echo esc_html($lolacore_playbook->getType()); ?></span>
                            </div>
                            <p class="lc-skill-desc"><?php echo esc_html($lolacore_playbook->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">
                            <button type="button"
                                    class="lc-action-btn ghost lc-playbook-view-btn"
                                    data-playbook-slug="<?php echo esc_attr($lolacore_slug); ?>"><?php echo esc_html__('View', 'lolacore'); ?></button>
                            <?php if ($lolacore_can_edit) : ?>
                                <a class="lc-action-btn ghost"
                                   href="<?php echo esc_url(add_query_arg(['view' => 'edit', 'playbook_slug' => $lolacore_slug], $listUrl)); ?>"><?php echo esc_html__('Edit', 'lolacore'); ?></a>
                            <?php endif; ?>
                            <?php if ($lolacore_can_delete) : ?>
                                <button type="button"
                                        class="lc-action-btn ghost lc-playbook-delete-btn"
                                        data-playbook-slug="<?php echo esc_attr($lolacore_slug); ?>"><?php echo esc_html__('Delete', 'lolacore'); ?></button>
                            <?php endif; ?>
                        </div>

                        <div class="lc-skill-viewer" style="display:none;">
                            <p class="lc-skill-viewer-hint">
                                <?php
                                if ($lolacore_can_edit) {
                                    esc_html_e('Read-only preview. Use Edit to change database playbooks, or ask Lola in the chat.', 'lolacore');
                                } else {
                                    esc_html_e('Read-only — shipped with the plugin, an addon, or your filesystem folder.', 'lolacore');
                                }
                                ?>
                            </p>
                            <pre class="lc-skill-viewer-source"><?php echo esc_html($lolacore_raw); ?></pre>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </details>
    <?php endforeach; ?>

    <?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 broken playbooks */
                    esc_html__('Broken playbooks (%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($error->getMessage()); ?>
                    </span>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

</div>
