<?php
/**
 * @var \App\View\AppView $this
 * @var iterable<\App\Model\Entity\Faq> $faqs
 * @var array|null $allTags
 * @var string|null $tag
 * @var string|null $q
 */
?>
<style>
    /* ===== Shell ===== */
    .faqs.index .page{max-width:1000px;margin:28px auto;padding:0 16px}
    .faqs.index .card{background:#fff;border:1px solid #eaeaea;border-radius:16px;box-shadow:0 6px 24px rgba(0,0,0,.06)}
    .faqs.index .header{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:16px 18px}
    .faqs.index .title{font-size:1.15rem;font-weight:800;margin:0;color:#111827}
    .faqs.index .primary-btn{background:#111827;color:#fff;border:1px solid #111827;border-radius:10px;padding:10px 14px;font-weight:600;text-decoration:none}

    /* ===== Filters ===== */
    .faqs.index .filters{padding:12px 18px 14px;border-top:1px solid #f0f0f0;background:#fafafa}
    .faqs.index .filters form{display:grid;gap:10px;grid-template-columns:220px minmax(200px,1fr) auto;align-items:center}
    .faqs.index .filters .btn-reset{border:1px solid #e5e7eb;background:#fff;color:#374151;border-radius:10px;padding:10px 14px;font-weight:600;text-decoration:none}
    @media (max-width:768px){.faqs.index .filters form{grid-template-columns:1fr}}

    /* ===== Desktop Table ===== */
    .faqs.index .table-wrap{border-top:1px solid #f3f4f6}
    .faqs.index .table-view{display:block}
    @media (max-width:768px){.faqs.index .table-view{display:none}}
    .faqs.index table{width:100%;border-collapse:collapse;background:#fff;table-layout:fixed}
    .faqs.index thead th{background:#fff;color:#374151;font-weight:700;font-size:.92rem;text-align:left;padding:10px 12px;white-space:nowrap;border-bottom:1px solid #e5e7eb}
    .faqs.index tbody td{padding:10px 12px;border-top:1px solid #f7f7f8;vertical-align:top}
    .faqs.index tbody tr:hover{background:#fbfbff}

    /* column widths */
    .faqs.index th.col-category{width:180px}
    .faqs.index th.col-question{width:35%}
    .faqs.index th.col-answer{width:28%}
    .faqs.index th.col-link{width:16%}
    .faqs.index th.col-tags{width:12%}
    .faqs.index th.col-updated{width:120px}
    .faqs.index th.col-created{width:120px}
    .faqs.index th.col-actions{width:120px}

    /* trim long text */
    .faqs.index .clamp-2{display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
    .faqs.index .link-cell{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}

    /* chips */
    .faqs.index .chips{display:flex;flex-wrap:wrap;gap:6px}
    .faqs.index .chip{display:inline-block;padding:.2rem .5rem;border-radius:999px;background:#eef2ff;color:#1e1b4b;font-weight:600;font-size:.78rem}
    .faqs.index .muted{color:#6b7280;font-size:.88rem}

    /* actions */
    .faqs.index td.actions a{display:inline-block;margin-right:8px;text-decoration:none;font-weight:600;font-size:.9rem;padding:6px 10px;border-radius:8px;border:1px solid #e5e7eb;color:#374151;background:#fff}
    .faqs.index td.actions a:hover{background:#f3f4f6}

    /* expand caret inside QUESTION cell */
    .faqs.index .inline-toggle{display:flex;align-items:flex-start;gap:8px}
    .faqs.index .caret-btn{border:1px solid #e5e7eb;background:#fff;border-radius:8px;padding:4px 8px;line-height:1;cursor:pointer}
    .faqs.index .caret{display:inline-block;transition:transform .15s ease}
    .faqs.index .caret.rotate{transform:rotate(90deg)}
    .faqs.index tr.expand{display:none;background:#fbfbff}
    .faqs.index tr.expand td{padding:14px 16px;border-top:0}
    .faqs.index .expand-inner{display:grid;gap:10px;grid-template-columns:1fr}
    .faqs.index .expand-title{font-weight:700;color:#111827;margin-bottom:4px}

    /* ===== Mobile Cards ===== */
    .faqs.index .card-list{display:none;padding:10px 12px 16px}
    @media (max-width:768px){.faqs.index .card-list{display:grid;gap:10px}}
    .faqs.index .faq-card{border:1px solid #eee;border-radius:12px;padding:10px 12px;background:#fff}
    .faqs.index .faq-card summary{list-style:none;display:flex;align-items:flex-start;gap:10px;cursor:pointer}
    .faqs.index .faq-card summary::-webkit-details-marker{display:none}
    .faqs.index .faq-card .caret-mobile{display:inline-block;transform:rotate(0deg);transition:transform .15s ease;margin-top:2px}
    .faqs.index .faq-card[open] .caret-mobile{transform:rotate(90deg)}
    .faqs.index .faq-card .meta{display:flex;gap:8px;flex-wrap:wrap}
    .faqs.index .faq-card .time{color:#6b7280;font-size:.8rem}
    .faqs.index .faq-card .body{padding-top:8px;display:grid;gap:10px}
    .faqs.index .faq-card .actions{padding-top:6px}

    .faqs.index .back-btn {
        display:inline-block;
        padding:6px 12px;
        border:1px solid #e5e7eb;
        border-radius:8px;
        background:#f9fafb;
        color:#374151;
        font-weight:600;
        text-decoration:none;
        font-size:.9rem;
    }
    .faqs.index .back-btn:hover {
        background:#f3f4f6;
    }
</style>

<div class="faqs index page">
    <div class="card">
        <div class="header">
            <div style="display:flex;align-items:center;gap:12px;">
                <?= $this->Html->link('← Back', '/admin', ['class' => 'back-btn']) ?>
                <h3 class="title">Knowledge Repository</h3>
            </div>
            <?= $this->Html->link('＋ New Prompt', ['action' => 'add'], ['class' => 'primary-btn']) ?>
        </div>

        <div class="filters">
            <form method="get" role="search" id="faq-filters">
                <select name="tag" class="form-select" aria-label="Filter by tag" onchange="this.form.submit()">
                    <option value="">All tags</option>
                    <?php foreach (($allTags ?? []) as $t): ?>
                        <option value="<?= h($t) ?>" <?= isset($tag) && strtolower((string)$tag) === (string)$t ? 'selected' : '' ?>><?= h($t) ?></option>
                    <?php endforeach; ?>
                </select>
                <input type="search" name="q" value="<?= h($q ?? '') ?>" class="form-control" placeholder="Search question, answer, link…" aria-label="Keyword">
                <a class="btn-reset" href="<?= $this->Url->build(['action' => 'index']) ?>">Reset</a>
            </form>
        </div>

        <!-- ===== Desktop / Tablet Table ===== -->
        <div class="table-wrap table-view">
            <div class="table-responsive">
                <table>
                    <thead>
                    <tr>
                        <th class="col-category"><?= $this->Paginator->sort('category', 'Category') ?></th>
                        <th class="col-question"><?= $this->Paginator->sort('question', 'Question') ?></th>
                        <th class="col-answer"><?= $this->Paginator->sort('answer', 'Answer') ?></th>
                        <th class="col-link"><?= $this->Paginator->sort('link', 'Link') ?></th>
                        <th class="col-tags">Tags</th>
                        <th class="col-updated"><?= $this->Paginator->sort('updated_at', 'Last Updated') ?></th>
                        <th class="col-created"><?= $this->Paginator->sort('created_at', 'Created') ?></th>
                        <th class="col-actions actions"><?= __('Actions') ?></th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($faqs as $faq): ?>
                        <?php $panelId = 'faq-' . (int)$faq->id . '-panel'; ?>
                        <!-- main row -->
                        <tr class="clickable" data-target="#<?= h($panelId) ?>">
                            <td>
                                <?= $faq->category ? '<span class="chip">'.h($faq->category).'</span>' : '<span class="muted">—</span>' ?>
                            </td>
                            <td>
                                <div class="inline-toggle">
                                    <button type="button" class="caret-btn" aria-expanded="false" aria-controls="<?= h($panelId) ?>">
                                        <span class="caret">▶</span>
                                    </button>
                                    <div class="clamp-2" title="<?= h($faq->question) ?>"><?= h($faq->question) ?></div>
                                </div>
                            </td>
                            <td title="<?= h($faq->answer) ?>"><div class="clamp-2"><?= h($faq->answer) ?></div></td>
                            <td class="link-cell">
                                <?php if (!empty($faq->link)): ?>
                                    <a href="<?= h($faq->link) ?>" target="_blank" rel="noopener noreferrer"><?= h($faq->link) ?></a>
                                <?php else: ?>
                                    <span class="muted">—</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if (!empty($faq->tags)): ?>
                                    <div class="chips">
                                        <?php foreach (explode(',', str_replace(' ', '', strtolower($faq->tags))) as $t): ?>
                                            <?php if ($t !== ''): ?><span class="chip"><?= h($t) ?></span><?php endif; ?>
                                        <?php endforeach; ?>
                                    </div>
                                <?php else: ?>
                                    <span class="muted">—</span>
                                <?php endif; ?>
                            </td>
                            <td><?= $faq->updated_at ? $faq->updated_at->i18nFormat('yyyy-MM-dd HH:mm','Australia/Melbourne') : '—' ?></td>
                            <td><?= $faq->created_at ? $faq->created_at->i18nFormat('yyyy-MM-dd HH:mm','Australia/Melbourne') : '—' ?></td>
                            <td class="actions">
                                <?= $this->Html->link('Edit', ['action' => 'edit', $faq->id]) ?>
                                <?= $this->Form->postLink('Archive', ['action' => 'delete', $faq->id], ['method'=>'delete','confirm'=>__('Do you confirm to archive this prompt # {0}?',$faq->id)]) ?>
                            </td>
                        </tr>
                        <!-- expand row -->
                        <tr id="<?= h($panelId) ?>" class="expand" role="region" aria-label="Details">
                            <td colspan="8">
                                <div class="expand-inner">
                                    <div>
                                        <div class="expand-title">Question</div>
                                        <div><?= nl2br(h($faq->question)) ?></div>
                                    </div>
                                    <div>
                                        <div class="expand-title">Answer</div>
                                        <div><?= nl2br(h($faq->answer)) ?></div>
                                    </div>
                                    <?php if (!empty($faq->link)): ?>
                                        <div>
                                            <div class="expand-title">Link</div>
                                            <a href="<?= h($faq->link) ?>" target="_blank" rel="noopener noreferrer"><?= h($faq->link) ?></a>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- ===== Mobile Card List ===== -->
        <div class="card-list">
            <?php foreach ($faqs as $faq): ?>
                <details class="faq-card">
                    <summary>
                        <span class="caret-mobile">▶</span>
                        <div>
                            <div style="font-weight:700;color:#111827;"><?= h($faq->question) ?></div>
                            <div class="meta">
                                <?= $faq->category ? '<span class="chip">'.h($faq->category).'</span>' : '' ?>
                                <?php if (!empty($faq->tags)): ?>
                                    <?php foreach (explode(',', str_replace(' ', '', strtolower($faq->tags))) as $t): ?>
                                        <?php if ($t !== ''): ?><span class="chip"><?= h($t) ?></span><?php endif; ?>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                            <div class="time">
                                <?= $faq->updated_at ? 'Updated '.$faq->updated_at->i18nFormat('yyyy-MM-dd HH:mm','Australia/Melbourne') : '' ?>
                            </div>
                        </div>
                    </summary>
                    <div class="body">
                        <div><strong>Answer</strong><br><?= nl2br(h($faq->answer)) ?></div>
                        <?php if (!empty($faq->link)): ?>
                            <div><strong>Link</strong><br><a href="<?= h($faq->link) ?>" target="_blank" rel="noopener noreferrer"><?= h($faq->link) ?></a></div>
                        <?php endif; ?>
                        <div class="actions">
                            <?= $this->Html->link('Edit', ['action' => 'edit', $faq->id]) ?> ·
                            <?= $this->Form->postLink('Delete', ['action' => 'delete', $faq->id], ['method'=>'delete','confirm'=>__('Delete # {0}?',$faq->id)]) ?>
                        </div>
                    </div>
                </details>
            <?php endforeach; ?>
        </div>

        <div class="footer">
            <ul class="pagination">
                <?= $this->Paginator->first('« First') ?>
                <?= $this->Paginator->prev('‹ Prev') ?>
                <?= $this->Paginator->numbers() ?>
                <?= $this->Paginator->next('Next ›') ?>
                <?= $this->Paginator->last('Last »') ?>
            </ul>
            <p class="muted"><?= $this->Paginator->counter(__('Page {{page}} of {{pages}}, showing {{current}} of {{count}}')) ?></p>
        </div>
    </div>
</div>

<script>
    // Desktop/tablet: expand/collapse (caret in Question cell or row click excluding links/forms)
    (() => {
        const table = document.querySelector('.faqs.index .table-view table');
        if (!table) return;

        function toggleRow(mainTr){
            const targetSel = mainTr.getAttribute('data-target');
            const panel = targetSel ? document.querySelector(targetSel) : null;
            if(!panel) return;
            const isOpen = panel.style.display === 'table-row';
            panel.style.display = isOpen ? 'none' : 'table-row';
            const btn = mainTr.querySelector('.caret-btn');
            const caret = mainTr.querySelector('.caret');
            if(btn) btn.setAttribute('aria-expanded', String(!isOpen));
            if(caret) caret.classList.toggle('rotate', !isOpen);
        }

        table.addEventListener('click', (e) => {
            const tr = e.target.closest('tr.clickable');
            if (!tr) return;
            if (e.target.closest('a') || e.target.closest('form') || e.target.closest('button:not(.caret-btn)')) return;
            toggleRow(tr);
        });

        table.querySelectorAll('.caret-btn').forEach(btn => {
            btn.addEventListener('click', (e) => { e.stopPropagation(); const tr = btn.closest('tr.clickable'); if (tr) toggleRow(tr); });
            btn.addEventListener('keydown', (e) => { if (e.key===' '||e.key==='Enter'){ e.preventDefault(); const tr=btn.closest('tr.clickable'); if(tr) toggleRow(tr);} });
        });
    })();
</script>
<script>
    /** --- Expand/collapse in table (desktop/tablet) --- */
    function initFaqExpand(scope = document) {
        const table = scope.querySelector('.faqs.index .table-view table');
        if (!table) return;

        // Remove old listeners by cloning nodes (to avoid multiple bindings after PJAX swaps)
        const cloned = table.cloneNode(true);
        table.parentNode.replaceChild(cloned, table);
        const tbl = cloned;

        function toggleRow(mainTr) {
            const targetSel = mainTr.getAttribute('data-target');
            const panel = targetSel ? document.querySelector(targetSel) : null;
            if (!panel) return;
            const isOpen = panel.style.display === 'table-row';
            panel.style.display = isOpen ? 'none' : 'table-row';
            const btn = mainTr.querySelector('.caret-btn');
            const caret = mainTr.querySelector('.caret');
            if (btn) btn.setAttribute('aria-expanded', String(!isOpen));
            if (caret) caret.classList.toggle('rotate', !isOpen);
        }

        tbl.addEventListener('click', (e) => {
            const tr = e.target.closest('tr.clickable');
            if (!tr) return;
            if (e.target.closest('a') || e.target.closest('form') || e.target.closest('button:not(.caret-btn)')) return;
            toggleRow(tr);
        });

        tbl.querySelectorAll('.caret-btn').forEach(btn => {
            btn.addEventListener('click', (e) => { e.stopPropagation(); const tr = btn.closest('tr.clickable'); if (tr) toggleRow(tr); });
            btn.addEventListener('keydown', (e) => {
                if (e.key===' '||e.key==='Enter'){ e.preventDefault(); const tr=btn.closest('tr.clickable'); if(tr) toggleRow(tr); }
            });
        });
    }

    /** --- PJAX: fetch part of page and swap DOM without losing focus --- */
    (function () {
        const container = document.querySelector('.faqs.index .card');
        const form = document.getElementById('faq-filters');
        if (!container || !form) { initFaqExpand(document); return; }

        const qInput    = form.querySelector('input[name="q"]');
        const tagSelect = form.querySelector('select[name="tag"]');
        const resetLink = form.querySelector('.btn-reset');

        const AREAS = ['.table-wrap', '.card-list', '.footer']; // areas to swap
        const DEBOUNCE_MS = 500;
        const MIN_LEN = 0;
        let timer = null;
        let lastQ = (qInput && qInput.value) || '';
        let lastTag = (tagSelect && tagSelect.value) || '';

        // Build URL from current form values
        function buildUrl() {
            const url = new URL(window.location.href);
            if (qInput)  url.searchParams.set('q', (qInput.value || '').trim());
            if (tagSelect) {
                const v = (tagSelect.value || '').trim();
                if (v) url.searchParams.set('tag', v); else url.searchParams.delete('tag');
            }
            url.searchParams.delete('page'); // reset to first page on new query
            return url.toString();
        }

        // PJAX load and swap sections
        async function pjaxLoad(url, {pushState = false} = {}) {
            try {
                const res = await fetch(url, { headers: { 'X-Requested-With': 'XMLHttpRequest' } });
                const html = await res.text();
                const doc = new DOMParser().parseFromString(html, 'text/html');

                // Swap selected areas
                AREAS.forEach(sel => {
                    const next = doc.querySelector(sel);
                    const curr = container.querySelector(sel);
                    if (next && curr) curr.replaceWith(next);
                });

                // Update URL (no full reload)
                if (pushState) history.pushState(null, '', url);
                else history.replaceState(null, '', url);

                // Re-init behaviours on new DOM
                initFaqExpand(document);
                bindDynamicLinks(); // rebind pagination/sort links

                // Keep cursor in the search input
                if (qInput) {
                    qInput.focus({ preventScroll: true });
                    const len = qInput.value.length;
                    qInput.setSelectionRange(len, len);
                }
            } catch (e) {
                // Fallback: hard navigate if PJAX fails
                window.location.href = url;
            }
        }

        // Intercept pagination & sort links to use PJAX
        function bindDynamicLinks() {
            // pagination
            container.querySelectorAll('.pagination a').forEach(a => {
                a.addEventListener('click', (ev) => {
                    ev.preventDefault();
                    pjaxLoad(a.href, { pushState: true });
                });
            });
            // sort headers
            container.querySelectorAll('thead th a').forEach(a => {
                a.addEventListener('click', (ev) => {
                    ev.preventDefault();
                    pjaxLoad(a.href, { pushState: true });
                });
            });
        }

        // Prevent full submit; run PJAX instead
        form.addEventListener('submit', (e) => {
            e.preventDefault();
            const url = buildUrl();
            pjaxLoad(url);
        });

        // Auto-search on typing (debounced, no reload)
        if (qInput) {
            const trigger = () => {
                const val = (qInput.value || '').trim();
                if (val.length < MIN_LEN && val.length !== 0) return;
                if (val === lastQ && (tagSelect ? tagSelect.value : '') === lastTag) return; // no duplicate request
                lastQ = val;
                lastTag = tagSelect ? tagSelect.value : '';
                pjaxLoad(buildUrl());
            };

            qInput.addEventListener('input', () => {
                if (timer) clearTimeout(timer);
                timer = setTimeout(trigger, DEBOUNCE_MS);
            });

            // Instant when user presses Enter
            qInput.addEventListener('keydown', (e) => {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    if (timer) clearTimeout(timer);
                    trigger();
                }
                if (e.key === 'Escape') {
                    qInput.value = '';
                    if (timer) clearTimeout(timer);
                    trigger();
                }
            });

            qInput.addEventListener('blur', () => {
                if (timer) clearTimeout(timer);
                const val = (qInput.value || '').trim();
                if (val.length >= MIN_LEN || val.length === 0) {
                    trigger();
                }
            });

            qInput.addEventListener('search', () => {
                if (timer) clearTimeout(timer);
                trigger();
            });
        }

        if (tagSelect) {
            tagSelect.addEventListener('change', () => {
                lastTag = tagSelect.value;
                lastQ = qInput ? qInput.value : '';
                pjaxLoad(buildUrl());
            });
        }

        if (resetLink) {
            resetLink.addEventListener('click', (e) => {
                e.preventDefault();
                if (qInput) qInput.value = '';
                if (tagSelect) tagSelect.value = '';
                lastQ = ''; lastTag = '';
                pjaxLoad(resetLink.getAttribute('href') || buildUrl());
            });
        }

        initFaqExpand(document);
        bindDynamicLinks();

        window.addEventListener('popstate', () => {
            pjaxLoad(window.location.href);
        });
    })();
</script>
