<?php ob_start(); ?>

<?php admin_content_header(__('admin.blog_tags.title'), 'pen-line', [
    ['url' => admin_url('blog/categories'), 'label' => __('admin.nav.categories')],
    ['url' => admin_url('blog'), 'label' => __('admin.blog_tags.back')],
]); ?>

<?php
$unusedCount = 0;
$totalCount  = count($tags);
foreach ($tags as $tag) {
    if ((int) $tag['post_count'] === 0) $unusedCount++;
}
?>

<!-- Filter bar: stats + live-search + unused-filter -->
<div class="filter-bar" style="justify-content:space-between;">
    <div style="display:flex; align-items:center; gap:0.75rem; flex-shrink:0;">
        <span style="font-size:0.875rem; color:var(--gray-600);">
            <?= __('admin.blog_tags.total_tags') ?>:
            <strong><?= $totalCount ?></strong>
        </span>
        <?php if ($unusedCount > 0): ?>
        <span class="badge badge-warning"><?= $unusedCount ?> <?= __('admin.blog_tags.unused') ?></span>
        <?php endif; ?>
    </div>
    <div style="display:flex; align-items:center; gap:0.5rem; flex:1; justify-content:flex-end; min-width:0;">
        <input type="search" id="tag-search"
               placeholder="<?= e(__('admin.blog_tags.search_placeholder')) ?>"
               oninput="filterTags()"
               style="max-width:280px;">
        <?php if ($unusedCount > 0): ?>
        <button type="button" id="btn-unused-filter" class="btn btn-sm btn-secondary"
                onclick="toggleUnusedFilter()" data-active="0">
            <?= __('admin.blog_tags.only_unused') ?>
        </button>
        <?php endif; ?>
    </div>
</div>

<?php if (!empty($tags) && $unusedCount > 0): ?>
<p style="font-size:0.8rem; color:var(--gray-500); margin:-0.5rem 0 1rem 0; line-height:1.4;">
    <?= __('admin.blog_tags.unused_help') ?>
    &nbsp;·&nbsp;
    <?= __('admin.blog_tags.auto_create_hint') ?>
</p>
<?php elseif (!empty($tags)): ?>
<p style="font-size:0.8rem; color:var(--gray-500); margin:-0.5rem 0 1rem 0; line-height:1.4;">
    <?= __('admin.blog_tags.auto_create_hint') ?>
</p>
<?php endif; ?>

<div class="table-responsive">
<table class="data-table">
    <thead>
        <tr>
            <th><?= __('admin.blog_tags.name') ?></th>
            <th><?= __('admin.common.slug') ?></th>
            <th><?= __('admin.blog_tags.posts') ?></th>
            <th><?= __('admin.common.actions') ?></th>
        </tr>
    </thead>
    <tbody id="tag-tbody">
        <?php if (empty($tags)): ?>
        <tr id="tag-empty-row"><td colspan="4" class="text-center text-muted"><?= __('admin.blog_tags.no_tags') ?></td></tr>
        <?php else: ?>
        <?php foreach ($tags as $tag): ?>
        <tr id="tag-row-<?= (int) $tag['id'] ?>"
            class="tag-data-row"
            data-id="<?= (int) $tag['id'] ?>"
            data-name="<?= e(mb_strtolower($tag['name'])) ?>"
            data-slug="<?= e(mb_strtolower($tag['slug'])) ?>"
            data-post-count="<?= (int) $tag['post_count'] ?>">
            <td>
                <strong><?= e($tag['name']) ?></strong>
                <?php if ((int) $tag['post_count'] === 0): ?>
                <span class="badge badge-secondary" style="margin-left:0.25rem;"><?= __('admin.blog_tags.unused_badge') ?></span>
                <?php endif; ?>
            </td>
            <td><code><?= e($tag['slug']) ?></code></td>
            <td>
                <?php if ((int) $tag['post_count'] > 0): ?>
                <a href="/blog/tag/<?= e($tag['slug']) ?>" target="_blank"><?= (int) $tag['post_count'] ?></a>
                <?php else: ?>
                <span class="text-muted">0</span>
                <?php endif; ?>
            </td>
            <td class="actions">
                <button type="button" class="btn btn-sm btn-secondary"
                        onclick="toggleTagEdit(<?= (int) $tag['id'] ?>)"><?= __('admin.common.edit') ?></button>
                <?php if ((int) $tag['post_count'] === 0): ?>
                <form method="POST" action="<?= admin_url('blog/tags/delete/' . (int) $tag['id']) ?>" class="inline-form"
                      onsubmit="return confirm('<?= e(__('admin.blog_tags.confirm_delete', [':name' => $tag['name']])) ?>')">
                    <?= $csrf->field() ?>
                    <button type="submit" class="btn btn-sm btn-danger"><?= __('admin.common.delete') ?></button>
                </form>
                <?php else: ?>
                <button type="button" class="btn btn-sm btn-danger" disabled
                        title="<?= e(__('admin.blog_tags.cannot_delete', [':count' => $tag['post_count']])) ?>"><?= __('admin.common.delete') ?></button>
                <?php endif; ?>
            </td>
        </tr>
        <!-- Inline edit row (hidden by default) -->
        <tr id="tag-edit-<?= (int) $tag['id'] ?>" class="tag-edit-row" style="display:none; background:#f9f9f9;">
            <td colspan="4" style="padding:1rem;">
                <form method="POST" action="<?= admin_url('blog/tags/update/' . (int) $tag['id']) ?>" class="admin-form">
                    <?= $csrf->field() ?>
                    <div style="display:grid; grid-template-columns:1fr 1fr; gap:0.75rem; margin-bottom:0.75rem;">
                        <div class="form-group" style="margin-bottom:0;">
                            <label><?= __('admin.blog_tags.name') ?> <span class="required">*</span></label>
                            <input type="text" name="name" value="<?= e($tag['name']) ?>" required>
                        </div>
                        <div class="form-group" style="margin-bottom:0;">
                            <label><?= __('admin.common.slug') ?></label>
                            <input type="text" name="slug" value="<?= e($tag['slug']) ?>">
                            <small class="form-hint"><?= __('admin.blog_categories.slug_help') ?></small>
                        </div>
                    </div>
                    <div style="display:flex; gap:0.5rem;">
                        <button type="submit" class="btn btn-sm btn-primary"><?= __('admin.common.save') ?></button>
                        <button type="button" class="btn btn-sm btn-secondary"
                                onclick="toggleTagEdit(<?= (int) $tag['id'] ?>)"><?= __('admin.common.cancel') ?></button>
                    </div>
                </form>
            </td>
        </tr>
        <?php endforeach; ?>
        <tr id="tag-no-results" style="display:none;">
            <td colspan="4" class="text-center text-muted"><?= __('admin.blog_tags.no_results') ?></td>
        </tr>
        <?php endif; ?>
    </tbody>
</table>
</div>

<script>
function toggleTagEdit(id) {
    var editRow = document.getElementById('tag-edit-' + id);
    editRow.style.display = (editRow.style.display === 'none') ? 'table-row' : 'none';
}

function filterTags() {
    var q      = (document.getElementById('tag-search').value || '').toLowerCase().trim();
    var btn    = document.getElementById('btn-unused-filter');
    var onlyUn = btn ? btn.dataset.active === '1' : false;
    var rows   = document.querySelectorAll('.tag-data-row');
    var visCount = 0;

    rows.forEach(function(row) {
        var name      = row.dataset.name  || '';
        var slug      = row.dataset.slug  || '';
        var postCount = parseInt(row.dataset.postCount, 10);
        var id        = row.dataset.id;
        var editRow   = document.getElementById('tag-edit-' + id);

        var matchSearch = !q || name.indexOf(q) !== -1 || slug.indexOf(q) !== -1;
        var matchFilter = !onlyUn || postCount === 0;
        var show        = matchSearch && matchFilter;

        row.style.display = show ? '' : 'none';
        if (editRow) editRow.style.display = 'none'; // collapse edit row on filter change
        if (show) visCount++;
    });

    var noRes = document.getElementById('tag-no-results');
    if (noRes) noRes.style.display = (visCount === 0 && rows.length > 0) ? 'table-row' : 'none';
}

function toggleUnusedFilter() {
    var btn = document.getElementById('btn-unused-filter');
    if (!btn) return;
    var isActive = btn.dataset.active === '1';
    btn.dataset.active = isActive ? '0' : '1';
    btn.classList.toggle('btn-primary', !isActive);
    btn.classList.toggle('btn-secondary', isActive);
    filterTags();
}
</script>

<?php $content = ob_get_clean(); include dirname(__DIR__) . '/layouts/admin.php'; ?>
