@extends('landingpage::layouts.admin') {{-- Now extends the module's admin layout --}}

@section('title', 'Edit Page - ' . $page->title)

@push('module_styles') {{-- Push to module_styles stack --}}
{{-- Select2 CSS --}}
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
{{-- Add any page-specific Tailwind-compatible styles here if absolutely necessary,
    or preferably, define them as components in your main CSS/SASS file processed by Tailwind. --}}
@endpush

@section('module_content') {{-- Content goes into module_content section --}}
<div class="px-4 sm:px-6 lg:px-8 py-8 w-full max-w-9xl mx-auto">
    <div class="sm:flex sm:justify-between sm:items-center mb-8">
        <h1 class="text-2xl md:text-3xl text-slate-800 dark:text-slate-100 font-bold">Edit Page: {{ $page->title }}</h1>
    </div>

    <nav class="mb-6 text-sm" aria-label="Breadcrumb">
        <ol class="list-none p-0 inline-flex">
            <li class="flex items-center">
                <a href="{{ route('admin.dashboard') }}" class="text-blue-500 hover:text-blue-700 hover:underline dark:text-blue-400 dark:hover:text-blue-300">Dashboard</a>
                <svg class="fill-current w-3 h-3 mx-3 text-slate-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><path d="M285.476 272.971L91.132 467.314c-9.373 9.373-24.569 9.373-33.941 0l-22.667-22.667c-9.357-9.357-9.375-24.522-.04-33.901L188.505 256 34.484 101.255c-9.335-9.379-9.317-24.544.04-33.901l22.667-22.667c9.373 9.373 24.569 9.373 33.941 0L285.475 239.03c9.373 9.372 9.373 24.568.001 33.941z"/></svg>
            </li>
            <li class="flex items-center">
                <a href="{{ route('admin.landingpage.pages.index') }}" class="text-blue-500 hover:text-blue-700 hover:underline dark:text-blue-400 dark:hover:text-blue-300">Manage Pages</a>
                <svg class="fill-current w-3 h-3 mx-3 text-slate-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><path d="M285.476 272.971L91.132 467.314c-9.373 9.373-24.569 9.373-33.941 0l-22.667-22.667c-9.357-9.357-9.375-24.522-.04-33.901L188.505 256 34.484 101.255c-9.335-9.379-9.317-24.544.04-33.901l22.667-22.667c9.373 9.373 24.569 9.373 33.941 0L285.475 239.03c9.373 9.372 9.373 24.568.001 33.941z"/></svg>
            </li>
            <li class="flex items-center">
                <span class="text-slate-500 dark:text-slate-400">Edit Page</span>
            </li>
        </ol>
    </nav> {{-- Corrected closing tag for nav --}}

    @if(session('success'))
        <div class="mb-6 p-4 bg-green-50 border-l-4 border-green-400 text-green-700 dark:bg-green-900 dark:text-green-300 dark:border-green-600 rounded-md relative" role="alert">
            <strong class="font-bold">Success!</strong>
            {{ session('success') }}
            <button type="button" class="absolute top-0 bottom-0 right-0 px-4 py-3 text-green-700 dark:text-green-300 hover:text-green-900 dark:hover:text-green-100" data-dismiss="alert" aria-label="Close" onclick="this.parentElement.style.display='none';">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    @endif

    <form action="{{ route('admin.landingpage.pages.update', $page->id) }}" method="POST" enctype="multipart/form-data">
        @csrf
        @method('PUT')

        <div class="bg-white dark:bg-slate-800 shadow-lg rounded-lg mb-6">
            <div class="px-6 py-4 border-b border-slate-200 dark:border-slate-700">
                <h3 class="text-lg font-medium text-slate-800 dark:text-slate-100">Page Details</h3>
            </div>
            <div class="p-6">
                <div class="mb-4"> {{-- Changed mb-3 to mb-4 for consistency --}}
                    <label for="title" class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Title <span class="text-red-500">*</span></label>
                    <input type="text" class="mt-1 block w-full rounded-md border-slate-300 dark:border-slate-600 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm dark:bg-slate-700 dark:text-slate-200 @error('title') border-red-500 @enderror" id="title" name="title" value="{{ old('title', $page->title) }}" required>
                    @error('title') <p class="mt-2 text-sm text-red-600 dark:text-red-400">{{ $message }}</p> @enderror
                </div>

                <div class="mb-4">
                    <label for="slug" class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Slug <span class="text-red-500">*</span></label>
                    <input type="text" class="mt-1 block w-full rounded-md border-slate-300 dark:border-slate-600 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm dark:bg-slate-700 dark:text-slate-200 @error('slug') border-red-500 @enderror" id="slug" name="slug" value="{{ old('slug', $page->slug) }}" required>
                    @error('slug') <p class="mt-2 text-sm text-red-600 dark:text-red-400">{{ $message }}</p> @enderror
                </div>

                <div class="mb-4">
                    <label for="main_content_editor" class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Main Content (Fallback/Default)</label>
                    <textarea class="mt-1 block w-full rounded-md border-slate-300 dark:border-slate-600 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm dark:bg-slate-700 dark:text-slate-200 @error('content') border-red-500 @enderror" id="main_content_editor" name="content" rows="10">{{ old('content', $page->content) }}</textarea>
                    @error('content') <p class="mt-2 text-sm text-red-600 dark:text-red-400">{{ $message }}</p> @enderror
                </div>

                {{-- Optional Hero Fields (if directly on LpPage model) --}}
                <h4 class="mt-6 text-md font-semibold text-slate-700 dark:text-slate-200 mb-2">Default Hero Section (if no 'hero' section is added below)</h4>
                 <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div class="mb-4">
                        <label for="hero_title" class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Hero Title</label>
                        <input type="text" class="mt-1 block w-full rounded-md border-slate-300 dark:border-slate-600 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm dark:bg-slate-700 dark:text-slate-200" id="hero_title" name="hero_title" value="{{ old('hero_title', $page->hero_title) }}">
                    </div>
                    <div class="mb-4">
                        <label for="hero_subtitle" class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Hero Subtitle</label>
                        <input type="text" class="mt-1 block w-full rounded-md border-slate-300 dark:border-slate-600 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm dark:bg-slate-700 dark:text-slate-200" id="hero_subtitle" name="hero_subtitle" value="{{ old('hero_subtitle', $page->hero_subtitle) }}">
                    </div>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div class="mb-4">
                        <label for="hero_cta_text" class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Hero CTA Text</label>
                        <input type="text" class="mt-1 block w-full rounded-md border-slate-300 dark:border-slate-600 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm dark:bg-slate-700 dark:text-slate-200" id="hero_cta_text" name="hero_cta_text" value="{{ old('hero_cta_text', $page->hero_cta_text) }}">
                    </div>
                    <div class="mb-4">
                        <label for="hero_cta_link" class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Hero CTA Link</label>
                        <input type="text" class="mt-1 block w-full rounded-md border-slate-300 dark:border-slate-600 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm dark:bg-slate-700 dark:text-slate-200" id="hero_cta_link" name="hero_cta_link" value="{{ old('hero_cta_link', $page->hero_cta_link) }}">
                    </div>
                </div>
            </div>
        </div>

        <div class="bg-white dark:bg-slate-800 shadow-lg rounded-lg mb-6">
            <div class="px-6 py-4 border-b border-slate-200 dark:border-slate-700">
                <h3 class="text-lg font-medium text-slate-800 dark:text-slate-100">SEO Settings</h3>
            </div>
            <div class="p-6">
                {{-- Meta Title, Description, Keywords fields --}}
                <div class="mb-4">
                    <label for="meta_title" class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Meta Title</label>
                    <input type="text" class="mt-1 block w-full rounded-md border-slate-300 dark:border-slate-600 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm dark:bg-slate-700 dark:text-slate-200" id="meta_title" name="meta_title" value="{{ old('meta_title', $page->meta_title) }}">
                </div>
                <div class="mb-4">
                    <label for="meta_description" class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Meta Description</label>
                    <textarea class="mt-1 block w-full rounded-md border-slate-300 dark:border-slate-600 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm dark:bg-slate-700 dark:text-slate-200" id="meta_description" name="meta_description" rows="3">{{ old('meta_description', $page->meta_description) }}</textarea>
                </div>
                <div class="mb-4">
                    <label for="meta_keywords" class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Meta Keywords (comma-separated)</label>
                    <input type="text" class="mt-1 block w-full rounded-md border-slate-300 dark:border-slate-600 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm dark:bg-slate-700 dark:text-slate-200" id="meta_keywords" name="meta_keywords" value="{{ old('meta_keywords', $page->meta_keywords) }}">
                </div>
            </div>
        </div>

        <div class="bg-white dark:bg-slate-800 shadow-lg rounded-lg mb-6">
            <div class="px-6 py-4 border-b border-slate-200 dark:border-slate-700">
                <h3 class="text-lg font-medium text-slate-800 dark:text-slate-100">Page Settings</h3>
            </div>
            <div class="p-6">
                <div class="mb-4">
                    <label for="theme_template" class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Theme Template</label>
                    <select id="theme_template" name="theme_template" class="mt-1 block w-full rounded-md border-slate-300 dark:border-slate-600 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm dark:bg-slate-700 dark:text-slate-200">
                        @foreach($themeTemplates as $value => $label)
                            <option value="{{ $value }}" {{ old('theme_template', $page->theme_template) == $value ? 'selected' : '' }}>{{ $label }}</option>
                        @endforeach
                    </select>
                    <p class="mt-1 text-xs text-slate-500 dark:text-slate-400">Select a page template from your active theme. Leave as 'Default' for standard rendering.</p>
                </div>
                <div class="mb-4">
                    <label for="sort_order" class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Sort Order</label>
                    <input type="number" class="mt-1 block w-full rounded-md border-slate-300 dark:border-slate-600 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm dark:bg-slate-700 dark:text-slate-200" id="sort_order" name="sort_order" value="{{ old('sort_order', $page->sort_order ?? 0) }}">
                </div>
                <div class="flex items-center mb-4">
                    <input id="is_published" name="is_published" type="checkbox" value="1" class="h-4 w-4 text-blue-600 border-slate-300 dark:border-slate-600 rounded focus:ring-blue-500 dark:bg-slate-700 dark:focus:ring-blue-600 dark:ring-offset-slate-800" {{ old('is_published', $page->is_published) ? 'checked' : '' }}>
                    <label for="is_published" class="ml-2 block text-sm text-slate-900 dark:text-slate-300">Published</label>
                </div>
            </div>
        </div>

        {{-- Sections Management --}}
        <div class="bg-white dark:bg-slate-800 shadow-lg rounded-lg mb-6">
            <div class="px-6 py-4 border-b border-slate-200 dark:border-slate-700 flex justify-between items-center">
                <h3 class="text-lg font-medium text-slate-800 dark:text-slate-100">Page Sections</h3>
                <button type="button" class="inline-flex items-center px-3 py-2 bg-green-500 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-green-600 active:bg-green-700 focus:outline-none focus:border-green-700 focus:ring ring-green-300 disabled:opacity-25 transition ease-in-out duration-150" id="add-section-btn">
                    <i class="fas fa-plus mr-1"></i> Add Section
                </button>
            </div>
            <div class="p-6" id="sections-container">
                @foreach($page->sections->sortBy('sort_order') as $index => $section)
                    @include('landingpage::admin.pages.partials.section-item', ['index' => $section->id, 'section' => $section, 'sectionTypes' => $sectionTypes, 'availableLayouts' => $availableLayouts])
                @endforeach
            </div>
        </div>

        <div class="flex justify-end space-x-3">
            <a href="{{ route('admin.landingpage.pages.index') }}" class="px-4 py-2 border border-slate-300 dark:border-slate-600 rounded-md text-sm font-medium text-slate-700 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 dark:focus:ring-offset-slate-900">Cancel</a>
            <button type="submit" class="inline-flex items-center px-6 py-3 bg-blue-600 border border-transparent rounded-md font-semibold text-sm text-white uppercase tracking-widest hover:bg-blue-700 active:bg-blue-800 focus:outline-none focus:border-blue-900 focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 transition ease-in-out duration-150">Update Page</button>
        </div>
    </form>
</div>

{{-- Section Template (for JavaScript cloning) --}}
<template id="section-template">
    @include('landingpage::admin.pages.partials.section-item', ['index' => 'new_X', 'section' => null, 'sectionTypes' => $sectionTypes, 'availableLayouts' => $availableLayouts])
</template>

@endsection

@push('module_scripts') {{-- Push to module_scripts stack --}}
{{-- Include TinyMCE from CDN --}}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> {{-- Select2 requires jQuery --}}
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script src="https://cdn.tiny.cloud/1/{{ setting('tinymce_api_key', 'YOUR_FALLBACK_TINYMCE_API_KEY_OR_LEAVE_EMPTY') }}/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>
{{-- The TinyMCE API Key should be configured in your admin settings. --}}
<script>
// Make PHP variables available to JS
const availableProjects = @json($availableProjects ?? []);
const sectionTypesJS = @json($sectionTypes ?? []);
const availableLayoutsJS = @json($availableLayouts ?? []);

document.addEventListener('DOMContentLoaded', function () {
    // Define common JS constants at the top of the DOMContentLoaded scope
    const commonInputClassesJS = "mt-1 block w-full rounded-md border-slate-300 dark:border-slate-600 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm dark:bg-slate-700 dark:text-slate-200";
    const commonLabelClassesJS = "block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1";
    const formGroupWrapperJS = (content) => `<div class="mb-4">${content}</div>`;
    const repeaterItemHeaderClassesJS = "text-md font-medium text-slate-700 dark:text-slate-200";

    const sectionsContainer = document.getElementById('sections-container');
    const addSectionBtn = document.getElementById('add-section-btn');
    const sectionTemplate = document.getElementById('section-template');
    let sectionCounter = {{ $page->sections->count() }}; // Start counter after existing sections

    // Initialize TinyMCE for the main content editor
    if (document.getElementById('main_content_editor')) {
        tinymce.init({
            selector: '#main_content_editor',
            plugins: 'advlist autolink lists link image charmap print preview anchor searchreplace visualblocks code fullscreen insertdatetime media table paste code help wordcount',
            toolbar: 'undo redo | formatselect | bold italic backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat | help | code',
            height: 400,
            setup: function (editor) {
                editor.on('change', function () {
                    editor.save();
                });
            }
        });
    }
    if (addSectionBtn) {
        addSectionBtn.addEventListener('click', function () {
            sectionCounter++;
            const newIndex = 'new_' + sectionCounter;
            let newSectionHtml = sectionTemplate.innerHTML.replace(/new_X/g, newIndex);
            
            const newSectionDiv = document.createElement('div');
            newSectionDiv.innerHTML = newSectionHtml;
            
            const newSectionElement = newSectionDiv.firstElementChild;
            // Ensure the new section element has the correct data-index attribute
            if (newSectionElement) {
                newSectionElement.dataset.index = newIndex;
            }
            sectionsContainer.appendChild(newSectionElement);
            initializeSectionEventListeners(newSectionElement);

            const typeSelect = newSectionElement.querySelector('.section-type-select');
            if (typeSelect && typeSelect.value) {
                renderContentFields(typeSelect.value, newSectionElement.querySelector('.content-fields-container'), `sections[${newIndex}][content]`, {});
                typeSelect.dataset.currentType = typeSelect.value;
            } else if (typeSelect) { // If no value is pre-selected, clear content fields
                 renderContentFields('', newSectionElement.querySelector('.content-fields-container'), `sections[${newIndex}][content]`, {});
                 typeSelect.dataset.currentType = '';
            }
        });
    }

    function initializeSectionEventListeners(sectionElement) {
        const removeBtn = sectionElement.querySelector('.remove-section-btn');
        if (removeBtn) {
            removeBtn.addEventListener('click', function () {
                destroySectionInstances(sectionElement);
                sectionElement.remove();
            });
        }

        const typeSelect = sectionElement.querySelector('.section-type-select');
        if (typeSelect) {
            typeSelect.addEventListener('change', function(event) {
                const contentContainer = sectionElement.querySelector('.content-fields-container');
                const previousType = typeSelect.dataset.currentType || ''; // Get previous type
                destroyDynamicEditorInstances(contentContainer, previousType); // Destroy based on old type
                renderContentFields(event.target.value, contentContainer, `sections[${sectionElement.dataset.index}][content]`, {});
                typeSelect.dataset.currentType = event.target.value; // Update current type
            });
            // Initial render for existing sections
            if (typeSelect.value) {
                 renderContentFields(typeSelect.value, sectionElement.querySelector('.content-fields-container'), `sections[${sectionElement.dataset.index}][content]`, JSON.parse(typeSelect.dataset.content || '{}'));
                 typeSelect.dataset.currentType = typeSelect.value;
            }
        }
    }

    document.querySelectorAll('.section-card').forEach(initializeSectionEventListeners);

    document.getElementById('sections-container').addEventListener('change', function(event) {
        if (event.target.matches('.dynamic-image-file-input')) {
            const itemIndex = event.target.dataset.itemIndex;
            const sectionCard = event.target.closest('.section-card');
            const sectionId = sectionCard ? sectionCard.dataset.index : null;
            if (!sectionId) {
                console.error('Could not determine section ID for image input.');
                return;
            }

            const listName = event.target.dataset.listName;
            const fieldName = event.target.dataset.fieldName || 'image';
            const previewContainerClass = event.target.dataset.previewClass;
            
            const previewContainer = document.querySelector(`.${previewContainerClass}-${itemIndex}`); // This selector needs to be unique per item
            const existingImageInputName = `sections[${sectionId}][content][${listName}][${itemIndex}][existing_${fieldName}_url]`;
            const removeImageCheckboxName = `sections[${sectionId}][content][${listName}][${itemIndex}][remove_${fieldName}]`;

            const existingImageHiddenInput = document.querySelector(`input[name="${existingImageInputName}"]`);

            if (event.target.files && event.target.files[0] && previewContainer) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    previewContainer.innerHTML = `<img src="${e.target.result}" alt="New Preview" class="max-h-32 rounded shadow">`;
                    const removeCheckbox = document.querySelector(`input[name="${removeImageCheckboxName}"]`);
                    if (removeCheckbox) removeCheckbox.checked = false; // Uncheck remove if new image is uploaded
                }
                reader.readAsDataURL(event.target.files[0]);
            } else if (previewContainer && existingImageHiddenInput && existingImageHiddenInput.value) {
                 previewContainer.innerHTML = `
                    <img src="/storage/${existingImageHiddenInput.value}" alt="Current Image" class="max-h-32 rounded shadow mb-2">
                    <input type="hidden" name="${existingImageInputName}" value="${existingImageHiddenInput.value}">
                    <label class="inline-flex items-center text-xs text-slate-600 dark:text-slate-400">
                        <input type="checkbox" name="${removeImageCheckboxName}" value="1" class="form-checkbox rounded text-blue-500 mr-1"> Remove current image
                    </label>`;
            } else if (previewContainer) {
                previewContainer.innerHTML = '<span class="text-xs text-slate-500 dark:text-slate-400">No image selected.</span>';
            }
        }
    });

    function destroySectionInstances(sectionElement) {
        const select2Elements = sectionElement.querySelectorAll('.select2-multiple');
        select2Elements.forEach(el => {
            if ($(el).data('select2')) {
                $(el).select2('destroy');
            }
        });

        const tinymceEditors = sectionElement.querySelectorAll('.custom-html-editor');
        tinymceEditors.forEach(editorEl => {
            if (tinymce.get(editorEl.id)) {
                tinymce.get(editorEl.id).remove();
            }
        });
    }

    function destroyDynamicEditorInstances(container, previousType) {
        if (previousType === 'featured-projects') {
            const select2Element = container.querySelector('.select2-multiple');
            if (select2Element && $(select2Element).data('select2')) {
                $(select2Element).select2('destroy');
            }
        } else if (previousType === 'custom-html') {
            const tinymceEditor = container.querySelector('.custom-html-editor');
            if (tinymceEditor && tinymce.get(tinymceEditor.id)) {
                tinymce.get(tinymceEditor.id).remove();
            }
        }
    }

    function renderContentFields(type, container, baseName, existingContent = {}) {
        container.innerHTML = ''; // Clear previous fields
        let fieldsHtml = '';
        let tempIdCounter = 0;

        switch (type) {
            case 'hero':
                fieldsHtml = `<h5 class="text-lg font-medium text-slate-700 dark:text-slate-200 mb-3">Hero Slides</h5><div class="hero-slides-repeater space-y-4">`;
                tempIdCounter = 0;
                const slides = Array.isArray(existingContent.slides) ? existingContent.slides : (existingContent.slides ? [existingContent.slides] : []); // Ensure array
                slides.forEach((slide, index) => {
                    fieldsHtml += getHeroSlideHtml(`${baseName}[slides]`, index, slide);
                    tempIdCounter = Math.max(tempIdCounter, index);
                });
                if (slides.length === 0) fieldsHtml += getHeroSlideHtml(`${baseName}[slides]`, 0);
                fieldsHtml += `</div><button type="button" class="mt-3 inline-flex items-center px-3 py-2 bg-slate-500 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-slate-600 active:bg-slate-700 focus:outline-none focus:border-slate-700 focus:ring ring-slate-300 disabled:opacity-25 transition ease-in-out duration-150 add-hero-slide-btn" data-basename="${baseName}[slides]" data-nextindex="${tempIdCounter + 1}">Add Hero Slide</button>`;
                break;
            case 'custom-html':
                const textareaId = `custom-html-editor-${baseName.replace(/\[|\]/g, '-')}-${Date.now()}`; // Ensure unique ID
                fieldsHtml = formGroupWrapperJS(`<label class="${commonLabelClassesJS}">HTML Content</label><textarea id="${textareaId}" name="${baseName}[html]" class="${commonInputClassesJS} custom-html-editor" rows="10">${existingContent.html || ''}</textarea>`);
                setTimeout(() => {
                    if (tinymce.get(textareaId)) tinymce.get(textareaId).remove(); // Remove existing instance if any
                    tinymce.init({
                        selector: `#${textareaId}`,
                        plugins: 'advlist autolink lists link image charmap print preview anchor searchreplace visualblocks code fullscreen insertdatetime media table paste code help wordcount',
                        toolbar: 'undo redo | formatselect | bold italic backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat | help | code',
                        height: 300,
                        setup: function (editor) { editor.on('change', function () { editor.save(); }); }
                    });
                }, 0);
                break;
            case 'featured-projects':
                let projectOptionsHtml = '';
                for (const slug in availableProjects) {
                    const isSelected = (existingContent.projects || []).includes(slug) ? 'selected' : '';
                    projectOptionsHtml += `<option value="${slug}" ${isSelected}>${availableProjects[slug]}</option>`;
                }
                fieldsHtml = `
                    ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">Select Projects</label><select name="${baseName}[projects][]" class="${commonInputClassesJS} select2-multiple" multiple="multiple" style="width: 100%;">${projectOptionsHtml}</select><p class="mt-1 text-xs text-slate-500 dark:text-slate-400">Hold Ctrl (or Cmd on Mac) to select multiple projects.</p>`)}
                    ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">Limit (number of projects)</label><input type="number" name="${baseName}[limit]" class="${commonInputClassesJS}" value="${existingContent.limit || 3}">`)}
                `;
                setTimeout(() => {
                    const selectElement = container.querySelector('.select2-multiple');
                    if (selectElement) {
                        if ($(selectElement).data('select2')) $(selectElement).select2('destroy'); // Destroy if exists
                        $(selectElement).select2({ placeholder: "Select projects", allowClear: true });
                    }
                }, 0);
                break;
            case 'services':
                fieldsHtml = `<h5 class="text-lg font-medium text-slate-700 dark:text-slate-200 mb-3">Services Items</h5><div class="services-repeater space-y-4">`;
                tempIdCounter = 0;
                const servicesList = Array.isArray(existingContent.services_list) ? existingContent.services_list : (existingContent.services_list ? [existingContent.services_list] : []);
                servicesList.forEach((service, index) => {
                    fieldsHtml += getServiceItemHtml(`${baseName}[services_list]`, index, service);
                    tempIdCounter = Math.max(tempIdCounter, index);
                });
                if (servicesList.length === 0) fieldsHtml += getServiceItemHtml(`${baseName}[services_list]`, 0);
                fieldsHtml += `</div><button type="button" class="mt-3 inline-flex items-center px-3 py-2 bg-slate-500 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-slate-600 active:bg-slate-700 focus:outline-none focus:border-slate-700 focus:ring ring-slate-300 disabled:opacity-25 transition ease-in-out duration-150 add-service-item-btn" data-basename="${baseName}[services_list]" data-nextindex="${tempIdCounter + 1}">Add Service Item</button>`;
                break;
            case 'testimonials':
                fieldsHtml = `<h5 class="text-lg font-medium text-slate-700 dark:text-slate-200 mb-3">Testimonials</h5><div class="testimonials-repeater space-y-4">`;
                tempIdCounter = 0;
                const testimonialsList = Array.isArray(existingContent.testimonials_list) ? existingContent.testimonials_list : (existingContent.testimonials_list ? [existingContent.testimonials_list] : []);
                testimonialsList.forEach((testimonial, index) => {
                    fieldsHtml += getTestimonialItemHtml(`${baseName}[testimonials_list]`, index, testimonial);
                    tempIdCounter = Math.max(tempIdCounter, index);
                });
                if (testimonialsList.length === 0) fieldsHtml += getTestimonialItemHtml(`${baseName}[testimonials_list]`, 0);
                fieldsHtml += `</div><button type="button" class="mt-3 inline-flex items-center px-3 py-2 bg-slate-500 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-slate-600 active:bg-slate-700 focus:outline-none focus:border-slate-700 focus:ring ring-slate-300 disabled:opacity-25 transition ease-in-out duration-150 add-testimonial-item-btn" data-basename="${baseName}[testimonials_list]" data-nextindex="${tempIdCounter + 1}">Add Testimonial</button>`;
                break;
            case 'team':
                fieldsHtml = `<h5 class="text-lg font-medium text-slate-700 dark:text-slate-200 mb-3">Team Members</h5><div class="team-repeater space-y-4">`;
                tempIdCounter = 0;
                const teamMembers = Array.isArray(existingContent.team_members) ? existingContent.team_members : (existingContent.team_members ? [existingContent.team_members] : []);
                teamMembers.forEach((member, index) => {
                    fieldsHtml += getTeamMemberItemHtml(`${baseName}[team_members]`, index, member);
                    tempIdCounter = Math.max(tempIdCounter, index);
                });
                if (teamMembers.length === 0) fieldsHtml += getTeamMemberItemHtml(`${baseName}[team_members]`, 0);
                fieldsHtml += `</div><button type="button" class="mt-3 inline-flex items-center px-3 py-2 bg-slate-500 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-slate-600 active:bg-slate-700 focus:outline-none focus:border-slate-700 focus:ring ring-slate-300 disabled:opacity-25 transition ease-in-out duration-150 add-team-member-btn" data-basename="${baseName}[team_members]" data-nextindex="${tempIdCounter + 1}">Add Team Member</button>`;
                break;
            case 'contact':
                fieldsHtml = `
                    ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">Description</label><textarea name="${baseName}[description]" class="${commonInputClassesJS}">${existingContent.description || ''}</textarea>`)}
                    ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">Button Text</label><input type="text" name="${baseName}[button_text]" class="${commonInputClassesJS}" value="${existingContent.button_text || ''}">`)}
                    ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">Contact Page Slug</label><input type="text" name="${baseName}[contact_page_slug]" class="${commonInputClassesJS}" value="${existingContent.contact_page_slug || 'contact'}">`)}
                `;
                break;
            case 'job-listings':
            case 'featured-products':
            case 'latest-tenders':
            case 'featured-companies':
            case 'company-projects':
            case 'portfolio-projects':
            case 'support-cta':
            case 'search_form':
            case 'news_listing': // Grouping similar simple field structures
                let defaultTitle = 'Section Content';
                if (type === 'job-listings') defaultTitle = 'Latest Job Openings';
                else if (type === 'featured-products') defaultTitle = 'Featured Products';
                else if (type === 'latest-tenders') defaultTitle = 'Latest Tenders';
                else if (type === 'featured-companies') defaultTitle = 'Featured Companies';
                else if (type === 'company-projects') defaultTitle = 'Recent Company Projects';
                else if (type === 'portfolio-projects') defaultTitle = 'Our Recent Work';
                else if (type === 'support-cta') defaultTitle = 'Need Help?';
                else if (type === 'search_form') defaultTitle = ''; // No default title for search form section itself
                else if (type === 'news_listing') defaultTitle = 'Latest News';


                fieldsHtml = `${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">Section Title</label><input type="text" name="${baseName}[title]" class="${commonInputClassesJS}" value="${existingContent.title || defaultTitle}">`)}`;
                if (['job-listings', 'featured-products', 'latest-tenders', 'featured-companies', 'company-projects', 'portfolio-projects', 'news_listing'].includes(type)) {
                    fieldsHtml += `${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">Number of Items to Display</label><input type="number" name="${baseName}[number_of_items]" class="${commonInputClassesJS}" value="${existingContent.number_of_items || (type === 'featured-products' || type === 'featured-companies' ? 4 : 3)}" min="1">`)}`;
                }
                if (['featured-products', 'featured-companies'].includes(type)) {
                    fieldsHtml += `${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">Display Type</label>
                        <select name="${baseName}[display_type]" class="${commonInputClassesJS}">
                            <option value="featured" ${existingContent.display_type === 'featured' ? 'selected' : ''}>Featured Only</option>
                            <option value="latest" ${existingContent.display_type === 'latest' ? 'selected' : ''}>Latest</option>
                        </select>`)}`;
                }
                if (type === 'company-projects') {
                    const companyProjectStatuses = {'all': 'All Statuses', 'planning': 'Planning', 'in_progress': 'In Progress', 'completed': 'Completed', 'on_hold': 'On Hold', 'cancelled': 'Cancelled'};
                    let statusOptionsHtml = Object.entries(companyProjectStatuses).map(([value, text]) => `<option value="${value}" ${existingContent.project_status === value ? 'selected' : ''}>${text}</option>`).join('');
                    fieldsHtml += `${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">Filter by Project Status</label><select name="${baseName}[project_status]" class="${commonInputClassesJS}">${statusOptionsHtml}</select>`)}`;
                }
                 if (['job-listings', 'featured-products', 'latest-tenders', 'featured-companies', 'company-projects', 'portfolio-projects', 'news_listing'].includes(type)) {
                    let placeholderUrl = '/' + type.replace('-','/');
                    if (type === 'portfolio-projects') placeholderUrl = '/portfolio';
                    if (type === 'news_listing') placeholderUrl = '/news';

                    fieldsHtml += `${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">"View All" Link URL (e.g., ${placeholderUrl})</label><input type="text" name="${baseName}[view_all_link]" class="${commonInputClassesJS}" value="${existingContent.view_all_link || ''}" placeholder="${placeholderUrl}">`)}`;
                    fieldsHtml += `${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">"View All" Button Text</label><input type="text" name="${baseName}[view_all_text]" class="${commonInputClassesJS}" value="${existingContent.view_all_text || 'View All'}">`)}`;
                }
                if (type === 'support-cta') {
                     fieldsHtml += `
                        ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">Description</label><textarea name="${baseName}[description]" class="${commonInputClassesJS}" rows="3">${existingContent.description || 'Our dedicated support team is here to assist you. Create a ticket or browse our FAQ.'}</textarea>`)}
                        ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">Primary Button Text</label><input type="text" name="${baseName}[primary_button_text]" class="${commonInputClassesJS}" value="${existingContent.primary_button_text || 'Open a Support Ticket'}">`)}
                        ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">Primary Button Link</label><input type="text" name="${baseName}[primary_button_link]" class="${commonInputClassesJS}" value="${existingContent.primary_button_link || '/support/tickets/create'}" placeholder="/support/tickets/create">`)}
                        ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">Secondary Button Text (Optional)</label><input type="text" name="${baseName}[secondary_button_text]" class="${commonInputClassesJS}" value="${existingContent.secondary_button_text || ''}" placeholder="Knowledge Base">`)}
                        ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">Secondary Button Link (Optional)</label><input type="text" name="${baseName}[secondary_button_link]" class="${commonInputClassesJS}" value="${existingContent.secondary_button_link || ''}" placeholder="/kb">`)}
                    `;
                }
                if (type === 'search_form') {
                     fieldsHtml = `
                        ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">Section Title (Optional)</label><input type="text" name="${baseName}[section_title]" class="${commonInputClassesJS}" value="${existingContent.section_title || ''}">`)}
                        ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">Keywords Placeholder</label><input type="text" name="${baseName}[search_placeholder_keywords]" class="${commonInputClassesJS}" value="${existingContent.search_placeholder_keywords || 'e.g., Software Engineer'}">`)}
                        ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">Location Placeholder</label><input type="text" name="${baseName}[search_placeholder_location]" class="${commonInputClassesJS}" value="${existingContent.search_placeholder_location || 'e.g., New York, NY'}">`)}
                        ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">Search Target URL</label><input type="text" name="${baseName}[search_target_url]" class="${commonInputClassesJS}" value="${existingContent.search_target_url || '/jobs'}" placeholder="/jobs">`)}
                        ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">Button Text</label><input type="text" name="${baseName}[button_text]" class="${commonInputClassesJS}" value="${existingContent.button_text || 'Search Jobs'}">`)}
                    `;
                }
                break;
            case 'features_ai':
                fieldsHtml = `
                    ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}" for="${baseName.replace(/\[|\]/g, '-')}-section_title">Section Title</label><input type="text" name="${baseName}[section_title]" id="${baseName.replace(/\[|\]/g, '-')}-section_title" value="${existingContent.section_title || 'Powerful Features, Effortless Creation'}" class="${commonInputClassesJS}">`)}
                    ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}" for="${baseName.replace(/\[|\]/g, '-')}-section_subtitle">Section Subtitle</label><textarea name="${baseName}[section_subtitle]" id="${baseName.replace(/\[|\]/g, '-')}-section_subtitle" rows="2" class="${commonInputClassesJS}">${existingContent.section_subtitle || 'Discover what makes our AI Website Maker the perfect tool for your online presence.'}</textarea>`)}
                    <h5 class="text-lg font-medium text-slate-700 dark:text-slate-200 mb-3 mt-4">Features</h5>
                    <div class="ai-features-repeater space-y-4">`;

                let featuresToRender = existingContent.features;
                // If features is undefined, null, or an empty array, default to 3 empty structures for the form
                if (!featuresToRender || (Array.isArray(featuresToRender) && featuresToRender.length === 0)) {
                    featuresToRender = [{}, {}, {}]; // Default to 3 empty feature structures
                }

                tempIdCounter = 0;
                if (Array.isArray(featuresToRender)) {
                    featuresToRender.forEach((feature, index) => {
                        fieldsHtml += getAiFeatureItemHtml(`${baseName}[features]`, index, feature);
                        tempIdCounter = Math.max(tempIdCounter, index);
                    });
                }

                fieldsHtml += `</div>
                    <button type="button" class="mt-3 inline-flex items-center px-3 py-2 bg-slate-500 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-slate-600 active:bg-slate-700 focus:outline-none focus:border-slate-700 focus:ring ring-slate-300 disabled:opacity-25 transition ease-in-out duration-150 add-ai-feature-item-btn"
                            data-basename="${baseName}[features]"
                            data-nextindex="${tempIdCounter + 1}">Add Another Feature</button>
                `;
                break;
            case 'pricing_plans_ai':
                fieldsHtml = `
                    ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}" for="${baseName.replace(/\[|\]/g, '-')}-section_title">Section Title</label><input type="text" name="${baseName}[section_title]" id="${baseName.replace(/\[|\]/g, '-')}-section_title" value="${existingContent.section_title || 'Flexible Pricing for Every Need'}" class="${commonInputClassesJS}">`)}
                    ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}" for="${baseName.replace(/\[|\]/g, '-')}-section_subtitle">Section Subtitle</label><textarea name="${baseName}[section_subtitle]" id="${baseName.replace(/\[|\]/g, '-')}-section_subtitle" rows="2" class="${commonInputClassesJS}">${existingContent.section_subtitle || 'Choose the perfect plan to launch and grow your online presence with AI.'}</textarea>`)}
                    <h5 class="text-lg font-medium text-slate-700 dark:text-slate-200 mb-3 mt-4">Pricing Plans</h5>
                    <div class="ai-pricing-plans-repeater space-y-4">`;

                let plansToRender = existingContent.plans;
                if (!plansToRender || (Array.isArray(plansToRender) && plansToRender.length === 0)) {
                    plansToRender = [{}, {}, {}]; // Default to 3 empty plan structures
                }

                tempIdCounter = 0;
                if (Array.isArray(plansToRender)) {
                    plansToRender.forEach((plan, index) => {
                        fieldsHtml += getPricingPlanItemHtml(`${baseName}[plans]`, index, plan);
                        tempIdCounter = Math.max(tempIdCounter, index);
                    });
                }

                fieldsHtml += `</div>
                    <button type="button" class="mt-3 inline-flex items-center px-3 py-2 bg-slate-500 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-slate-600 active:bg-slate-700 focus:outline-none focus:border-slate-700 focus:ring ring-slate-300 disabled:opacity-25 transition ease-in-out duration-150 add-ai-pricing-plan-item-btn"
                            data-basename="${baseName}[plans]"
                            data-nextindex="${tempIdCounter + 1}">Add Another Plan</button>
                `;
                break;
            case 'faq_ai':
                fieldsHtml = `
                    ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}" for="${baseName.replace(/\[|\]/g, '-')}-section_title">Section Title</label><input type="text" name="${baseName}[section_title]" id="${baseName.replace(/\[|\]/g, '-')}-section_title" value="${existingContent.section_title || 'Frequently Asked Questions'}" class="${commonInputClassesJS}">`)}
                    ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}" for="${baseName.replace(/\[|\]/g, '-')}-section_subtitle">Section Subtitle</label><textarea name="${baseName}[section_subtitle]" id="${baseName.replace(/\[|\]/g, '-')}-section_subtitle" rows="2" class="${commonInputClassesJS}">${existingContent.section_subtitle || 'Find answers to common questions about our AI Website Maker.'}</textarea>`)}
                    <h5 class="text-lg font-medium text-slate-700 dark:text-slate-200 mb-3 mt-4">FAQ Items</h5>
                    <div class="ai-faq-items-repeater space-y-4">`;

                let faqsToRender = existingContent.faqs;
                if (!faqsToRender || (Array.isArray(faqsToRender) && faqsToRender.length === 0)) {
                    faqsToRender = [{}, {}, {}]; // Default to 3 empty FAQ structures
                }

                tempIdCounter = 0;
                if (Array.isArray(faqsToRender)) {
                    faqsToRender.forEach((faq, index) => {
                        fieldsHtml += getFaqItemHtml(`${baseName}[faqs]`, index, faq);
                        tempIdCounter = Math.max(tempIdCounter, index);
                    });
                }
                fieldsHtml += `</div>
                    <button type="button" class="mt-3 inline-flex items-center px-3 py-2 bg-slate-500 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-slate-600 active:bg-slate-700 focus:outline-none focus:border-slate-700 focus:ring ring-slate-300 disabled:opacity-25 transition ease-in-out duration-150 add-ai-faq-item-btn"
                            data-basename="${baseName}[faqs]"
                            data-nextindex="${tempIdCounter + 1}">Add Another FAQ</button>
                `;
                break;

            default:
                fieldsHtml = `<p class="text-slate-500 dark:text-slate-400">No specific fields for this section type. Content will be managed by the selected layout.</p>`;
        }
        container.innerHTML = fieldsHtml;
        attachRepeaterButtonListeners(container);
        if (type === 'services') initializeDynamicServiceVisualToggle(container);
    }

    function attachRepeaterButtonListeners(container) {
        container.querySelectorAll('.add-hero-slide-btn').forEach(btn => {
            btn.addEventListener('click', function() { addRepeaterItem(this, getHeroSlideHtml); });
        });
        container.querySelectorAll('.add-service-item-btn').forEach(btn => {
            btn.addEventListener('click', function() { addRepeaterItem(this, getServiceItemHtml); });
        });
        container.querySelectorAll('.add-testimonial-item-btn').forEach(btn => {
            btn.addEventListener('click', function() { addRepeaterItem(this, getTestimonialItemHtml); });
        });
        container.querySelectorAll('.add-team-member-btn').forEach(btn => {
            btn.addEventListener('click', function() { addRepeaterItem(this, getTeamMemberItemHtml); });
        });
        container.querySelectorAll('.add-ai-feature-item-btn').forEach(btn => {
            btn.addEventListener('click', function() { addRepeaterItem(this, getAiFeatureItemHtml); });
        });
        container.querySelectorAll('.add-ai-pricing-plan-item-btn').forEach(btn => {
            btn.addEventListener('click', function() { addRepeaterItem(this, getPricingPlanItemHtml); });
        });
        container.querySelectorAll('.add-ai-faq-item-btn').forEach(btn => {
            btn.addEventListener('click', function() { addRepeaterItem(this, getFaqItemHtml); });
        });

        container.addEventListener('click', function(event) {
            if (event.target.classList.contains('remove-repeater-item-btn') || event.target.closest('.remove-repeater-item-btn')) {
                const button = event.target.classList.contains('remove-repeater-item-btn') ? event.target : event.target.closest('.remove-repeater-item-btn');
                button.closest('.repeater-item').remove();
            }
        });

        container.addEventListener('change', function(event) {
            if (event.target.classList.contains('service-visual-type-selector-dynamic')) {
                const selectedValue = event.target.value;
                const repeaterItem = event.target.closest('.repeater-item');
                if (repeaterItem) {
                    const iconField = repeaterItem.querySelector('.service-icon-field-dynamic');
                    const imageField = repeaterItem.querySelector('.service-image-field-dynamic');
                    if (iconField) iconField.style.display = selectedValue === 'icon' ? 'block' : 'none';
                    if (imageField) imageField.style.display = selectedValue === 'image' ? 'block' : 'none';
                }
            }
        });
    }

    function addRepeaterItem(button, htmlGeneratorFunc) {
        const baseName = button.dataset.basename;
        let nextIndex = parseInt(button.dataset.nextindex);
        const repeaterContainer = button.previousElementSibling;

        const newItemHtml = htmlGeneratorFunc(baseName, nextIndex, {}); // Pass empty object for new item
        const div = document.createElement('div');
        div.innerHTML = newItemHtml;
        const newItemElement = div.firstElementChild;
        repeaterContainer.appendChild(newItemElement);

        if (htmlGeneratorFunc === getServiceItemHtml) {
            const visualSelect = newItemElement.querySelector('.service-visual-type-selector-dynamic');
            if (visualSelect) {
                 const iconField = newItemElement.querySelector('.service-icon-field-dynamic');
                 const imageField = newItemElement.querySelector('.service-image-field-dynamic');
                 if (iconField) iconField.style.display = visualSelect.value === 'icon' ? 'block' : 'none';
                 if (imageField) imageField.style.display = visualSelect.value === 'image' ? 'block' : 'none';
            }
        }
        button.dataset.nextindex = nextIndex + 1;
    }

    function getHeroSlideHtml(baseName, index, slide = {}) {
        const uniqueIdSuffix = `${index}-${Date.now()}`; // Ensure unique IDs for previews
        return `
            <div class="repeater-item bg-slate-50 dark:bg-slate-700/50 p-4 border border-slate-200 dark:border-slate-600 rounded-md shadow-sm space-y-3">
                <div class="flex justify-between items-center"><h6 class="${repeaterItemHeaderClassesJS}">Hero Slide ${index + 1}</h6> <button type="button" class="text-red-500 hover:text-red-700 text-sm remove-repeater-item-btn"><i class="fas fa-trash-alt mr-1"></i> Remove</button></div>
                ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">Slide Title</label><input type="text" name="${baseName}[${index}][title]" class="${commonInputClassesJS}" value="${slide.title || ''}">`)}
                ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">Slide Subtitle</label><textarea name="${baseName}[${index}][subtitle]" class="${commonInputClassesJS}" rows="2">${slide.subtitle || ''}</textarea>`)}
                ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">CTA Text</label><input type="text" name="${baseName}[${index}][cta_text]" class="${commonInputClassesJS}" value="${slide.cta_text || ''}">`)}
                ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">CTA Link</label><input type="text" name="${baseName}[${index}][cta_link]" class="${commonInputClassesJS}" value="${slide.cta_link || ''}">`)}
                <div>
                    <label class="${commonLabelClassesJS}">Background Image</label>
                    <input type="file" name="${baseName}[${index}][image_file]"
                           class="mt-1 block w-full text-sm text-slate-500 dark:text-slate-400
                                  file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0
                                  file:text-sm file:font-semibold
                                  file:bg-blue-50 file:text-blue-700 dark:file:bg-blue-700 dark:file:text-blue-100
                                  hover:file:bg-blue-100 dark:hover:file:bg-blue-600 dynamic-image-file-input"
                           accept="image/*" data-item-index="${uniqueIdSuffix}" data-list-name="slides" data-field-name="image" data-preview-class="hero-slide-image-preview">
                    <input type="hidden" name="${baseName}[${index}][existing_image_url]" value="${slide.image_url || ''}">
                    <div class="mt-2 hero-slide-image-preview-${uniqueIdSuffix}">
                        ${slide.image_url ?
                            `<img src="/storage/${slide.image_url}" alt="Current Image" class="max-h-32 rounded shadow mb-2">
                             <label class="inline-flex items-center text-xs text-slate-600 dark:text-slate-400">
                                <input type="checkbox" name="${baseName}[${index}][remove_image]" value="1" class="form-checkbox rounded text-blue-500 mr-1"> Remove current image
                             </label>` :
                            '<span class="text-xs text-slate-500 dark:text-slate-400">No image selected.</span>'
                        }
                    </div>
                </div>
            </div>`;
    }

    function getServiceItemHtml(baseName, index, service = {}) {
        const visualType = service.visual_type || 'icon';
        const uniqueIdSuffix = `${index}-${Date.now()}`;
        return `
            <div class="repeater-item bg-slate-50 dark:bg-slate-700/50 p-4 border border-slate-200 dark:border-slate-600 rounded-md shadow-sm space-y-3">
                <div class="flex justify-between items-center"><h6 class="${repeaterItemHeaderClassesJS}">Service Item ${index + 1}</h6> <button type="button" class="text-red-500 hover:text-red-700 text-sm remove-repeater-item-btn"><i class="fas fa-trash-alt mr-1"></i> Remove</button></div>
                ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">Title</label><input type="text" name="${baseName}[${index}][title]" class="${commonInputClassesJS}" value="${service.title || ''}">`)}
                ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">Description</label><textarea name="${baseName}[${index}][description]" class="${commonInputClassesJS}">${service.description || ''}</textarea>`)}
                ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">Link</label><input type="text" name="${baseName}[${index}][link]" class="${commonInputClassesJS}" value="${service.link || ''}">`)}
                ${formGroupWrapperJS(`
                    <label class="${commonLabelClassesJS}">Visual Type</label>
                    <select name="${baseName}[${index}][visual_type]" class="${commonInputClassesJS} service-visual-type-selector-dynamic">
                        <option value="icon" ${ visualType === 'icon' ? 'selected' : '' }>Icon</option>
                        <option value="image" ${ visualType === 'image' ? 'selected' : '' }>Image</option>
                    </select>
                `)}
                <div class="service-icon-field-dynamic" style="${ visualType === 'image' ? 'display:none;' : '' }">
                    ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">Icon HTML/SVG or Class</label><textarea name="${baseName}[${index}][icon_html]" class="${commonInputClassesJS}" rows="2" placeholder="<svg>...</svg> or fas fa-icon">${service.icon_html || ''}</textarea><p class="mt-1 text-xs text-slate-500 dark:text-slate-400">Paste SVG or FontAwesome class.</p>`)}
                </div>
                <div class="service-image-field-dynamic" style="${ visualType === 'icon' ? 'display:none;' : '' }">
                    <div>
                        <label class="${commonLabelClassesJS}">Service Image</label>
                        <input type="file" name="${baseName}[${index}][image_file]"
                               class="mt-1 block w-full text-sm text-slate-500 dark:text-slate-400
                                      file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0
                                      file:text-sm file:font-semibold
                                      file:bg-blue-50 file:text-blue-700 dark:file:bg-blue-700 dark:file:text-blue-100
                                      hover:file:bg-blue-100 dark:hover:file:bg-blue-600 dynamic-image-file-input service-image-file-input"
                               accept="image/*" data-item-index="${uniqueIdSuffix}" data-list-name="services_list" data-field-name="image" data-preview-class="service-image-preview">
                        <input type="hidden" name="${baseName}[${index}][existing_image_url]" value="${service.image_url || ''}">
                        <div class="mt-2 service-image-preview-${uniqueIdSuffix}">
                            ${service.image_url ?
                                `<img src="/storage/${service.image_url}" alt="Current Image" class="max-h-32 rounded shadow mb-2">
                                 <label class="inline-flex items-center text-xs text-slate-600 dark:text-slate-400">
                                    <input type="checkbox" name="${baseName}[${index}][remove_image]" value="1" class="form-checkbox rounded text-blue-500 mr-1"> Remove current image
                                 </label>` :
                                '<span class="text-xs text-slate-500 dark:text-slate-400">No image selected.</span>'
                            }
                        </div>
                    </div>
                </div>
            </div>`;
    }
    function getTestimonialItemHtml(baseName, index, testimonial = {}) {
        const uniqueIdSuffix = `${index}-${Date.now()}`;
        return `
            <div class="repeater-item bg-slate-50 dark:bg-slate-700/50 p-4 border border-slate-200 dark:border-slate-600 rounded-md shadow-sm space-y-3">
                <div class="flex justify-between items-center"><h6 class="${repeaterItemHeaderClassesJS}">Testimonial ${index + 1}</h6> <button type="button" class="text-red-500 hover:text-red-700 text-sm remove-repeater-item-btn"><i class="fas fa-trash-alt mr-1"></i> Remove</button></div>
                ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">Quote</label><textarea name="${baseName}[${index}][quote]" class="${commonInputClassesJS}" rows="3">${testimonial.quote || ''}</textarea>`)}
                ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">Author</label><input type="text" name="${baseName}[${index}][author]" class="${commonInputClassesJS}" value="${testimonial.author || ''}">`)}
                <div>
                    <label class="${commonLabelClassesJS}">Author Image (Optional)</label>
                    <input type="file" name="${baseName}[${index}][author_image_file]"
                           class="mt-1 block w-full text-sm text-slate-500 dark:text-slate-400
                                  file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0
                                  file:text-sm file:font-semibold
                                  file:bg-blue-50 file:text-blue-700 dark:file:bg-blue-700 dark:file:text-blue-100
                                  hover:file:bg-blue-100 dark:hover:file:bg-blue-600 dynamic-image-file-input"
                           accept="image/*" data-item-index="${uniqueIdSuffix}" data-list-name="testimonials_list" data-field-name="author_image" data-preview-class="testimonial-author-image-preview">
                    <input type="hidden" name="${baseName}[${index}][existing_author_image_url]" value="${testimonial.author_image_url || ''}">
                    <div class="mt-2 testimonial-author-image-preview-${uniqueIdSuffix}">
                        ${testimonial.author_image_url ?
                            `<img src="/storage/${testimonial.author_image_url}" alt="Current Author Image" class="max-h-32 rounded shadow mb-2">
                             <label class="inline-flex items-center text-xs text-slate-600 dark:text-slate-400">
                                <input type="checkbox" name="${baseName}[${index}][remove_author_image]" value="1" class="form-checkbox rounded text-blue-500 mr-1"> Remove current image
                             </label>` :
                            '<span class="text-xs text-slate-500 dark:text-slate-400">No image selected.</span>'
                        }
                    </div>
                </div>
                ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">Company (Optional)</label><input type="text" name="${baseName}[${index}][company]" class="${commonInputClassesJS}" value="${testimonial.company || ''}">`)}
            </div>`;
    }
    function getTeamMemberItemHtml(baseName, index, member = {}) {
        const socialLinks = member.social_links || {};
        const uniqueIdSuffix = `${index}-${Date.now()}`;
        return `
            <div class="repeater-item bg-slate-50 dark:bg-slate-700/50 p-4 border border-slate-200 dark:border-slate-600 rounded-md shadow-sm space-y-3">
                <div class="flex justify-between items-center"><h6 class="${repeaterItemHeaderClassesJS}">Team Member ${index + 1}</h6> <button type="button" class="text-red-500 hover:text-red-700 text-sm remove-repeater-item-btn"><i class="fas fa-trash-alt mr-1"></i> Remove</button></div>
                ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">Name</label><input type="text" name="${baseName}[${index}][name]" class="${commonInputClassesJS}" value="${member.name || ''}">`)}
                ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">Title/Role</label><input type="text" name="${baseName}[${index}][title]" class="${commonInputClassesJS}" value="${member.title || ''}">`)}
                <div>
                    <label class="${commonLabelClassesJS}">Member Image</label>
                    <input type="file" name="${baseName}[${index}][image_file]"
                           class="mt-1 block w-full text-sm text-slate-500 dark:text-slate-400
                                  file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0
                                  file:text-sm file:font-semibold
                                  file:bg-blue-50 file:text-blue-700 dark:file:bg-blue-700 dark:file:text-blue-100
                                  hover:file:bg-blue-100 dark:hover:file:bg-blue-600 dynamic-image-file-input"
                           accept="image/*" data-item-index="${uniqueIdSuffix}" data-list-name="team_members" data-field-name="image" data-preview-class="team-member-image-preview">
                    <input type="hidden" name="${baseName}[${index}][existing_image_url]" value="${member.image_url || ''}">
                    <div class="mt-2 team-member-image-preview-${uniqueIdSuffix}">
                        ${member.image_url ?
                            `<img src="/storage/${member.image_url}" alt="Current Image" class="max-h-32 rounded shadow mb-2">
                             <label class="inline-flex items-center text-xs text-slate-600 dark:text-slate-400">
                                <input type="checkbox" name="${baseName}[${index}][remove_image]" value="1" class="form-checkbox rounded text-blue-500 mr-1"> Remove current image
                             </label>` :
                            '<span class="text-xs text-slate-500 dark:text-slate-400">No image selected.</span>'
                        }
                    </div>
                </div>
                ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">Social - Twitter URL (Optional)</label><input type="text" name="${baseName}[${index}][social_links][twitter]" class="${commonInputClassesJS}" value="${socialLinks.twitter || ''}">`)}
                ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}">Social - LinkedIn URL (Optional)</label><input type="text" name="${baseName}[${index}][social_links][linkedin]" class="${commonInputClassesJS}" value="${socialLinks.linkedin || ''}">`)}
            </div>`;
    }

    function getAiFeatureItemHtml(baseName, index, feature = {}) {
        const itemBaseName = `${baseName}[${index}]`;
        const uniqueIdPrefix = itemBaseName.replace(/\[|\]/g, '-');

        return `
            <div class="repeater-item bg-slate-50 dark:bg-slate-700/50 p-4 border border-slate-200 dark:border-slate-600 rounded-md shadow-sm space-y-3">
                <div class="flex justify-between items-center">
                    <h6 class="${repeaterItemHeaderClassesJS}">Feature ${index + 1}</h6>
                    <button type="button" class="text-red-500 hover:text-red-700 text-sm remove-repeater-item-btn"><i class="fas fa-trash-alt mr-1"></i> Remove</button>
                </div>
                ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}" for="${uniqueIdPrefix}-title">Title</label><input type="text" name="${itemBaseName}[title]" id="${uniqueIdPrefix}-title" value="${feature.title || ''}" class="${commonInputClassesJS}">`)}
                ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}" for="${uniqueIdPrefix}-description">Description</label><textarea name="${itemBaseName}[description]" id="${uniqueIdPrefix}-description" rows="2" class="${commonInputClassesJS}">${feature.description || ''}</textarea>`)}
                ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}" for="${uniqueIdPrefix}-icon">Icon (SVG Code or Class)</label><textarea name="${itemBaseName}[icon]" id="${uniqueIdPrefix}-icon" rows="3" class="${commonInputClassesJS} font-mono text-xs" placeholder="<svg>...</svg> or fas fa-icon">${feature.icon || ''}</textarea>`)}
                ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}" for="${uniqueIdPrefix}-link">Link (Optional)</label><input type="url" name="${itemBaseName}[link]" id="${uniqueIdPrefix}-link" value="${feature.link || ''}" class="${commonInputClassesJS}" placeholder="https://example.com/feature-details">`)}
            </div>`;
    }

    function getPricingPlanItemHtml(baseName, index, plan = {}) {
        const itemBaseName = `${baseName}[${index}]`;
        const uniqueIdPrefix = itemBaseName.replace(/\[|\]/g, '-');
        const featuresString = Array.isArray(plan.features) ? plan.features.join('\n') : '';

        return `
            <div class="repeater-item bg-slate-50 dark:bg-slate-700/50 p-4 border border-slate-200 dark:border-slate-600 rounded-md shadow-sm space-y-3">
                <div class="flex justify-between items-center">
                    <h6 class="${repeaterItemHeaderClassesJS}">Plan ${index + 1}</h6>
                    <button type="button" class="text-red-500 hover:text-red-700 text-sm remove-repeater-item-btn"><i class="fas fa-trash-alt mr-1"></i> Remove</button>
                </div>
                ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}" for="${uniqueIdPrefix}-name">Plan Name</label><input type="text" name="${itemBaseName}[name]" id="${uniqueIdPrefix}-name" value="${plan.name || ''}" class="${commonInputClassesJS}">`)}
                <div class="grid grid-cols-2 gap-4">
                    ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}" for="${uniqueIdPrefix}-price">Price</label><input type="text" name="${itemBaseName}[price]" id="${uniqueIdPrefix}-price" value="${plan.price || ''}" class="${commonInputClassesJS}" placeholder="$29 or Free">`)}
                    ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}" for="${uniqueIdPrefix}-frequency">Frequency</label><input type="text" name="${itemBaseName}[frequency]" id="${uniqueIdPrefix}-frequency" value="${plan.frequency || '/month'}" class="${commonInputClassesJS}" placeholder="/month or /year">`)}
                </div>
                ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}" for="${uniqueIdPrefix}-features">Features (one per line)</label><textarea name="${itemBaseName}[features_textarea]" id="${uniqueIdPrefix}-features" rows="4" class="${commonInputClassesJS}" placeholder="Feature 1\nFeature 2\nFeature 3">${featuresString}</textarea>`)}
                <div class="grid grid-cols-2 gap-4">
                    ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}" for="${uniqueIdPrefix}-cta_text">CTA Button Text</label><input type="text" name="${itemBaseName}[cta_text]" id="${uniqueIdPrefix}-cta_text" value="${plan.cta_text || 'Choose Plan'}" class="${commonInputClassesJS}">`)}
                    ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}" for="${uniqueIdPrefix}-cta_link">CTA Button Link</label><input type="url" name="${itemBaseName}[cta_link]" id="${uniqueIdPrefix}-cta_link" value="${plan.cta_link || '#'}" class="${commonInputClassesJS}" placeholder="https://example.com/signup">`)}
                </div>
                <div class="flex items-center">
                    <input type="checkbox" name="${itemBaseName}[highlighted]" id="${uniqueIdPrefix}-highlighted" value="1" class="h-4 w-4 text-blue-600 border-slate-300 rounded focus:ring-blue-500 dark:bg-slate-700 dark:border-slate-600" ${plan.highlighted ? 'checked' : ''}>
                    <label for="${uniqueIdPrefix}-highlighted" class="ml-2 text-sm text-slate-700 dark:text-slate-300">Highlight this plan?</label>
                </div>
                ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}" for="${uniqueIdPrefix}-highlight_text">Highlight Text (if highlighted)</label><input type="text" name="${itemBaseName}[highlight_text]" id="${uniqueIdPrefix}-highlight_text" value="${plan.highlight_text || 'Popular'}" class="${commonInputClassesJS}">`)}
            </div>`;
    }

    function getFaqItemHtml(baseName, index, faq = {}) {
        const itemBaseName = `${baseName}[${index}]`;
        const uniqueIdPrefix = itemBaseName.replace(/\[|\]/g, '-');

        return `
            <div class="repeater-item bg-slate-50 dark:bg-slate-700/50 p-4 border border-slate-200 dark:border-slate-600 rounded-md shadow-sm space-y-3">
                <div class="flex justify-between items-center">
                    <h6 class="${repeaterItemHeaderClassesJS}">FAQ Item ${index + 1}</h6>
                    <button type="button" class="text-red-500 hover:text-red-700 text-sm remove-repeater-item-btn"><i class="fas fa-trash-alt mr-1"></i> Remove</button>
                </div>
                ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}" for="${uniqueIdPrefix}-question">Question</label><input type="text" name="${itemBaseName}[question]" id="${uniqueIdPrefix}-question" value="${faq.question || ''}" class="${commonInputClassesJS}">`)}
                ${formGroupWrapperJS(`<label class="${commonLabelClassesJS}" for="${uniqueIdPrefix}-answer">Answer</label><textarea name="${itemBaseName}[answer]" id="${uniqueIdPrefix}-answer" rows="3" class="${commonInputClassesJS}">${faq.answer || ''}</textarea>`)}
            </div>`;
    }

    function initializeDynamicServiceVisualToggle(containerElement) {
        containerElement.querySelectorAll('.service-visual-type-selector-dynamic').forEach(select => {
            const repeaterItem = select.closest('.repeater-item');
            if (repeaterItem) {
                const iconField = repeaterItem.querySelector('.service-icon-field-dynamic');
                const imageField = repeaterItem.querySelector('.service-image-field-dynamic');
                if (iconField && imageField) {
                    iconField.style.display = select.value === 'icon' ? 'block' : 'none';
                    imageField.style.display = select.value === 'image' ? 'block' : 'none';
                }
            }
        });
    }
});
</script>
@endpush
