<x-app-layout>
<x-slot name="header">
    <div class="d-flex flex-wrap align-items-center justify-content-between gap-3">
        <div>
            <h2 class="h4 mb-1">Homepage CMS</h2>
            <p class="text-muted mb-0 small">Publish, order and edit only the content shown on the public homepage.</p>
        </div>
        <a href="{{ route('home') }}" target="_blank" class="btn btn-outline-primary"><i class="fas fa-external-link-alt me-1"></i> Preview homepage</a>
    </div>
</x-slot>

@php
    $simpleFields = [
        'hero' => ['eyebrow' => 'Eyebrow', 'title' => 'Title', 'description' => 'Description', 'primary_label' => 'Primary button label', 'primary_url' => 'Primary button URL', 'secondary_label' => 'Secondary button label', 'secondary_url' => 'Secondary button URL'],
        'overview' => ['eyebrow' => 'Eyebrow', 'title' => 'Title', 'description' => 'Description'],
        'packages' => ['eyebrow' => 'Eyebrow', 'title' => 'Title', 'description' => 'Description'],
        'mission' => ['mission_title' => 'Mission title', 'mission_text' => 'Mission description', 'vision_title' => 'Vision title', 'vision_text' => 'Vision description'],
        'cta' => ['title' => 'Title', 'description' => 'Description', 'button_label' => 'Button label', 'button_url' => 'Button URL'],
        'contact' => ['eyebrow' => 'Eyebrow', 'title' => 'Title', 'description' => 'Description', 'map_embed_url' => 'Google Maps embed URL', 'facebook_url' => 'Facebook page URL', 'whatsapp_number' => 'WhatsApp number with country code'],
    ];
    $itemSchemas = [
        'statistics' => ['value' => 'Number / value', 'label' => 'Label'],
        'services' => ['title' => 'Service title', 'description' => 'Description', 'icon' => 'Icon: wifi, briefcase, activity, shield, globe'],
        'process' => ['title' => 'Step title', 'description' => 'Description'],
        'testimonials' => ['quote' => 'Quote', 'name' => 'Name', 'role' => 'Role / company'],
        'faq' => ['question' => 'Question', 'answer' => 'Answer'],
    ];
@endphp

<div class="cms-intro">
    <div><strong>{{ $sections->where('is_enabled', true)->count() }}</strong><span>Visible sections</span></div>
    <div><strong>{{ $sections->where('status', 'draft')->count() }}</strong><span>Draft sections</span></div>
    <div><strong>{{ $sections->count() }}</strong><span>Total sections</span></div>
</div>

<div class="accordion cms-builder" id="homepageBuilder">
@foreach($sections as $section)
    @php $content = $section->content ?? []; @endphp
    <article class="accordion-item cms-section">
        <h2 class="accordion-header">
            <button class="accordion-button {{ $loop->first ? '' : 'collapsed' }}" type="button" data-bs-toggle="collapse" data-bs-target="#section-{{ $section->id }}">
                <span class="order-pill">{{ $section->sort_order }}</span>
                <span class="flex-grow-1">{{ $section->name }}</span>
                <span class="status-dot {{ $section->is_enabled && $section->status === 'published' ? 'is-live' : '' }}"></span>
                <span class="small me-3">{{ $section->is_enabled && $section->status === 'published' ? 'Live' : ucfirst($section->status) }}</span>
            </button>
        </h2>
        <div id="section-{{ $section->id }}" class="accordion-collapse collapse {{ $loop->first ? 'show' : '' }}" data-bs-parent="#homepageBuilder">
            <div class="accordion-body">
                <form class="cms-section-form" action="{{ route('admin.cms.homepage.update', $section) }}" enctype="multipart/form-data">
                    @csrf @method('PUT')
                    <div class="section-controls">
                        <label class="form-check form-switch mb-0">
                            <input type="hidden" name="is_enabled" value="0">
                            <input class="form-check-input" type="checkbox" name="is_enabled" value="1" @checked($section->is_enabled)>
                            <span class="form-check-label">Show section</span>
                        </label>
                        <label><span>State</span><select class="form-select" name="status"><option value="published" @selected($section->status === 'published')>Published</option><option value="draft" @selected($section->status === 'draft')>Draft</option></select></label>
                        <label><span>Display order</span><input class="form-control" type="number" name="sort_order" min="0" max="1000" value="{{ $section->sort_order }}" required></label>
                    </div>

                    @if(isset($simpleFields[$section->key]))
                        <div class="row g-3 mt-1">
                            @foreach($simpleFields[$section->key] as $field => $label)
                                @php $long = in_array($field, ['description','mission_text','vision_text'], true); @endphp
                                <div class="{{ $long ? 'col-12' : 'col-md-6' }}">
                                    <label class="form-label">{{ $label }}</label>
                                    @if($long)
                                        <textarea class="form-control" rows="3" name="content[{{ $field }}]">{{ $content[$field] ?? '' }}</textarea>
                                    @else
                                        <input class="form-control" name="content[{{ $field }}]" value="{{ $content[$field] ?? '' }}" @if($field === 'map_embed_url') type="url" @endif>
                                    @endif
                                </div>
                            @endforeach
                        </div>
                    @endif

                    @if(in_array($section->key, ['hero','overview'], true))
                        <div class="row g-3 mt-1">
                            <div class="col-md-6"><label class="form-label">Section image</label><input class="form-control" type="file" name="image" accept=".jpg,.jpeg,.png,.webp"></div>
                            @if($section->key === 'hero')<div class="col-md-6"><label class="form-label">Background image</label><input class="form-control" type="file" name="background" accept=".jpg,.jpeg,.png,.webp"></div>@endif
                        </div>
                    @endif

                    @if(isset($itemSchemas[$section->key]))
                        @if(in_array($section->key, ['services','process','testimonials','faq'], true))
                            <div class="row g-3 mt-1 mb-3">
                                <div class="col-md-6"><label class="form-label">Eyebrow</label><input class="form-control" name="content[eyebrow]" value="{{ $content['eyebrow'] ?? '' }}"></div>
                                <div class="col-md-6"><label class="form-label">Title</label><input class="form-control" name="content[title]" value="{{ $content['title'] ?? '' }}"></div>
                                @if($section->key === 'services')<div class="col-12"><label class="form-label">Description</label><textarea class="form-control" rows="2" name="content[description]">{{ $content['description'] ?? '' }}</textarea></div>@endif
                            </div>
                        @endif
                        <div class="repeat-grid">
                            @foreach(array_pad($content['items'] ?? [], $section->key === 'statistics' ? 4 : 3, []) as $index => $item)
                                <div class="repeat-card">
                                    <span class="repeat-number">{{ $index + 1 }}</span>
                                    @foreach($itemSchemas[$section->key] as $field => $label)
                                        <label class="form-label">{{ $label }}
                                            @if(in_array($field, ['description','quote','answer'], true))
                                                <textarea class="form-control" rows="2" name="content[items][{{ $index }}][{{ $field }}]">{{ $item[$field] ?? '' }}</textarea>
                                            @else
                                                <input class="form-control" name="content[items][{{ $index }}][{{ $field }}]" value="{{ $item[$field] ?? '' }}">
                                            @endif
                                        </label>
                                    @endforeach
                                </div>
                            @endforeach
                        </div>
                    @endif

                    @if($section->key === 'clients')
                        <div class="row g-3 mt-1">
                            <div class="col-md-6"><label class="form-label">Eyebrow</label><input class="form-control" name="content[eyebrow]" value="{{ $content['eyebrow'] ?? '' }}"></div>
                            <div class="col-md-6"><label class="form-label">Title</label><input class="form-control" name="content[title]" value="{{ $content['title'] ?? '' }}"></div>
                            <div class="col-12"><label class="form-label">Add client logos</label><input class="form-control" type="file" name="logos[]" accept=".jpg,.jpeg,.png,.webp,.svg" multiple></div>
                            @if(!empty($content['logos']))<div class="col-12 client-logo-editor">@foreach($content['logos'] as $logo)<label><img src="{{ asset('storage/'.$logo) }}" alt=""><input type="checkbox" name="remove_logos[]" value="{{ $logo }}"> Remove</label>@endforeach</div>@endif
                        </div>
                    @endif

                    <div class="d-flex justify-content-end mt-4"><button class="btn btn-primary save-section" type="submit"><i class="fas fa-save me-1"></i> Save section</button></div>
                </form>
            </div>
        </div>
    </article>
@endforeach
</div>

@push('scripts')
<style>
.cms-intro{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:1rem;margin-bottom:1.25rem}.cms-intro div{background:#fff;border:1px solid #e7edf4;border-radius:16px;padding:1rem 1.2rem;box-shadow:0 8px 24px rgba(15,23,42,.04)}.cms-intro strong,.cms-intro span{display:block}.cms-intro strong{font-size:1.5rem;color:#172554}.cms-intro span{font-size:.8rem;color:#64748b}.cms-builder{display:grid;gap:.85rem}.cms-section{border:1px solid #e4eaf2!important;border-radius:16px!important;overflow:hidden;box-shadow:0 8px 30px rgba(15,23,42,.04)}.cms-section .accordion-button{gap:.65rem;font-weight:700;padding:1rem 1.15rem}.cms-section .accordion-button:not(.collapsed){background:#f7f9ff;color:#1d4ed8}.order-pill{display:grid;place-items:center;width:34px;height:28px;border-radius:8px;background:#eef2ff;color:#4338ca;font-size:.75rem}.status-dot{width:9px;height:9px;border-radius:50%;background:#f59e0b}.status-dot.is-live{background:#22c55e;box-shadow:0 0 0 4px rgba(34,197,94,.12)}.section-controls{display:grid;grid-template-columns:minmax(180px,1fr) 190px 150px;gap:1rem;align-items:end;padding:1rem;border-radius:14px;background:#f8fafc;border:1px solid #edf1f6}.section-controls>label:not(.form-check) span{display:block;font-size:.78rem;font-weight:700;margin-bottom:.35rem;color:#475569}.repeat-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:1rem}.repeat-card{position:relative;border:1px solid #e5eaf0;border-radius:14px;padding:1rem;background:#fff}.repeat-card .form-label{display:block;font-size:.78rem;font-weight:600}.repeat-card .form-label:last-child{margin-bottom:0}.repeat-number{position:absolute;right:.7rem;top:.6rem;color:#94a3b8;font-size:.72rem}.client-logo-editor{display:flex;flex-wrap:wrap;gap:.75rem}.client-logo-editor label{border:1px solid #e5e7eb;border-radius:12px;padding:.6rem;font-size:.75rem}.client-logo-editor img{display:block;width:96px;height:54px;object-fit:contain;margin-bottom:.4rem}@media(max-width:767.98px){.cms-intro{grid-template-columns:1fr}.section-controls,.repeat-grid{grid-template-columns:1fr}.cms-section .accordion-button{padding:.85rem}.cms-section .accordion-body{padding:1rem}}
</style>
<script>
document.querySelectorAll('.cms-section-form').forEach(form=>form.addEventListener('submit',async event=>{
    event.preventDefault(); const button=form.querySelector('.save-section'); const original=button.innerHTML;
    button.disabled=true; button.innerHTML='<span class="spinner-border spinner-border-sm me-1"></span> Saving';
    try {
        const response=await axios.post(form.action,new FormData(form));
        showToast(response.data.message,'success');
    } catch(error) {
        const errors=error.response?.data?.errors; const message=errors ? Object.values(errors).flat()[0] : (error.response?.data?.message || 'Section could not be saved.');
        showToast(message,'error');
    } finally { button.disabled=false; button.innerHTML=original; }
}));
</script>
@endpush
</x-app-layout>
