{% 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><a href="{{ route('admin.blocks.templates.index') }}">Templates</a> /</li>
        <li class="end">{{ block_template ? 'Edit' : 'Create' }}</li>
    </ul>

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

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

    <form action="{{ block_template ? route('admin.blocks.templates.update', {'id': block_template.id}) : route('admin.blocks.templates.store') }}" method="POST" class="block-edit-form style" id="blockTemplateForm">
        {% if block_template %}
            <input type="hidden" name="_method" value="PUT">
        {% endif %}

        <div class="form-columns">
            <div class="form-main">
                <fieldset class="show">
                    <h1>
                        <a class="show el">
                            Template Details
                            <i class="fa fa-caret-right"></i>
                        </a>
                    </h1>

                    <div class="row">
                        <label for="name">Name <span class="required">*</span></label>
                        <input type="text" name="name" id="name" value="{{ block_template.name ?? '' }}" required>
                    </div>

                    <div class="row">
                        <label for="description">Description</label>
                        <textarea name="description" id="description" rows="3">{{ block_template.description ?? '' }}</textarea>
                    </div>
                </fieldset>

                <fieldset class="show">
                    <h1>
                        <a class="show el">
                            Blocks
                            <i class="fa fa-caret-right"></i>
                        </a>
                    </h1>

                    <div class="block-template-editor-wrap">
                     <div class="block-template-editor">
                        <div class="block-template-available">
                            <h3>Available Blocks</h3>
                            <div class="block-template-search">
                                <input type="text" id="blockTemplateSearch" placeholder="Search blocks...">
                            </div>
                            <div class="block-template-available-list" id="availableBlocksList">
                                {% set currentCategory = '' %}
                                {% for block in blocks %}
                                    {% set catName = block.category ? block.category.name : 'Uncategorized' %}
                                    {% if catName != currentCategory %}
                                        {% set currentCategory = catName %}
                                        <div class="block-template-category-header" data-category="{{ catName }}">
                                            <i class="fa {{ block.category ? block.category.icon ?? 'fa-folder' : 'fa-folder' }}"></i>
                                            {{ catName }}
                                        </div>
                                    {% endif %}
                                    <div class="block-template-available-item"
                                         data-item-type="block"
                                         data-item-id="{{ block.id }}"
                                         data-block-name="{{ block.name }}"
                                         data-block-icon="{{ block.icon ?? 'fa-cube' }}"
                                         data-category="{{ catName }}">
                                        <i class="fa {{ block.icon ?? 'fa-cube' }}"></i>
                                        <span>{{ block.name }}</span>
                                        <button type="button" class="block-template-add-btn" title="Add to template">
                                            <i class="fa fa-plus"></i>
                                        </button>
                                    </div>
                                {% endfor %}

                                {% if global_blocks is defined and global_blocks|length > 0 %}
                                    <div class="block-template-category-header block-template-category-header--global" data-category="Global Blocks">
                                        <i class="fa fa-globe"></i>
                                        Global Blocks
                                    </div>
                                    {% for global in global_blocks %}
                                        <div class="block-template-available-item block-template-available-item--global"
                                             data-item-type="global"
                                             data-item-id="{{ global.id }}"
                                             data-block-name="{{ global.name ?: (global.block ? global.block.name : 'Global Block') }}"
                                             data-block-icon="{{ global.block and global.block.icon ? global.block.icon : 'fa-globe' }}"
                                             data-category="Global Blocks">
                                            <i class="fa {{ global.block and global.block.icon ? global.block.icon : 'fa-globe' }}"></i>
                                            <span>{{ global.name ?: (global.block ? global.block.name : 'Global Block') }}</span>
                                            {% if global.block and global.block.name != global.name %}
                                                <small class="block-template-item-meta">{{ global.block.name }}</small>
                                            {% endif %}
                                            <button type="button" class="block-template-add-btn" title="Add to template">
                                                <i class="fa fa-plus"></i>
                                            </button>
                                        </div>
                                    {% endfor %}
                                {% endif %}
                            </div>
                        </div>

                        <div class="block-template-selected">
                            <h3>Selected Blocks <span class="badge" id="selectedBlockCount">0</span></h3>
                            <div class="block-template-selected-list" id="selectedBlocksList">
                                <p class="block-template-empty-msg" id="selectedBlocksEmpty">
                                    <i class="fa fa-info-circle"></i> No blocks selected. Click blocks on the left to add them.
                                </p>
                            </div>
                        </div>
                     </div>
                    </div>

                    <div id="blockItemsContainer"></div>
                </fieldset>

                <fieldset class="show">
                    <h1>
                        <a class="show el">
                            Template Assignments
                            <i class="fa fa-caret-right"></i>
                        </a>
                    </h1>

                    <div class="fields-section">
                        <p class="help-text">Select which templates this block template should be available on.</p>

                        <table class="template-table">
                            <thead>
                                <tr>
                                    <th class="checkbox-cell">
                                        <input type="checkbox" id="selectAllTemplates">
                                    </th>
                                    <th>Template</th>
                                </tr>
                            </thead>
                            <tbody>
                            {% set currentGroup = '' %}
                            {% for template in templates %}
                                {% if template.group != currentGroup %}
                                    {% set currentGroup = template.group %}
                                    <tr class="template-group-header">
                                        <td colspan="2">{{ currentGroup }}</td>
                                    </tr>
                                {% endif %}
                                {% set isAssigned = false %}
                                {% if block_template and block_template.templateAssignments %}
                                    {% for assignment in block_template.templateAssignments %}
                                        {% if assignment.template_name == template.name %}
                                            {% set isAssigned = true %}
                                        {% endif %}
                                    {% endfor %}
                                {% endif %}
                                <tr class="template-row {{ isAssigned ? 'is-assigned' : '' }}">
                                    <td class="checkbox-cell">
                                        <input type="checkbox" name="templates[]" value="{{ template.name }}" class="template-checkbox" {{ isAssigned ? 'checked' : '' }}>
                                    </td>
                                    <td>{{ template.label ?? template.name }}</td>
                                </tr>
                            {% endfor %}
                            </tbody>
                        </table>

                        <script>
                        (function() {
                            const selectAll = document.getElementById('selectAllTemplates');
                            const checkboxes = document.querySelectorAll('.template-checkbox');

                            selectAll.addEventListener('change', function() {
                                checkboxes.forEach(function(cb) { cb.checked = selectAll.checked; });
                            });

                            checkboxes.forEach(function(cb) {
                                cb.addEventListener('change', function() {
                                    selectAll.checked = Array.from(checkboxes).every(function(c) { return c.checked; });
                                });
                            });
                        })();
                        </script>
                    </div>
                </fieldset>
            </div>

            <div class="form-sidebar">
                <div class="sidebar-section">
                    <button type="submit" class="btn btn-primary btn-block">
                        <i class="fa fa-save"></i>
                        {{ block_template ? 'Update Template' : 'Create Template' }}
                    </button>

                    {% if block_template %}
                        <a href="{{ route('admin.blocks.templates.index') }}" class="btn btn-secondary btn-block" style="margin-top:10px;">
                            Cancel
                        </a>
                    {% endif %}
                </div>
            </div>
        </div>
    </form>

    <script>
    // Pass existing selected items to JS — each item is either a block-type
    // slot (type='block', id=BlockRegistry.id) or a global-block reference
    // (type='global', id=EntityBlock.id of the global source).
    window.blockTemplateExistingItems = [
        {% if block_template and block_template.items %}
            {% for item in block_template.items %}
                {% if item.source_block_id and item.sourceBlock %}
                    {
                        type: 'global',
                        id: {{ item.source_block_id }},
                        name: '{{ (item.sourceBlock.name ?: (item.sourceBlock.block ? item.sourceBlock.block.name : 'Global Block'))|e('js') }}',
                        icon: '{{ item.sourceBlock.block and item.sourceBlock.block.icon ? item.sourceBlock.block.icon : 'fa-globe' }}'
                    }
                {% else %}
                    {
                        type: 'block',
                        id: {{ item.block_id }},
                        name: '{{ (item.block ? item.block.name : 'Block')|e('js') }}',
                        icon: '{{ item.block and item.block.icon ? item.block.icon : 'fa-cube' }}'
                    }
                {% endif %}{% if not loop.last %},{% endif %}
            {% endfor %}
        {% endif %}
    ];
    </script>
    <script src="/modules/BlockRegistry/js/block-template-edit.js"></script>

{% endblock %}
