<x-front-layout>
@php
    $storeName = \App\Models\Setting::where('key', 'store_name')->value('value') ?? 'DigiShop';
    $pageDesc = $page->meta_description ? strip_tags($page->meta_description) : strip_tags(Str::limit($page->content ?? '', 160));
@endphp
@section('title', $page->title . ' - ' . $storeName)
@section('meta_description', Str::limit($pageDesc, 160))
@php
    $allPages = \App\Models\Page::published()->orderBy('title')->get();
    $waNum    = preg_replace('/[^0-9]/', '', \App\Models\Setting::where('key', 'whatsapp_number')->value('value') ?? '');
@endphp

<div>
    {{-- Page Hero Strip --}}
    <div class="relative bg-white border-b border-gray-100 overflow-hidden" id="page-hero">
        {{-- Subtle Abstract Background Pattern/Gradient --}}
        <div class="absolute inset-0 bg-[linear-gradient(to_right,#8080800a_1px,transparent_1px),linear-gradient(to_bottom,#8080800a_1px,transparent_1px)] bg-[size:14px_24px] [mask-image:radial-gradient(ellipse_60%_50%_at_50%_0%,#000_70%,transparent_100%)]"></div>
        <div class="absolute right-0 top-0 -mr-20 -mt-20 w-64 h-64 rounded-full bg-orange-50/70 blur-3xl pointer-events-none"></div>

        <div class="relative max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-10 sm:py-14">

            {{-- Breadcrumb --}}
            <nav class="flex items-center gap-1.5 text-xs font-semibold text-slate-400 mb-5">
                <a href="{{ route('home') }}" class="hover:text-orange-600 transition-colors">Beranda</a>
                <svg class="w-3.5 h-3.5 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7" />
                </svg>
                <span class="text-slate-600 truncate" id="hero-breadcrumb">{{ $page->title }}</span>
            </nav>

            <h1 class="text-3xl sm:text-4xl font-black text-slate-900 tracking-tight leading-tight" id="hero-title">
                {{ $page->title }}
            </h1>

            <p class="mt-3 text-base text-slate-500 leading-relaxed max-w-2xl hidden" id="hero-desc">{{ $page->meta_description }}</p>

            @if($page->meta_description)
            <script>
                document.querySelector('#hero-desc').textContent = @json($page->meta_description);
                document.querySelector('#hero-desc').classList.remove('hidden');
            </script>
            @endif

            <div class="mt-4 flex items-center gap-1.5 text-xs text-slate-400">
                <svg class="w-3.5 h-3.5 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                </svg>
                <span id="hero-date">Diperbarui: {{ $page->updated_at->translatedFormat('d F Y') }}</span>
            </div>
        </div>
    </div>

    {{-- Main Content Area --}}
    <div class="bg-[#f8f9fb] py-8">
        <div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="grid grid-cols-1 lg:grid-cols-4 gap-8">

                {{-- Main Content Card --}}
                <div class="lg:col-span-3">
                    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-8 sm:p-10 relative">

                        {{-- Loading overlay --}}
                        <div id="page-loading" class="absolute inset-0 bg-white/80 rounded-2xl flex items-center justify-center hidden z-10">
                            <div class="flex items-center gap-2.5 text-sm text-slate-500 font-medium">
                                <svg class="w-5 h-5 text-orange-500 animate-spin" fill="none" viewBox="0 0 24 24">
                                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
                                </svg>
                                Memuat halaman...
                            </div>
                        </div>

                        {{-- Actual Content --}}
                        <div id="page-content-body" class="prose prose-slate max-w-none
                            prose-headings:font-extrabold prose-headings:text-slate-900 prose-headings:tracking-tight
                            prose-h1:text-2xl prose-h2:text-xl prose-h3:text-lg prose-h4:text-base
                            prose-p:text-slate-600 prose-p:leading-relaxed prose-p:text-[15px]
                            prose-li:text-[15px] prose-li:text-slate-600 prose-li:leading-relaxed prose-li:my-0.5
                            prose-a:text-orange-600 prose-a:font-semibold prose-a:no-underline hover:prose-a:underline
                            prose-strong:text-slate-800
                            prose-blockquote:border-l-4 prose-blockquote:border-orange-400 prose-blockquote:bg-orange-50/60 prose-blockquote:rounded-r-xl prose-blockquote:py-3 prose-blockquote:px-5 prose-blockquote:not-italic prose-blockquote:text-slate-700
                            prose-code:text-orange-700 prose-code:bg-orange-50 prose-code:rounded-md prose-code:px-1.5 prose-code:py-0.5 prose-code:text-sm prose-code:font-mono prose-code:before:content-none prose-code:after:content-none
                            prose-pre:bg-slate-900 prose-pre:border prose-pre:border-slate-700 prose-pre:rounded-xl prose-pre:text-sm prose-pre:shadow-none
                            prose-img:rounded-xl prose-img:shadow-sm prose-img:my-6
                            prose-hr:border-gray-100 prose-hr:my-8
                            prose-table:text-sm prose-thead:bg-gray-50 prose-th:text-slate-600 prose-th:font-bold prose-td:text-slate-600">
                            @if($page->content)
                                {!! clean($page->content) !!}
                            @else
                            <div class="flex flex-col items-center justify-center py-20 text-center">
                                <svg class="w-12 h-12 text-slate-200 mb-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                                </svg>
                                <p class="text-sm text-slate-400 font-medium">Belum ada konten untuk halaman ini.</p>
                            </div>
                            @endif
                        </div>
                    </div>

                    {{-- Back Button --}}
                    <div class="mt-5">
                        <a href="{{ route('home') }}"
                           class="inline-flex items-center gap-2 px-5 py-2.5 bg-white border border-gray-200 rounded-xl text-sm font-bold text-slate-600 hover:text-slate-900 hover:border-gray-300 transition-colors shadow-sm">
                            <svg class="w-4 h-4 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
                            </svg>
                            Kembali ke Beranda
                        </a>
                    </div>
                </div>

                {{-- Sidebar --}}
                <div class="space-y-4">

                    {{-- Daftar Halaman (SPA Nav) --}}
                    @if($allPages->count() > 0)
                    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
                        <div class="px-5 py-4 border-b border-gray-50">
                            <h3 class="text-[10px] font-black uppercase tracking-widest text-slate-400">Halaman</h3>
                        </div>
                        <ul class="divide-y divide-gray-50" id="page-nav-list">
                            @foreach($allPages as $p)
                            <li>
                                <button
                                    data-slug="{{ $p->slug }}"
                                    data-url="{{ route('page.show', $p->slug) }}"
                                    onclick="loadPage('{{ $p->slug }}', this)"
                                    class="page-nav-item w-full flex items-center gap-3 px-5 py-3.5 text-left group
                                        {{ $page->slug === $p->slug
                                            ? 'bg-orange-50 border-l-2 border-orange-500'
                                            : 'hover:bg-slate-50 border-l-2 border-transparent' }}">
                                    <svg class="w-4 h-4 flex-shrink-0 {{ $page->slug === $p->slug ? 'text-orange-500' : 'text-slate-300 group-hover:text-orange-400' }}" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                                    </svg>
                                    <span class="text-sm font-semibold {{ $page->slug === $p->slug ? 'text-orange-700' : 'text-slate-600 group-hover:text-orange-700' }}">
                                        {{ $p->title }}
                                    </span>
                                </button>
                            </li>
                            @endforeach
                        </ul>
                    </div>
                    @endif

                    {{-- WhatsApp CTA --}}
                    @if($waNum)
                    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-5">
                        <h3 class="text-[10px] font-black uppercase tracking-widest text-slate-400 mb-3">Butuh Bantuan?</h3>
                        <p class="text-sm text-slate-500 mb-4 leading-relaxed">Hubungi kami langsung, kami siap membantu Anda.</p>
                        <a href="https://wa.me/{{ $waNum }}" target="_blank" rel="noopener"
                           class="flex items-center justify-center gap-2 w-full py-2.5 bg-green-500 hover:bg-green-600 text-white text-sm font-bold rounded-xl transition-colors">
                            <svg class="w-4 h-4 flex-shrink-0" fill="currentColor" viewBox="0 0 24 24">
                                <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347z"/>
                                <path d="M12 0C5.373 0 0 5.373 0 12c0 2.124.554 4.121 1.523 5.854L0 24l6.335-1.615A11.945 11.945 0 0012 24c6.627 0 12-5.373 12-12S18.627 0 12 0zm0 21.818a9.818 9.818 0 01-5.013-1.374l-.36-.214-3.73.95.985-3.638-.235-.374A9.818 9.818 0 1112 21.818z"/>
                            </svg>
                            Chat via WhatsApp
                        </a>
                    </div>
                    @endif

                </div>{{-- /sidebar --}}
            </div>{{-- /grid --}}
        </div>{{-- /container --}}
    </div>{{-- /bg section --}}
</div>

{{-- SPA Logic --}}
<script>
const currentSlug = @json($page->slug);

function loadPage(slug, triggerEl) {
    if (slug === currentSlug && !triggerEl) return; // skip if same page on first load

    // Show loading
    document.getElementById('page-loading').classList.remove('hidden');

    fetch(`/api/page/${slug}`, {
        headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }
    })
    .then(r => {
        if (!r.ok) throw new Error('Page not found');
        return r.json();
    })
    .then(data => {
        // Update hero
        document.getElementById('hero-breadcrumb').textContent = data.title;
        document.getElementById('hero-title').textContent = data.title;
        document.getElementById('hero-date').textContent = 'Diperbarui: ' + data.updated_at;

        const descEl = document.getElementById('hero-desc');
        if (data.meta_description) {
            descEl.textContent = data.meta_description;
            descEl.classList.remove('hidden');
        } else {
            descEl.classList.add('hidden');
        }

        // Update content
        const contentEl = document.getElementById('page-content-body');
        if (data.content) {
            contentEl.innerHTML = data.content;
        } else {
            contentEl.innerHTML = `
                <div class="flex flex-col items-center justify-center py-20 text-center">
                    <svg class="w-12 h-12 text-slate-200 mb-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                    </svg>
                    <p class="text-sm text-slate-400 font-medium">Belum ada konten untuk halaman ini.</p>
                </div>`;
        }

        // Update document title
        document.title = data.title;

        // Update URL with History API
        window.history.pushState({ slug: data.slug }, data.title, data.url);

        // Update active state in nav
        document.querySelectorAll('.page-nav-item').forEach(btn => {
            const isActive = btn.dataset.slug === data.slug;
            btn.classList.toggle('bg-orange-50', isActive);
            btn.classList.toggle('border-l-orange-500', isActive);
            btn.classList.toggle('border-l-transparent', !isActive);

            const icon = btn.querySelector('svg');
            const label = btn.querySelector('span');
            if (isActive) {
                icon.classList.add('text-orange-500');
                icon.classList.remove('text-slate-300');
                label.classList.add('text-orange-700');
                label.classList.remove('text-slate-600');
            } else {
                icon.classList.remove('text-orange-500');
                icon.classList.add('text-slate-300');
                label.classList.remove('text-orange-700');
                label.classList.add('text-slate-600');
            }
        });

        // Scroll to top of content smoothly
        document.getElementById('page-hero').scrollIntoView({ behavior: 'smooth', block: 'start' });
    })
    .catch(() => {
        // Fallback: navigate normally
        window.location.href = `/page/${slug}`;
    })
    .finally(() => {
        document.getElementById('page-loading').classList.add('hidden');
    });
}

// Handle browser back/forward
window.addEventListener('popstate', (e) => {
    if (e.state && e.state.slug) {
        loadPage(e.state.slug, null);
    }
});

// Set initial history state so back button works from first page
window.history.replaceState({ slug: currentSlug }, document.title, window.location.href);
</script>
</x-front-layout>

