<x-layouts.site>
    <x-slot:title>Book a Consultation</x-slot:title>
    <x-slot:description>Book a one-on-one consultation with the Money-Wise team, debt, investing, corporate wellness or your diaspora plan. Four quick steps.</x-slot:description>

    <div class="relative min-h-[calc(100vh-4.75rem)] overflow-hidden bg-mesh" x-data="consultFlow()">
        <div class="blob -left-32 top-20 h-80 w-80 bg-wise-300/30" aria-hidden="true"></div>
        <div class="blob -right-24 bottom-10 h-72 w-72 bg-navy-200/40" aria-hidden="true"></div>

        <div class="container-site section relative max-w-4xl">
            <div class="mx-auto max-w-2xl text-center" data-hero>
                <span class="icon-tile mx-auto h-20 w-20 bg-wise-400 text-navy-950 shadow-wise" data-hero-item><x-icon name="calendar" class="h-9 w-9" /></span>
                <h1 class="mt-4 font-display text-display-sm font-bold text-navy-900" data-hero-item>Book a consultation</h1>
                <p class="mt-3 text-lg text-navy-600" data-hero-item>Four quick steps. A real conversation. No judgement, no jargon.</p>
            </div>

            {{-- Progress steps --}}
            <div class="mx-auto mt-8 flex max-w-lg items-center justify-between" x-show="!done">
                <template x-for="(s, i) in ['Who you are', 'What you need', 'Your details', 'Confirm']" :key="i">
                    <div class="flex flex-1 items-center">
                        <div class="flex flex-col items-center gap-1.5" :class="i > 0 && 'flex-1'">
                            <span class="grid h-9 w-9 place-items-center rounded-full font-display text-sm font-extrabold transition-all duration-300"
                                  :class="step > i ? 'bg-emerald-500 text-white' : (step === i ? 'bg-wise-400 text-navy-950 shadow-wise scale-110' : 'bg-white text-navy-300 ring-2 ring-navy-100')">
                                <span x-show="step <= i" x-text="i + 1"></span>
                                <svg x-show="step > i" class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg>
                            </span>
                            <span class="hidden text-[10px] font-bold uppercase tracking-wide sm:block" :class="step >= i ? 'text-navy-700' : 'text-navy-300'" x-text="s"></span>
                        </div>
                        <div x-show="i < 3" class="mx-2 h-0.5 flex-1 rounded-full" :class="step > i ? 'bg-emerald-400' : 'bg-navy-100'"></div>
                    </div>
                </template>
            </div>

            {{-- ============ STEP 0: segment ============ --}}
            <div x-show="step === 0 && !done" class="mt-10">
                <h2 class="text-center font-display text-xl font-bold text-navy-900">Who are we talking to?</h2>
                <div class="mt-6 grid gap-4 sm:grid-cols-3">
                    @foreach ([
                        ['key' => 'individual', 'img' => 'stock/individuals.jpg', 'title' => 'Me & my family', 'desc' => 'Personal money, debt, savings, investing'],
                        ['key' => 'corporate', 'img' => 'stock/corporate.jpg', 'title' => 'My company or group', 'desc' => 'Staff wellness, chama or investor education'],
                        ['key' => 'diaspora', 'img' => 'stock/diaspora.jpg', 'title' => 'I live abroad', 'desc' => 'Investing back home, cross-border plans'],
                    ] as $seg)
                        <button @click="form.segment = '{{ $seg['key'] }}'; nextStep()"
                                class="card-photo group block h-56 text-left ring-2 transition"
                                :class="form.segment === '{{ $seg['key'] }}' ? 'ring-wise-500' : 'ring-transparent'">
                            <img src="{{ asset('images/'.$seg['img']) }}" alt="">
                            <span class="overlay !p-5">
                                <span class="font-display text-lg font-bold text-white">{{ $seg['title'] }}</span>
                                <span class="mt-1 text-xs text-navy-100">{{ $seg['desc'] }}</span>
                                <span class="mt-2.5 inline-flex items-center gap-1 text-sm font-bold text-wise-300">
                                    Choose <x-icon name="arrow-right" class="h-3.5 w-3.5 transition-transform group-hover:translate-x-1" />
                                </span>
                            </span>
                        </button>
                    @endforeach
                </div>
            </div>

            {{-- ============ STEP 1: topic ============ --}}
            <div x-show="step === 1 && !done" x-cloak class="mt-10">
                <h2 class="text-center font-display text-xl font-bold text-navy-900">What should we focus on?</h2>
                <div class="mx-auto mt-6 grid max-w-2xl gap-3 sm:grid-cols-2">
                    <template x-for="t in topicsFor()" :key="t.key">
                        <button @click="form.topic = t.key; nextStep()"
                                class="answer-card" :class="form.topic === t.key && 'selected'">
                            <span class="icon-tile !h-11 !w-11" x-html="icon(t.icon)"></span>
                            <span class="flex-1">
                                <span class="block font-display font-bold text-navy-900" x-text="t.title"></span>
                                <span class="text-sm text-navy-500" x-text="t.desc"></span>
                            </span>
                        </button>
                    </template>
                </div>
                <div class="mt-6 text-center">
                    <button @click="step = 0" class="btn-ghost btn-sm"><x-icon name="arrow-left" class="h-4 w-4" /> Back</button>
                </div>
            </div>

            {{-- ============ STEP 2: details ============ --}}
            <div x-show="step === 2 && !done" x-cloak class="mx-auto mt-10 max-w-xl">
                <div class="card space-y-5 p-7">
                    <div class="grid gap-5 sm:grid-cols-2">
                        <div>
                            <label class="mb-1 block text-sm font-semibold text-navy-700">Your name *</label>
                            <input type="text" x-model="form.name" placeholder="e.g. Amina Otieno"
                                   class="w-full rounded-2xl border-navy-200 px-4 py-3 focus:border-wise-400 focus:ring-wise-400">
                        </div>
                        <div>
                            <label class="mb-1 block text-sm font-semibold text-navy-700">Email *</label>
                            <input type="email" x-model="form.email" placeholder="you@example.com"
                                   class="w-full rounded-2xl border-navy-200 px-4 py-3 focus:border-wise-400 focus:ring-wise-400">
                        </div>
                    </div>
                    <div class="grid gap-5 sm:grid-cols-2">
                        <div>
                            <label class="mb-1 block text-sm font-semibold text-navy-700">Phone / WhatsApp</label>
                            <input type="tel" x-model="form.phone" placeholder="+254 …"
                                   class="w-full rounded-2xl border-navy-200 px-4 py-3 focus:border-wise-400 focus:ring-wise-400">
                        </div>
                        <div>
                            <label class="mb-1 block text-sm font-semibold text-navy-700">Country</label>
                            <select x-model="form.country" class="w-full rounded-2xl border-navy-200 px-4 py-3 focus:border-wise-400 focus:ring-wise-400">
                                <option value="">Select…</option>
                                @foreach (['Kenya', 'Nigeria', 'Ghana', 'South Africa', 'Tanzania', 'Uganda', 'Rwanda', 'USA', 'UK', 'UAE', 'Other'] as $c)
                                    <option value="{{ $c }}">{{ $c }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>

                    <div>
                        <label class="mb-2 block text-sm font-semibold text-navy-700">How should we reach you? *</label>
                        <div class="grid grid-cols-3 gap-2">
                            <template x-for="m in [['whatsapp','WhatsApp'],['call','Phone call'],['email','Email']]" :key="m[0]">
                                <button @click="form.contact_method = m[0]"
                                        class="rounded-2xl px-3 py-2.5 text-sm font-bold ring-2 transition"
                                        :class="form.contact_method === m[0] ? 'bg-wise-50 text-navy-900 ring-wise-500' : 'bg-white text-navy-500 ring-navy-100 hover:ring-wise-300'"
                                        x-text="m[1]"></button>
                            </template>
                        </div>
                    </div>

                    <div>
                        <label class="mb-2 block text-sm font-semibold text-navy-700">Best time to talk? *</label>
                        <div class="grid grid-cols-3 gap-2">
                            <template x-for="t in [['morning','Morning'],['afternoon','Afternoon'],['evening','Evening']]" :key="t[0]">
                                <button @click="form.preferred_time = t[0]"
                                        class="rounded-2xl px-3 py-2.5 text-sm font-bold ring-2 transition"
                                        :class="form.preferred_time === t[0] ? 'bg-wise-50 text-navy-900 ring-wise-500' : 'bg-white text-navy-500 ring-navy-100 hover:ring-wise-300'"
                                        x-text="t[1]"></button>
                            </template>
                        </div>
                    </div>

                    <div>
                        <label class="mb-1 block text-sm font-semibold text-navy-700">Anything we should know? <span class="font-normal text-navy-400">(optional)</span></label>
                        <textarea x-model="form.message" rows="3" placeholder="Your situation, your goal, your question…"
                                  class="w-full rounded-2xl border-navy-200 px-4 py-3 focus:border-wise-400 focus:ring-wise-400"></textarea>
                    </div>

                    <p x-show="error" x-text="error" class="text-sm font-medium text-rose-600"></p>

                    <div class="flex items-center justify-between gap-3">
                        <button @click="step = 1" class="btn-ghost btn-sm"><x-icon name="arrow-left" class="h-4 w-4" /> Back</button>
                        <button @click="toReview()" class="btn-accent">Review my booking <x-icon name="arrow-right" class="h-4 w-4" /></button>
                    </div>
                </div>
            </div>

            {{-- ============ STEP 3: review ============ --}}
            <div x-show="step === 3 && !done" x-cloak class="mx-auto mt-10 max-w-xl">
                <div class="card p-7">
                    <h2 class="flex items-center gap-2 font-display text-lg font-bold text-navy-900">
                        <x-icon name="check-circle" class="h-5 w-5 text-wise-600" /> One last look
                    </h2>
                    <dl class="mt-4 divide-y divide-navy-100 text-sm">
                        <template x-for="row in reviewRows()" :key="row[0]">
                            <div class="flex items-center justify-between py-2.5">
                                <dt class="font-semibold text-navy-500" x-text="row[0]"></dt>
                                <dd class="font-bold text-navy-900" x-text="row[1]"></dd>
                            </div>
                        </template>
                    </dl>
                    <div class="mt-5 flex items-center justify-between gap-3">
                        <button @click="step = 2" class="btn-ghost btn-sm"><x-icon name="arrow-left" class="h-4 w-4" /> Edit</button>
                        <button @click="submit()" class="btn-accent btn-lg" :disabled="busy">
                            <span x-show="!busy">Book my consultation</span>
                            <span x-cloak x-show="busy">Booking…</span>
                        </button>
                    </div>
                </div>
            </div>

            {{-- ============ SUCCESS ============ --}}
            <div x-show="done" x-cloak x-transition class="mx-auto mt-10 max-w-xl text-center">
                <div class="card p-9">
                    <span class="mx-auto grid h-16 w-16 place-items-center rounded-full bg-emerald-100 text-emerald-600">
                        <x-icon name="check-circle" class="h-8 w-8" />
                    </span>
                    <h2 class="mt-4 font-display text-2xl font-bold text-navy-900">Booked! We'll be in touch.</h2>
                    <p class="mt-2 text-navy-600">
                        Expect to hear from us within one working day, 
                        <span class="font-bold" x-text="form.contact_method === 'whatsapp' ? 'on WhatsApp' : (form.contact_method === 'call' ? 'by phone' : 'by email')"></span>,
                        in the <span class="font-bold" x-text="form.preferred_time"></span>.
                    </p>
                    <div class="mt-6 flex flex-wrap justify-center gap-3">
                        <a href="{{ route('assessments.show', 'financial-health') }}" class="btn-accent">Take the free check while you wait</a>
                        <a href="{{ route('home') }}" class="btn-ghost">Back home</a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    @push('scripts')
    <script>
        function consultFlow() {
            const icon = (paths) => `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="h-5 w-5">${paths}</svg>`;
            const ICONS = @js(collect(\App\Support\IconPaths::MAP)->only(['unlink','trending-up','users','globe','compass','briefcase'])->all());

            return {
                step: 0,
                done: false,
                busy: false,
                error: '',
                form: { segment: '', topic: '', name: '', email: '', phone: '', country: '', contact_method: '', preferred_time: '', message: '' },

                icon(name) { return icon(ICONS[name] ?? ICONS['compass']); },

                topicsFor() {
                    const base = {
                        individual: [
                            { key: 'debt', icon: 'unlink', title: 'Getting out of debt', desc: 'A payoff plan that finally sticks' },
                            { key: 'investing', icon: 'trending-up', title: 'Starting to invest', desc: 'From first savings to a portfolio' },
                            { key: 'coaching', icon: 'compass', title: 'Full money coaching', desc: 'Values, plan, accountability' },
                            { key: 'other', icon: 'users', title: 'Something else', desc: 'Tell us in the next step' },
                        ],
                        corporate: [
                            { key: 'corporate-training', icon: 'briefcase', title: 'Staff financial wellness', desc: 'Programmes & workshops for teams' },
                            { key: 'investing', icon: 'trending-up', title: 'Investor education', desc: 'For SACCOs, chamas & groups' },
                            { key: 'coaching', icon: 'compass', title: 'Leadership coaching', desc: 'Money clarity for decision-makers' },
                            { key: 'other', icon: 'users', title: 'Something else', desc: 'Tell us in the next step' },
                        ],
                        diaspora: [
                            { key: 'diaspora-plan', icon: 'globe', title: 'My cross-border plan', desc: 'Two economies, one strategy' },
                            { key: 'investing', icon: 'trending-up', title: 'Investing back home', desc: 'Verified, remote-friendly vehicles' },
                            { key: 'coaching', icon: 'compass', title: 'Full money coaching', desc: 'Values, plan, accountability' },
                            { key: 'other', icon: 'users', title: 'Something else', desc: 'Tell us in the next step' },
                        ],
                    };
                    return base[this.form.segment] ?? base.individual;
                },

                nextStep() { this.step++; window.scrollTo({ top: 0, behavior: 'smooth' }); },

                toReview() {
                    if (!this.form.name.trim()) { this.error = 'Tell us your name.'; return; }
                    if (!this.form.email.includes('@')) { this.error = 'That email doesn\'t look right.'; return; }
                    if (!this.form.contact_method) { this.error = 'Pick how we should reach you.'; return; }
                    if (!this.form.preferred_time) { this.error = 'Pick the best time to talk.'; return; }
                    this.error = '';
                    this.nextStep();
                },

                reviewRows() {
                    const labels = { individual: 'Me & my family', corporate: 'Company / group', diaspora: 'Living abroad' };
                    const topic = this.topicsFor().find(t => t.key === this.form.topic);
                    return [
                        ['Who', labels[this.form.segment] ?? this.form.segment],
                        ['Focus', topic ? topic.title : this.form.topic],
                        ['Name', this.form.name],
                        ['Email', this.form.email],
                        ['Phone', this.form.phone || ', '],
                        ['Country', this.form.country || ', '],
                        ['Reach me via', this.form.contact_method],
                        ['Best time', this.form.preferred_time],
                    ];
                },

                submit() {
                    this.busy = true;
                    fetch('{{ route('consultation.store') }}', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name=csrf-token]').content },
                        body: JSON.stringify(this.form),
                    })
                        .then(r => { if (!r.ok) throw new Error(); return r.json(); })
                        .then(() => {
                            this.done = true;
                            this.busy = false;
                            window.scrollTo({ top: 0, behavior: 'smooth' });
                            setTimeout(() => window.celebrate?.(), 400);
                        })
                        .catch(() => { this.busy = false; this.error = 'Something went wrong, please try again.'; this.step = 2; });
                },
            };
        }
    </script>
    @endpush
</x-layouts.site>
