<script>
let _pendingTagForm = null;

function tagsToggleAll(src) {
    document.querySelectorAll('input[name="selected_tags[]"]').forEach(cb => cb.checked = src.checked);
    tagsUpdateBulk();
}

function tagsUpdateBulk() {
    const n = document.querySelectorAll('input[name="selected_tags[]"]:checked').length;
    document.getElementById('tags-selected-count').textContent = n;
    document.getElementById('tags-bulk-actions').style.display = n > 1 ? 'flex' : 'none';
}

function tagsConfirmBulkMerge() {
    const checked = document.querySelectorAll('input[name="selected_tags[]"]:checked');
    if (checked.length < 2) return;
    document.getElementById('bulk-merge-count').textContent = checked.length;
    const sel = document.getElementById('bulk-merge-target-select');
    sel.innerHTML = '<option value="">— Choisir la destination —</option>';
    checked.forEach(cb => {
        const tr = cb.closest('tr');
        sel.innerHTML += '<option value="' + cb.value + '">' + tr.querySelector('.tag-name-cell').textContent.trim() + '</option>';
    });
    document.getElementById('bulk-merge-dialog').showModal();
}

function tagsExecBulkMerge() {
    const targetId = document.getElementById('bulk-merge-target-select').value;
    if (!targetId) return;
    document.getElementById('tags-bulk-target').value = targetId;
    const container = document.getElementById('tags-bulk-checkboxes');
    container.innerHTML = '';
    document.querySelectorAll('input[name="selected_tags[]"]:checked').forEach(cb => {
        const inp = document.createElement('input');
        inp.type = 'hidden';
        inp.name = 'selected_tags[]';
        inp.value = cb.value;
        container.appendChild(inp);
    });
    document.getElementById('bulk-merge-dialog').close();
    document.getElementById('tags-bulk-form').submit();
}

// ── Inline rename via HTMX ──────────────────────────────────────────────────
function tagsStartRename(id) {
    var cell = document.getElementById('tag-name-' + id);
    var csrf = document.querySelector('input[name="csrf_token"]').value;
    cell.innerHTML = '<form hx-post=\"/admin/actions/tag.php\" hx-target=\"#tags-table-wrap\" hx-swap=\"innerHTML\" class=\"admin-inline-form\">'
        + '<input type=\"hidden\" name=\"csrf_token\" value=\"' + csrf + '\">'
        + '<input type=\"hidden\" name=\"action\" value=\"rename\">'
        + '<input type=\"hidden\" name=\"tag_id\" value=\"' + id + '\">'
        + '<input type=\"text\" name=\"new_name\" value=\"' + cell.getAttribute('data-name') + '\" required class=\"admin-input--inline\">'
        + '<button type=\"submit\" class=\"admin-icon-btn admin-icon-btn--edit\" title=\"Valider\">'
        + '<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"32\" height=\"32\" fill=\"currentColor\" viewBox=\"0 0 256 256\"><path d=\"M229.66,77.66l-128,128a8,8,0,0,1-11.32,0l-56-56a8,8,0,0,1,11.32-11.32L96,188.69,218.34,66.34a8,8,0,0,1,11.32,11.32Z\"/></svg>'
        + '</button>'
        + '<button type=\"button\" class=\"admin-icon-btn admin-icon-btn--delete\" onclick=\"tagsCancelRename(' + id + ')\" title=\"Annuler\">'
        + '<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"32\" height=\"32\" fill=\"currentColor\" viewBox=\"0 0 256 256\"><path d=\"M208.49,191.51a12,12,0,0,1-17,17L128,145,64.49,208.49a12,12,0,0,1-17-17L111,128,47.51,64.49a12,12,0,0,1,17-17L128,111l63.51-63.52a12,12,0,0,1,17,17L145,128Z\"/></svg>'
        + '</button></form>';
    cell.querySelector('input').focus();
}

function tagsCancelRename(id) {
    var cell = document.getElementById('tag-name-' + id);
    cell.innerHTML = '<span class=\"tag-name-cell\">' + cell.getAttribute('data-name') + '</span>'
        + '<button type=\"button\" class=\"admin-icon-btn admin-icon-btn--edit\" title=\"Renommer\" onclick=\"tagsStartRename(' + id + ')\">'
        + '<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"32\" height=\"32\" fill=\"currentColor\" viewBox=\"0 0 256 256\"><path d=\"M248,92.68a15.86,15.86,0,0,0-4.69-11.31L174.63,12.68a16,16,0,0,0-22.63,0L123.57,41.11l-58,21.77A16.06,16.06,0,0,0,55.35,75.23L32.11,214.68A8,8,0,0,0,40,224a8.4,8.4,0,0,0,1.32-.11l139.44-23.24a16,16,0,0,0,12.35-10.17l21.77-58L243.31,104A15.87,15.87,0,0,0,248,92.68Zm-69.87,92.19L63.32,204l47.37-47.37a28,28,0,1,0-11.32-11.32L52,192.7,71.13,77.86,126,57.29,198.7,130ZM112,132a12,12,0,1,1,12,12A12,12,0,0,1,112,132Zm96-15.32L139.31,48l24-24L232,92.68Z\"/></svg>'
        + '</button>';
}

function tagsConfirmDelete(btn, name) {
    _pendingTagForm = btn.closest('form');
    document.getElementById('delete-tag-name').textContent = name;
    document.getElementById('delete-tag-dialog').showModal();
}

function _submitPendingTagForm() {
    if (_pendingTagForm) _pendingTagForm.submit();
}

document.addEventListener('htmx:afterSwap', function(evt) {
    if (evt.target.id === 'tags-table-wrap') {
        document.querySelectorAll('input[name=\"selected_tags[]\"]').forEach(cb => cb.addEventListener('change', tagsUpdateBulk));
        tagsUpdateBulk();
    }
});
</script>

<main id="main-content" class="admin-main--list">
    <div class="admin-list-toolbar admin-list-toolbar--list" style="margin-bottom:var(--space-s)">
        <div class="admin-toolbar-top">
            <div class="admin-toolbar-title-row">
                <h1><a href="/admin/" class="admin-back-btn" title="Retour à la liste"><svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" fill="currentColor" viewBox="0 0 256 256"><path d="M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm0,192a88,88,0,1,1,88-88A88.1,88.1,0,0,1,128,216Zm48-88a8,8,0,0,1-8,8H107.31l18.35,18.34a8,8,0,0,1-11.32,11.32l-32-32a8,8,0,0,1,0-11.32l32-32a8,8,0,0,1,11.32,11.32L107.31,120H168A8,8,0,0,1,176,128Z"></path></svg></a> Mots-clés</h1>
                <span id="tags-total-count" class="admin-stat admin-stat--inline" style="margin-left:auto"></span>
            </div>
        </div>

        <form id="tags-search-form"
              hx-get="/admin/tags-fragment.php"
              hx-target="#tags-table-wrap"
              hx-swap="innerHTML"
              hx-trigger="input changed delay:200ms from:input[name=q], keyup[key=='Enter'] from:input[name=q]"
              hx-push-url="false"
              style="margin-bottom:var(--space-xs)">
            <input type="text" name="q" placeholder="Rechercher un mot-clé…" style="max-width:300px">
        </form>
    </div>

    <div id="tags-table-wrap"
         hx-get="/admin/tags-fragment.php"
         hx-trigger="load delay:100ms"
         hx-swap="innerHTML">
        <div style="padding:var(--space-m);text-align:center;color:var(--text-tertiary)">
            <img alt="Chargement…" class="htmx-indicator" width="24" src="/assets/img/bars.svg" style="opacity:0.5">
        </div>
    </div>
</main>

<dialog id="delete-tag-dialog" class="admin-dialog admin-dialog--sm" aria-labelledby="delete-tag-title">
    <div class="admin-dialog__header">
        <h2 id="delete-tag-title">Supprimer le tag</h2>
        <button type="button" class="admin-dialog__close" aria-label="Fermer"
                onclick="this.closest('dialog').close()">&#x2715;</button>
    </div>
    <div class="admin-dialog__alert">
        <p>Supprimer « <strong id="delete-tag-name"></strong> » ? Cette action est irréversible.</p>
    </div>
    <div class="admin-dialog__footer">
        <button type="button" class="btn btn--danger" onclick="this.closest('dialog').close(); _submitPendingTagForm()">Supprimer</button>
        <button type="button" class="btn btn--secondary" onclick="this.closest('dialog').close()">Annuler</button>
    </div>
</dialog>

<dialog id="bulk-merge-dialog" class="admin-dialog admin-dialog--sm" aria-labelledby="bulk-merge-title">
    <div class="admin-dialog__header">
        <h2 id="bulk-merge-title">Fusionner des tags</h2>
        <button type="button" class="admin-dialog__close" aria-label="Fermer"
                onclick="this.closest('dialog').close()">&#x2715;</button>
    </div>
    <div class="admin-dialog__alert">
        <p>Fusionner <strong><span id="bulk-merge-count"></span> tag(s)</strong> sélectionné(s) dans :</p>
        <select id="bulk-merge-target-select" class="admin-select--inline" style="margin-top:var(--space-xs); width:100%" required>
            <option value="">— Choisir la destination —</option>
        </select>
    </div>
    <div class="admin-dialog__footer">
        <button type="button" class="btn btn--warning" onclick="tagsExecBulkMerge()">Fusionner</button>
        <button type="button" class="btn btn--secondary" onclick="this.closest('dialog').close()">Annuler</button>
    </div>
</dialog>
