@extends('frontend.layout')

@php
    $siteName = \App\Helpers\BrandingHelper::name();

    $hero = array_merge([
        'badge'           => __('Talk to our AI assistant'),
        'title_line1'     => __('Meet your AI guide for'),
        'title_highlight' => $siteName,
        'title_line2'     => '',
        'subtitle'        => __('Ask any question, get instant answers, and let our AI agent route you to the right product, plan, or person — live, right now.'),
        'cta_text'        => __('Get Started Free'),
        'cta_url'         => '/register',
        'cta2_text'       => __('See Features'),
        'cta2_url'        => '#features',
    ], is_array($hero ?? null) ? $hero : []);

    $featureItems = $features['items'] ?? [];
    if (! is_array($featureItems) || count($featureItems) === 0) {
        $featureItems = [
            ['title' => __('Always-on AI Agent'),     'desc' => __('Answers visitor questions 24/7 using your business context and the configured model.')],
            ['title' => __('Live Lead Capture'),       'desc' => __('Every chat becomes a structured lead with name, email, company, and use case.')],
            ['title' => __('Unified Inbox'),           'desc' => __('Email, WhatsApp, SMS, Slack, and Telegram in one inbox.')],
            ['title' => __('CRM & Deals'),             'desc' => __('Track contacts, pipelines, and lead activity from first message to closed deal.')],
            ['title' => __('Workflow Automation'),     'desc' => __('No-code triggers, routing, and follow-up automation.')],
            ['title' => __('Analytics Dashboard'),     'desc' => __('Measure conversations, conversions, AI cost, and team performance.')],
        ];
    }

    $testimonialItems = $testimonials['items'] ?? [];
    if (! is_array($testimonialItems) || count($testimonialItems) === 0) {
        $testimonialItems = [
            ['quote' => __('The AI agent on our homepage qualifies leads while we sleep — and the answers actually match our pricing.'), 'name' => 'Marcus Rivera',   'role' => __('CEO'),                 'company' => 'GrowthStack'],
            ['quote' => __('Visitors leave with a clear next step every time. Our demo bookings tripled in three weeks.'),                'name' => 'Emily Watson',    'role' => __('Marketing Director'),  'company' => 'Vertex Labs'],
            ['quote' => __('We replaced two contact forms and a chatbot with one agent — and the inbox finally feels manageable.'),     'name' => 'Raj Patel',       'role' => __('Lead Engineer'),       'company' => 'CloudNine'],
        ];
    }

    $faqItems = $faq['items'] ?? [];
    if (! is_array($faqItems) || count($faqItems) === 0) {
        $faqItems = [
            ['question' => __('How does the AI agent know about my business?'),                   'answer' => __('You add a short business context paragraph under Admin → Frontend Settings → Agent Configuration. The agent uses it to answer accurately and qualify leads.')],
            ['question' => __('Which AI providers are supported?'),                               'answer' => __('OpenAI, Anthropic, Google Gemini, and Mistral. Pick the provider, paste your API key under Admin → AI Providers, and the homepage agent uses it immediately.')],
            ['question' => __('Where do captured leads go?'),                                     'answer' => __('Every chat becomes a row under Admin → Homepage Leads with the full transcript, contact details, status workflow, and CSV export.')],
            ['question' => __('Can I edit the greeting and agent name?'),                         'answer' => __('Yes — both live under Admin → Frontend Settings → Agent Configuration. Changes apply on the next page load.')],
            ['question' => __('What happens if the AI is not configured?'),                       'answer' => __("The homepage still renders the full marketing page with all sections — only the chat panel is replaced with a friendly placeholder until an API key is saved.")],
        ];
    }

    $cta = array_merge([
        'badge'    => __('Ready to automate'),
        'title'    => __('Ready to put an AI agent on your homepage?'),
        'subtitle' => __('Activate it in two minutes, capture leads from the first visitor.'),
        'cta_text' => __('Get Started Free'),
        'cta_url'  => '/register',
    ], is_array($cta ?? null) ? $cta : []);

    // Pricing is driven by the `plans` table — active plans only, sorted by sort_order.
    $plans = \App\Models\Plan::where('is_active', true)
        ->orderBy('sort_order')
        ->orderBy('monthly_price')
        ->get()
        ->map(function ($plan) {
            $monthly = (float) $plan->monthly_price;
            $yearly  = (float) ($plan->yearly_price ?? round($monthly * 12 * 0.8, 0));
            return [
                'name'            => $plan->name,
                'monthly'         => $monthly,
                'yearly'          => $yearly,
                'monthly_display' => \App\Helpers\CurrencyHelper::display($monthly),
                'yearly_display'  => \App\Helpers\CurrencyHelper::display($yearly),
                'desc'            => (string) ($plan->description ?? ''),
                'popular'         => (bool) $plan->is_popular,
                'cta'             => $monthly <= 0
                    ? __('Start Free')
                    : ((stripos($plan->name, 'enterprise') !== false) ? __('Contact Sales') : __('Get Started')),
                'features'        => is_array($plan->features) ? $plan->features : [],
            ];
        })
        ->all();
@endphp

@push('styles')
<style>
    .mh-reveal {
        opacity: 0;
        transform: translateY(26px);
        transition: opacity .75s cubic-bezier(.16,1,.3,1), transform .75s cubic-bezier(.16,1,.3,1);
    }
    .mh-reveal.is-visible { opacity: 1; transform: translateY(0); }
    .mh-grid-bg {
        background-image:
            linear-gradient(color-mix(in srgb, var(--color-border) 34%, transparent) 1px, transparent 1px),
            linear-gradient(90deg, color-mix(in srgb, var(--color-border) 34%, transparent) 1px, transparent 1px);
        background-size: 42px 42px;
    }
    .mh-panel {
        background: color-mix(in srgb, var(--color-surface-2) 92%, transparent);
        border: 1px solid color-mix(in srgb, var(--color-border) 78%, transparent);
        box-shadow: 0 18px 60px rgba(15, 23, 42, .08);
    }
    .dark .mh-panel, [data-theme="dark"] .mh-panel { box-shadow: 0 18px 60px rgba(0, 0, 0, .28); }
    .mh-bento {
        background:
            linear-gradient(135deg, color-mix(in srgb, var(--color-brand) 10%, transparent), transparent 34%),
            linear-gradient(315deg, color-mix(in srgb, var(--color-success) 8%, transparent), transparent 38%),
            var(--color-surface-2);
    }

    /* ── Chat panel ── */
    .chat-card {
        background: var(--color-surface-2);
        border: 1px solid color-mix(in srgb, var(--color-border) 78%, transparent);
        border-radius: 1.5rem;
        box-shadow: 0 24px 70px rgba(15, 23, 42, .12);
    }
    .dark .chat-card, [data-theme="dark"] .chat-card { box-shadow: 0 24px 70px rgba(0, 0, 0, .35); }

    .chat-bubble-in { animation: bubbleIn .22s cubic-bezier(.34,1.56,.64,1) both; }
    @keyframes bubbleIn {
        from { opacity:0; transform: translateY(8px) scale(.96); }
        to   { opacity:1; transform: translateY(0) scale(1); }
    }
    .typing-dot { animation: typingBounce 1.2s infinite; }
    .typing-dot:nth-child(2) { animation-delay: .2s; }
    .typing-dot:nth-child(3) { animation-delay: .4s; }
    @keyframes typingBounce {
        0%,60%,100% { transform: translateY(0); }
        30%         { transform: translateY(-5px); }
    }
    .hide-scroll::-webkit-scrollbar { display: none; }
    .hide-scroll { -ms-overflow-style: none; scrollbar-width: none; }

    @media (prefers-reduced-motion: reduce) {
        .mh-reveal { opacity: 1; transform: none; transition: none; }
        .chat-bubble-in, .typing-dot { animation: none; }
    }
</style>
@endpush

@section('content')
<div class="overflow-hidden text-ink" x-data="{ billingCycle: 'monthly' }">

    {{-- ═══════════════════════════════════════════════════════════════
         HERO — 2 columns: marketing copy + AI chat panel
    ═══════════════════════════════════════════════════════════════ --}}
    <section class="relative mh-grid-bg pt-28 sm:pt-36 lg:pt-40 pb-16 lg:pb-24 overflow-hidden">
        <div class="max-w-7xl mx-auto px-4">
            <div class="grid gap-12 lg:grid-cols-2 lg:items-center">

                {{-- ── LEFT: marketing copy ────────────────────────── --}}
                <div class="mh-reveal text-center lg:text-left">
                    <span class="inline-flex items-center gap-2 px-4 py-1.5 rounded-full text-xs font-semibold bg-brand/10 text-brand border border-brand/20">
                        <span class="w-1.5 h-1.5 rounded-full bg-brand animate-pulse"></span>
                        {{ $hero['badge'] }}
                    </span>
                    <h1 class="mt-6 text-4xl sm:text-5xl lg:text-6xl font-extrabold leading-[1.08] tracking-tight">
                        {{ $hero['title_line1'] }}
                        <span class="gradient-text">{{ $hero['title_highlight'] }}</span>
                        @if(!empty($hero['title_line2']))
                            <br class="hidden sm:block">{{ $hero['title_line2'] }}
                        @endif
                    </h1>
                    <p class="mt-6 text-lg sm:text-xl text-muted max-w-xl mx-auto lg:mx-0 leading-relaxed">
                        {{ $hero['subtitle'] }}
                    </p>

                    <div class="mt-10 flex flex-col sm:flex-row items-center justify-center lg:justify-start gap-4">
                        <a href="{{ url($hero['cta_url']) }}"
                           class="w-full sm:w-auto inline-flex items-center justify-center gap-2 px-8 py-3.5 text-base font-semibold text-white bg-gradient-to-r from-brand to-brand-strong rounded-2xl shadow-lg shadow-brand/25 hover:shadow-brand/40 hover:brightness-110 transition-all">
                            {{ $hero['cta_text'] }}
                            <svg viewBox="0 0 24 24" class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M5 12h14M13 5l7 7-7 7"/></svg>
                        </a>
                        <a href="{{ url($hero['cta2_url']) }}"
                           class="w-full sm:w-auto inline-flex items-center justify-center gap-2 px-8 py-3.5 text-base font-semibold text-ink border border-border bg-surface-2/70 rounded-2xl hover:border-brand/60 hover:bg-surface-2 transition-all">
                            {{ $hero['cta2_text'] }}
                        </a>
                    </div>

                    {{-- Trust pills --}}
                    <div class="mt-10 flex flex-wrap justify-center lg:justify-start gap-2 text-xs text-muted">
                        @foreach([__('No credit card'), __('Self-hosted ready'), __('Live in 2 minutes')] as $pill)
                            <span class="inline-flex items-center gap-1.5 rounded-full border border-border bg-surface-2 px-3 py-1.5 font-semibold">
                                <svg viewBox="0 0 24 24" class="h-3 w-3 text-success" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M5 13l4 4L19 7"/></svg>
                                {{ $pill }}
                            </span>
                        @endforeach
                    </div>
                </div>

                {{-- ── RIGHT: AI chat panel (or fallback placeholder) ── --}}
                <div class="mh-reveal" style="transition-delay: 120ms">
                    @if($agentReady)

                    <div class="chat-card overflow-hidden"
                         x-data="agentChat({
                             agentName: @js($agentName),
                             greeting:  @js($agentGreeting),
                             baseUrl:   @js(url('/')),
                         })"
                         x-init="init()">

                        {{-- Chat header --}}
                        <div class="flex items-center gap-3 px-5 py-4 border-b border-border/60 bg-surface-2/60">
                            <div class="relative">
                                <div class="w-10 h-10 rounded-xl bg-gradient-to-br from-brand to-brand-strong flex items-center justify-center shadow-lg shadow-brand/20">
                                    <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" stroke-width="1.8" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.86 9.86 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"/>
                                    </svg>
                                </div>
                                <span class="absolute -bottom-0.5 -right-0.5 w-3.5 h-3.5 rounded-full bg-emerald-400 border-2 border-surface-2"></span>
                            </div>
                            <div class="flex-1 min-w-0">
                                <p class="text-sm font-bold text-ink leading-tight" x-text="agentName"></p>
                                <p class="text-[11px] text-emerald-500 font-semibold">{{ __('Online · AI Assistant') }}</p>
                            </div>
                            <button x-show="step === 'chat'" @click="resetChat()" x-cloak
                                    class="p-1.5 text-muted hover:text-ink rounded-lg hover:bg-surface transition" title="{{ __('Start over') }}">
                                <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
                            </button>
                        </div>

                        {{-- ── Intro step ────────────────────────────── --}}
                        <div x-show="step === 'intro'" x-cloak class="p-5">
                            <div class="rounded-2xl rounded-tl-sm bg-surface px-4 py-3 mb-4 text-sm text-ink leading-relaxed border border-border/60"
                                 x-text="greeting"></div>

                            <p class="text-[11px] font-bold uppercase tracking-wider text-muted mb-3">{{ __('Start the conversation') }}</p>

                            <div class="grid grid-cols-2 gap-3 mb-3">
                                <div>
                                    <label class="block text-[11px] text-muted mb-1">{{ __('Your name') }} <span class="text-brand">*</span></label>
                                    <input type="text" x-model="visitorName" placeholder="{{ __('e.g. Sarah') }}"
                                           class="w-full bg-surface border border-border rounded-xl px-3 py-2.5 text-sm text-ink placeholder-muted/60 focus:outline-none focus:ring-2 focus:ring-brand/30 focus:border-brand/60 transition">
                                </div>
                                <div>
                                    <label class="block text-[11px] text-muted mb-1">{{ __('Email') }} <span class="text-muted/60">({{ __('optional') }})</span></label>
                                    <input type="email" x-model="visitorEmail" placeholder="{{ __('you@example.com') }}"
                                           class="w-full bg-surface border border-border rounded-xl px-3 py-2.5 text-sm text-ink placeholder-muted/60 focus:outline-none focus:ring-2 focus:ring-brand/30 focus:border-brand/60 transition">
                                </div>
                            </div>

                            <div class="grid grid-cols-2 gap-3 mb-4">
                                <div>
                                    <label class="block text-[11px] text-muted mb-1">{{ __('Company') }} <span class="text-muted/60">({{ __('optional') }})</span></label>
                                    <input type="text" x-model="visitorCompany" placeholder="{{ __('Acme Inc.') }}"
                                           class="w-full bg-surface border border-border rounded-xl px-3 py-2.5 text-sm text-ink placeholder-muted/60 focus:outline-none focus:ring-2 focus:ring-brand/30 focus:border-brand/60 transition">
                                </div>
                                <div>
                                    <label class="block text-[11px] text-muted mb-1">{{ __('What brings you here?') }}</label>
                                    <select x-model="visitorUseCase"
                                            class="w-full bg-surface border border-border rounded-xl px-3 py-2.5 text-sm text-ink focus:outline-none focus:ring-2 focus:ring-brand/30 focus:border-brand/60 transition">
                                        <option value="">{{ __('Select…') }}</option>
                                        <option value="pricing">{{ __('Pricing & plans') }}</option>
                                        <option value="demo">{{ __('Request a demo') }}</option>
                                        <option value="features">{{ __('Feature questions') }}</option>
                                        <option value="support">{{ __('Technical support') }}</option>
                                        <option value="other">{{ __('Something else') }}</option>
                                    </select>
                                </div>
                            </div>

                            <button @click="startChat()" :disabled="starting || !visitorName.trim()"
                                    class="w-full flex items-center justify-center gap-2 py-3 text-sm font-semibold text-white bg-gradient-to-r from-brand to-brand-strong disabled:opacity-60 disabled:cursor-not-allowed rounded-xl shadow-lg shadow-brand/20 hover:brightness-110 transition-all">
                                <template x-if="!starting">
                                    <span class="flex items-center gap-2">
                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.86 9.86 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"/></svg>
                                        {{ __('Chat with') }} <span x-text="agentName"></span>
                                    </span>
                                </template>
                                <template x-if="starting">
                                    <span class="flex items-center gap-2">
                                        <svg class="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="3" opacity=".25"/><path fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"/></svg>
                                        {{ __('Connecting...') }}
                                    </span>
                                </template>
                            </button>
                            <p x-show="startError" x-cloak x-text="startError" class="text-xs text-danger text-center pt-2"></p>
                        </div>

                        {{-- ── Chat step ─────────────────────────────── --}}
                        <div x-show="step === 'chat'" x-cloak class="flex flex-col" style="height: 480px">
                            <div x-ref="messageList" class="flex-1 overflow-y-auto hide-scroll px-4 py-4 space-y-3 bg-surface/40">

                                {{-- Static greeting --}}
                                <div class="flex items-end gap-2 chat-bubble-in">
                                    <div class="w-7 h-7 rounded-lg bg-gradient-to-br from-brand to-brand-strong flex items-center justify-center shrink-0">
                                        <svg class="w-3.5 h-3.5 text-white" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.86 9.86 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"/></svg>
                                    </div>
                                    <div class="max-w-[80%] bg-surface-2 border border-border/60 rounded-2xl rounded-bl-sm px-3.5 py-2.5 text-sm text-ink leading-relaxed" x-text="greeting"></div>
                                </div>

                                {{-- Dynamic messages --}}
                                <template x-for="msg in messages" :key="msg.id">
                                    <div class="chat-bubble-in"
                                         :class="msg.role === 'user' ? 'flex justify-end' : 'flex items-end gap-2'">
                                        <template x-if="msg.role !== 'user'">
                                            <div class="w-7 h-7 rounded-lg bg-gradient-to-br from-brand to-brand-strong flex items-center justify-center shrink-0">
                                                <svg class="w-3.5 h-3.5 text-white" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.86 9.86 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"/></svg>
                                            </div>
                                        </template>
                                        <div class="max-w-[80%] px-3.5 py-2.5 text-sm leading-relaxed whitespace-pre-wrap"
                                             :class="msg.role === 'user'
                                                 ? 'bg-brand text-white rounded-2xl rounded-br-sm'
                                                 : 'bg-surface-2 border border-border/60 text-ink rounded-2xl rounded-bl-sm'"
                                             x-text="msg.body"></div>
                                    </div>
                                </template>

                                {{-- Typing indicator --}}
                                <div x-show="typing" x-cloak class="flex items-end gap-2 chat-bubble-in">
                                    <div class="w-7 h-7 rounded-lg bg-gradient-to-br from-brand to-brand-strong flex items-center justify-center shrink-0">
                                        <svg class="w-3.5 h-3.5 text-white" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.86 9.86 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"/></svg>
                                    </div>
                                    <div class="bg-surface-2 border border-border/60 rounded-2xl rounded-bl-sm px-4 py-3 flex items-center gap-1.5">
                                        <span class="typing-dot w-2 h-2 rounded-full bg-muted block"></span>
                                        <span class="typing-dot w-2 h-2 rounded-full bg-muted block"></span>
                                        <span class="typing-dot w-2 h-2 rounded-full bg-muted block"></span>
                                    </div>
                                </div>
                            </div>

                            <div class="border-t border-border/60 px-3 py-3 flex items-end gap-2 bg-surface-2/60">
                                <textarea x-ref="messageInput" x-model="inputMessage"
                                    @keydown.enter.prevent="if(!$event.shiftKey && inputMessage.trim()) sendMessage()"
                                    @input="autoResize($el)" rows="1"
                                    placeholder="{{ __('Type a message… (Enter to send)') }}"
                                    class="flex-1 bg-surface border border-border rounded-xl px-3.5 py-2.5 text-sm text-ink placeholder-muted/60 focus:outline-none focus:ring-2 focus:ring-brand/30 focus:border-brand/60 transition resize-none overflow-y-auto hide-scroll"
                                    style="min-height: 42px; max-height: 112px;"
                                    :disabled="sending"></textarea>
                                <button @click="if(inputMessage.trim()) sendMessage()"
                                        :disabled="sending || !inputMessage.trim()"
                                        class="shrink-0 w-10 h-10 rounded-xl bg-gradient-to-r from-brand to-brand-strong text-white disabled:opacity-40 disabled:cursor-not-allowed flex items-center justify-center shadow-lg shadow-brand/20 hover:brightness-110 transition-all">
                                    <template x-if="!sending">
                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2.2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"/></svg>
                                    </template>
                                    <template x-if="sending">
                                        <svg class="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="3" opacity=".25"/><path fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"/></svg>
                                    </template>
                                </button>
                            </div>
                        </div>
                    </div>

                    @else
                    {{-- AI not configured — friendly placeholder card --}}
                    <div class="chat-card p-8 text-center space-y-5">
                        <div class="mx-auto w-14 h-14 rounded-2xl bg-brand/10 text-brand flex items-center justify-center">
                            <svg class="w-7 h-7" fill="none" stroke="currentColor" stroke-width="1.6" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.86 9.86 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"/>
                            </svg>
                        </div>
                        <div>
                            <h3 class="text-lg font-bold text-ink">{{ __('AI assistant launching soon') }}</h3>
                            <p class="mt-2 text-sm text-muted leading-relaxed">{{ __("We're activating the AI agent right now. In the meantime, jump straight in — sign up takes less than a minute.") }}</p>
                        </div>
                        <div class="flex flex-col sm:flex-row gap-2.5">
                            <a href="{{ url('/register') }}" class="flex-1 inline-flex items-center justify-center gap-2 px-5 py-3 text-sm font-semibold text-white bg-gradient-to-r from-brand to-brand-strong rounded-xl shadow-lg shadow-brand/20 hover:brightness-110 transition">
                                {{ __('Get Started Free') }}
                            </a>
                            <a href="{{ url('/login') }}" class="flex-1 inline-flex items-center justify-center px-5 py-3 text-sm font-semibold text-ink border border-border rounded-xl hover:border-brand/40 hover:bg-surface-2 transition">
                                {{ __('Sign in') }}
                            </a>
                        </div>
                        @auth
                            @if(auth()->user()->is_admin ?? false)
                                <p class="text-xs text-amber-500 pt-2 border-t border-border/40">
                                    {{ __('Admin tip: paste a provider API key under') }}
                                    <a href="{{ route('admin.ai-providers') }}" class="font-bold hover:underline">{{ __('Admin → AI Providers') }}</a>
                                    {{ __('to activate this chat.') }}
                                </p>
                            @endif
                        @endauth
                    </div>
                    @endif
                </div>
            </div>
        </div>
    </section>

    {{-- ═══════════════════════════════════════════════════════════════
         HOW IT WORKS
    ═══════════════════════════════════════════════════════════════ --}}
    <section id="how-it-works" class="py-20 md:py-28">
        <div class="max-w-7xl mx-auto px-4">
            <div class="text-center max-w-3xl mx-auto mb-12 mh-reveal">
                <span class="inline-flex items-center gap-2 px-3 py-1 rounded-full text-xs font-semibold bg-brand/10 text-brand border border-brand/20 mb-4">{{ __('How it works') }}</span>
                <h2 class="text-3xl sm:text-4xl lg:text-5xl font-extrabold tracking-tight">
                    {{ __('From visitor to') }} <span class="gradient-text italic">{{ __('captured lead.') }}</span>
                </h2>
                <p class="mt-4 text-lg text-muted">{{ __('The AI greets visitors, answers in your voice, qualifies them, and routes the lead straight to your CRM.') }}</p>
            </div>
            <div class="grid gap-4 md:grid-cols-4">
                @foreach([
                    [__('Visitor lands'),  __('Your homepage opens with the AI assistant ready in the hero panel.')],
                    [__('AI talks'),       __('Trained on your business context, it answers product, pricing, and support questions instantly.')],
                    [__('Lead captured'),  __('Name, email, company, use case, and full transcript saved to Homepage Leads.')],
                    [__('Team follows up'), __('Triage in admin, mark contacted/qualified, export to CSV, close the deal.')],
                ] as $index => $step)
                    <div class="mh-reveal relative rounded-2xl border border-border bg-surface-2 p-5 shadow-soft" style="transition-delay: {{ $index * 80 }}ms">
                        <span class="flex h-11 w-11 items-center justify-center rounded-xl bg-brand text-white text-sm font-extrabold">{{ $index + 1 }}</span>
                        <h3 class="mt-5 text-lg font-extrabold text-ink">{{ $step[0] }}</h3>
                        <p class="mt-2 text-sm leading-6 text-muted">{{ $step[1] }}</p>
                    </div>
                @endforeach
            </div>
        </div>
    </section>

    {{-- ═══════════════════════════════════════════════════════════════
         FEATURES (bento grid)
    ═══════════════════════════════════════════════════════════════ --}}
    <section id="features" class="py-20 lg:py-28 border-y border-border/40 bg-surface-2/45">
        <div class="max-w-7xl mx-auto px-4">
            <div class="text-center max-w-3xl mx-auto mb-12 mh-reveal">
                <span class="inline-flex items-center gap-2 px-3 py-1 rounded-full text-xs font-semibold bg-brand/10 text-brand border border-brand/20 mb-4">{{ $features['badge'] ?? __('Features') }}</span>
                <h2 class="text-3xl sm:text-4xl lg:text-5xl font-extrabold tracking-tight">
                    {{ $features['title'] ?? __('Everything you need to convert visitors') }}
                </h2>
                <p class="mt-4 text-lg text-muted">{{ $features['subtitle'] ?? __('A complete CRM + AI agent stack in one self-hosted workspace.') }}</p>
            </div>

            <div class="grid gap-5 lg:grid-cols-12">
                @foreach($featureItems as $index => $item)
                    <article class="mh-reveal mh-bento rounded-2xl border border-border p-5 shadow-soft {{ $index === 0 ? 'lg:col-span-7 lg:row-span-2' : ($index === 1 ? 'lg:col-span-5' : 'lg:col-span-4') }}" style="transition-delay: {{ ($index % 6) * 70 }}ms">
                        <div class="flex items-start justify-between gap-4">
                            <span class="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl {{ ['bg-brand/10 text-brand','bg-success/10 text-success','bg-warning/10 text-warning','bg-info/10 text-info','bg-danger/10 text-danger','bg-secondary-500/10 text-secondary-600'][$index % 6] }}">
                                <svg viewBox="0 0 24 24" class="h-5 w-5" fill="none" stroke="currentColor" stroke-width="1.8"><path d="{{ ['M3 7h18M5 7v10a2 2 0 002 2h10a2 2 0 002-2V7', 'M12 3l2.4 5.6L20 11l-5.6 2.4L12 19l-2.4-5.6L4 11l5.6-2.4L12 3z', 'M4 19V5m0 14h16M8 16V9m5 7V7m5 9v-4', 'M4 6h16M4 12h16M4 18h10', 'M7 8h10M7 12h6m-9 8h16a1 1 0 001-1V5a1 1 0 00-1-1H4a1 1 0 00-1 1v14a1 1 0 001 1z', 'M4 12h4l3-7 4 14 3-7h2'][$index % 6] }}"/></svg>
                            </span>
                            <span class="text-xs font-extrabold text-muted/60">{{ str_pad($index + 1, 2, '0', STR_PAD_LEFT) }}</span>
                        </div>
                        <h3 class="mt-5 text-xl font-extrabold text-ink">{{ $item['title'] ?? '' }}</h3>
                        <p class="mt-3 text-sm leading-7 text-muted">{{ $item['desc'] ?? '' }}</p>
                        @if($index === 0)
                            <div class="mt-6 grid gap-3 sm:grid-cols-3">
                                @foreach([__('Live AI'), __('Lead Capture'), __('CRM Inbox')] as $chip)
                                    <span class="rounded-xl border border-border bg-surface-2 px-3 py-2 text-xs font-bold text-ink">{{ $chip }}</span>
                                @endforeach
                            </div>
                        @endif
                    </article>
                @endforeach
            </div>
        </div>
    </section>

    {{-- ═══════════════════════════════════════════════════════════════
         TESTIMONIALS
    ═══════════════════════════════════════════════════════════════ --}}
    <section id="testimonials" class="py-20 lg:py-28">
        <div class="max-w-7xl mx-auto px-4">
            <div class="text-center max-w-2xl mx-auto mb-12 mh-reveal">
                <span class="inline-flex items-center gap-2 px-3 py-1 rounded-full text-xs font-semibold bg-brand/10 text-brand border border-brand/20 mb-4">{{ __('Testimonials') }}</span>
                <h2 class="text-3xl sm:text-4xl lg:text-5xl font-extrabold tracking-tight">
                    {{ $testimonials['title'] ?? __('Loved by teams worldwide') }}
                </h2>
                <p class="mt-4 text-lg text-muted">{{ $testimonials['subtitle'] ?? __('See what customers say about :brand.', ['brand' => $siteName]) }}</p>
            </div>
            <div class="grid gap-5 lg:grid-cols-3">
                @foreach($testimonialItems as $index => $item)
                    <blockquote class="mh-reveal rounded-2xl border border-border bg-surface-2 p-6 shadow-soft" style="transition-delay: {{ $index * 90 }}ms">
                        <div class="mb-4 flex gap-0.5 text-amber-400">
                            @for($i = 0; $i < 5; $i++)
                                <svg viewBox="0 0 20 20" class="h-4 w-4" fill="currentColor"><path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"/></svg>
                            @endfor
                        </div>
                        <p class="text-sm leading-7 text-ink/80 italic">"{{ $item['quote'] ?? $item['body'] ?? '' }}"</p>
                        <footer class="mt-6 flex items-center gap-3 border-t border-border/40 pt-5">
                            <span class="flex h-10 w-10 items-center justify-center rounded-full bg-brand/10 text-sm font-bold text-brand">{{ substr($item['name'] ?? 'C', 0, 1) }}</span>
                            <div>
                                <div class="text-sm font-semibold text-ink">{{ $item['name'] ?? __('Customer') }}</div>
                                <div class="text-xs text-muted">{{ trim(($item['role'] ?? '') . (($item['company'] ?? '') ? ' at ' . $item['company'] : '')) }}</div>
                            </div>
                        </footer>
                    </blockquote>
                @endforeach
            </div>
        </div>
    </section>

    {{-- ═══════════════════════════════════════════════════════════════
         PRICING
    ═══════════════════════════════════════════════════════════════ --}}
    @if(count($plans))
    <section id="pricing" class="py-20 lg:py-28 border-y border-border/40 bg-surface-2/45 relative">
        <div class="absolute inset-0 bg-gradient-to-b from-transparent via-brand/5 to-transparent -z-10" aria-hidden="true"></div>
        <div class="max-w-7xl mx-auto px-4">
            <div class="text-center max-w-2xl mx-auto mb-12 lg:mb-16 mh-reveal">
                <span class="inline-flex items-center gap-2 px-3 py-1 rounded-full text-xs font-semibold bg-brand/10 text-brand border border-brand/20 mb-4">{{ __('Pricing') }}</span>
                <h2 class="text-3xl sm:text-4xl lg:text-5xl font-extrabold tracking-tight">
                    {{ __('Simple,') }} <span class="gradient-text">{{ __('transparent') }}</span> {{ __('pricing') }}
                </h2>
                <p class="mt-4 text-lg text-muted">{{ __("Start free, upgrade when you're ready. No hidden fees.") }}</p>

                <div class="mt-8 inline-flex items-center gap-3 bg-surface-2 border border-border/50 rounded-2xl p-1.5">
                    <button @click="billingCycle = 'monthly'"
                            :class="billingCycle === 'monthly' ? 'bg-brand text-white shadow-lg shadow-brand/20' : 'text-muted hover:text-ink'"
                            class="px-5 py-2 rounded-xl text-sm font-semibold transition-all">{{ __('Monthly') }}</button>
                    <button @click="billingCycle = 'yearly'"
                            :class="billingCycle === 'yearly' ? 'bg-brand text-white shadow-lg shadow-brand/20' : 'text-muted hover:text-ink'"
                            class="px-5 py-2 rounded-xl text-sm font-semibold transition-all flex items-center gap-2">
                        {{ __('Yearly') }}
                        <span class="text-[10px] px-1.5 py-0.5 rounded-full bg-success/20 text-success font-bold" :class="billingCycle === 'yearly' ? 'bg-white/20 text-white' : ''">{{ __('Save 20%') }}</span>
                    </button>
                </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-5 lg:gap-6">
                @foreach($plans as $index => $plan)
                    <div class="mh-reveal relative rounded-2xl border bg-surface-2/80 p-6 flex flex-col {{ $plan['popular'] ? 'pricing-popular border-brand' : 'border-border/50' }}" style="transition-delay: {{ $index * 80 }}ms">
                        @if($plan['popular'])
                            <div class="absolute -top-3 left-1/2 -translate-x-1/2">
                                <span class="px-4 py-1 rounded-full bg-brand text-white text-xs font-bold shadow-lg shadow-brand/30">{{ __('Most Popular') }}</span>
                            </div>
                        @endif
                        <div class="mb-5">
                            <h3 class="text-lg font-bold text-ink">{{ $plan['name'] }}</h3>
                            <p class="text-sm text-muted mt-1">{{ $plan['desc'] }}</p>
                        </div>
                        <div class="mb-6">
                            <div class="flex items-baseline gap-1">
                                <span class="text-4xl font-extrabold text-ink" x-text="billingCycle === 'monthly' ? @js($plan['monthly_display']) : @js($plan['yearly_display'])">{{ $plan['monthly_display'] }}</span>
                                @if($plan['monthly'] > 0)<span class="text-sm text-muted">{{ __('/mo') }}</span>@endif
                            </div>
                        </div>
                        <div class="space-y-2.5 flex-1 mb-6">
                            @foreach($plan['features'] as $feature)
                                <div class="flex items-center gap-2.5 text-sm">
                                    <svg class="w-4 h-4 text-success shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path d="m4.5 12.75 6 6 9-13.5"/></svg>
                                    <span class="text-ink/80">{{ $feature }}</span>
                                </div>
                            @endforeach
                        </div>
                        <a href="{{ url($plan['name'] === __('Enterprise') ? '/contact' : '/register') }}"
                           class="block text-center px-5 py-3 rounded-xl text-sm font-semibold transition-all mt-auto {{ $plan['popular'] ? 'bg-gradient-to-r from-brand to-brand-strong text-white shadow-lg shadow-brand/20 hover:shadow-brand/40 hover:brightness-110' : 'border border-border text-ink hover:border-brand/40 hover:bg-brand/5' }}">
                            {{ $plan['cta'] }}
                        </a>
                    </div>
                @endforeach
            </div>
        </div>
    </section>
    @endif

    {{-- ═══════════════════════════════════════════════════════════════
         FAQ
    ═══════════════════════════════════════════════════════════════ --}}
    @if(count($faqItems))
    <section id="faq" class="py-20 lg:py-28">
        <div class="max-w-4xl mx-auto px-4">
            <div class="text-center mb-10 mh-reveal">
                <span class="inline-flex items-center gap-2 px-3 py-1 rounded-full text-xs font-semibold bg-brand/10 text-brand border border-brand/20 mb-4">{{ __('FAQ') }}</span>
                <h2 class="text-3xl sm:text-4xl lg:text-5xl font-extrabold tracking-tight">{{ $faq['title'] ?? __('Frequently Asked Questions') }}</h2>
                @if(!empty($faq['subtitle']))
                    <p class="mt-4 text-lg text-muted">{{ $faq['subtitle'] }}</p>
                @endif
            </div>
            <div class="space-y-3">
                @foreach($faqItems as $index => $item)
                    <details class="mh-reveal group rounded-2xl border border-border bg-surface-2 p-5 shadow-soft" style="transition-delay: {{ $index * 60 }}ms">
                        <summary class="flex cursor-pointer list-none items-center justify-between gap-4 text-base font-bold text-ink">
                            {{ $item['question'] ?? '' }}
                            <span class="rounded-lg border border-border p-1 text-muted transition group-open:rotate-45">
                                <svg viewBox="0 0 24 24" class="h-4 w-4" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 5v14M5 12h14"/></svg>
                            </span>
                        </summary>
                        <p class="mt-4 text-sm leading-7 text-muted">{{ $item['answer'] ?? '' }}</p>
                    </details>
                @endforeach
            </div>
        </div>
    </section>
    @endif

    {{-- ═══════════════════════════════════════════════════════════════
         FINAL CTA
    ═══════════════════════════════════════════════════════════════ --}}
    <section class="py-20 lg:py-28 border-t border-border/40">
        <div class="max-w-7xl mx-auto px-4">
            <div class="mh-reveal rounded-3xl p-10 sm:p-14 lg:p-20 text-center relative overflow-hidden bg-surface-2 border border-border/50">
                <div class="relative z-10">
                    <div class="inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-brand/10 border border-brand/20 mb-6">
                        <span class="relative flex h-2 w-2"><span class="animate-ping absolute inset-0 rounded-full bg-green-400 opacity-75"></span><span class="relative inline-flex rounded-full h-2 w-2 bg-green-400"></span></span>
                        <span class="text-sm font-medium text-muted">{{ $cta['badge'] ?? '' }}</span>
                    </div>
                    <h2 class="text-3xl sm:text-4xl lg:text-5xl font-extrabold tracking-tight max-w-3xl mx-auto">{{ $cta['title'] }}</h2>
                    <p class="mt-5 text-lg text-muted max-w-2xl mx-auto leading-relaxed">{{ $cta['subtitle'] }}</p>
                    <div class="mt-10 flex flex-col sm:flex-row items-center justify-center gap-4">
                        <a href="{{ url($cta['cta_url'] ?? '/register') }}" class="group w-full sm:w-auto inline-flex items-center justify-center gap-2 px-8 py-3.5 text-base font-bold rounded-2xl bg-gradient-to-r from-brand to-brand-strong text-white shadow-lg shadow-brand/20 hover:shadow-brand/40 hover:brightness-110 transition-all">
                            {{ $cta['cta_text'] ?? __('Get Started Free') }}
                            <svg class="w-4 h-4 group-hover:translate-x-0.5 transition-transform" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.5 4.5 21 12m0 0-7.5 7.5M21 12H3"/></svg>
                        </a>
                        <a href="#pricing" class="w-full sm:w-auto inline-flex items-center justify-center gap-2 px-8 py-3.5 text-base font-semibold text-ink border border-border rounded-2xl hover:border-brand/40 hover:bg-brand/5 transition-all">
                            {{ __('View Pricing') }}
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>
@endsection

@push('scripts')
<script>
// Reveal-on-scroll for .mh-reveal elements
document.addEventListener('DOMContentLoaded', function () {
    var items = document.querySelectorAll('.mh-reveal');
    if (!('IntersectionObserver' in window)) {
        items.forEach(function (item) { item.classList.add('is-visible'); });
        return;
    }
    var observer = new IntersectionObserver(function (entries) {
        entries.forEach(function (entry) {
            if (entry.isIntersecting) {
                entry.target.classList.add('is-visible');
                observer.unobserve(entry.target);
            }
        });
    }, { threshold: 0.12, rootMargin: '0px 0px -30px 0px' });
    items.forEach(function (item) { observer.observe(item); });
});
</script>

@if($agentReady)
<script>
function agentChat({ agentName, greeting, baseUrl }) {
    return {
        step: 'intro',
        agentName,
        greeting,

        // intro form
        visitorName: '',
        visitorEmail: '',
        visitorCompany: '',
        visitorUseCase: '',
        starting: false,
        startError: '',

        // chat
        messages: [],
        inputMessage: '',
        sending: false,
        typing: false,

        headers() {
            return {
                'Content-Type':     'application/json',
                'Accept':           'application/json',
                'X-CSRF-TOKEN':     document.querySelector('meta[name="csrf-token"]')?.content ?? '',
                'X-Requested-With': 'XMLHttpRequest',
            };
        },

        init() {
            window.addEventListener('beforeunload', () => {});
        },

        autoResize(el) {
            el.style.height = 'auto';
            el.style.height = Math.min(el.scrollHeight, 112) + 'px';
        },

        async startChat() {
            if (this.starting || !this.visitorName.trim()) return;
            this.starting = true;
            this.startError = '';

            try {
                const res = await fetch(baseUrl + '/agent-chat/start', {
                    method: 'POST',
                    credentials: 'same-origin',
                    headers: this.headers(),
                    body: JSON.stringify({
                        name:     this.visitorName.trim(),
                        email:    this.visitorEmail.trim() || null,
                        company:  this.visitorCompany.trim() || null,
                        use_case: this.visitorUseCase || null,
                        page_url: window.location.href,
                    }),
                });

                if (!res.ok) {
                    const json = await res.json().catch(() => ({}));
                    this.startError = json.message || `Server error (${res.status}). Please try again.`;
                    return;
                }
                const json = await res.json();
                if (!json.success) {
                    this.startError = json.message || 'Could not connect. Please try again.';
                    return;
                }

                this.step = 'chat';
                this.$nextTick(() => {
                    this.$refs.messageInput?.focus();
                    this.scrollToBottom();
                });
            } catch (e) {
                this.startError = 'Network error. Please check your connection and try again.';
            } finally {
                this.starting = false;
            }
        },

        async resetChat() {
            this.sending = false;
            this.typing = false;
            this.messages = [];
            this.inputMessage = '';
            this.startError = '';
            this.step = 'intro';
            try {
                await fetch(baseUrl + '/agent-chat/reset', {
                    method: 'POST',
                    credentials: 'same-origin',
                    headers: this.headers(),
                });
            } catch (e) { /* ignore */ }
        },

        async sendMessage() {
            const body = this.inputMessage.trim();
            if (!body || this.sending) return;
            this.sending = true;
            this.inputMessage = '';
            if (this.$refs.messageInput) this.$refs.messageInput.style.height = '42px';

            const tempId = 'temp-' + Date.now();
            this.messages.push({ id: tempId, role: 'user', body });
            this.scrollToBottom();

            this.typing = true;
            this.scrollToBottom();

            try {
                const res = await fetch(baseUrl + '/agent-chat/send', {
                    method: 'POST',
                    credentials: 'same-origin',
                    headers: this.headers(),
                    body: JSON.stringify({ message: body }),
                });

                if (res.status === 401) {
                    this.typing = false;
                    this.messages = [];
                    this.step = 'intro';
                    this.startError = 'Your chat session expired. Please start a new chat.';
                    return;
                }

                const json = await res.json().catch(() => ({}));
                if (!res.ok || !json.success) {
                    this.typing = false;
                    this.messages.push({
                        id: 'err-' + Date.now(),
                        role: 'agent',
                        body: json.message || 'Sorry, I could not process that. Please try again.',
                    });
                    this.scrollToBottom();
                    return;
                }

                const data = json.data || {};
                this.messages = this.messages.filter(m => m.id !== tempId);
                if (data.user_message)  this.messages.push(data.user_message);
                this.typing = false;
                if (data.agent_reply)   this.messages.push(data.agent_reply);
                this.scrollToBottom();
            } catch (e) {
                this.typing = false;
                this.messages.push({
                    id: 'err-' + Date.now(),
                    role: 'agent',
                    body: 'Network error — please check your connection and try again.',
                });
                this.scrollToBottom();
            } finally {
                this.sending = false;
                this.$nextTick(() => this.$refs.messageInput?.focus());
            }
        },

        scrollToBottom() {
            this.$nextTick(() => {
                const el = this.$refs.messageList;
                if (el) el.scrollTop = el.scrollHeight;
            });
        },
    };
}
</script>
@endif
@endpush
