<?php
/**
 * @var \App\View\AppView $this
 * @var \App\Model\Entity\Faq $faq
 * @var array|null $categories
 * @var array|null $allTags
 */
?>
<div class="row">
    <div class="col-12 col-md-10 offset-md-1">
        <div class="card shadow-sm p-4 mt-4">
            <div class="d-flex gap-2">
                <?= $this->Html->link('← Back', ['controller' => 'Admin', 'action' => 'index'], ['class' => 'btn btn-outline-secondary']) ?>
                <?= $this->Html->link('Back to List', ['action' => 'index'], ['class' => 'btn btn-outline-secondary']) ?>
            </div>
            <h2 class="mb-4 text-center"><?= __('Add New Prompt') ?></h2>

            <?= $this->Form->create($faq, ['class' => 'needs-validation']) ?>

            <!-- Category: free text with suggestions (allows new values) -->
            <div class="mb-3">
                <label for="category-input" class="form-label">Category (optional)</label>
                <input
                    type="text"
                    id="category-input"
                    name="category"
                    class="form-control"
                    value="<?= h($faq->category ?? '') ?>"
                    placeholder="Select or type a new category…"
                    list="categories-suggestions"
                    autocomplete="off"
                >
                <datalist id="categories-suggestions">
                    <?php foreach (($categories ?? []) as $c): ?>
                        <option value="<?= h($c) ?>"></option>
                    <?php endforeach; ?>
                </datalist>
                <div class="form-text">Pick from suggestions or type a new category.</div>
            </div>

            <div class="mb-3">
                <?= $this->Form->control('question', [
                    'type' => 'textarea',
                    'label' => 'Question / Prompt',
                    'class' => 'form-control',
                    'rows' => 3,
                    'placeholder' => 'Enter the question or chatbot prompt'
                ]) ?>
            </div>

            <div class="mb-3">
                <?= $this->Form->control('answer', [
                    'type' => 'textarea',
                    'label' => 'Answer / Canonical Content',
                    'class' => 'form-control',
                    'rows' => 6,
                    'placeholder' => 'Provide the official answer/content here'
                ]) ?>
            </div>

            <div class="mb-3">
                <?= $this->Form->control('link', [
                    'label' => 'Reference Link (optional)',
                    'class' => 'form-control',
                    'placeholder' => 'https://example.com'
                ]) ?>
            </div>

            <!-- Tags: input on top, chips displayed below; writes CSV to hidden 'tags' -->
            <div class="mb-3">
                <label class="form-label">Tags</label>

                <!-- Typing input with datalist suggestions (from $allTags) -->
                <input
                    type="text"
                    id="tag-typing"
                    class="form-control"
                    placeholder="Type a tag and press Enter (or comma)…"
                    list="tags-suggestions"
                    autocomplete="off"
                >
                <datalist id="tags-suggestions">
                    <?php foreach (($allTags ?? []) as $t): ?>
                        <option value="<?= h($t) ?>"></option>
                    <?php endforeach; ?>
                </datalist>

                <!-- Chips container now sits BELOW the input -->
                <div id="tag-chips" class="tag-chips border rounded p-2 d-flex flex-wrap gap-2 mt-2"></div>

                <!-- Hidden field that actually gets submitted as CSV -->
                <?= $this->Form->hidden('tags', ['id' => 'tags-hidden']) ?>

                <div class="form-text">Press <strong>Enter</strong> or <strong>,</strong> to add. Click a chip to remove.</div>
            </div>

            <!-- Submit + end of form -->
            <div class="text-center mt-3">
                <?= $this->Form->button(__('Save'), [
                    'type' => 'submit',
                    'class' => 'btn btn-primary btn-lg px-5'
                ]) ?>
                <?= $this->Html->link(__('Cancel'), '/admin', [
                    'class' => 'btn btn-outline-secondary ms-2'
                ]) ?>
            </div>

            <?= $this->Form->end() ?>

            <style>
                /* Minimal chip styling */
                .tag-chips { min-height: 44px; background: #fafafa; }
                .tag-chip {
                    display: inline-flex; align-items: center; gap: .35rem;
                    padding: .35rem .6rem; border-radius: 999px;
                    background: #eef2ff; color: #1e1b4b; font-weight: 600;
                    box-shadow: 0 1px 2px rgba(0,0,0,.05);
                }
                .tag-chip button {
                    border: 0; background: transparent; margin-left: .1rem;
                    font-size: 1rem; line-height: 1; cursor: pointer; color: #334155;
                }
                .tag-chip button:hover { color: #ef4444; }
            </style>

            <script>
                // Lightweight tags input: chips below input, writes CSV to hidden 'tags'
                (() => {
                    const input  = document.getElementById('tag-typing');
                    const hidden = document.getElementById('tags-hidden');
                    const chips  = document.getElementById('tag-chips');

                    // Maintain unique set of tags
                    const set = new Set();

                    function refreshHidden() {
                        hidden.value = Array.from(set).join(',');
                    }

                    function normalize(raw) {
                        // Lowercase, trim, collapse spaces into hyphen for consistency
                        return (raw || '').toLowerCase().trim().replace(/\s+/g, '-');
                    }

                    function createChip(tag) {
                        const el = document.createElement('span');
                        el.className = 'tag-chip';
                        el.textContent = tag;

                        const btn = document.createElement('button');
                        btn.type = 'button';
                        btn.setAttribute('aria-label', 'Remove');
                        btn.innerHTML = '&times;';
                        btn.onclick = () => {
                            set.delete(tag);
                            el.remove();
                            refreshHidden();
                        };

                        el.appendChild(btn);
                        return el;
                    }

                    function addTag(raw) {
                        const tag = normalize(raw);
                        if (!tag || set.has(tag)) return;
                        set.add(tag);
                        chips.appendChild(createChip(tag));
                        refreshHidden();
                    }

                    // Add on Enter or comma
                    input.addEventListener('keydown', (e) => {
                        if (e.key === 'Enter' || e.key === ',') {
                            e.preventDefault();
                            addTag(input.value);
                            input.value = '';
                        }
                    });

                    // Also add on blur
                    input.addEventListener('blur', () => {
                        if (input.value.trim() !== '') {
                            addTag(input.value);
                            input.value = '';
                        }
                    });

                    // Restore from hidden value (useful on validation errors or edit reuse)
                    if (hidden.value) {
                        hidden.value.split(',').forEach(addTag);
                    }
                })();
            </script>
