<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <meta name="description" content="@yield('meta_description', 'Texora — All-in-One Compliance & Tax Platform for Pakistan and International businesses.')">
    <title>@yield('title', App\Models\SiteSetting::getValue('site_name', 'Texora')) — {{ App\Models\SiteSetting::getValue('site_tagline', 'All-in-One Compliance & Tax Platform') }}</title>

    @php
        $favicon = App\Models\SiteSetting::getValue('site_favicon');
        
        // Helper to convert hex to rgb for Tailwind rgba() support
        $hexToRgb = function($hex) {
            $hex = str_replace('#', '', $hex);
            if(strlen($hex) == 3) {
                $r = hexdec(substr($hex,0,1).substr($hex,0,1));
                $g = hexdec(substr($hex,1,1).substr($hex,1,1));
                $b = hexdec(substr($hex,2,1).substr($hex,2,1));
            } else {
                $r = hexdec(substr($hex,0,2));
                $g = hexdec(substr($hex,2,2));
                $b = hexdec(substr($hex,4,2));
            }
            return "$r, $g, $b";
        };
    @endphp
    @if($favicon)
        <link rel="icon" type="image/x-icon" href="{{ asset('storage/' . $favicon) }}">
    @endif

    {{-- Preconnect fonts --}}
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>

    {{-- Dynamic Theme Overrides --}}
    <style>
        :root {
            @if($cp = App\Models\SiteSetting::getValue('color_primary')) 
                --tx-electric: {{ $cp }}; 
                --color-electric: {{ $cp }};
                --tx-electric-rgb: {{ $hexToRgb($cp) }};
            @endif
            @if($cs = App\Models\SiteSetting::getValue('color_secondary')) 
                --tx-navy: {{ $cs }}; 
                --color-navy: {{ $cs }};
                --tx-navy-rgb: {{ $hexToRgb($cs) }};
            @endif
            @if($ca = App\Models\SiteSetting::getValue('color_accent')) 
                --tx-neon: {{ $ca }}; 
                --color-neon: {{ $ca }};
                --tx-neon-rgb: {{ $hexToRgb($ca) }};
            @endif
            @if($cb = App\Models\SiteSetting::getValue('color_bg_body')) --tx-bg: {{ $cb }}; @endif
        }
        @if($cb = App\Models\SiteSetting::getValue('color_bg_body')) 
        body { background-color: {{ $cb }} !important; } 
        @endif
        @if($ch = App\Models\SiteSetting::getValue('color_bg_header')) 
        .tx-hero, .tx-why, .tx-global, .tx-cta { background-color: {{ $ch }} !important; }
        @endif
    </style>

    {{-- livewire --}}
    @livewireStyles
    @livewireScripts
    {{-- Vite assets --}}
    @vite(['resources/css/app.css', 'resources/js/app.js'])

    {{-- Awwwards-Level Animation Engine (GSAP + Lenis) --}}
    <script defer src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/gsap.min.js"></script>
    <script defer src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/ScrollTrigger.min.js"></script>
    <script defer src="https://unpkg.com/lenis@1.1.14/dist/lenis.min.js"></script>

    @stack('head')
</head>

<body class="antialiased">
    <div class="noise-overlay"></div>

    {{-- Custom cursor (desktop only) --}}
    <div id="tx-cursor" aria-hidden="true"></div>
    <div id="tx-cursor-dot" aria-hidden="true"></div>

    {{-- Navbar --}}
    @include('frontend.partials.navbar')

    {{-- Flash messages --}}
    @if(session('success'))
        <div class="fixed top-20 right-4 z-50 bg-emerald text-white px-6 py-3 rounded-xl shadow-lg flex items-center gap-2 animate-fade-in"
             x-data x-init="setTimeout(() => $el.remove(), 4000)">
            <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd"/></svg>
            {{ session('success') }}
        </div>
    @endif

    @if(session('error'))
        <div class="fixed top-20 right-4 z-50 bg-red-500 text-white px-6 py-3 rounded-xl shadow-lg flex items-center gap-2 animate-fade-in"
             x-data x-init="setTimeout(() => $el.remove(), 5000)">
            <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clip-rule="evenodd"/></svg>
            {{ session('error') }}
        </div>
    @endif

    {{-- Page content --}}
    @yield('content')

    {{-- Footer --}}
    @include('frontend.partials.footer')

    {{-- Master Conversion Engine (Chat + Lead + Help) --}}
    @include('frontend.partials.conversion-engine')

    {{-- Global premium interactions --}}
    <script>
    // ── Lenis Smooth Scroll ───────────────────────────────
    let lenis;
    document.addEventListener('DOMContentLoaded', () => {
        const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
        const compactDevice = window.matchMedia('(max-width: 767px)').matches;

        if (typeof Lenis !== 'undefined' && !reducedMotion && !compactDevice) {
            lenis = new Lenis({
                lerp: 0.09,
                smoothWheel: true,
                syncTouch: false,
            });
            // Connect Lenis to GSAP ScrollTrigger
            if (typeof ScrollTrigger !== 'undefined' && typeof gsap !== 'undefined') {
                lenis.on('scroll', ScrollTrigger.update);
                gsap.ticker.add((time) => lenis.raf(time * 1000));
                gsap.ticker.lagSmoothing(0);

                // Force refresh on content changes
                window.addEventListener('resize', () => lenis.resize());
                document.addEventListener('lenis-refresh', () => lenis.resize());
                
                // Safety: periodically check height for first 5 seconds (until all dynamic blocks settle)
                let attempts = 0;
                const refreshInterval = setInterval(() => {
                    lenis.resize();
                    if (++attempts > 10) clearInterval(refreshInterval);
                }, 500);
            } else {
                function raf(time) { lenis.raf(time); requestAnimationFrame(raf); }
                requestAnimationFrame(raf);
            }
        }

        // ── IntersectionObserver (lightweight fallback) ───
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) entry.target.classList.add('visible');
            });
        }, { threshold: 0.1 });
        document.querySelectorAll('.animate-on-scroll').forEach(el => observer.observe(el));

        // ── Custom Cursor (desktop only) ─────────────────
        if (typeof gsap !== 'undefined' && window.innerWidth > 1024) {
            const cursor    = document.getElementById('tx-cursor');
            const cursorDot = document.getElementById('tx-cursor-dot');
            if (cursor && cursorDot) {
                let mx = 0, my = 0;
                window.addEventListener('mousemove', e => {
                    mx = e.clientX; my = e.clientY;
                    gsap.to(cursorDot, { x: mx, y: my, duration: 0.1, ease: 'none' });
                    gsap.to(cursor,    { x: mx, y: my, duration: 0.55, ease: 'power3.out' });
                });
                // Enlarge on interactive elements
                document.querySelectorAll('a, button, .txss-panel, .tx-index__row').forEach(el => {
                    el.addEventListener('mouseenter', () => cursor.classList.add('is-hover'));
                    el.addEventListener('mouseleave', () => cursor.classList.remove('is-hover'));
                });
                // Hide on leave
                document.addEventListener('mouseleave', () => {
                    cursor.style.opacity = '0';
                    cursorDot.style.opacity = '0';
                });
                document.addEventListener('mouseenter', () => {
                    cursor.style.opacity = '1';
                    cursorDot.style.opacity = '1';
                });
            }
        }

        // ── Magnetic Buttons ──────────────────────────────
        if (typeof gsap !== 'undefined' && window.innerWidth > 1024) {
            document.querySelectorAll('.tx-btn-primary, .tx-btn-ghost, .txss-cta-btn').forEach(btn => {
                btn.addEventListener('mousemove', e => {
                    const r = btn.getBoundingClientRect();
                    const x = (e.clientX - r.left - r.width  / 2) * 0.22;
                    const y = (e.clientY - r.top  - r.height / 2) * 0.22;
                    gsap.to(btn, { x, y, duration: 0.35, ease: 'power2.out' });
                });
                btn.addEventListener('mouseleave', () => {
                    gsap.to(btn, { x: 0, y: 0, duration: 0.6, ease: 'elastic.out(1, 0.4)' });
                });
            });
        }
    });
    </script>
    @stack('scripts')
</body>
</html>
