{% 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">{{ block ? 'Edit' : 'Create' }}</li>
    </ul>

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

    {% include 'admin/block_registry/_tabnav.twig' with { active_tab: 'edit', tab_edit_label: block ? 'Edit Block' : 'Add New Block' } %}

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

    {% if is_production is defined and is_production %}
        <div class="alert alert-warning">
            <strong>Read-only on production.</strong> Block definitions cannot be modified here. Make changes on local/staging and sync via JSON.
        </div>
    {% endif %}

    <form action="{{ block ? route('admin.blocks.update', {'id': block.id}) : route('admin.blocks.store') }}" method="POST" class="block-edit-form style" id="blockForm" data-instance-count="{{ stats.instance_count ?? 0 }}"{{ (is_production is defined and is_production) ? ' data-locked="1"' : '' }}>
        {% if block %}
            <input type="hidden" name="_method" value="PUT">
        {% endif %}

        <div class="form-columns">
            <div class="form-main">
                <fieldset class="show">
                    <h1>
                        <a class="show el">
                            Block 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.name ?? '' }}" required>
                    </div>

                    <div class="row">
                        <label for="slug">Slug</label>
                        <input type="text" name="slug" id="slug" value="{{ block.slug ?? '' }}" placeholder="auto-generated if empty">
                        <div class="hint el"><i class="fa fa-info-circle"></i><div class="text">Unique identifier for this block type</div></div>
                    </div>

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

                    <div class="row">
                        <label for="category_id">Category</label>
                        <select name="category_id" id="category_id">
                            <option value="">-- Uncategorized --</option>
                            {% for category in categories %}
                                <option value="{{ category.id }}" {{ block.category_id == category.id ? 'selected' : '' }}>
                                    {{ category.name }}
                                </option>
                            {% endfor %}
                        </select>
                    </div>

                    <div class="row">
                        <label for="icon">Icon</label>
                        <input type="text" name="icon" id="icon" value="{{ block.icon ?? 'fa-cube' }}" placeholder="fa-cube">
                        <div class="hint el"><i class="fa fa-info-circle"></i><div class="text">FontAwesome icon class (e.g., fa-image, fa-text-width)</div></div>
                    </div>

                    <div class="row">
                        <label for="template">Render Template</label>
                        <select name="template" id="template">
                            <option value="">-- No Auto-Render Template --</option>
                            {% for category, categoryTemplates in componentTemplates %}
                                <optgroup label="{{ category|replace({'_': ' ', '/': ' / '})|title }}">
                                    {% for tmpl in categoryTemplates %}
                                        <option value="{{ tmpl.path }}"
                                                {{ block.template == tmpl.path or block.template == 'includes/' ~ tmpl.path ? 'selected' : '' }}
                                                title="{{ tmpl.description }}">
                                            {{ tmpl.name }}
                                        </option>
                                    {% endfor %}
                                </optgroup>
                            {% endfor %}
                        </select>
                        <div class="hint el"><i class="fa fa-info-circle"></i><div class="text">Select a Twig template to auto-render this block on the frontend</div></div>
                    </div>

                    <div class="row checkboxRow">
                        <label class="active-checkbox-label">
                            <input type="checkbox" name="is_active" value="1" {{ (block is null or block.is_active) ? 'checked' : '' }}>
                            Active <small>(available for use)</small>
                        </label>
                        <div class="hint el"><i class="fa fa-info-circle"></i><div class="text">When inactive, this block will be hidden from the block picker. Existing block instances on pages will not be affected.</div></div>
                    </div>
                </fieldset>

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

                    <div class="fields-section">
                    <div id="fieldsList" class="fields-list" data-field-count="{{ block and block.fields ? block.fields|length : 0 }}">
                        {% if block and block.fields %}
                            {% for field in block.fields %}
                                <div class="field-item collapsed" data-index="{{ loop.index0 }}">
                                    <div class="field-header" onclick="toggleField(this)">
                                        <span class="field-drag"><i class="fa fa-bars"></i></span>
                                        <span class="field-title">{{ field.label ?? field.name }}</span>
                                        <span class="field-type-badge">{{ field.type }}</span>
                                        <button type="button" class="btn-remove-field" onclick="event.stopPropagation(); removeField(this)">
                                            <i class="fa fa-times"></i>
                                        </button>
                                    </div>
                                    <div class="field-body">
                                        <div class="field-row">
                                            <label>Name</label>
                                            <input type="text" name="field_name[]" value="{{ field.name }}" required>
                                            <input type="hidden" name="field_label[]" value="{{ field.label ?? field.name }}">
                                        </div>
                                        <div class="field-row">
                                            <label>Type</label>
                                            <select name="field_type[]" onchange="updateFieldOptions(this)">
                                                {% for type, typeLabel in fieldTypes %}
                                                    <option value="{{ type }}" {{ field.type == type ? 'selected' : '' }}>{{ typeLabel }}</option>
                                                {% endfor %}
                                            </select>
                                        </div>
                                        <div class="field-row">
                                            <label>CSS Class <div class="hint el"><i class="fa fa-info-circle"></i><div class="text">For textarea fields: <strong>tinymce</strong> (full editor), <strong>simpletinymce</strong> (basic formatting), <strong>linkOnlyTinyMce</strong> (links only)</div></div></label>
                                            <input type="text" name="field_css_class[]" value="{{ field.css_class }}" placeholder="optional">
                                        </div>
                                        <div class="field-row field-options-row" style="{{ field.type in ['select', 'radio', 'checkbox'] ? '' : 'display:none' }}">
                                            <label>Options</label>
                                            <textarea name="field_options[]" placeholder="option1|Label 1&#10;option2|Label 2">{{ field.options }}</textarea>
                                        </div>
                                        <div class="field-row">
                                            <label>Info Text</label>
                                            <input type="text" name="field_info[]" value="{{ field.info }}" placeholder="Helper text shown to editors">
                                        </div>
                                        <div class="field-row inline-checkboxes">
                                            <label>
                                                <input type="checkbox" name="field_required[{{ loop.index0 }}]" value="1" {{ field.required ? 'checked' : '' }}>
                                                Required
                                            </label>
                                        </div>

                                        {% set imgSettings = field.settings ? (field.settings is iterable ? field.settings : field.settings|json_decode) : {} %}
                                        {% set imageConfig = imgSettings.image_settings ?? {} %}
                                        {% include 'admin/block_registry/_image_settings.twig' with {
                                            crop_name: 'field_crop_enabled[' ~ loop.index0 ~ ']',
                                            ratio_name: 'field_aspect_ratio[' ~ loop.index0 ~ ']',
                                            custom_ratio_name: 'field_custom_ratio[' ~ loop.index0 ~ ']',
                                            srcset_name: 'field_srcset_sizes[' ~ loop.index0 ~ ']',
                                            image_config: imageConfig,
                                            use_hidden_flag: false,
                                            field_type: field.type,
                                        } only %}

                                        {# Page selector settings - shown when type is "page_selector" #}
                                        {% set psSettings = field.settings ? (field.settings is iterable ? field.settings : field.settings|json_decode) : {} %}
                                        {% set psConfig = psSettings.page_selector_settings ?? {} %}
                                        <div class="page-selector-settings" style="{{ field.type == 'page_selector' ? '' : 'display:none' }}">
                                            <div class="page-selector-settings-header">Page Selector Settings</div>
                                            <div class="field-row">
                                                <label>Mode</label>
                                                <select name="field_page_mode[{{ loop.index0 }}]" onchange="togglePageSelectorMode(this)">
                                                    <option value="manual" {{ (psConfig.mode ?? 'manual') == 'manual' ? 'selected' : '' }}>Manual (admin picks pages)</option>
                                                    <option value="auto" {{ (psConfig.mode ?? 'manual') == 'auto' ? 'selected' : '' }}>Auto (fetch recent pages)</option>
                                                </select>
                                            </div>
                                            <div class="field-row">
                                                <label>Listing Container (optional)</label>
                                                <select name="field_page_container[{{ loop.index0 }}]" class="page-selector-container-select" data-value="{{ psConfig.container_id ?? '' }}">
                                                    <option value="">All pages</option>
                                                </select>
                                            </div>
                                            <div class="field-row page-selector-limit-row" style="{{ (psConfig.mode ?? 'manual') == 'auto' ? '' : 'display:none' }}">
                                                <label>Limit (auto mode)</label>
                                                <input type="number" name="field_page_limit[{{ loop.index0 }}]" value="{{ psConfig.limit ?? 8 }}" min="1" max="50">
                                            </div>
                                        </div>

                                        {# Repeater settings - shown when type is "repeater" #}
                                        <div class="repeater-settings" style="{{ field.type == 'repeater' ? '' : 'display:none' }}">
                                            <div class="repeater-settings-header">Repeater Settings</div>
                                            <div class="repeater-settings-row">
                                                <div class="field-row">
                                                    <label>Min Rows</label>
                                                    <input type="number" name="field_repeater_min[]" value="{{ field.repeater_min ?? 0 }}" min="0">
                                                </div>
                                                <div class="field-row">
                                                    <label>Max Rows</label>
                                                    <input type="number" name="field_repeater_max[]" value="{{ field.repeater_max ?? 100 }}" min="1">
                                                </div>
                                                <div class="field-row">
                                                    <label>Add Button Text</label>
                                                    <input type="text" name="field_repeater_text[]" value="{{ field.repeater_text ?? 'Add Row' }}">
                                                </div>
                                            </div>

                                            <div class="sub-fields-section">
                                                <div class="sub-fields-header">
                                                    <span>Sub-fields</span>
                                                    <button type="button" class="btn-add-subfield" onclick="addSubField(this, {{ loop.index0 }})">
                                                        <i class="fa fa-plus"></i> Add Sub-field
                                                    </button>
                                                </div>
                                                <div class="sub-fields-list" data-parent-index="{{ loop.index0 }}">
                                                    {% if field.subFields is defined %}
                                                        {% for subField in field.subFields %}
                                                            {% include 'admin/block_registry/_sub_field_item.twig' with {
                                                                sf: subField,
                                                                parent_index: loop.parent.loop.index0,
                                                                sub_field_types: subFieldTypes,
                                                                is_template: false,
                                                            } only %}
                                                        {% endfor %}
                                                    {% endif %}
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            {% endfor %}
                        {% endif %}
                    </div>

                    <div class="fields-actions">
                        <button type="button" class="btn btn-secondary" onclick="addField()">
                            <i class="fa fa-plus"></i> Add Field
                        </button>
                    </div>
                    </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 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 and block.templateAssignments %}
                                    {% for assignment in block.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">
                {% if block and stats %}
                <div class="sidebar-box">
                    <h3>Statistics</h3>
                    <ul class="stats-list">
                        <li>
                            <span class="stat-label">Pages using this block:</span>
                            <span class="stat-value">{{ stats.page_count ?? 0 }}</span>
                        </li>
                        <li>
                            <span class="stat-label">Total instances:</span>
                            <span class="stat-value">{{ stats.instance_count ?? 0 }}</span>
                        </li>
                        <li>
                            <span class="stat-label">Last modified:</span>
                            <span class="stat-value">{{ block.updated_at|date('d M Y H:i') }}</span>
                        </li>
                    </ul>
                </div>
                {% endif %}

                <div class="sidebar-box">
                    <h3>Actions</h3>

                    {% if is_production is defined and is_production %}
                        <span class="tag tag-yellow" style="display:block;text-align:center;padding:8px">Locked on production</span>
                    {% else %}
                        <button type="submit" class="btn sidebar-box__btn sidebar-box__btn--primary">
                            <i class="fa fa-save"></i> {{ block ? 'Update Block' : 'Create Block' }}
                        </button>
                    {% endif %}
                </div>
            </div>
        </div>
    </form>

    <template id="fieldTemplate">
        <div class="field-item" data-index="__INDEX__">
            <div class="field-header" onclick="toggleField(this)">
                <span class="field-drag"><i class="fa fa-bars"></i></span>
                <span class="field-title">New Field</span>
                <span class="field-type-badge">text</span>
                <button type="button" class="btn-remove-field" onclick="event.stopPropagation(); removeField(this)">
                    <i class="fa fa-times"></i>
                </button>
            </div>
            <div class="field-body">
                <div class="field-row">
                    <label>Name</label>
                    <input type="text" name="field_name[]" placeholder="Field Name">
                    <input type="hidden" name="field_label[]" value="">
                </div>
                <div class="field-row">
                    <label>Type</label>
                    <select name="field_type[]" onchange="updateFieldOptions(this)">
                        {% for type, typeLabel in fieldTypes %}
                            <option value="{{ type }}">{{ typeLabel }}</option>
                        {% endfor %}
                    </select>
                </div>
                <div class="field-row">
                    <label>CSS Class <div class="hint el"><i class="fa fa-info-circle"></i><div class="text">For textarea fields: <strong>tinymce</strong> (full editor), <strong>simpletinymce</strong> (basic formatting), <strong>linkOnlyTinyMce</strong> (links only)</div></div></label>
                    <input type="text" name="field_css_class[]" placeholder="optional">
                </div>
                <div class="field-row field-options-row" style="display:none">
                    <label>Options</label>
                    <textarea name="field_options[]" placeholder="option1|Label 1&#10;option2|Label 2"></textarea>
                </div>
                <div class="field-row">
                    <label>Info Text</label>
                    <input type="text" name="field_info[]" placeholder="Helper text shown to editors">
                </div>
                <div class="field-row inline-checkboxes">
                    <label>
                        <input type="checkbox" name="field_required[__INDEX__]" value="1">
                        Required
                    </label>
                </div>

                {% include 'admin/block_registry/_image_settings.twig' with {
                    crop_name: 'field_crop_enabled[__INDEX__]',
                    ratio_name: 'field_aspect_ratio[__INDEX__]',
                    custom_ratio_name: 'field_custom_ratio[__INDEX__]',
                    srcset_name: 'field_srcset_sizes[__INDEX__]',
                    image_config: {},
                    use_hidden_flag: false,
                    field_type: 'text',
                } only %}

                {# Page selector settings - hidden by default #}
                <div class="page-selector-settings" style="display:none">
                    <div class="page-selector-settings-header">Page Selector Settings</div>
                    <div class="field-row">
                        <label>Mode</label>
                        <select name="field_page_mode[__INDEX__]" onchange="togglePageSelectorMode(this)">
                            <option value="manual">Manual (admin picks pages)</option>
                            <option value="auto">Auto (fetch recent pages)</option>
                        </select>
                    </div>
                    <div class="field-row">
                        <label>Listing Container (optional)</label>
                        <select name="field_page_container[__INDEX__]" class="page-selector-container-select">
                            <option value="">All pages</option>
                        </select>
                    </div>
                    <div class="field-row page-selector-limit-row" style="display:none">
                        <label>Limit (auto mode)</label>
                        <input type="number" name="field_page_limit[__INDEX__]" value="8" min="1" max="50">
                    </div>
                </div>

                {# Repeater settings - hidden by default #}
                <div class="repeater-settings" style="display:none">
                    <div class="repeater-settings-header">Repeater Settings</div>
                    <div class="repeater-settings-row">
                        <div class="field-row">
                            <label>Min Rows</label>
                            <input type="number" name="field_repeater_min[]" value="0" min="0">
                        </div>
                        <div class="field-row">
                            <label>Max Rows</label>
                            <input type="number" name="field_repeater_max[]" value="100" min="1">
                        </div>
                        <div class="field-row">
                            <label>Add Button Text</label>
                            <input type="text" name="field_repeater_text[]" value="Add Row">
                        </div>
                    </div>

                    <div class="sub-fields-section">
                        <div class="sub-fields-header">
                            <span>Sub-fields</span>
                            <button type="button" class="btn-add-subfield" onclick="addSubField(this, __INDEX__)">
                                <i class="fa fa-plus"></i> Add Sub-field
                            </button>
                        </div>
                        <div class="sub-fields-list" data-parent-index="__INDEX__"></div>
                    </div>
                </div>
            </div>
        </div>
    </template>

    <template id="subFieldTemplate">
        {% include 'admin/block_registry/_sub_field_item.twig' with {
            sf: null,
            parent_index: '__PARENT_INDEX__',
            sub_field_types: subFieldTypes,
            is_template: true,
        } only %}
    </template>

    <script src="/modules/BlockRegistry/js/block-registry-drag.js"></script>
    <script src="/modules/BlockRegistry/js/block-registry-edit.js"></script>

{% endblock %}
