<template>
    <a-spin :spinning="loading">
        <template v-if="data">
            <a-form layout="vertical">
                <a-tabs v-model:activeKey="activeTab">
                    <!-- Basic Info Tab -->
                    <a-tab-pane
                        key="basic"
                        :tab="$t('website_builder.basic_info')"
                    >
                        <a-row :gutter="16">
                            <a-col :xs="24" :sm="24" :md="24" :lg="24">
                                <a-form-item
                                    :label="$t('website_builder.section_layout')"
                                    name="section_layout"
                                    :help="rules.section_layout ? rules.section_layout.message : null"
                                    :validateStatus="rules.section_layout ? 'error' : null"
                                    class="required"
                                >
                                    <!-- Section Layout Preview Card -->
                                    <div
                                        class="section-layout-preview-card"
                                        @click="openLayoutModal"
                                    >
                                        <div class="layout-preview-iframe">
                                            <IframeLivePreview
                                                v-if="currentLayoutPreviewUrl"
                                                :key="'layout-preview-' + formData.section_layout"
                                                :url="currentLayoutPreviewUrl"
                                                :scaled-full-page="true"
                                                :scale-factor="0.18"
                                                :viewport-width="1440"
                                                height="140px"
                                                :clickable="false"
                                                :show-overlay="false"
                                                :show-badge="false"
                                                border-radius="8px 8px 0 0"
                                                spin-size="small"
                                            />
                                            <div v-else class="layout-preview-placeholder">
                                                <AppstoreOutlined class="placeholder-icon" />
                                                <span>{{ $t('website_builder.no_preview') }}</span>
                                            </div>
                                        </div>
                                        <div class="layout-preview-info">
                                            <div class="layout-preview-name">
                                                {{ currentLayoutLabel }}
                                            </div>
                                            <a-button type="link" size="small" class="change-layout-btn">
                                                <template #icon><EditOutlined /></template>
                                                {{ $t('website_builder.change_layout') }}
                                            </a-button>
                                        </div>
                                    </div>
                                </a-form-item>
                            </a-col>
                            <!-- Title and Subtitle fields - Hidden for header and footer sections -->
                            <a-col :xs="24" :sm="24" :md="24" :lg="24" v-if="!isLayoutSection">
                                <a-form-item
                                    :label="$t('website_builder.title')"
                                    name="title"
                                    :help="rules.title ? rules.title.message : null"
                                    :validateStatus="rules.title ? 'error' : null"
                                    class="required"
                                >
                                    <a-input
                                        v-model:value="formData.title"
                                        :placeholder="
                                            $t('common.placeholder_default_text', [
                                                $t('website_builder.title'),
                                            ])
                                        "
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :xs="24" :sm="24" :md="24" :lg="24" v-if="!isLayoutSection">
                                <a-form-item
                                    :label="$t('website_builder.subtitle')"
                                    name="subtitle"
                                    :help="rules.subtitle ? rules.subtitle.message : null"
                                    :validateStatus="rules.subtitle ? 'error' : null"
                                >
                                    <a-textarea
                                        v-model:value="formData.subtitle"
                                        :placeholder="
                                            $t('common.placeholder_default_text', [
                                                $t('website_builder.subtitle'),
                                            ])
                                        "
                                        :auto-size="{ minRows: 2 }"
                                    />
                                </a-form-item>
                            </a-col>
                            <!-- White Background Option - Hidden for header and footer sections -->
                            <a-col :xs="24" :sm="24" :md="12" :lg="6" v-if="!isLayoutSection">
                                <a-form-item
                                    :label="$t('website_builder.is_white_background')"
                                    name="is_white_background"
                                >
                                    <a-switch
                                        v-model:checked="formData.is_white_background"
                                    />
                                </a-form-item>
                            </a-col>
                        </a-row>

                        <!-- Custom Padding Row - Hidden for header and footer sections -->
                        <a-row :gutter="16" v-if="!isLayoutSection" class="mt-4">
                            <!-- Padding Top -->
                            <a-col :xs="24" :sm="24" :md="12" :lg="12">
                                <a-form-item
                                    :label="$t('website_builder.padding_top')"
                                    name="padding_top"
                                    :help="$t('website_builder.padding_help')"
                                >
                                    <div class="padding-input-wrapper">
                                        <a-switch
                                            :checked="formData.padding_top !== null"
                                            @change="(checked) => formData.padding_top = checked ? 48 : null"
                                            class="padding-switch"
                                        />
                                        <a-input-number
                                            v-if="formData.padding_top !== null"
                                            v-model:value="formData.padding_top"
                                            :min="0"
                                            :max="200"
                                            :step="4"
                                            addon-after="px"
                                            class="padding-input"
                                        />
                                        <span v-else class="padding-default-text">{{ $t('website_builder.padding_default') }}</span>
                                    </div>
                                </a-form-item>
                            </a-col>
                            <!-- Padding Bottom -->
                            <a-col :xs="24" :sm="24" :md="12" :lg="12">
                                <a-form-item
                                    :label="$t('website_builder.padding_bottom')"
                                    name="padding_bottom"
                                    :help="$t('website_builder.padding_help')"
                                >
                                    <div class="padding-input-wrapper">
                                        <a-switch
                                            :checked="formData.padding_bottom !== null"
                                            @change="(checked) => formData.padding_bottom = checked ? 48 : null"
                                            class="padding-switch"
                                        />
                                        <a-input-number
                                            v-if="formData.padding_bottom !== null"
                                            v-model:value="formData.padding_bottom"
                                            :min="0"
                                            :max="200"
                                            :step="4"
                                            addon-after="px"
                                            class="padding-input"
                                        />
                                        <span v-else class="padding-default-text">{{ $t('website_builder.padding_default') }}</span>
                                    </div>
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-tab-pane>

                    <!-- Content Tab - Dynamic Form Builder -->
                    <a-tab-pane
                        key="content"
                        :tab="$t('website_builder.content_data')"
                    >
                        <div v-if="contentSchema && contentSchema.length > 0">
                            <!-- Render dynamic fields based on schema -->
                            <template v-for="field in contentSchema" :key="field.name">
                                <!-- Text Input -->
                                <a-form-item
                                    v-if="field.type === 'text'"
                                    :label="getFieldLabel(field.name) || field.label"
                                    :name="'content.' + field.name"
                                    :class="{ required: field.required }"
                                >
                                    <a-input
                                        v-model:value="contentData[field.name]"
                                        :placeholder="'Enter ' + (getFieldLabel(field.name) || field.label)"
                                    />
                                </a-form-item>

                                <!-- Textarea -->
                                <a-form-item
                                    v-else-if="field.type === 'textarea'"
                                    :label="getFieldLabel(field.name) || field.label"
                                    :name="'content.' + field.name"
                                    :class="{ required: field.required }"
                                >
                                    <a-textarea
                                        v-model:value="contentData[field.name]"
                                        :placeholder="'Enter ' + (getFieldLabel(field.name) || field.label)"
                                        :auto-size="{ minRows: 3, maxRows: 6 }"
                                    />
                                </a-form-item>

                                <!-- Number Input -->
                                <a-form-item
                                    v-else-if="field.type === 'number'"
                                    :label="getFieldLabel(field.name) || field.label"
                                    :name="'content.' + field.name"
                                    :class="{ required: field.required }"
                                >
                                    <a-input-number
                                        v-model:value="contentData[field.name]"
                                        :placeholder="'Enter ' + (getFieldLabel(field.name) || field.label)"
                                        style="width: 100%"
                                    />
                                </a-form-item>

                                <!-- Select -->
                                <a-form-item
                                    v-else-if="field.type === 'select'"
                                    :label="getFieldLabel(field.name) || field.label"
                                    :name="'content.' + field.name"
                                    :class="{ required: field.required }"
                                >
                                    <a-select
                                        v-model:value="contentData[field.name]"
                                        :placeholder="'Select ' + (getFieldLabel(field.name) || field.label)"
                                        :options="field.options"
                                    />
                                </a-form-item>

                                <!-- Switch -->
                                <a-form-item
                                    v-else-if="field.type === 'switch'"
                                    :label="getFieldLabel(field.name) || field.label"
                                    :name="'content.' + field.name"
                                    :class="{ required: field.required }"
                                >
                                    <a-switch v-model:checked="contentData[field.name]" />
                                </a-form-item>

                                <!-- Image Upload -->
                                <a-form-item
                                    v-else-if="field.type === 'image'"
                                    :label="getFieldLabel(field.name) || field.label"
                                    :name="'content.' + field.name"
                                    :class="{ required: field.required }"
                                >
                                    <ImageUpload
                                        :formData="getImageFormData(field.name)"
                                        imageField="file"
                                        @onFileSelected="
                                            (file) =>
                                                onContentImageSelected(field.name, file)
                                        "
                                        @onRemove="() => onContentImageRemoved(field.name)"
                                    />
                                </a-form-item>

                                <!-- Icon Picker -->
                                <a-form-item
                                    v-else-if="field.type === 'icon'"
                                    :label="getFieldLabel(field.name) || field.label"
                                    :name="'content.' + field.name"
                                    :class="{ required: field.required }"
                                >
                                    <IconPicker
                                        v-model="contentData[field.name]"
                                        :placeholder="'Select ' + (getFieldLabel(field.name) || field.label)"
                                    />
                                </a-form-item>

                                <!-- Repeater -->
                                <div
                                    v-else-if="field.type === 'repeater'"
                                    class="repeater-field"
                                >
                                    <a-divider orientation="left">{{
                                        getFieldLabel(field.name) || field.label
                                    }}</a-divider>

                                    <!-- Header Row -->
                                    <a-row
                                        :gutter="8"
                                        class="repeater-header"
                                        v-if="getRepeaterItems(field.name).length > 0"
                                    >
                                        <a-col
                                            :flex="getFieldFlex(subField)"
                                            v-for="subField in getRegularFields(field.fields)"
                                            :key="'header-' + subField.name"
                                        >
                                            <span class="repeater-header-label">{{
                                                getFieldLabel(subField.name, field.name) || subField.label
                                            }}</span>
                                        </a-col>
                                        <a-col :flex="'40px'">
                                            <span class="repeater-header-label"></span>
                                        </a-col>
                                    </a-row>

                                    <!-- Data Rows -->
                                    <div
                                        v-for="(item, index) in getRepeaterItems(
                                            field.name
                                        )"
                                        :key="index"
                                        class="repeater-row"
                                    >
                                        <!-- Main Row - Regular fields -->
                                        <a-row :gutter="8" align="middle">
                                            <template
                                                v-for="subField in getRegularFields(field.fields)"
                                                :key="subField.name"
                                            >
                                                <a-col :flex="getFieldFlex(subField)">
                                                    <!-- Sub Text Input -->
                                                    <a-input
                                                        v-if="subField.type === 'text'"
                                                        v-model:value="
                                                            item[subField.name]
                                                        "
                                                        :placeholder="getFieldLabel(subField.name, field.name) || subField.label"
                                                    />

                                                    <!-- Sub Textarea -->
                                                    <a-textarea
                                                        v-else-if="
                                                            subField.type === 'textarea'
                                                        "
                                                        v-model:value="
                                                            item[subField.name]
                                                        "
                                                        :placeholder="getFieldLabel(subField.name, field.name) || subField.label"
                                                        :auto-size="{
                                                            minRows: 1,
                                                            maxRows: 3,
                                                        }"
                                                    />

                                                    <!-- Sub Number Input -->
                                                    <a-input-number
                                                        v-else-if="
                                                            subField.type === 'number'
                                                        "
                                                        v-model:value="
                                                            item[subField.name]
                                                        "
                                                        :placeholder="getFieldLabel(subField.name, field.name) || subField.label"
                                                        style="width: 100%"
                                                    />

                                                    <!-- Sub Select -->
                                                    <a-select
                                                        v-else-if="
                                                            subField.type === 'select'
                                                        "
                                                        v-model:value="
                                                            item[subField.name]
                                                        "
                                                        :placeholder="getFieldLabel(subField.name, field.name) || subField.label"
                                                        :options="subField.options"
                                                        style="width: 100%"
                                                    />

                                                    <!-- Sub Switch -->
                                                    <a-switch
                                                        v-else-if="
                                                            subField.type === 'switch'
                                                        "
                                                        v-model:checked="
                                                            item[subField.name]
                                                        "
                                                    />

                                                    <!-- Sub Image Upload -->
                                                    <ImageUpload
                                                        v-else-if="
                                                            subField.type === 'image'
                                                        "
                                                        :formData="
                                                            getRepeaterImageFormData(
                                                                field.name,
                                                                index,
                                                                subField.name,
                                                                item
                                                            )
                                                        "
                                                        imageField="file"
                                                        @onFileSelected="
                                                            (file) =>
                                                                onRepeaterImageSelected(
                                                                    field.name,
                                                                    index,
                                                                    subField.name,
                                                                    file
                                                                )
                                                        "
                                                        @onRemove="() => onRepeaterImageRemoved(field.name, index, subField.name)"
                                                    />

                                                    <!-- Sub Icon Picker -->
                                                    <IconPicker
                                                        v-else-if="
                                                            subField.type === 'icon'
                                                        "
                                                        v-model="
                                                            item[subField.name]
                                                        "
                                                        :placeholder="getFieldLabel(subField.name, field.name) || subField.label"
                                                    />
                                                </a-col>
                                            </template>
                                            <a-col :flex="'40px'">
                                                <a-button
                                                    type="text"
                                                    danger
                                                    @click="
                                                        removeRepeaterItem(
                                                            field.name,
                                                            index
                                                        )
                                                    "
                                                >
                                                    <DeleteOutlined />
                                                </a-button>
                                            </a-col>
                                        </a-row>

                                        <!-- Nested Repeaters - Separate rows below main fields -->
                                        <template
                                            v-for="subField in getNestedRepeaterFields(field.fields)"
                                            :key="'nested-' + subField.name"
                                        >
                                            <div class="nested-repeater">
                                                <div class="nested-repeater-label">{{ getFieldLabel(subField.name, field.name) || subField.label }}</div>
                                                <!-- Nested Repeater Header Row -->
                                                <a-row
                                                    :gutter="8"
                                                    class="nested-repeater-header"
                                                    v-if="getNestedRepeaterItems(item, subField.name).length > 0"
                                                >
                                                    <a-col
                                                        :flex="getFieldFlex(nestedField)"
                                                        v-for="nestedField in subField.fields"
                                                        :key="'nested-header-' + nestedField.name"
                                                    >
                                                        <span class="nested-header-label">{{
                                                            getFieldLabel(nestedField.name, field.name + '_' + subField.name) || nestedField.label
                                                        }}</span>
                                                    </a-col>
                                                    <a-col :flex="'40px'">
                                                        <span class="nested-header-label"></span>
                                                    </a-col>
                                                </a-row>
                                                <div
                                                    v-for="(nestedItem, nestedIndex) in getNestedRepeaterItems(item, subField.name)"
                                                    :key="nestedIndex"
                                                    class="nested-repeater-row"
                                                >
                                                    <a-row :gutter="8" align="middle">
                                                        <template
                                                            v-for="nestedField in subField.fields"
                                                            :key="nestedField.name"
                                                        >
                                                            <a-col :flex="getFieldFlex(nestedField)">
                                                                <!-- Nested Text Input -->
                                                                <a-input
                                                                    v-if="nestedField.type === 'text'"
                                                                    v-model:value="nestedItem[nestedField.name]"
                                                                    :placeholder="getFieldLabel(nestedField.name, field.name + '_' + subField.name) || nestedField.label"
                                                                    size="middle"
                                                                />
                                                                <!-- Nested Icon Picker -->
                                                                <IconPicker
                                                                    v-else-if="nestedField.type === 'icon'"
                                                                    v-model="nestedItem[nestedField.name]"
                                                                    :placeholder="getFieldLabel(nestedField.name, field.name + '_' + subField.name) || nestedField.label"
                                                                    size="middle"
                                                                />
                                                                <!-- Nested Image Upload -->
                                                                <ImageUpload
                                                                    v-else-if="nestedField.type === 'image'"
                                                                    :formData="getNestedRepeaterImageFormData(field.name, index, subField.name, nestedIndex, nestedField.name, nestedItem)"
                                                                    imageField="file"
                                                                    @onFileSelected="(file) => onNestedRepeaterImageSelected(field.name, index, subField.name, nestedIndex, nestedField.name, file)"
                                                                    @onRemove="() => onNestedRepeaterImageRemoved(field.name, index, subField.name, nestedIndex, nestedField.name)"
                                                                />
                                                                <!-- Nested Select -->
                                                                <a-select
                                                                    v-else-if="nestedField.type === 'select'"
                                                                    v-model:value="nestedItem[nestedField.name]"
                                                                    :placeholder="getFieldLabel(nestedField.name, field.name + '_' + subField.name) || nestedField.label"
                                                                    :options="nestedField.options"
                                                                    size="middle"
                                                                    style="width: 100%"
                                                                />
                                                                <!-- Nested Switch -->
                                                                <a-switch
                                                                    v-else-if="nestedField.type === 'switch'"
                                                                    v-model:checked="nestedItem[nestedField.name]"
                                                                    size="small"
                                                                />
                                                            </a-col>
                                                        </template>
                                                        <a-col :flex="'40px'">
                                                            <a-button
                                                                type="text"
                                                                danger
                                                                size="middle"
                                                                @click="removeNestedRepeaterItem(item, subField.name, nestedIndex)"
                                                            >
                                                                <DeleteOutlined />
                                                            </a-button>
                                                        </a-col>
                                                    </a-row>
                                                </div>
                                                <a-button
                                                    type="dashed"
                                                    size="middle"
                                                    @click="addNestedRepeaterItem(item, subField)"
                                                    class="mt-1"
                                                >
                                                    <PlusOutlined /> {{ $t('common.add') }} {{ getFieldLabel(subField.name, field.name) || subField.label }}
                                                </a-button>
                                            </div>
                                        </template>
                                    </div>

                                    <a-button
                                        type="dashed"
                                        size="middle"
                                        @click="addRepeaterItem(field)"
                                        class="mt-2"
                                    >
                                        <PlusOutlined /> {{ $t('common.add') }}
                                    </a-button>
                                </div>

                                <!-- Group with Repeater - Object with heading fields and nested repeater -->
                                <div
                                    v-else-if="field.type === 'group_with_repeater'"
                                    class="group-with-repeater-field"
                                >
                                    <a-divider orientation="left">{{
                                        getFieldLabel(field.name) || field.label
                                    }}</a-divider>

                                    <!-- Heading Fields (non-repeater fields) -->
                                    <a-row :gutter="16" class="group-heading-fields">
                                        <template v-for="headingField in getGroupHeadingFields(field.fields)" :key="headingField.name">
                                            <!-- Switch -->
                                            <a-col :xs="24" :sm="12" :md="8" :lg="6" v-if="headingField.type === 'switch'">
                                                <a-form-item :label="getFieldLabel(headingField.name, field.name) || headingField.label">
                                                    <a-switch v-model:checked="getGroupData(field.name)[headingField.name]" />
                                                </a-form-item>
                                            </a-col>
                                            <!-- Text -->
                                            <a-col :xs="24" :sm="24" :md="12" :lg="12" v-else-if="headingField.type === 'text'">
                                                <a-form-item :label="getFieldLabel(headingField.name, field.name) || headingField.label">
                                                    <a-input
                                                        v-model:value="getGroupData(field.name)[headingField.name]"
                                                        :placeholder="getFieldLabel(headingField.name, field.name) || headingField.label"
                                                    />
                                                </a-form-item>
                                            </a-col>
                                            <!-- Textarea -->
                                            <a-col :xs="24" :sm="24" :md="24" :lg="24" v-else-if="headingField.type === 'textarea'">
                                                <a-form-item :label="getFieldLabel(headingField.name, field.name) || headingField.label">
                                                    <a-textarea
                                                        v-model:value="getGroupData(field.name)[headingField.name]"
                                                        :placeholder="getFieldLabel(headingField.name, field.name) || headingField.label"
                                                        :auto-size="{ minRows: 2 }"
                                                    />
                                                </a-form-item>
                                            </a-col>
                                        </template>
                                    </a-row>

                                    <!-- Nested Repeater Fields -->
                                    <template v-for="repeaterField in getGroupRepeaterFields(field.fields)" :key="repeaterField.name">
                                        <div class="group-nested-repeater">
                                            <div class="group-nested-repeater-label">{{ getFieldLabel(repeaterField.name, field.name) || repeaterField.label }}</div>

                                            <!-- Header Row -->
                                            <a-row
                                                :gutter="8"
                                                class="repeater-header"
                                                v-if="getGroupRepeaterItems(field.name, repeaterField.name).length > 0"
                                            >
                                                <a-col
                                                    :flex="getFieldFlex(subField)"
                                                    v-for="subField in repeaterField.fields"
                                                    :key="'group-header-' + subField.name"
                                                >
                                                    <span class="repeater-header-label">{{
                                                        getFieldLabel(subField.name, field.name + '_' + repeaterField.name) || subField.label
                                                    }}</span>
                                                </a-col>
                                                <a-col :flex="'40px'">
                                                    <span class="repeater-header-label"></span>
                                                </a-col>
                                            </a-row>

                                            <!-- Data Rows -->
                                            <div
                                                v-for="(item, index) in getGroupRepeaterItems(field.name, repeaterField.name)"
                                                :key="index"
                                                class="repeater-row"
                                            >
                                                <a-row :gutter="8" align="middle">
                                                    <template v-for="subField in repeaterField.fields" :key="subField.name">
                                                        <a-col :flex="getFieldFlex(subField)">
                                                            <!-- Text Input -->
                                                            <a-input
                                                                v-if="subField.type === 'text'"
                                                                v-model:value="item[subField.name]"
                                                                :placeholder="getFieldLabel(subField.name, field.name + '_' + repeaterField.name) || subField.label"
                                                            />
                                                            <!-- Image Upload -->
                                                            <ImageUpload
                                                                v-else-if="subField.type === 'image'"
                                                                :formData="getGroupRepeaterImageFormData(field.name, repeaterField.name, index, subField.name, item)"
                                                                imageField="file"
                                                                @onFileSelected="(file) => onGroupRepeaterImageSelected(field.name, repeaterField.name, index, subField.name, file)"
                                                                @onRemove="() => onGroupRepeaterImageRemoved(field.name, repeaterField.name, index, subField.name)"
                                                            />
                                                            <!-- Icon Picker -->
                                                            <IconPicker
                                                                v-else-if="subField.type === 'icon'"
                                                                v-model="item[subField.name]"
                                                                :placeholder="getFieldLabel(subField.name, field.name + '_' + repeaterField.name) || subField.label"
                                                            />
                                                            <!-- Switch -->
                                                            <a-switch
                                                                v-else-if="subField.type === 'switch'"
                                                                v-model:checked="item[subField.name]"
                                                                size="small"
                                                            />
                                                        </a-col>
                                                    </template>
                                                    <a-col :flex="'40px'">
                                                        <a-button
                                                            type="text"
                                                            danger
                                                            @click="removeGroupRepeaterItem(field.name, repeaterField.name, index)"
                                                        >
                                                            <DeleteOutlined />
                                                        </a-button>
                                                    </a-col>
                                                </a-row>
                                            </div>

                                            <a-button
                                                type="dashed"
                                                size="middle"
                                                @click="addGroupRepeaterItem(field.name, repeaterField)"
                                                class="mt-2"
                                            >
                                                <PlusOutlined /> {{ $t('common.add') }} {{ getFieldLabel(repeaterField.name, field.name) || repeaterField.label }}
                                            </a-button>
                                        </div>
                                    </template>
                                </div>
                            </template>
                        </div>
                        <a-empty
                            v-else
                            :description="
                                $t('website_builder.no_content_schema')
                            "
                        />
                    </a-tab-pane>
                </a-tabs>

                <!-- Submit Button -->
                <a-row :gutter="16" style="margin-top: 24px">
                    <a-col :xs="24" :sm="24" :md="24" :lg="24">
                        <a-form-item>
                            <a-button
                                v-if="
                                    permsArray.includes('website_builder_edit') ||
                                    permsArray.includes('admin')
                                "
                                type="primary"
                                :loading="loading"
                                @click="onSubmit"
                            >
                                <template #icon>
                                    <SaveOutlined />
                                </template>
                                {{ $t("common.update") }}
                            </a-button>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </template>
        <template v-else>
            <a-empty :description="$t('website_builder.select_section')" />
        </template>
    </a-spin>

    <!-- Section Layout Selection Modal -->
    <SectionLayoutModal
        v-model:open="layoutModalVisible"
        :section-key="props.data?.section_key"
        :current-layout="formData.section_layout"
        :business-id="props.websiteId"
        :layouts="sectionLayoutOptions"
        :loading="loadingLayouts"
        @select="onLayoutSelect"
    />
</template>

<script setup>
import { ref, watch, reactive, computed } from "vue";
import { SaveOutlined, PlusOutlined, DeleteOutlined, EditOutlined, AppstoreOutlined } from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import { useI18n } from "vue-i18n";
import IframeLivePreview from "../../../common/components/IframeLivePreview.vue";
import SectionLayoutModal from "./SectionLayoutModal.vue";

const { t, te } = useI18n();
const apiAdmin = window.__composables.apiAdmin;
const axiosAdmin = window.axiosAdmin;
const addEditUrl = "website-builder";
const { permsArray } = window.__composables.common();

const props = defineProps({
    data: Object,
    langId: String,
    websiteId: String,
    businessPageId: String,
});

const emit = defineEmits(["addEditSuccess"]);

// Check if current section is a layout section (header or footer)
// Layout sections don't need title and subtitle fields
const isLayoutSection = computed(() => {
    return ['header', 'footer'].includes(props.data?.section_key);
});

const formData = ref({});
const activeTab = ref("basic");
const contentJson = ref("{}");
const contentData = reactive({});
const contentImages = reactive({});
const contentSchema = ref([]);
const { addEditFileRequestAdmin, loading, rules } = apiAdmin();

// Section layout options - fetched from API
const sectionLayoutOptions = ref([]);
const loadingLayouts = ref(false);

// Layout modal state
const layoutModalVisible = ref(false);

// Computed: Get current layout preview URL
// Always forces light mode for consistent preview display regardless of admin panel theme
const currentLayoutPreviewUrl = computed(() => {
    if (!props.data?.section_key || !formData.value.section_layout) return null;

    const baseUrl = window.location.origin;
    let url = `${baseUrl}/section-preview/${props.data.section_key}/${formData.value.section_layout}`;

    // Add website_id if provided
    if (props.websiteId) {
        url += `?website_id=${props.websiteId}&force_light_mode=1`;
    } else {
        url += `?force_light_mode=1`;
    }

    return url;
});

// Computed: Get current layout label
const currentLayoutLabel = computed(() => {
    if (!formData.value.section_layout) return t('website_builder.no_layout_selected');

    const layout = sectionLayoutOptions.value.find(l => l.value === formData.value.section_layout);
    return layout?.label || formData.value.section_layout;
});

// Open layout selection modal
const openLayoutModal = () => {
    layoutModalVisible.value = true;
};

// Handle layout selection from modal
const onLayoutSelect = (layout) => {
    formData.value.section_layout = layout.value;
};

// Fetch section layouts from API
const fetchSectionLayouts = async (sectionKey) => {
    if (!sectionKey) {
        sectionLayoutOptions.value = [];
        return;
    }

    try {
        loadingLayouts.value = true;
        const params = new URLSearchParams();
        params.append('section_key', sectionKey);
        if (props.websiteId) {
            params.append('website_id', props.websiteId);
        }

        const response = await axiosAdmin.get(`website-builder/section-layouts?${params.toString()}`);
        if (response && response.data) {
            sectionLayoutOptions.value = response.data;
        } else {
            // Fallback to section_key if no layouts returned
            sectionLayoutOptions.value = [{ value: sectionKey, label: sectionKey }];
        }
    } catch (error) {
        console.error('Error fetching section layouts:', error);
        // Fallback to section_key on error
        sectionLayoutOptions.value = [{ value: sectionKey, label: sectionKey }];
    } finally {
        loadingLayouts.value = false;
    }
};

// Get repeater items for a field
const getRepeaterItems = (fieldName) => {
    if (!contentData[fieldName]) {
        contentData[fieldName] = [];
    }
    return contentData[fieldName];
};

// Get regular fields (non-nested-repeater) from field list
const getRegularFields = (fields) => {
    return fields.filter(f => f.type !== 'nested_repeater');
};

// Get nested repeater fields from field list
const getNestedRepeaterFields = (fields) => {
    return fields.filter(f => f.type === 'nested_repeater');
};

// Add new item to repeater
const addRepeaterItem = (field) => {
    if (!contentData[field.name]) {
        contentData[field.name] = [];
    }

    const newItem = {};
    field.fields.forEach((subField) => {
        if (subField.type === "switch") {
            newItem[subField.name] = false;
        } else if (subField.type === "number") {
            newItem[subField.name] = 0;
        } else if (subField.type === "nested_repeater") {
            newItem[subField.name] = [];
        } else {
            newItem[subField.name] = "";
        }
    });

    contentData[field.name].push(newItem);
};

// Remove item from repeater
const removeRepeaterItem = (fieldName, index) => {
    if (contentData[fieldName] && contentData[fieldName].length > index) {
        contentData[fieldName].splice(index, 1);
    }
};

// Get nested repeater items for a parent item
const getNestedRepeaterItems = (parentItem, fieldName) => {
    if (!parentItem[fieldName]) {
        parentItem[fieldName] = [];
    }
    return parentItem[fieldName];
};

// Add new item to nested repeater
const addNestedRepeaterItem = (parentItem, field) => {
    if (!parentItem[field.name]) {
        parentItem[field.name] = [];
    }

    const newItem = {};
    field.fields.forEach((nestedField) => {
        if (nestedField.type === "switch") {
            newItem[nestedField.name] = false;
        } else if (nestedField.type === "number") {
            newItem[nestedField.name] = 0;
        } else {
            newItem[nestedField.name] = "";
        }
    });

    parentItem[field.name].push(newItem);
};

// Remove item from nested repeater
const removeNestedRepeaterItem = (parentItem, fieldName, index) => {
    if (parentItem[fieldName] && parentItem[fieldName].length > index) {
        parentItem[fieldName].splice(index, 1);
    }
};

// ============================================
// GROUP WITH REPEATER FUNCTIONS
// ============================================

// Get group data (object) for a field
const getGroupData = (fieldName) => {
    if (!contentData[fieldName] || typeof contentData[fieldName] !== 'object' || Array.isArray(contentData[fieldName])) {
        contentData[fieldName] = {};
    }
    return contentData[fieldName];
};

// Get heading fields (non-repeater) from group_with_repeater field list
const getGroupHeadingFields = (fields) => {
    return fields.filter(f => f.type !== 'repeater');
};

// Get repeater fields from group_with_repeater field list
const getGroupRepeaterFields = (fields) => {
    return fields.filter(f => f.type === 'repeater');
};

// Get items from a repeater inside a group
const getGroupRepeaterItems = (groupFieldName, repeaterFieldName) => {
    const groupData = getGroupData(groupFieldName);
    if (!groupData[repeaterFieldName]) {
        groupData[repeaterFieldName] = [];
    }
    return groupData[repeaterFieldName];
};

// Add new item to a repeater inside a group
const addGroupRepeaterItem = (groupFieldName, repeaterField) => {
    const groupData = getGroupData(groupFieldName);
    if (!groupData[repeaterField.name]) {
        groupData[repeaterField.name] = [];
    }

    const newItem = {};
    repeaterField.fields.forEach((subField) => {
        if (subField.type === "switch") {
            newItem[subField.name] = false;
        } else if (subField.type === "number") {
            newItem[subField.name] = 0;
        } else {
            newItem[subField.name] = "";
        }
    });

    groupData[repeaterField.name].push(newItem);
};

// Remove item from a repeater inside a group
const removeGroupRepeaterItem = (groupFieldName, repeaterFieldName, index) => {
    const groupData = getGroupData(groupFieldName);
    if (groupData[repeaterFieldName] && groupData[repeaterFieldName].length > index) {
        groupData[repeaterFieldName].splice(index, 1);
    }
};

// Get image form data for group repeater ImageUpload component
const getGroupRepeaterImageFormData = (groupFieldName, repeaterFieldName, index, subFieldName, item) => {
    const imageKey = `${groupFieldName}_${repeaterFieldName}_${index}_${subFieldName}`;
    const urlKey = subFieldName + "_url";

    // Check for newly selected file
    const newFile = contentImages[imageKey] || null;
    if (newFile) {
        return {
            file: newFile,
            file_url: null,
        };
    }

    // Check for existing image URL
    const existingUrl = item[urlKey] || null;
    const existingFilename = item[subFieldName] || null;

    if (existingUrl && typeof existingUrl === "string" && existingUrl.startsWith("http")) {
        return {
            file: existingFilename || "existing",
            file_url: existingUrl,
        };
    }

    return {
        file: null,
        file_url: null,
    };
};

// Handle group repeater image selection
const onGroupRepeaterImageSelected = (groupFieldName, repeaterFieldName, index, subFieldName, file) => {
    const imageKey = `${groupFieldName}_${repeaterFieldName}_${index}_${subFieldName}`;
    contentImages[imageKey] = file;
    if (file) {
        const groupData = getGroupData(groupFieldName);
        if (groupData[repeaterFieldName] && groupData[repeaterFieldName][index]) {
            groupData[repeaterFieldName][index][subFieldName] = file;
        }
    }
};

// Handle group repeater image removal
const onGroupRepeaterImageRemoved = (groupFieldName, repeaterFieldName, index, subFieldName) => {
    const imageKey = `${groupFieldName}_${repeaterFieldName}_${index}_${subFieldName}`;
    delete contentImages[imageKey];
    const groupData = getGroupData(groupFieldName);
    if (groupData[repeaterFieldName] && groupData[repeaterFieldName][index]) {
        groupData[repeaterFieldName][index][subFieldName] = null;
        groupData[repeaterFieldName][index][subFieldName + "_url"] = null;
    }
};

// ============================================
// END GROUP WITH REPEATER FUNCTIONS
// ============================================

// Get image form data for ImageUpload component
const getImageFormData = (fieldName) => {
    const newFile = contentImages[fieldName] || null;
    const existingUrl = contentData[fieldName + "_url"] || null;
    const existingFilename = contentData[fieldName] || null;

    // If there's a new file selected, use it
    if (newFile) {
        return {
            file: newFile,
            file_url: null,
        };
    }

    // If there's an existing image (URL exists), return the filename
    if (
        existingUrl &&
        typeof existingUrl === "string" &&
        existingUrl.startsWith("http")
    ) {
        return {
            file: existingFilename || "existing",
            file_url: existingUrl,
        };
    }

    // No image
    return {
        file: null,
        file_url: null,
    };
};

// Handle content image selection
const onContentImageSelected = (fieldName, file) => {
    contentImages[fieldName] = file;
    if (file) {
        contentData[fieldName] = file;
    }
};

// Handle content image removal
const onContentImageRemoved = (fieldName) => {
    // Clear from contentImages
    delete contentImages[fieldName];
    // Clear from contentData - set to null to indicate removal
    contentData[fieldName] = null;
    contentData[fieldName + "_url"] = null;
};

// Get image form data for repeater ImageUpload component
const getRepeaterImageFormData = (fieldName, index, subFieldName, item) => {
    const imageKey = `${fieldName}_${index}_${subFieldName}`;
    const urlKey = subFieldName + "_url";

    const newFile = contentImages[imageKey] || null;
    const existingUrl = item?.[urlKey] || null;
    const existingFilename = item?.[subFieldName] || null;

    let fileValue = newFile;
    if (
        !newFile &&
        existingUrl &&
        typeof existingUrl === "string" &&
        existingUrl.startsWith("http")
    ) {
        fileValue = existingFilename || "existing";
    }

    return {
        file: fileValue,
        file_url: existingUrl,
    };
};

// Handle repeater image selection
const onRepeaterImageSelected = (fieldName, index, subFieldName, file) => {
    const imageKey = `${fieldName}_${index}_${subFieldName}`;
    contentImages[imageKey] = file;
    if (contentData[fieldName] && contentData[fieldName][index]) {
        contentData[fieldName][index][subFieldName] = file;
    }
};

// Handle repeater image removal
const onRepeaterImageRemoved = (fieldName, index, subFieldName) => {
    const imageKey = `${fieldName}_${index}_${subFieldName}`;
    // Clear from contentImages
    delete contentImages[imageKey];
    // Clear from contentData - set to null to indicate removal
    if (contentData[fieldName] && contentData[fieldName][index]) {
        contentData[fieldName][index][subFieldName] = null;
        contentData[fieldName][index][subFieldName + "_url"] = null;
    }
};

// Get image form data for nested repeater ImageUpload component
const getNestedRepeaterImageFormData = (parentFieldName, parentIndex, nestedFieldName, nestedIndex, imageFieldName, nestedItem) => {
    const imageKey = `${parentFieldName}_${parentIndex}_${nestedFieldName}_${nestedIndex}_${imageFieldName}`;
    const urlKey = imageFieldName + "_url";

    const newFile = contentImages[imageKey] || null;
    const existingUrl = nestedItem?.[urlKey] || null;
    const existingFilename = nestedItem?.[imageFieldName] || null;

    let fileValue = newFile;
    if (
        !newFile &&
        existingUrl &&
        typeof existingUrl === "string" &&
        existingUrl.startsWith("http")
    ) {
        fileValue = existingFilename || "existing";
    }

    return {
        file: fileValue,
        file_url: existingUrl,
    };
};

// Handle nested repeater image selection
const onNestedRepeaterImageSelected = (parentFieldName, parentIndex, nestedFieldName, nestedIndex, imageFieldName, file) => {
    const imageKey = `${parentFieldName}_${parentIndex}_${nestedFieldName}_${nestedIndex}_${imageFieldName}`;
    contentImages[imageKey] = file;

    // Update the nested item with the file
    if (contentData[parentFieldName] &&
        contentData[parentFieldName][parentIndex] &&
        contentData[parentFieldName][parentIndex][nestedFieldName] &&
        contentData[parentFieldName][parentIndex][nestedFieldName][nestedIndex]) {
        contentData[parentFieldName][parentIndex][nestedFieldName][nestedIndex][imageFieldName] = file;
    }
};

// Handle nested repeater image removal
const onNestedRepeaterImageRemoved = (parentFieldName, parentIndex, nestedFieldName, nestedIndex, imageFieldName) => {
    const imageKey = `${parentFieldName}_${parentIndex}_${nestedFieldName}_${nestedIndex}_${imageFieldName}`;
    // Clear from contentImages
    delete contentImages[imageKey];
    // Clear from contentData - set to null to indicate removal
    if (contentData[parentFieldName] &&
        contentData[parentFieldName][parentIndex] &&
        contentData[parentFieldName][parentIndex][nestedFieldName] &&
        contentData[parentFieldName][parentIndex][nestedFieldName][nestedIndex]) {
        contentData[parentFieldName][parentIndex][nestedFieldName][nestedIndex][imageFieldName] = null;
        contentData[parentFieldName][parentIndex][nestedFieldName][nestedIndex][imageFieldName + "_url"] = null;
    }
};

// Get translated label for a field
// Uses translation key pattern: website_builder.{section_key}_{field_name}
const getFieldLabel = (fieldName, parentFieldName = null) => {
    const sectionKey = props.data?.section_key;
    if (!sectionKey) return fieldName;

    let translationKey;
    if (parentFieldName) {
        // Nested field in repeater: website_builder.{section_key}_{parent}_{field}
        translationKey = `website_builder.${sectionKey}_${parentFieldName}_${fieldName}`;
    } else {
        // Regular field: website_builder.{section_key}_{field}
        translationKey = `website_builder.${sectionKey}_${fieldName}`;
    }

    // Check if translation exists, otherwise return the original label
    if (te(translationKey)) {
        return t(translationKey);
    }

    // Fallback to field name formatted nicely
    return fieldName;
};

// Calculate flex value for repeater field columns
const getFieldFlex = (subField) => {
    if (subField.type === "textarea") return "auto";
    if (subField.type === "switch") return "60px";
    if (subField.type === "number") return "80px";
    if (subField.type === "select") return "120px";
    if (subField.type === "image") return "140px";
    if (subField.type === "icon") return "200px";
    if (subField.type === "nested_repeater") return "100%";
    return "auto";
};

// Sync contentData to contentJson
const syncContentDataToJson = () => {
    try {
        const cleanData = JSON.parse(
            JSON.stringify(contentData, (_key, value) => {
                if (value instanceof File) return undefined;
                return value;
            })
        );
        contentJson.value = JSON.stringify(cleanData, null, 2);
    } catch (e) {
        console.error("Error syncing content data to JSON:", e);
    }
};

const onSubmit = (langIdParam = null, websiteIdParam = null) => {
    // Use props if no valid parameters passed (e.g., when called from internal button with event)
    // Check if langIdParam is an event object (has target property or is not a string)
    const langId = (langIdParam && typeof langIdParam === 'string') ? langIdParam : props.langId;
    const websiteId = (websiteIdParam && typeof websiteIdParam === 'string') ? websiteIdParam : props.websiteId;

    // Clear previous validation errors
    Object.keys(rules).forEach((key) => delete rules[key]);

    // Validate section_layout (required)
    if (!formData.value.section_layout?.trim()) {
        rules.section_layout = {
            message: window.i18n.global.t("common.required_message", [
                window.i18n.global.t("website_builder.section_layout"),
            ]),
        };
        message.error(window.i18n.global.t("common.required_message", [
            window.i18n.global.t("website_builder.section_layout"),
        ]));
        return;
    }

    syncContentDataToJson();

    let parsedContent = {};
    try {
        if (
            contentJson.value &&
            contentJson.value.trim() !== "" &&
            contentJson.value.trim() !== "{}"
        ) {
            parsedContent = JSON.parse(contentJson.value);
        }
    } catch (e) {
        message.error("Invalid JSON in content field");
        return;
    }

    const cleanedContent = JSON.parse(JSON.stringify(parsedContent));

    // Remove File objects from cleanedContent
    // Use regex to properly detect repeater patterns (fieldName_number_subFieldName)
    Object.keys(contentImages).forEach((key) => {
        if (contentImages[key] instanceof File) {
            // Check for nested repeater image (format: parentFieldName_parentIndex_nestedFieldName_nestedIndex_imageFieldName)
            // This pattern has numbers at positions 1 and 3 when split
            const nestedRepeaterMatch = key.match(/^(.+?)_(\d+)_(.+?)_(\d+)_(.+)$/);
            if (nestedRepeaterMatch) {
                const [, parentFieldName, parentIndexStr, nestedFieldName, nestedIndexStr, imageFieldName] = nestedRepeaterMatch;
                const parentIndex = parseInt(parentIndexStr);
                const nestedIndex = parseInt(nestedIndexStr);

                // Remove the file from the nested repeater item
                if (
                    cleanedContent[parentFieldName] &&
                    Array.isArray(cleanedContent[parentFieldName]) &&
                    cleanedContent[parentFieldName][parentIndex] &&
                    cleanedContent[parentFieldName][parentIndex][nestedFieldName] &&
                    Array.isArray(cleanedContent[parentFieldName][parentIndex][nestedFieldName]) &&
                    cleanedContent[parentFieldName][parentIndex][nestedFieldName][nestedIndex]
                ) {
                    delete cleanedContent[parentFieldName][parentIndex][nestedFieldName][nestedIndex][imageFieldName];
                }
                return;
            }

            // Check for regular repeater image (format: fieldName_index_subFieldName)
            // The index must be a number
            const repeaterMatch = key.match(/^(.+?)_(\d+)_(.+)$/);
            if (repeaterMatch) {
                const [, fieldName, indexStr, subFieldName] = repeaterMatch;
                const index = parseInt(indexStr);

                // Remove the file from the repeater item
                if (
                    cleanedContent[fieldName] &&
                    Array.isArray(cleanedContent[fieldName]) &&
                    cleanedContent[fieldName][index]
                ) {
                    delete cleanedContent[fieldName][index][subFieldName];
                }
                return;
            }

            // Regular content image (may or may not have underscores, but not a repeater pattern)
            delete cleanedContent[key];
        }
    });

    const submitData = {
        _method: "PUT",
        title: formData.value.title,
        subtitle: formData.value.subtitle,
        section_layout: formData.value.section_layout,
        is_white_background: formData.value.is_white_background ? 1 : 0,
        padding_top: formData.value.padding_top,
        padding_bottom: formData.value.padding_bottom,
        section_key: props.data.section_key,
        content: JSON.stringify(cleanedContent),
    };

    // Add website_language_id if provided
    if (langId) {
        submitData.website_language_id = langId;
    }

    // Add website_id if provided
    if (websiteId) {
        submitData.website_id = websiteId;
    }

    // Add website_page_id if provided
    if (props.businessPageId) {
        submitData.website_page_id = props.businessPageId;
    }

    // Add content images
    Object.keys(contentImages).forEach((key) => {
        if (contentImages[key] instanceof File) {
            submitData[`content_image_${key}`] = contentImages[key];
        }
    });

    addEditFileRequestAdmin({
        url: `${addEditUrl}/${props.data.xid}`,
        data: submitData,
        successMessage: window.i18n.global.t("common.updated"),
        success: (response) => {
            // Clear successfully uploaded images from contentImages
            // This ensures fresh state for next upload
            Object.keys(contentImages).forEach((key) => {
                if (contentImages[key] instanceof File) {
                    delete contentImages[key];
                }
            });

            // Get the actual data from response (could be wrapped in 'data' property)
            const responseData = response?.data || response;

            // Update contentData with server response to sync URLs
            if (responseData && responseData.content_with_urls) {
                Object.keys(responseData.content_with_urls).forEach((key) => {
                    contentData[key] = responseData.content_with_urls[key];
                });
            } else if (responseData && responseData.content) {
                // Fallback to regular content if content_with_urls not available
                const content = typeof responseData.content === 'string'
                    ? JSON.parse(responseData.content)
                    : responseData.content;
                Object.keys(content).forEach((key) => {
                    contentData[key] = content[key];
                });
            }

            emit("addEditSuccess");
        },
    });
};

// Initialize content data from schema
const initializeContentData = (content, schema) => {
    Object.keys(contentData).forEach((key) => delete contentData[key]);
    Object.keys(contentImages).forEach((key) => delete contentImages[key]);

    if (content && typeof content === "object") {
        Object.keys(content).forEach((key) => {
            contentData[key] = content[key];
        });
    }

    if (schema && Array.isArray(schema)) {
        schema.forEach((field) => {
            if (!(field.name in contentData)) {
                // Set defaults for missing fields
                if (field.type === "repeater") {
                    contentData[field.name] = [];
                } else if (field.type === "group_with_repeater") {
                    // Initialize group_with_repeater as an object with default values
                    const groupData = {};
                    if (field.fields && Array.isArray(field.fields)) {
                        field.fields.forEach((subField) => {
                            if (subField.type === "repeater") {
                                groupData[subField.name] = [];
                            } else if (subField.type === "switch") {
                                groupData[subField.name] = false;
                            } else if (subField.type === "number") {
                                groupData[subField.name] = 0;
                            } else {
                                groupData[subField.name] = "";
                            }
                        });
                    }
                    contentData[field.name] = groupData;
                } else if (field.type === "switch") {
                    contentData[field.name] = false;
                } else if (field.type === "number") {
                    contentData[field.name] = 0;
                } else {
                    contentData[field.name] = "";
                }
            } else if (field.type === "number" && typeof contentData[field.name] === "string") {
                // Convert string numbers to actual numbers for number fields
                const numValue = parseFloat(contentData[field.name]);
                contentData[field.name] = isNaN(numValue) ? 0 : numValue;
            } else if (field.type === "group_with_repeater" && contentData[field.name]) {
                // Ensure group_with_repeater has all required fields initialized
                if (typeof contentData[field.name] !== 'object' || Array.isArray(contentData[field.name])) {
                    contentData[field.name] = {};
                }
                if (field.fields && Array.isArray(field.fields)) {
                    field.fields.forEach((subField) => {
                        if (!(subField.name in contentData[field.name])) {
                            if (subField.type === "repeater") {
                                contentData[field.name][subField.name] = [];
                            } else if (subField.type === "switch") {
                                contentData[field.name][subField.name] = false;
                            } else if (subField.type === "number") {
                                contentData[field.name][subField.name] = 0;
                            } else {
                                contentData[field.name][subField.name] = "";
                            }
                        }
                    });
                }
            }
        });
    }
};

// Initialize form
const initializeForm = async () => {
    if (!props.data) return;

    formData.value = {
        title: props.data.title || "",
        subtitle: props.data.subtitle || "",
        section_layout: props.data.section_layout || props.data.section_key || "",
        is_white_background: props.data.is_white_background || false,
        padding_top: props.data.padding_top ?? null,
        padding_bottom: props.data.padding_bottom ?? null,
    };

    contentSchema.value = props.data.content_schema || [];

    const contentForDisplay = props.data.content_with_urls || props.data.content;

    initializeContentData(contentForDisplay, contentSchema.value);

    if (props.data.content && typeof props.data.content === "object") {
        contentJson.value = JSON.stringify(props.data.content, null, 2);
    } else {
        contentJson.value = "{}";
    }

    activeTab.value = "basic";

    // Fetch section layouts from API
    await fetchSectionLayouts(props.data.section_key);
};

// Track current section xid to prevent unnecessary re-initialization
const currentSectionXid = ref(null);

// Watch for data changes - only reinitialize when section changes
watch(
    () => props.data?.xid,
    (newXid) => {
        if (newXid && newXid !== currentSectionXid.value) {
            currentSectionXid.value = newXid;
            initializeForm();
        }
    },
    { immediate: true }
);

// Expose onSubmit method to parent component
defineExpose({
    onSubmit,
});
</script>

<style scoped>
.repeater-field {
    margin-bottom: 24px;
}

.repeater-header {
    margin-bottom: 8px;
    padding: 0 4px;
}

.repeater-header-label {
    font-size: 12px;
    font-weight: 500;
    color: rgba(0, 0, 0, 0.45);
}

.repeater-row {
    margin-bottom: 16px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;
}

.repeater-row:last-child {
    margin-bottom: 0;
    padding-bottom: 0;
    border-bottom: none;
}

.mt-2 {
    margin-top: 12px;
}

.mt-1 {
    margin-top: 8px;
}

.nested-repeater {
    background: #fafafa;
    border: 1px solid #f0f0f0;
    border-radius: 6px;
    padding: 12px;
    width: 100%;
    margin-top: 12px;
}

.nested-repeater-label {
    font-size: 12px;
    font-weight: 500;
    color: rgba(0, 0, 0, 0.65);
    margin-bottom: 8px;
}

.nested-repeater-header {
    margin-bottom: 6px;
    padding: 0 4px;
}

.nested-header-label {
    font-size: 11px;
    font-weight: 500;
    color: rgba(0, 0, 0, 0.45);
}

.nested-repeater-row {
    margin-bottom: 8px;
    padding-bottom: 8px;
    border-bottom: 1px dashed #e8e8e8;
}

.nested-repeater-row:last-child {
    margin-bottom: 0;
    padding-bottom: 0;
    border-bottom: none;
}

/* Group with Repeater Styles */
.group-with-repeater-field {
    margin-bottom: 16px;
}

.group-heading-fields {
    margin-bottom: 16px;
}

.group-nested-repeater {
    background: #fafafa;
    border: 1px solid #f0f0f0;
    border-radius: 6px;
    padding: 12px;
    margin-top: 12px;
}

.group-nested-repeater-label {
    font-size: 13px;
    font-weight: 500;
    color: rgba(0, 0, 0, 0.65);
    margin-bottom: 8px;
}

:global(.dark_theme) .group-nested-repeater,
:global(html[data-dark-mode="true"]) .group-nested-repeater,
:global(body.ant-dark) .group-nested-repeater,
:global([data-theme="dark"]) .group-nested-repeater {
    background: #1f1f1f;
    border-color: #303030;
}

:global(.dark_theme) .group-nested-repeater-label,
:global(html[data-dark-mode="true"]) .group-nested-repeater-label,
:global(body.ant-dark) .group-nested-repeater-label,
:global([data-theme="dark"]) .group-nested-repeater-label {
    color: rgba(255, 255, 255, 0.65);
}

/* Section Layout Preview Card Styles */
.section-layout-preview-card {
    background: var(--layout-card-bg, #fff);
    border: 2px solid var(--layout-card-border, #e8e8e8);
    border-radius: 8px;
    overflow: hidden;
    cursor: pointer;
    transition: all 0.2s ease;
    max-width: 320px;
}

.section-layout-preview-card:hover {
    border-color: var(--layout-card-hover-border, #1890ff);
    box-shadow: 0 4px 12px rgba(24, 144, 255, 0.15);
}

.layout-preview-iframe {
    height: 140px;
    background: var(--layout-preview-bg, #f5f5f5);
    overflow: hidden;
    position: relative;
    pointer-events: none; /* Allow clicks to pass through to parent card */
}

.layout-preview-iframe :deep(.iframe-live-preview) {
    width: 100%;
    height: 100%;
    pointer-events: none;
}

.layout-preview-iframe :deep(.preview-container) {
    border-radius: 0;
    pointer-events: none;
}

.layout-preview-iframe :deep(iframe) {
    pointer-events: none;
}

.layout-preview-placeholder {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 8px;
    background: linear-gradient(135deg, #e6f4ff 0%, #bae0ff 100%);
    color: #1890ff;
}

.layout-preview-placeholder .placeholder-icon {
    font-size: 36px;
    opacity: 0.6;
}

.layout-preview-placeholder span {
    font-size: 12px;
    opacity: 0.8;
}

.layout-preview-info {
    padding: 10px 12px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 8px;
    border-top: 1px solid var(--layout-info-border, #f0f0f0);
}

.layout-preview-name {
    font-size: 13px;
    font-weight: 500;
    color: var(--layout-name-color, #262626);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.change-layout-btn {
    flex-shrink: 0;
    font-size: 12px;
    padding: 0;
}

/* Dark mode styles for Section Layout Preview Card */
:global(.dark_theme) .section-layout-preview-card {
    --layout-card-bg: #1f1f1f;
    --layout-card-border: #424242;
    --layout-card-hover-border: #177ddc;
}

:global(.dark_theme) .layout-preview-iframe {
    --layout-preview-bg: #141414;
}

:global(.dark_theme) .layout-preview-placeholder {
    background: linear-gradient(135deg, #111d2c 0%, #15395b 100%);
}

:global(.dark_theme) .layout-preview-info {
    --layout-info-border: #303030;
    --layout-name-color: rgba(255, 255, 255, 0.85);
}

:global(html[data-dark-mode="true"]) .section-layout-preview-card,
:global(body.ant-dark) .section-layout-preview-card,
:global([data-theme="dark"]) .section-layout-preview-card {
    --layout-card-bg: #1f1f1f;
    --layout-card-border: #424242;
    --layout-card-hover-border: #177ddc;
}

:global(html[data-dark-mode="true"]) .layout-preview-iframe,
:global(body.ant-dark) .layout-preview-iframe,
:global([data-theme="dark"]) .layout-preview-iframe {
    --layout-preview-bg: #141414;
}

:global(html[data-dark-mode="true"]) .layout-preview-info,
:global(body.ant-dark) .layout-preview-info,
:global([data-theme="dark"]) .layout-preview-info {
    --layout-info-border: #303030;
    --layout-name-color: rgba(255, 255, 255, 0.85);
}

/* Front Form Select Wrapper Styles */
.front-form-select-wrapper {
    display: flex;
    align-items: flex-start;
    gap: 0;
}

.front-form-select-wrapper .front-form-select {
    flex: 1;
}

.front-form-select-wrapper :deep(.ant-btn) {
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
}

.front-form-select-wrapper :deep(.ant-select .ant-select-selector) {
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
}

/* Padding Input Wrapper Styles */
.padding-input-wrapper {
    display: flex;
    align-items: center;
    gap: 12px;
}

.padding-switch {
    flex-shrink: 0;
}

.padding-input {
    width: 120px;
}

.padding-default-text {
    color: var(--text-color-secondary, #8c8c8c);
    font-size: 13px;
}

:global(.dark_theme) .padding-default-text {
    color: rgba(255, 255, 255, 0.45);
}
</style>
