<?php

use App\Livewire\LivewireBaseComponent;
use App\Models\WebsiteLegalPage;
use App\Models\WebsiteBuilder;

/**
 * Page Livewire Component
 *
 * Displays individual front pages (Privacy Policy, Terms of Service, Cookie Policy, etc.)
 * Extends LivewireBaseComponent to inherit common data (theme, seo, company, nav, social, footer, services)
 * Includes header and footer sections from website_builder
 */
new class extends LivewireBaseComponent {
    // Page-specific properties
    public ?WebsiteLegalPage $page = null;

    // Header and Footer sections from website_builder
    public ?WebsiteBuilder $headerSection = null;
    public ?WebsiteBuilder $footerSection = null;

    // Flag to track if page was found
    public bool $pageNotFound = false;
    public string $notFoundReason = '';

    public function mount($slug = null, $pageSlug = '')
    {
        // Store website slug
        $this->websiteSlug = $slug;

        // Initialize common data (theme, seo, company, nav, social, footer, services)
        parent::mount($slug);

        // Check if website was found
        if (!$this->frontWebsite) {
            $this->pageNotFound = true;
            $this->notFoundReason = 'website';
        } else {
            // Load the page from database using the slug from route parameter
            $this->loadPage($pageSlug);
        }

        // Load header and footer sections
        $this->loadHeaderFooterSections();

        // Override SEO with page-specific data
        $this->overrideSeo();
    }

    /**
     * Load page from database by slug
     */
    protected function loadPage(string $slug): void
    {
        try {
            $query = WebsiteLegalPage::withoutGlobalScopes()->where('slug', $slug)->where('status', 'active');

            // Filter by website if we have one
            if ($this->frontWebsite) {
                $query->where('website_id', $this->frontWebsite->id);

                // Try to get page for current language first
                $page = (clone $query)->where('website_language_id', $this->currentLangId)->first();

                // Fallback to English if not found
                if (!$page && $this->currentLangKey !== 'en') {
                    $enLang = \App\Models\WebsiteLanguage::withoutGlobalScopes()->where('key', 'en')->where('company_id', $this->frontWebsite->company_id)->first();
                    $page = (clone $query)->where('website_language_id', $enLang?->id)->first();
                }

                // Final fallback: any language
                if (!$page) {
                    $page = $query->first();
                }

                if (!$page) {
                    $this->pageNotFound = true;
                    $this->notFoundReason = 'page';
                    return;
                }

                $this->page = $page;
            } else {
                // No website context - use company-level pages
                $page = $query->whereNull('website_id')->first();
                if (!$page) {
                    $this->pageNotFound = true;
                    $this->notFoundReason = 'page';
                    return;
                }
                $this->page = $page;
            }
        } catch (\Exception $e) {
            $this->pageNotFound = true;
            $this->notFoundReason = 'page';
        }
    }

    /**
     * Load header and footer sections from website_builder
     */
    protected function loadHeaderFooterSections(): void
    {
        try {
            $query = WebsiteBuilder::withoutGlobalScopes()->where('website_language_id', $this->currentLangId);

            if ($this->frontWebsite) {
                $query->where('website_id', $this->frontWebsite->id);
            }

            // Get header section
            $this->headerSection = (clone $query)->where('section_key', 'header')->first();

            // Fallback to English if no header found
            if (!$this->headerSection && $this->currentLangKey !== 'en' && $this->frontWebsite) {
                $enLang = \App\Models\WebsiteLanguage::withoutGlobalScopes()->where('key', 'en')->where('company_id', $this->frontWebsite->company_id)->first();
                $headerQuery = WebsiteBuilder::withoutGlobalScopes()->where('website_language_id', $enLang?->id)->where('section_key', 'header');
                if ($this->frontWebsite) {
                    $headerQuery->where('website_id', $this->frontWebsite->id);
                }
                $this->headerSection = $headerQuery->first();
            }

            // Get footer section
            $this->footerSection = (clone $query)->where('section_key', 'footer')->first();

            // Fallback to English if no footer found
            if (!$this->footerSection && $this->currentLangKey !== 'en' && $this->frontWebsite) {
                $enLang = \App\Models\WebsiteLanguage::withoutGlobalScopes()->where('key', 'en')->where('company_id', $this->frontWebsite->company_id)->first();
                $footerQuery = WebsiteBuilder::withoutGlobalScopes()->where('website_language_id', $enLang?->id)->where('section_key', 'footer');
                if ($this->frontWebsite) {
                    $footerQuery->where('website_id', $this->frontWebsite->id);
                }
                $this->footerSection = $footerQuery->first();
            }
        } catch (\Exception $e) {
            // Silently fail - header/footer will be null
        }
    }

    /**
     * Override SEO metadata with page-specific data
     */
    protected function overrideSeo(): void
    {
        if ($this->pageNotFound) {
            $this->seo = array_merge($this->seo, [
                'title' => 'Page Not Found',
                'description' => 'The requested page could not be found.',
                'keywords' => '',
            ]);
        } elseif ($this->page) {
            $this->seo = array_merge($this->seo, [
                'title' => $this->page->meta_title ?: $this->page->title,
                'description' => $this->page->meta_description ?: '',
                'keywords' => $this->page->meta_keywords ?: '',
            ]);
        }
    }

    /**
     * Get component name for a section
     */
    public function getComponentName(WebsiteBuilder $section): string
    {
        $sectionKey = $section->section_key;
        $layout = $section->section_layout ?? $sectionKey;

        return $this->themeName . '::components.' . $sectionKey . '.' . $layout;
    }

    /**
     * Get standardized props for any section component
     */
    public function getSectionProps(WebsiteBuilder $section): array
    {
        // Ensure content is an array (handle JSON string case)
        $content = $section->content_with_urls ?? ($section->content ?? []);
        if (is_string($content)) {
            $content = json_decode($content, true) ?? [];
        }
        if (!is_array($content)) {
            $content = [];
        }

        // Ensure items is always an array
        $items = $content['items'] ?? [];
        if (is_string($items)) {
            $items = json_decode($items, true) ?? [];
        }
        if (!is_array($items)) {
            $items = [];
        }

        // Build the standardized section data
        $sectionData = array_merge(
            [
                'section_key' => $section->section_key,
                'section_layout' => $section->section_layout ?? $section->section_key,
                'title' => $section->title,
                'subtitle' => $section->subtitle,
            ],
            $content,
        );

        // For header sections on page.blade.php, force light text color mode
        // because the breadcrumb section below has a dark gradient background
        if ($section->section_key === 'header') {
            $sectionData['text_color_mode'] = 'light';
        }

        return [
            'section' => $sectionData,
            'items' => $items,
            'company' => $this->company,
            'nav' => $this->nav,
            'navItems' => $this->navItems,
            'social' => $this->social,
            'footer' => $this->footer, // Footer defaults from LivewireBaseComponent
            'services' => $this->services,
            'languages' => $this->languages,
            'currentLangKey' => $this->currentLangKey,
            'websiteSlug' => $this->websiteSlug,
            'isWhiteBackground' => $section->is_white_background ?? false,
            'paddingTop' => $section->padding_top,
            'paddingBottom' => $section->padding_bottom,
        ];
    }

    /**
     * Get the home route for this context
     * Uses global helper landing_home_url() for consistent URL generation
     */
    public function getHomeRoute(): string
    {
        return landing_home_url($this->frontWebsite, $this->websiteSlug);
    }

    /**
     * Get inline padding style for a section
     * Returns empty string if no custom padding is set
     */
    public function getSectionPaddingStyle(WebsiteBuilder $section): string
    {
        $styles = [];
        if ($section->padding_top !== null) {
            $styles[] = "padding-top: {$section->padding_top}px";
        }
        if ($section->padding_bottom !== null) {
            $styles[] = "padding-bottom: {$section->padding_bottom}px";
        }
        return !empty($styles) ? implode('; ', $styles) : '';
    }

    /**
     * Check if section has custom padding
     */
    public function hasCustomPadding(WebsiteBuilder $section): bool
    {
        return $section->padding_top !== null || $section->padding_bottom !== null;
    }

    /**
     * Get the translated "Home" page name
     * Returns the translated name from website_pages + website_page_translations
     * Falls back to "Home" if not found
     */
    public function getHomePageName(): string
    {
        try {
            // Look for the home page (page_key = 'home')
            $homePage = \App\Models\WebsitePage::withoutGlobalScopes()->where('page_key', 'home');

            if ($this->frontWebsite) {
                $homePage->where('website_id', $this->frontWebsite->id);
            }

            $homePage = $homePage->first();

            if (!$homePage) {
                return 'Home';
            }

            // Try to get translation for current language
            $translation = \App\Models\WebsitePageTranslation::withoutGlobalScopes()->where('website_page_id', $homePage->id)->where('website_language_id', $this->currentLangId)->first();

            if ($translation && !empty($translation->name)) {
                return $translation->name;
            }

            // Fallback to English
            if ($this->currentLangKey !== 'en' && $this->frontWebsite) {
                $enLang = \App\Models\WebsiteLanguage::withoutGlobalScopes()->where('key', 'en')->where('company_id', $this->frontWebsite->company_id)->first();

                if ($enLang) {
                    $translation = \App\Models\WebsitePageTranslation::withoutGlobalScopes()->where('website_page_id', $homePage->id)->where('website_language_id', $enLang->id)->first();

                    if ($translation && !empty($translation->name)) {
                        return $translation->name;
                    }
                }
            }

            // Final fallback to default page name or "Home"
            return $homePage->name ?? 'Home';
        } catch (\Exception $e) {
            return 'Home';
        }
    }
};
?>

<div>
    <div class="bg-white dark:bg-gray-900">

        {{-- Header Section --}}
        @if ($headerSection)
            @if ($this->hasCustomPadding($headerSection))
                <div style="{{ $this->getSectionPaddingStyle($headerSection) }}">
                    @livewire($this->getComponentName($headerSection), $this->getSectionProps($headerSection), key('header-' . $headerSection->id))
                </div>
            @else
                @livewire($this->getComponentName($headerSection), $this->getSectionProps($headerSection), key('header-' . $headerSection->id))
            @endif
        @endif

        {{-- Hero Section - Clean & Professional --}}
        <section class="relative gradient-hero pt-40 pb-20 overflow-hidden">
            {{-- Subtle Pattern Overlay --}}
            <div class="absolute inset-0 opacity-5">
                <div class="absolute inset-0"
                    style="background-image: url('data:image/svg+xml,%3Csvg width=\"60\" height=\"60\" viewBox=\"0 0 60 60\" xmlns=\"http://www.w3.org/2000/svg\"%3E%3Cg fill=\"none\" fill-rule=\"evenodd\"%3E%3Cg fill=\"%23ffffff\" fill-opacity=\"1\"%3E%3Cpath d=\"M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z\"/%3E%3C/g%3E%3C/g%3E%3C/svg%3E');">
                </div>
            </div>

            {{-- Animated Shapes --}}
            <div class="hero-shape hero-shape-1"></div>
            <div class="hero-shape hero-shape-2"></div>
            <div class="hero-shape hero-shape-3"></div>
            <div class="hero-shape hero-shape-4"></div>
            <div class="hero-shape hero-shape-5"></div>

            {{-- Hero Content --}}
            <div class="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                {{-- Breadcrumb --}}
                <nav class="mb-8">
                    <ol class="flex items-center justify-center space-x-2 text-sm">
                        <li>
                            <a href="{{ $this->getHomeRoute() }}" wire:navigate
                                class="text-white/80 hover:text-white transition-colors flex items-center gap-1">
                                <svg class="w-4 h-4 text-white" fill="currentColor" viewBox="0 0 20 20">
                                    <path
                                        d="M10.707 2.293a1 1 0 00-1.414 0l-7 7a1 1 0 001.414 1.414L4 10.414V17a1 1 0 001 1h2a1 1 0 001-1v-2a1 1 0 011-1h2a1 1 0 011 1v2a1 1 0 001 1h2a1 1 0 001-1v-6.586l.293.293a1 1 0 001.414-1.414l-7-7z">
                                    </path>
                                </svg>
                                <span>{{ $this->getHomePageName() }}</span>
                            </a>
                        </li>
                        <li>
                            <svg class="w-4 h-4 text-white/80" fill="currentColor" viewBox="0 0 20 20">
                                <path fill-rule="evenodd"
                                    d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z"
                                    clip-rule="evenodd"></path>
                            </svg>
                        </li>
                        <li class="text-white font-medium">
                            @if ($pageNotFound)
                                Page Not Found
                            @else
                                {{ $page->title }}
                            @endif
                        </li>
                    </ol>
                </nav>

                {{-- Page Title --}}
                <div class="text-center">
                    <h1 class="text-3xl sm:text-4xl lg:text-5xl font-bold text-white mb-4 tracking-tight">
                        @if ($pageNotFound)
                            Page Not Found
                        @else
                            {{ $page->title }}
                        @endif
                    </h1>
                    @if (!$pageNotFound && $page)
                        <div class="flex items-center justify-center gap-4 text-white/80 text-sm">
                            <span class="flex items-center gap-1.5">
                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                        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">
                                    </path>
                                </svg>
                                Last updated: {{ $page->updated_at->format('M d, Y') }}
                            </span>
                        </div>
                    @endif
                </div>
            </div>
        </section>

        {{-- Content Section --}}
        <section class="relative page-background bg-white dark:bg-gray-900">
            {{-- Top Border Accent --}}
            <div
                class="absolute top-0 left-0 right-0 h-px bg-gradient-to-r from-transparent via-gray-200 dark:via-gray-700 to-transparent">
            </div>

            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12 lg:py-16">
                {{-- Content Card --}}
                <article class="bg-white dark:bg-gray-800 rounded-lg">
                    @if ($pageNotFound)
                        {{-- Not Found Message --}}
                        <div class="text-center py-16">
                            {{-- 404 Icon --}}
                            <div class="mb-8">
                                <svg class="w-24 h-24 mx-auto text-gray-300 dark:text-gray-600" fill="none"
                                    stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
                                        d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z">
                                    </path>
                                </svg>
                            </div>

                            {{-- Error Code --}}
                            <div class="text-6xl font-bold text-gray-200 dark:text-gray-700 mb-4">404</div>

                            {{-- Error Message --}}
                            <h2 class="text-2xl font-semibold text-gray-700 dark:text-gray-300 mb-4">
                                @if ($notFoundReason === 'website')
                                    Website Not Found
                                @else
                                    Page Not Found
                                @endif
                            </h2>

                            <p class="text-gray-500 dark:text-gray-400 mb-8 max-w-md mx-auto">
                                @if ($notFoundReason === 'website')
                                    The website you are looking for does not exist or may have been removed.
                                @else
                                    The page you are looking for does not exist, may have been moved, or is temporarily
                                    unavailable.
                                @endif
                            </p>

                            {{-- Back to Home Button --}}
                            <a href="{{ $this->getHomeRoute() }}" wire:navigate
                                class="inline-flex items-center gap-2 px-6 py-3 bg-primary-600 hover:bg-primary-700 text-white font-medium rounded-lg transition-colors">
                                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                        d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6">
                                    </path>
                                </svg>
                                <span>Back to {{ $this->getHomePageName() }}</span>
                            </a>
                        </div>
                    @else
                        {{-- Document Style Content --}}
                        <div class="page-content text-gray-700 dark:text-gray-300 leading-relaxed">
                            {!! $page->content !!}
                        </div>
                    @endif
                </article>

                {{-- Bottom Navigation (only show if page exists) --}}
                @if (!$pageNotFound)
                    <div class="mt-12 pt-8 border-t border-gray-200 dark:border-gray-700">
                        <div class="flex flex-col sm:flex-row items-center justify-between gap-4">
                            <a href="{{ $this->getHomeRoute() }}" wire:navigate
                                class="inline-flex items-center gap-2 text-gray-600 dark:text-gray-400 hover:text-primary-600 dark:hover:text-primary-400 transition-colors group">
                                <svg class="w-5 h-5 transform group-hover:-translate-x-1 transition-transform"
                                    fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                        d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
                                </svg>
                                <span class="font-medium">Back to {{ $this->getHomePageName() }}</span>
                            </a>
                            <p class="text-sm text-gray-400 dark:text-gray-500">
                                {{ $company['name'] ?? 'Company' }} &bull; All rights reserved
                            </p>
                        </div>
                    </div>
                @endif
            </div>
        </section>

        {{-- Footer Section --}}
        @if ($footerSection)
            @if ($this->hasCustomPadding($footerSection))
                <div style="{{ $this->getSectionPaddingStyle($footerSection) }}">
                    @livewire($this->getComponentName($footerSection), $this->getSectionProps($footerSection), key('footer-' . $footerSection->id))
                </div>
            @else
                @livewire($this->getComponentName($footerSection), $this->getSectionProps($footerSection), key('footer-' . $footerSection->id))
            @endif
        @endif
    </div>


    <style>
        /* Hero shapes */
        .hero-shape {
            position: absolute;
            opacity: 0.1;
        }

        .hero-shape-1 {
            top: 10%;
            right: 5%;
            width: 300px;
            height: 300px;
            background: radial-gradient(circle, rgba(255, 255, 255, 0.8) 0%, transparent 70%);
            border-radius: 50%;
            animation: float 8s ease-in-out infinite;
        }

        .hero-shape-2 {
            bottom: 15%;
            left: 5%;
            width: 200px;
            height: 200px;
            background: linear-gradient(135deg, rgba(255, 255, 255, 0.6) 0%, transparent 70%);
            border-radius: 30% 70% 70% 30% / 30% 30% 70% 70%;
            animation: float 10s ease-in-out infinite reverse;
        }

        .hero-shape-3 {
            top: 40%;
            left: 10%;
            width: 150px;
            height: 150px;
            background: radial-gradient(circle, rgba(255, 255, 255, 0.5) 0%, transparent 60%);
            border-radius: 50%;
            animation: pulse 6s ease-in-out infinite;
        }

        .hero-shape-4 {
            top: 20%;
            left: 30%;
            width: 100px;
            height: 100px;
            background: linear-gradient(45deg, rgba(255, 255, 255, 0.4) 0%, transparent 70%);
            border-radius: 20% 80% 80% 20% / 80% 20% 80% 20%;
            animation: rotate 15s linear infinite;
        }

        .hero-shape-5 {
            bottom: 10%;
            right: 15%;
            width: 180px;
            height: 180px;
            background: radial-gradient(circle, rgba(255, 255, 255, 0.6) 0%, transparent 65%);
            border-radius: 40% 60% 60% 40% / 40% 50% 60% 50%;
            animation: morph 12s ease-in-out infinite;
        }

        @keyframes float {

            0%,
            100% {
                transform: translateY(0) translateX(0);
            }

            50% {
                transform: translateY(-30px) translateX(20px);
            }
        }

        @keyframes pulse {

            0%,
            100% {
                transform: scale(1);
                opacity: 0.1;
            }

            50% {
                transform: scale(1.2);
                opacity: 0.15;
            }
        }

        @keyframes rotate {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }

        @keyframes morph {

            0%,
            100% {
                border-radius: 40% 60% 60% 40% / 40% 50% 60% 50%;
            }

            50% {
                border-radius: 60% 40% 40% 60% / 60% 50% 40% 50%;
            }
        }

        /* Light background for content section in dark mode */
        .dark .page-background {
            background-color: var(--color-bg-primary, #ffffff) !important;
        }

        .page-content h1 {
            font-size: 1.875rem;
            font-weight: 700;
            color: var(--color-primary-700, #1d4ed8);
            margin-top: 2rem;
            margin-bottom: 1rem;
            padding-bottom: 0.5rem;
            border-bottom: 2px solid var(--color-primary-200, #bfdbfe);
        }

        .page-content h2 {
            font-size: 1.5rem;
            font-weight: 600;
            color: var(--color-primary-600, #2563eb);
            margin-top: 2rem;
            margin-bottom: 0.75rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .page-content h2::before {
            content: '';
            display: inline-block;
            width: 4px;
            height: 1.5rem;
            background: linear-gradient(to bottom, var(--color-primary-500, #3b82f6), var(--color-primary-600, #2563eb));
            border-radius: 2px;
        }

        .page-content h3 {
            font-size: 1.25rem;
            font-weight: 600;
            color: var(--color-primary-600, #2563eb);
            margin-top: 1.5rem;
            margin-bottom: 0.5rem;
        }

        .page-content p {
            margin-bottom: 1rem;
            line-height: 1.75;
        }

        .page-content ul,
        .page-content ol {
            margin: 1rem 0;
            padding-left: 1.5rem;
        }

        .page-content li {
            margin-bottom: 0.5rem;
            line-height: 1.75;
        }

        .page-content ul li {
            list-style-type: disc;
        }

        .page-content ul li::marker {
            color: var(--color-primary-500, #3b82f6);
        }

        .page-content ol li {
            list-style-type: decimal;
        }

        .page-content a {
            color: var(--color-primary-600, #2563eb);
            text-decoration: none;
            border-bottom: 1px solid transparent;
            transition: border-color 0.2s;
        }

        .page-content a:hover {
            border-bottom-color: var(--color-primary-600, #2563eb);
        }

        .page-content strong {
            font-weight: 600;
            color: #1f2937;
        }

        .page-content blockquote {
            margin: 1.5rem 0;
            padding: 1rem 1.5rem;
            background: #f9fafb;
            border-left: 4px solid var(--color-primary-500, #3b82f6);
            border-radius: 0 0.5rem 0.5rem 0;
            font-style: italic;
            color: #4b5563;
        }

        .page-content table {
            width: 100%;
            margin: 1.5rem 0;
            border-collapse: collapse;
            font-size: 0.875rem;
        }

        .page-content th {
            background: #f9fafb;
            padding: 0.75rem 1rem;
            text-align: left;
            font-weight: 600;
            color: #374151;
            border: 1px solid #e5e7eb;
        }

        .page-content td {
            padding: 0.75rem 1rem;
            border: 1px solid #e5e7eb;
        }

        .page-content code {
            background: #f3f4f6;
            padding: 0.125rem 0.375rem;
            border-radius: 0.25rem;
            font-size: 0.875em;
            color: var(--color-primary-600, #2563eb);
        }

        .page-content pre {
            background: #1f2937;
            color: #e5e7eb;
            padding: 1rem;
            border-radius: 0.5rem;
            overflow-x: auto;
            margin: 1.5rem 0;
        }

        .page-content pre code {
            background: none;
            padding: 0;
            color: inherit;
        }

        .page-content hr {
            margin: 2rem 0;
            border: none;
            border-top: 1px solid #e5e7eb;
        }

        .page-content img {
            max-width: 100%;
            height: auto;
            border-radius: 0.5rem;
            margin: 1.5rem 0;
        }
    </style>
</div>
