{% 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 %}

    <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 %}
                    <div class="row field-{{ field.type }}">
                        <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 == '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 == '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>

                                <button type="button" class="btn btn-add-row" onclick="addRepeaterRow('{{ field.name }}')">
                                    <i class="fa fa-plus"></i> {{ field.repeater_text ?? 'Add Row' }}
                                </button>

                                {# 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>

                    <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>

    {# 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"></script>
    <script src="/modules/BlockRegistry/js/block-registry-edit-data.js"></script>

{% endblock %}
