@php
    $branches = $data['branches'] ?? collect();
    $formFields = $section->getSetting('form_fields', []);
    $showMap = $section->getSetting('show_map', false);
    $mapEmbed = $section->getSetting('map_embed_url', '');
    $subjects = $section->getSetting('subjects', []);
    $hasSubjects = !empty($subjects);

    $defaultFields = empty($formFields);
@endphp

<div class="site-section site-section--alt" x-data="{
    form: { name: '', phone: '', email: '', message: '', subject: ''@if(!$defaultFields)@foreach($formFields as $f), '{{ $f['key'] ?? '' }}': ''@endforeach @endif },
    loading: false,
    success: false,
    errors: {},
    async submit() {
        this.loading = true;
        this.errors = {};
        try {
            const res = await fetch('{{ route('website.contact.submit', $academy->slug ?? 'default') }}', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': '{{ csrf_token() }}', 'Accept': 'application/json' },
                body: JSON.stringify(this.form)
            });
            const data = await res.json();
            if (res.ok) {
                this.success = true;
                Object.keys(this.form).forEach(k => this.form[k] = '');
            } else if (data.errors) {
                this.errors = data.errors;
            }
        } catch(e) { }
        this.loading = false;
    }
}">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="text-center mb-12 reveal">
            <h2 class="section-title mx-auto">{{ $section->title ?? 'تواصل معنا' }}</h2>
            @if($section->subtitle)
                <p class="mt-4 text-gray-500 text-lg">{{ $section->subtitle }}</p>
            @endif
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-12">
            {{-- Contact Form --}}
            <div class="reveal">
                <div x-show="!success">
                    <form @submit.prevent="submit" class="space-y-4">
                        {{-- Name --}}
                        <div>
                            <input type="text" x-model="form.name" placeholder="الاسم الكامل *"
                                   class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-gray-900 placeholder-gray-400 focus:ring-2 focus:ring-[var(--site-accent)] focus:border-transparent transition" required>
                            <template x-if="errors.name"><p class="text-red-500 text-sm mt-1" x-text="errors.name[0]"></p></template>
                        </div>

                        {{-- Phone --}}
                        <div>
                            <input type="tel" x-model="form.phone" placeholder="رقم الهاتف *"
                                   class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-gray-900 placeholder-gray-400 focus:ring-2 focus:ring-[var(--site-accent)] focus:border-transparent transition" dir="ltr" required>
                            <template x-if="errors.phone"><p class="text-red-500 text-sm mt-1" x-text="errors.phone[0]"></p></template>
                        </div>

                        {{-- Email --}}
                        <div>
                            <input type="email" x-model="form.email" placeholder="البريد الإلكتروني (اختياري)"
                                   class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-gray-900 placeholder-gray-400 focus:ring-2 focus:ring-[var(--site-accent)] focus:border-transparent transition" dir="ltr">
                            <template x-if="errors.email"><p class="text-red-500 text-sm mt-1" x-text="errors.email[0]"></p></template>
                        </div>

                        {{-- Subject Dropdown --}}
                        @if($hasSubjects)
                            <div>
                                <select x-model="form.subject"
                                        class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-gray-900 focus:ring-2 focus:ring-[var(--site-accent)] focus:border-transparent transition">
                                    <option value="">اختر الموضوع...</option>
                                    @foreach($subjects as $subject)
                                        <option value="{{ $subject }}">{{ $subject }}</option>
                                    @endforeach
                                </select>
                            </div>
                        @endif

                        {{-- Custom Fields --}}
                        @if(!$defaultFields)
                            @foreach($formFields as $field)
                                <div>
                                    @if(($field['type'] ?? 'text') === 'select')
                                        <select x-model="form['{{ $field['key'] }}']"
                                                class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-gray-900 focus:ring-2 focus:ring-[var(--site-accent)] focus:border-transparent transition"
                                                {{ ($field['required'] ?? false) ? 'required' : '' }}>
                                            <option value="">{{ $field['label'] ?? '' }}</option>
                                            @foreach($field['options'] ?? [] as $opt)
                                                <option value="{{ $opt }}">{{ $opt }}</option>
                                            @endforeach
                                        </select>
                                    @elseif(($field['type'] ?? 'text') === 'textarea')
                                        <textarea x-model="form['{{ $field['key'] }}']"
                                                  placeholder="{{ $field['label'] ?? '' }}{{ ($field['required'] ?? false) ? ' *' : '' }}"
                                                  rows="3"
                                                  class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-gray-900 placeholder-gray-400 focus:ring-2 focus:ring-[var(--site-accent)] focus:border-transparent transition resize-none"
                                                  {{ ($field['required'] ?? false) ? 'required' : '' }}></textarea>
                                    @else
                                        <input type="{{ $field['type'] ?? 'text' }}"
                                               x-model="form['{{ $field['key'] }}']"
                                               placeholder="{{ $field['label'] ?? '' }}{{ ($field['required'] ?? false) ? ' *' : '' }}"
                                               class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-gray-900 placeholder-gray-400 focus:ring-2 focus:ring-[var(--site-accent)] focus:border-transparent transition"
                                               {{ ($field['required'] ?? false) ? 'required' : '' }}>
                                    @endif
                                    <template x-if="errors['{{ $field['key'] }}']"><p class="text-red-500 text-sm mt-1" x-text="errors['{{ $field['key'] }}'][0]"></p></template>
                                </div>
                            @endforeach
                        @endif

                        {{-- Message --}}
                        <div>
                            <textarea x-model="form.message" placeholder="رسالتك *" rows="4"
                                      class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-gray-900 placeholder-gray-400 focus:ring-2 focus:ring-[var(--site-accent)] focus:border-transparent transition resize-none" required></textarea>
                            <template x-if="errors.message"><p class="text-red-500 text-sm mt-1" x-text="errors.message[0]"></p></template>
                        </div>

                        <button type="submit" class="site-btn site-btn--primary w-full justify-center" :disabled="loading">
                            <span x-show="!loading">إرسال الرسالة</span>
                            <span x-show="loading" class="flex items-center gap-2">
                                <svg class="animate-spin w-5 h-5" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"/><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"/></svg>
                                جارٍ الإرسال...
                            </span>
                        </button>
                    </form>
                </div>

                {{-- Success State --}}
                <div x-show="success" x-transition class="text-center py-12">
                    <div class="w-16 h-16 mx-auto mb-4 rounded-full bg-green-50 flex items-center justify-center">
                        <svg class="w-8 h-8 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
                        </svg>
                    </div>
                    <h3 class="text-xl font-bold text-gray-900">تم إرسال رسالتك بنجاح!</h3>
                    <p class="text-gray-500 mt-2">سنتواصل معك في أقرب وقت</p>
                    <button @click="success = false" class="mt-4 text-[var(--site-accent)] text-sm font-medium hover:underline">إرسال رسالة أخرى</button>
                </div>
            </div>

            {{-- Contact Info --}}
            <div class="reveal reveal--delay-2 space-y-6">
                @foreach($branches->take(3) as $branch)
                    <div class="p-5 rounded-xl bg-white border border-gray-200 shadow-sm">
                        <h4 class="font-bold text-gray-900 flex items-center gap-2">
                            <svg class="w-5 h-5 text-[var(--site-accent)]" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"/></svg>
                            {{ $branch->name_ar }}
                        </h4>
                        @if($branch->address)
                            <p class="text-gray-500 text-sm mt-2 flex items-start gap-2">
                                <svg class="w-4 h-4 mt-0.5 shrink-0 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"/></svg>
                                {{ $branch->address }}
                            </p>
                        @endif
                        @if($branch->phone)
                            <p class="text-gray-500 text-sm mt-1 flex items-center gap-2" dir="ltr">
                                <svg class="w-4 h-4 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z"/></svg>
                                {{ $branch->phone }}
                            </p>
                        @endif
                    </div>
                @endforeach

                @if(empty($branches) || $branches->isEmpty())
                    <div class="p-5 rounded-xl bg-white border border-gray-200 shadow-sm">
                        <div class="flex items-center gap-3">
                            <svg class="w-5 h-5 text-[var(--site-accent)]" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z"/></svg>
                            <span class="text-gray-500 text-sm">{{ $academy->phone ?? 'أضف رقم هاتف من الإعدادات' }}</span>
                        </div>
                    </div>
                @endif

                {{-- Social Links --}}
                @if(is_array($settings->social_links ?? null) && count(array_filter($settings->social_links ?? [])))
                    <div class="p-5 rounded-xl bg-white border border-gray-200 shadow-sm">
                        <h4 class="font-bold text-gray-900 mb-3">تابعنا</h4>
                        <div class="flex items-center gap-3">
                            @foreach(['facebook', 'instagram', 'twitter', 'youtube', 'tiktok'] as $platform)
                                @if(!empty($settings->social_links[$platform]))
                                    <a href="{{ safe_url($settings->social_links[$platform] ?? null) ?: url('/') }}"
                                       target="_blank"
                                       rel="noopener"
                                       class="w-10 h-10 rounded-lg bg-gray-50 border border-gray-200 flex items-center justify-center text-gray-400 hover:text-[var(--site-accent)] hover:border-[var(--site-accent)] transition-all">
                                        @include("website.icons.{$platform}")
                                    </a>
                                @endif
                            @endforeach
                        </div>
                    </div>
                @endif

                {{-- Map Embed --}}
                @if($showMap && $mapEmbed)
                    <div class="rounded-xl overflow-hidden border border-gray-200 shadow-sm">
                        <iframe src="{{ $mapEmbed }}"
                                class="w-full h-52"
                                style="border:0;"
                                allowfullscreen=""
                                loading="lazy"
                                referrerpolicy="no-referrer-when-downgrade"></iframe>
                    </div>
                @endif
            </div>
        </div>
    </div>
</div>
