{% extends 'layouts/admin.twig' %}

{% block head %}
    <link rel="stylesheet" href="/modules/BlockRegistry/admin/css/block_registry.css">
{% endblock %}

{% block content %}

    <ul class="breadcrumbs el">
        <li><a href="/admin/">Admin</a> /</li>
        <li><a href="{{ route('admin.blocks.index') }}">Block Registry</a> /</li>
        <li class="end">Global Blocks</li>
    </ul>

    <h1>{{ title }}</h1>

    {% include 'admin/block_registry/_tabnav.twig' with { active_tab: 'global' } %}

    {% for message in messages %}
        <div class="alert alert-{{ message.type }}">
            {{ message.content }}
        </div>
    {% endfor %}

    <div class="block-registry-toolbar">
        <div class="toolbar-left">
            <a href="{{ route('admin.blocks.global.create') }}" class="btn btn-primary">
                <i class="fa fa-plus"></i> Create Global Block
            </a>
        </div>
    </div>

    {% if globalBlocks|length > 0 %}
        <table class="manage-items">
            <thead>
                <tr>
                    <th width="40">#</th>
                    <th>Name</th>
                    <th>Block Type</th>
                    <th>Category</th>
                    <th width="80">Status</th>
                    <th width="100">References</th>
                    <th width="150">Actions</th>
                </tr>
            </thead>
            <tbody class="tabular">
                {% for gb in globalBlocks %}
                <tr>
                    <td>{{ gb.id }}</td>
                    <td>
                        <i class="fa {{ gb.block.icon ?? 'fa-cube' }}"></i>
                        <strong>{{ gb.name }}</strong>
                    </td>
                    <td>{{ gb.block.name ?? 'Unknown' }}</td>
                    <td>
                        {% if gb.block.category %}
                            <span class="category-tag">
                                <i class="fa {{ gb.block.category.icon ?? 'fa-folder' }}"></i>
                                {{ gb.block.category.name }}
                            </span>
                        {% else %}
                            <span class="category-tag uncategorized">Uncategorized</span>
                        {% endif %}
                    </td>
                    <td>
                        {% if gb.status == 'published' %}
                            <button type="button"
                                    class="toggleStatusBtn toggleStatusBtn--published"
                                    data-entity-block-id="{{ gb.id }}"
                                    data-status="published">
                                Published
                            </button>
                        {% else %}
                            <button type="button"
                                    class="toggleStatusBtn toggleStatusBtn--draft"
                                    data-entity-block-id="{{ gb.id }}"
                                    data-status="draft">
                                Draft
                            </button>
                        {% endif %}
                    </td>
                    <td>
                        <span class="badge">{{ gb.references_count }}</span>
                    </td>
                    <td class="actions">
                        <a href="{{ route('admin.blocks.data.edit', {'id': gb.id}) }}" title="Edit Data">
                            <i class="fa fa-pencil"></i> Edit Data
                        </a>
                        <form action="{{ route('admin.blocks.global.destroy', {'id': gb.id}) }}" method="POST" onsubmit="return confirm('Delete this global block? {{ gb.references_count }} reference(s) will be unlinked.')">
                            <input type="hidden" name="_method" value="DELETE">
                            <button type="submit" title="Delete" class="btn-link error">
                                <i class="fa fa-times-circle"></i>
                            </button>
                        </form>
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    {% else %}
        <div class="empty-state">
            <i class="fa fa-globe fa-3x"></i>
            <h3>No global blocks yet</h3>
            <p>Global blocks let you create content once and sync it across multiple pages. Changes to a global block update everywhere it's used.</p>
            <a href="{{ route('admin.blocks.global.create') }}" class="btn btn-primary">
                <i class="fa fa-plus"></i> Create Global Block
            </a>
        </div>
    {% endif %}

    <script>
    (function() {
        document.querySelectorAll('.toggleStatusBtn').forEach(function(btn) {
            btn.addEventListener('click', function() {
                let entityBlockId = this.getAttribute('data-entity-block-id');
                let currentStatus = this.getAttribute('data-status');
                let newStatus = currentStatus === 'published' ? 'draft' : 'published';
                let button = this;
                let row = this.closest('tr');

                fetch('/admin/blocks/ajax/toggle-status', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    body: JSON.stringify({ id: parseInt(entityBlockId), status: newStatus })
                })
                .then(function(response) { return response.json(); })
                .then(function(data) {
                    if (data.success) {
                        button.setAttribute('data-status', data.status);
                        if (data.status === 'published') {
                            button.textContent = 'Published';
                            button.className = 'toggleStatusBtn toggleStatusBtn--published';
                            row.style.opacity = '1';
                        } else {
                            button.textContent = 'Draft';
                            button.className = 'toggleStatusBtn toggleStatusBtn--draft';
                            row.style.opacity = '0.55';
                        }
                    } else {
                        alert('Failed to update status: ' + (data.error || 'Unknown error'));
                    }
                })
                .catch(function(error) {
                    console.error('Error toggling status:', error);
                    alert('Failed to update status. Please try again.');
                });
            });
        });
    })();
    </script>

{% endblock %}
