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

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

{% block content %}
    {# Cropper.js CSS for image cropping #}
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.6.1/cropper.min.css" integrity="sha512-hvNR0F/e2J7zPPfLC9auFe3/SE0yG4aJCOd/qxew74NN7eyiSKjr7xJJMu1Jy2wf7FXITpWS1E/RY8yzuXN7VA==" crossorigin="anonymous" referrerpolicy="no-referrer" />

    <ul class="breadcrumbs el">
        <li><a href="/admin/">Admin</a> /</li>
        <li><a href="{{ backUrl }}">Back to {{ entityBlock.entity_type|capitalize }}</a> /</li>
        <li class="end">Edit Block Data</li>
    </ul>

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

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

    {% if prefillExample %}
        <div class="alert alert-info">
            <i class="fa fa-magic"></i>
            Showing <strong>example content</strong> for this block — review the fields below, then <strong>Save</strong> to apply it.
            Leave without saving to discard. <a href="{{ route('admin.blocks.data.edit', {'id': entityBlock.id}) }}">Cancel</a>
        </div>
    {% endif %}

    <form action="{{ route('admin.blocks.data.update', {'id': entityBlock.id}) }}" method="POST" class="block-data-form style">
        <div class="form-columns">
            <div class="form-main">
                <fieldset class="show">
                    <h1>
                        <i class="fa {{ block.icon ?? 'fa-cube' }}"></i>
                        {{ block.name }}
                    </h1>

                    {% if block.description %}
                    <p class="block-description">{{ block.description }}</p>
                    {% endif %}

                    {% for field in fields %}
                    {% set fieldSettings = field.settings ? (field.settings is iterable ? field.settings : field.settings|json_decode) : {} %}
                    {% set vis = fieldSettings.visibility ?? null %}
                    <div class="row field-{{ field.type }}" data-field-name="{{ field.name }}"{% if vis %} data-visibility-field="{{ vis.field }}" data-visibility-values="{{ vis.values|join(',') }}"{% endif %}>
                        <label for="field_{{ field.name }}">
                            {{ field.label ?? field.name }}
                            {% if field.required %}<span class="required">*</span>{% endif %}
                        </label>

                        {% set fieldValue = data[field.name] ?? field.default_value ?? '' %}

                        {% if field.type == 'textarea' %}
                            <textarea
                                name="field_{{ field.name }}"
                                id="field_{{ field.name }}"
                                class="{{ field.css_class }}"
                                {% if field.required %}required{% endif %}
                                rows="4"
                            >{{ fieldValue }}</textarea>

                        {% elseif field.type == 'richtext' or field.type == 'wysiwyg' %}
                            <textarea
                                name="field_{{ field.name }}"
                                id="field_{{ field.name }}"
                                class="wysiwyg {{ field.css_class }}"
                                {% if field.required %}required{% endif %}
                                rows="8"
                            >{{ fieldValue }}</textarea>

                        {% elseif field.type == 'select' %}
                            <select
                                name="field_{{ field.name }}"
                                id="field_{{ field.name }}"
                                class="{{ field.css_class }}"
                                {% if field.required %}required{% endif %}
                            >
                                <option value="">-- Select --</option>
                                {% set options = field.options|split("\n") %}
                                {% for option in options %}
                                    {% set parts = option|split('|') %}
                                    {% set optValue = parts[0]|trim %}
                                    {% set optLabel = parts[1]|default(parts[0])|trim %}
                                    <option value="{{ optValue }}" {{ fieldValue == optValue ? 'selected' : '' }}>
                                        {{ optLabel }}
                                    </option>
                                {% endfor %}
                            </select>

                        {% elseif field.type == 'product_selector' %}
                            <div class="product-selector-wrapper">
                                <input type="hidden" name="field_{{ field.name }}" id="field_{{ field.name }}" value="{{ fieldValue }}">
                                <input type="text" id="field_{{ field.name }}_name" class="product-selector-name" value="" readonly placeholder="No product selected">
                                <button type="button" class="btn btn-small" onclick="window.open('/shop/admin/products/manage.products.mini.php?field=field_{{ field.name }}', 'productPicker', 'status=yes,scrollbars=yes,resizable=yes,width=500,height=600')">
                                    <i class="fa fa-search"></i> Browse
                                </button>
                                <button type="button" class="btn btn-small btn-link" onclick="document.getElementById('field_{{ field.name }}').value=''; document.getElementById('field_{{ field.name }}_name').value=''; document.getElementById('field_{{ field.name }}').dispatchEvent(new Event('change'));">
                                    <i class="fa fa-times"></i>
                                </button>
                            </div>

                        {% elseif field.type == 'page_selector' %}
                            {% set psFieldSettings = field.settings ? (field.settings is iterable ? field.settings : field.settings|json_decode) : {} %}
                            {% set psFieldConfig = psFieldSettings.page_selector_settings ?? {} %}
                            {% set psFieldMode = psFieldConfig.mode ?? 'manual' %}
                            {% set psFieldContainerId = psFieldConfig.container_id ?? '' %}

                            {% if psFieldMode == 'auto' %}
                                <div class="page-selector-auto-wrapper">
                                    <select name="field_{{ field.name }}" id="field_{{ field.name }}" class="page-selector-container-picker" data-value="{{ fieldValue }}">
                                        <option value="">-- Select a listing container --</option>
                                    </select>
                                    <small>Fetches up to {{ psFieldConfig.limit ?? 8 }} most recent child pages from the selected container</small>
                                </div>
                            {% else %}
                                <div class="page-selector-wrapper" data-container-id="{{ psFieldContainerId }}">
                                    <input type="hidden" name="field_{{ field.name }}" id="field_{{ field.name }}" value="{{ fieldValue }}">
                                    <input type="text" id="field_{{ field.name }}_display" class="page-selector-display" value="" readonly placeholder="No page selected">
                                    <button type="button" class="btn btn-small" onclick="openPagePicker('field_{{ field.name }}', '{{ psFieldContainerId }}')">
                                        <i class="fa fa-search"></i> Browse
                                    </button>
                                    <button type="button" class="btn btn-small btn-link" onclick="clearPageSelector('field_{{ field.name }}')">
                                        <i class="fa fa-times"></i>
                                    </button>
                                </div>
                            {% endif %}

                        {% elseif field.type == 'checkbox' %}
                            <div class="checkbox-wrapper">
                                <input
                                    type="checkbox"
                                    name="field_{{ field.name }}"
                                    id="field_{{ field.name }}"
                                    value="1"
                                    {{ fieldValue == '1' ? 'checked' : '' }}
                                >
                                <label for="field_{{ field.name }}" class="checkbox-label">
                                    {{ field.info ?? 'Enable' }}
                                </label>
                            </div>

                        {% elseif field.type == 'image' or field.type == 'file' %}
                            {# Image data comes pre-parsed from controller as {url, alt, crop} or simple string #}
                            {% set imageUrl = fieldValue.url is defined ? fieldValue.url : fieldValue %}
                            {% set imageAlt = fieldValue.alt is defined ? fieldValue.alt : '' %}
                            {% set imageCrop = fieldValue.crop is defined ? fieldValue.crop : {} %}
                            {% set fieldSettings = field.settings ? (field.settings is iterable ? field.settings : field.settings|json_decode) : {} %}
                            {% set imageConfig = fieldSettings.image_settings ?? {} %}
                            {% set cropEnabled = imageConfig.crop_enabled ?? false %}

                            <div class="file-field">
                                <input
                                    type="text"
                                    name="field_{{ field.name }}[url]"
                                    id="field_{{ field.name }}_url"
                                    class="{{ field.css_class }} image-url-input"
                                    value="{{ imageUrl }}"
                                    {% if field.required %}required{% endif %}
                                    placeholder="Enter file path or URL"
                                    data-field-name="{{ field.name }}"
                                    data-crop-enabled="{{ cropEnabled ? '1' : '0' }}"
                                >
                                <button type="button" class="btn btn-small" onclick="openMediaPicker('field_{{ field.name }}_url')">
                                    <i class="fa fa-folder-open"></i> Browse
                                </button>
                            </div>
                            {% if field.type == 'image' %}
                            <div class="alt-text-field">
                                <label for="field_{{ field.name }}_alt">Alt Text</label>
                                <div class="file-field">
                                    <input
                                        type="text"
                                        name="field_{{ field.name }}[alt]"
                                        id="field_{{ field.name }}_alt"
                                        class="{{ field.css_class }}"
                                        value="{{ imageAlt }}"
                                        placeholder="Describe the image for accessibility"
                                    >
                                    {% if cropEnabled %}
                                    <button type="button" class="btn btn-small" onclick="resetCrop('{{ field.name }}')" id="crop_{{ field.name }}_reset" {% if not imageUrl %}style="display: none;"{% endif %}>
                                        <i class="fa fa-refresh"></i> Reset Crop
                                    </button>
                                    {% endif %}
                                </div>
                            </div>

                            {% if cropEnabled %}
                                {# Crop coordinates (hidden) #}
                                <input type="hidden" name="field_{{ field.name }}[crop][x]" id="field_{{ field.name }}_crop_x" value="{{ imageCrop.x ?? 0 }}">
                                <input type="hidden" name="field_{{ field.name }}[crop][y]" id="field_{{ field.name }}_crop_y" value="{{ imageCrop.y ?? 0 }}">
                                <input type="hidden" name="field_{{ field.name }}[crop][width]" id="field_{{ field.name }}_crop_width" value="{{ imageCrop.width ?? 0 }}">
                                <input type="hidden" name="field_{{ field.name }}[crop][height]" id="field_{{ field.name }}_crop_height" value="{{ imageCrop.height ?? 0 }}">

                                <div class="crop-controls" {% if not imageUrl %}style="display: none;"{% endif %} id="crop_{{ field.name }}_controls">
                                    <span class="crop-info">
                                        {% if imageConfig.aspect_ratio %}Aspect ratio: {{ imageConfig.aspect_ratio }}{% else %}Free crop{% endif %}
                                    </span>
                                </div>

                                <div id="crop_{{ field.name }}_warning" class="crop-warning" style="display: none;"></div>

                                <div class="crop-container" id="crop_{{ field.name }}_container" {% if not imageUrl %}style="display: none;"{% endif %}>
                                    <div class="crop-image-wrapper">
                                        <img src="{{ imageUrl }}"
                                             id="crop_{{ field.name }}_image"
                                             class="crop-target"
                                             data-field-name="{{ field.name }}"
                                             data-aspect-ratio="{{ imageConfig.aspect_ratio ?? '' }}"
                                             data-min-width="{{ imageConfig.srcset_sizes is defined ? min(imageConfig.srcset_sizes) : 0 }}"
                                             data-max-width="{{ imageConfig.srcset_sizes is defined ? max(imageConfig.srcset_sizes) : 0 }}"
                                             >
                                    </div>
                                </div>
                            {% else %}
                                {% if imageUrl %}
                                <div class="image-preview">
                                    <img src="{{ imageUrl }}" alt="{{ imageAlt ?: 'Preview' }}">
                                </div>
                                {% endif %}
                            {% endif %}
                            {% endif %}

                        {% elseif field.type == 'number' %}
                            <input
                                type="number"
                                name="field_{{ field.name }}"
                                id="field_{{ field.name }}"
                                class="{{ field.css_class }}"
                                value="{{ fieldValue }}"
                                {% if field.required %}required{% endif %}
                            >

                        {% elseif field.type == 'email' %}
                            <input
                                type="email"
                                name="field_{{ field.name }}"
                                id="field_{{ field.name }}"
                                class="{{ field.css_class }}"
                                value="{{ fieldValue }}"
                                {% if field.required %}required{% endif %}
                            >

                        {% elseif field.type == 'url' %}
                            <input
                                type="url"
                                name="field_{{ field.name }}"
                                id="field_{{ field.name }}"
                                class="{{ field.css_class }}"
                                value="{{ fieldValue }}"
                                {% if field.required %}required{% endif %}
                                placeholder="https://"
                            >

                        {% elseif field.type == 'datetime' or field.type == 'date' %}
                            <input
                                type="date"
                                name="field_{{ field.name }}"
                                id="field_{{ field.name }}"
                                class="{{ field.css_class }}"
                                value="{{ fieldValue }}"
                                {% if field.required %}required{% endif %}
                            >

                        {% elseif field.type == 'colorpicker' or field.type == 'color' %}
                            <div class="color-field-wrapper">
                                <input
                                    type="color"
                                    id="field_{{ field.name }}_picker"
                                    value="{{ fieldValue ?: '#000000' }}"
                                    onchange="this.nextElementSibling.value = this.value"
                                    oninput="this.nextElementSibling.value = this.value"
                                >
                                <input
                                    type="text"
                                    name="field_{{ field.name }}"
                                    id="field_{{ field.name }}"
                                    value="{{ fieldValue ?: '#000000' }}"
                                    pattern="#[0-9a-fA-F]{6}"
                                    placeholder="#000000"
                                    maxlength="7"
                                    onchange="this.previousElementSibling.value = this.value"
                                    oninput="this.previousElementSibling.value = this.value"
                                >
                            </div>

                        {% elseif field.type == 'icon' %}
                            <div class="icon-field-wrapper" id="icon_field_{{ field.name }}_wrapper">
                                <span class="icon-field-preview" id="icon_field_{{ field.name }}_preview">
                                    {% if fieldValue %}
                                        <i class="{{ fieldValue }}"></i>
                                    {% else %}
                                        <i class="fal fa-icons" style="opacity: 0.3;"></i>
                                    {% endif %}
                                </span>
                                <input
                                    type="text"
                                    name="field_{{ field.name }}"
                                    id="field_{{ field.name }}"
                                    class="{{ field.css_class }} icon-field-input"
                                    value="{{ fieldValue }}"
                                    {% if field.required %}required{% endif %}
                                    placeholder="e.g. fal fa-users"
                                    data-field-id="field_{{ field.name }}"
                                >
                                <button type="button" class="btn btn-small" onclick="openIconPicker('field_{{ field.name }}')">
                                    <i class="fa fa-search"></i> Browse
                                </button>
                                <button type="button" class="btn btn-small btn-link" onclick="clearIconField('field_{{ field.name }}')">
                                    <i class="fa fa-times"></i>
                                </button>
                            </div>

                        {% elseif field.type == 'link' %}
                            {% set linkUrl = fieldValue.url is defined ? fieldValue.url : '' %}
                            {% set linkTitle = fieldValue.title is defined ? fieldValue.title : '' %}
                            {% set linkTarget = fieldValue.target is defined ? fieldValue.target : '' %}
                            <div class="link-field-wrapper" id="link_{{ field.name }}_wrapper">
                                <input type="hidden" name="field_{{ field.name }}[url]" id="field_{{ field.name }}_url" value="{{ linkUrl }}">
                                <input type="hidden" name="field_{{ field.name }}[title]" id="field_{{ field.name }}_title" value="{{ linkTitle }}">
                                <input type="hidden" name="field_{{ field.name }}[target]" id="field_{{ field.name }}_target" value="{{ linkTarget }}">

                                <div class="link-display" id="link_{{ field.name }}_display" style="{{ linkUrl ? '' : 'display:none' }}">
                                    <span class="link-display-title" id="link_{{ field.name }}_display_title">{{ linkTitle }}</span>
                                    <a class="link-display-url" id="link_{{ field.name }}_display_url" href="{{ linkUrl }}" target="_blank">{{ linkUrl }}</a>
                                    <span class="link-display-actions">
                                        <a href="{{ linkUrl }}" target="_blank" class="link-action" title="Open link"><i class="fa fa-external-link"></i></a>
                                        <button type="button" class="link-action" onclick="openLinkPicker('{{ field.name }}')" title="Edit link"><i class="fa fa-pencil"></i></button>
                                        <button type="button" class="link-action link-action--danger" onclick="clearLink('{{ field.name }}')" title="Remove link"><i class="fa fa-times"></i></button>
                                    </span>
                                </div>
                                <button type="button" class="btn btn-small" id="link_{{ field.name }}_select_btn" onclick="openLinkPicker('{{ field.name }}')" style="{{ linkUrl ? 'display:none' : '' }}">
                                    <i class="fa fa-link"></i> Select Link
                                </button>
                            </div>

                        {% elseif field.type == 'repeater' %}
                            {# Repeater Field #}
                            {% set repeaterData = fieldValue is iterable ? fieldValue : [] %}
                            <div class="repeater-field"
                                 data-field-name="{{ field.name }}"
                                 data-min-rows="{{ field.repeater_min ?? 0 }}"
                                 data-max-rows="{{ field.repeater_max ?? 100 }}">

                                <div class="repeater-rows" id="repeater_{{ field.name }}_rows">
                                    {% for rowIndex, rowData in repeaterData %}
                                        <div class="repeater-row" data-row-index="{{ rowIndex }}">
                                            <div class="repeater-row-header">
                                                <span class="repeater-row-drag"><i class="fa fa-bars"></i></span>
                                                <span class="repeater-row-number">Row {{ rowIndex + 1 }}</span>
                                                <button type="button" class="btn-remove-row" onclick="removeRepeaterRow(this)">
                                                    <i class="fa fa-times"></i>
                                                </button>
                                            </div>
                                            <div class="repeater-row-fields">
                                                {% for subField in field.subFields %}
                                                    {% set sfSettings = subField.settings ? (subField.settings is iterable ? subField.settings : subField.settings|json_decode) : {} %}
                                                    {% set sfImageConfig = sfSettings.image_settings ?? {} %}
                                                    {% set sfCropEnabled = sfImageConfig.crop_enabled ?? false %}
                                                    {% include 'admin/block_registry/_repeater_subfield.twig' with {
                                                        field: field,
                                                        subField: subField,
                                                        row_index: rowIndex,
                                                        value: rowData[subField.name] ?? '',
                                                        is_template: false,
                                                        sfFieldId: field.name ~ '_' ~ rowIndex ~ '_' ~ subField.name,
                                                        sfSettings: sfSettings,
                                                        sfImageConfig: sfImageConfig,
                                                        sfCropEnabled: sfCropEnabled,
                                                    } only %}
                                                {% endfor %}
                                            </div>
                                        </div>
                                    {% endfor %}
                                </div>

                                <div class="repeater-actions">
                                    <button type="button" class="btn btn-add-row" onclick="addRepeaterRow('{{ field.name }}')">
                                        <i class="fa fa-plus"></i> {{ field.repeater_text ?? 'Add Row' }}
                                    </button>
                                    <button type="button" class="btn btn-duplicate-row" onclick="duplicateLastRepeaterRow('{{ field.name }}')">
                                        <i class="fa fa-copy"></i> Duplicate Last
                                    </button>
                                </div>

                                {# Hidden template for new rows #}
                                <template id="repeater_{{ field.name }}_template">
                                    <div class="repeater-row" data-row-index="__ROW_INDEX__">
                                        <div class="repeater-row-header">
                                            <span class="repeater-row-drag"><i class="fa fa-bars"></i></span>
                                            <span class="repeater-row-number">Row __ROW_NUM__</span>
                                            <button type="button" class="btn-remove-row" onclick="removeRepeaterRow(this)">
                                                <i class="fa fa-times"></i>
                                            </button>
                                        </div>
                                        <div class="repeater-row-fields">
                                            {% for subField in field.subFields %}
                                                {% set sfSettings = subField.settings ? (subField.settings is iterable ? subField.settings : subField.settings|json_decode) : {} %}
                                                {% set sfImageConfig = sfSettings.image_settings ?? {} %}
                                                {% set sfCropEnabled = sfImageConfig.crop_enabled ?? false %}
                                                {% include 'admin/block_registry/_repeater_subfield.twig' with {
                                                    field: field,
                                                    subField: subField,
                                                    row_index: '__ROW_INDEX__',
                                                    value: '',
                                                    is_template: true,
                                                    sfFieldId: field.name ~ '___ROW_INDEX___' ~ subField.name,
                                                    sfSettings: sfSettings,
                                                    sfImageConfig: sfImageConfig,
                                                    sfCropEnabled: sfCropEnabled,
                                                } only %}
                                            {% endfor %}
                                        </div>
                                    </div>
                                </template>
                            </div>

                        {% else %}
                            {# Default to text input #}
                            <input
                                type="text"
                                name="field_{{ field.name }}"
                                id="field_{{ field.name }}"
                                class="{{ field.css_class }}"
                                value="{{ fieldValue }}"
                                {% if field.required %}required{% endif %}
                            >
                        {% endif %}

                        {% if field.info and field.type != 'checkbox' and field.type != 'repeater' %}
                            <small class="field-info">{{ field.info }}</small>
                        {% endif %}
                    </div>
                    {% endfor %}

                    {% if fields|length == 0 %}
                    <p class="no-fields">This block has no fields configured.</p>
                    {% endif %}
                </fieldset>
            </div>

            <div class="form-sidebar">
                <div class="sidebar-box">
                    <h3>Block Info</h3>
                    <ul class="info-list">
                        <li>
                            <span class="info-label">Block Type:</span>
                            <span class="info-value">{{ block.name }}</span>
                        </li>
                        <li>
                            <span class="info-label">Category:</span>
                            <span class="info-value">{{ block.category.name ?? 'Uncategorized' }}</span>
                        </li>
                        <li>
                            <span class="info-label">Fields:</span>
                            <span class="info-value">{{ fields|length }}</span>
                        </li>
                        <li>
                            <span class="info-label">Entity:</span>
                            <span class="info-value">{{ entityBlock.entity_type|capitalize }} #{{ entityBlock.entity_id }}</span>
                        </li>
                    </ul>
                </div>

                {% if isGlobal is defined and isGlobal %}
                <div class="sidebar-box sidebar-box--global">
                    <h3><i class="fa fa-globe"></i> Global Block</h3>
                    <p>This is a global block. Changes here will be reflected on all pages that use it.</p>
                    <ul class="info-list">
                        <li>
                            <span class="info-label">Name:</span>
                            <span class="info-value">{{ entityBlock.name }}</span>
                        </li>
                        <li>
                            <span class="info-label">Used on:</span>
                            <span class="info-value">{{ referenceCount }} page(s)</span>
                        </li>
                    </ul>
                    <a href="{{ route('admin.blocks.global.index') }}" class="btn sidebar-box__btn sidebar-box__btn--secondary">
                        <i class="fa fa-arrow-left"></i> All Global Blocks
                    </a>
                </div>
                {% endif %}

                <div class="sidebar-box status-box">
                    <h3>Status</h3>
                    <div class="status-control">
                        <select name="status" id="status" class="status-select">
                            <option value="draft" {{ entityBlock.status != 'published' ? 'selected' : '' }}>
                                Draft
                            </option>
                            <option value="published" {{ entityBlock.status == 'published' ? 'selected' : '' }}>
                                Published
                            </option>
                        </select>
                        <small class="status-hint">
                            {% if entityBlock.status == 'published' %}
                                This block is visible on the frontend.
                            {% else %}
                                This block is hidden until published.
                            {% endif %}
                        </small>
                    </div>
                </div>

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

                    <button type="submit" class="btn sidebar-box__btn sidebar-box__btn--primary">
                        <i class="fa fa-save"></i> Save Data
                    </button>

                    <button type="submit" name="status" value="published" class="btn sidebar-box__btn sidebar-box__btn--success">
                        <i class="fa fa-check"></i> Save &amp; Publish
                    </button>

                    {% if hasExampleData and not prefillExample %}
                        <a href="{{ route('admin.blocks.data.edit', {'id': entityBlock.id}) }}?prefill=example"
                           class="btn sidebar-box__btn sidebar-box__btn--secondary"
                           title="Populates the fields with this block's example content for you to review before saving.">
                            <i class="fa fa-magic"></i> Fill with example content
                        </a>
                    {% endif %}

                    {% if (isGlobal is not defined or not isGlobal) and not entityBlock.source_block_id %}
                        <button type="button" id="saveAsGlobalBtn" class="btn sidebar-box__btn sidebar-box__btn--secondary">
                            <i class="fa fa-globe"></i> Save as Global Block
                        </button>
                    {% endif %}

                    <a href="{{ backUrl }}" class="btn sidebar-box__btn sidebar-box__btn--secondary">
                        <i class="fa fa-arrow-left"></i> Back
                    </a>

                    <button type="button" class="btn sidebar-box__btn sidebar-box__btn--danger" onclick="confirmDelete()">
                        <i class="fa fa-trash"></i> Remove Block
                    </button>
                </div>
            </div>
        </div>
    </form>

    {# Delete form must be outside the main form #}
    <form id="deleteBlockForm" action="{{ route('admin.blocks.data.destroy', {'id': entityBlock.id}) }}" method="POST" class="form-hidden">
        <input type="hidden" name="_method" value="DELETE">
    </form>

    {% if (isGlobal is not defined or not isGlobal) and not entityBlock.source_block_id %}
    <!-- Save as Global Block Modal -->
    <div id="saveAsGlobalModal" class="modal" style="display:none;">
        <div class="modal-content">
            <div class="modal-header">
                <h2><i class="fa fa-globe"></i> Save as Global Block</h2>
                <button type="button" class="modal-close" id="saveAsGlobalClose">&times;</button>
            </div>
            <form id="saveAsGlobalForm" action="{{ route('admin.blocks.data.saveAsGlobal', {'id': entityBlock.id}) }}" method="POST">
                <div class="modal-body">
                    <p>This will create a new global block from the current content. The block on this page will be linked to it, so future edits sync everywhere it's used.</p>
                    <div class="save-as-global-field">
                        <label for="global_name">Global block name <span class="required">*</span></label>
                        <input type="text" name="global_name" id="global_name" value="{{ block.name }}" required maxlength="255" autocomplete="off">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary"><i class="fa fa-globe"></i> Save as Global</button>
                    <button type="button" class="btn btn-danger" id="saveAsGlobalCancel">Cancel</button>
                </div>
            </form>
        </div>
    </div>
    {% endif %}

    {# Template Preview Section #}
    {% if block.template %}
    <div class="preview-section">
        <div class="preview-header">
            <h2>
                <i class="fa fa-eye"></i> Template Preview
                <small>({{ block.template }})</small>
            </h2>
            <div class="preview-actions">
                <button type="button" class="btn btn-small" onclick="refreshPreview()">
                    <i class="fa fa-refresh"></i> Refresh
                </button>
                <button type="button" class="btn btn-small" onclick="togglePreview()">
                    <i class="fa fa-chevron-down" id="previewToggleIcon"></i> Toggle
                </button>
            </div>
        </div>
        <div class="preview-container" id="previewContainer">
            <div class="preview-frame">
                <iframe
                    id="previewIframe"
                    src="{{ route('admin.blocks.data.preview', {'id': entityBlock.id}) }}"
                    frameborder="0"
                    class="preview-iframe"
                    onload="resizePreviewIframe()"
                ></iframe>
            </div>
            <p class="preview-note">
                <i class="fa fa-info-circle"></i>
                This is a preview of how the block will render on the frontend. Save changes and click "Refresh" to update.
            </p>
        </div>
    </div>
    {% else %}
    <div class="preview-section no-template">
        <div class="preview-header">
            <h2><i class="fa fa-eye-slash"></i> No Template Linked</h2>
        </div>
        <p class="preview-note">
            This block does not have a template linked. To enable preview, assign a template to this block in the
            <a href="{{ route('admin.blocks.edit', {'id': block.id}) }}">block definition</a>.
        </p>
    </div>
    {% endif %}

    {# Cropper.js Library #}
    <script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.6.1/cropper.min.js" integrity="sha512-9KkIqdfN7ipEW6B6k+Aq20PV31bjODg4AA52W+tYtAE0jE0kMx49bjJ3FgvS56wzmyfMUHbQ4Km2b7l9+Y/+Eg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

    <script src="/modules/BlockRegistry/js/block-registry-drag.js?v={{ "now"|date("U") }}"></script>
    <script src="/modules/BlockRegistry/js/block-registry-edit-data.js?v={{ "now"|date("U") }}"></script>

    {# Override admin base float styles for repeater fields — must load after less.js compiles admin LESS #}
    <style>
        .repeater-row-fields,
        .repeater-row-fields .repeater-subfield,
        .repeater-row-fields .repeater-subfield label,
        .repeater-row-fields .repeater-subfield input[type="text"],
        .repeater-row-fields .repeater-subfield textarea,
        .repeater-row-fields .repeater-subfield select,
        .repeater-row-fields .mce-tinymce,
        .repeater-row-fields .mce-tinymce iframe,
        .repeater-row-fields .image-field-wrapper,
        .repeater-row-fields .alt-text-field,
        .repeater-row-fields .alt-text-field label,
        .repeater-row-fields .alt-text-field input {
            float: none !important;
        }
        .repeater-row-fields .repeater-subfield {
            clear: both;
            width: 100% !important;
            margin-bottom: 12px;
        }
        .repeater-row-fields .repeater-subfield label {
            display: block !important;
            width: 100% !important;
            padding-bottom: 4px;
        }
        .repeater-row-fields .repeater-subfield input[type="text"],
        .repeater-row-fields .repeater-subfield textarea,
        .repeater-row-fields .repeater-subfield select {
            width: 100% !important;
            box-sizing: border-box;
        }
        .repeater-row-fields .mce-tinymce {
            width: 100% !important;
            box-sizing: border-box;
        }
        .repeater-row-fields .file-field {
            display: flex !important;
            gap: 5px;
        }
        .repeater-row-fields .file-field input { flex: 1 !important; }
        .repeater-row-fields .file-field .btn { flex-shrink: 0; }

        .product-selector-wrapper {
            display: flex !important;
            gap: 5px;
            align-items: center;
        }
        .product-selector-wrapper input[type="text"] {
            flex: 1 !important;
            cursor: default;
            background: #f9f9f9;
        }
        .product-selector-wrapper .btn { flex-shrink: 0; }
        .repeater-row-fields .product-selector-wrapper { display: flex !important; gap: 5px; align-items: center; }
        .repeater-row-fields .product-selector-wrapper input[type="text"] { flex: 1 !important; }

        .page-selector-wrapper {
            display: flex !important;
            gap: 5px;
            align-items: center;
        }
        .page-selector-wrapper input[type="text"] {
            flex: 1 !important;
            cursor: default;
            background: #f9f9f9;
        }
        .page-selector-wrapper .btn { flex-shrink: 0; }
        .repeater-row-fields .page-selector-wrapper { display: flex !important; gap: 5px; align-items: center; }
        .repeater-row-fields .page-selector-wrapper input[type="text"] { flex: 1 !important; }
        .page-selector-auto-wrapper select { width: 100%; margin-bottom: 4px; }
        .page-selector-auto-wrapper small { color: #888; }

        .page-selector-settings-header {
            font-weight: bold;
            margin-bottom: 8px;
            padding-top: 8px;
            border-top: 1px solid #ddd;
        }

        .repeater-row-fields .repeater-subfield:has(> input[type="checkbox"]) {
            display: inline-flex !important;
            align-items: center;
            gap: 6px;
            width: auto !important;
            clear: none !important;
            margin-right: 20px;
            margin-bottom: 8px;
        }
        .repeater-row-fields .repeater-subfield:has(> input[type="checkbox"]) label {
            display: inline !important;
            width: auto !important;
            padding-bottom: 0;
            white-space: nowrap;
        }
        .repeater-row-fields .repeater-subfield:has(> input[type="checkbox"]) input[type="checkbox"] {
            width: auto !important;
            margin: 0;
        }

        .btn-add-row {
            float: none !important;
            clear: both;
        }

        .repeater-row-fields .link-field-wrapper,
        .repeater-row-fields .link-display {
            float: none !important;
        }

        .repeater-row-fields .icon-field-wrapper {
            display: flex !important;
            gap: 5px;
            align-items: center;
            float: none !important;
        }
        .repeater-row-fields .icon-field-wrapper input[type="text"] {
            flex: 1 !important;
        }
    </style>

{% endblock %}
