@props([
    'pageType'    => 'home',
    'title'       => null,
    'description' => null,
    'image'       => null,
    'url'         => null,
    'type'        => 'website',
    'noindex'     => false,
    'articleData' => null, // For Article schema: published_at, author, category, image
    'breadcrumbData' => null, // For Breadcrumb schema: array of ['name' => '', 'url' => '']
    'faqData'     => null, // For FAQPage schema: array of ['question' => '', 'answer' => '']
])

@php
    use App\Models\SeoSetting;
    use App\Models\AppSetting;

    $seo      = SeoSetting::where('page_type', $pageType)->first();
    $appSettings = AppSetting::getAllCached();

    $siteName    = $appSettings['site_name']        ?? config('app.name', 'AskeriPlatform');
    $siteUrl     = $appSettings['site_url']         ?? config('app.url');
    $siteDesc    = $appSettings['site_description'] ?? 'Askeri kariyer, KPSS hazırlık ve üniversite bilgileri için kapsamlı rehber.';
    $siteLogo    = $appSettings['site_logo']        ?? null;
    $twitterUser = $appSettings['contact_twitter']  ?? null;
    $gaId        = $appSettings['google_analytics_id'] ?? null;
    $gscCode     = $appSettings['google_search_console'] ?? null;
    $contactEmail = $appSettings['contact_email']   ?? null;

    // Priority: prop > seo db record > app setting / fallback
    $metaTitle       = $title       ?? $seo->meta_title       ?? $siteName;
    $metaDescription = $description ?? $seo->meta_description ?? $siteDesc;
    $canonicalUrl    = $url         ?? $seo->canonical_url    ?? request()->url();
    $ogImage         = $image       ?? $seo->og_image         ?? ($siteLogo ? asset($siteLogo) : null);
    $robotsValue     = $noindex     ? 'noindex, nofollow'
                                    : ($seo->robots ?? 'index, follow');
    $schemaMarkup    = $seo->schema_markup ?? null;
    $ogTags          = $seo->og_tags ?? [];

    // Ensure canonical URL is absolute
    if (!str_starts_with($canonicalUrl, 'http')) {
        $canonicalUrl = $siteUrl . '/' . ltrim($canonicalUrl, '/');
    }

    // Twitter handle (@username extraction)
    if ($twitterUser) {
        preg_match('/twitter\.com\/([^\/\?]+)/i', $twitterUser, $m);
        $twitterHandle = isset($m[1]) ? '@' . $m[1] : null;
    } else {
        $twitterHandle = null;
    }

    // Build article schema data
    $articleSchema = null;
    if ($type === 'article' && $articleData) {
        $articleSchema = [
            '@type' => 'Article',
            '@id' => $canonicalUrl . '#article',
            'headline' => $metaTitle,
            'description' => Str::limit($metaDescription, 160),
            'url' => $canonicalUrl,
            'inLanguage' => 'tr-TR',
            'isPartOf' => ['@id' => $siteUrl . '/#website'],
        ];
        
        if (isset($articleData['published_at'])) {
            $articleSchema['datePublished'] = $articleData['published_at'];
        }
        if (isset($articleData['modified_at'])) {
            $articleSchema['dateModified'] = $articleData['modified_at'];
        }
        if (isset($articleData['author'])) {
            $articleSchema['author'] = [
                '@type' => 'Person',
                'name' => $articleData['author']
            ];
        }
        if (isset($articleData['category'])) {
            $articleSchema['articleSection'] = $articleData['category'];
        }
        if ($ogImage) {
            $articleSchema['image'] = [
                '@type' => 'ImageObject',
                'url' => $ogImage
            ];
        }
        if (isset($articleData['word_count'])) {
            $articleSchema['wordCount'] = $articleData['word_count'];
        }
    }

    // Build breadcrumb schema
    $breadcrumbSchema = null;
    if ($breadcrumbData && is_array($breadcrumbData) && count($breadcrumbData) > 1) {
        $items = [];
        $position = 1;
        foreach ($breadcrumbData as $item) {
            $items[] = [
                '@type' => 'ListItem',
                'position' => $position++,
                'name' => $item['name'],
                'item' => str_starts_with($item['url'], 'http') ? $item['url'] : $siteUrl . '/' . ltrim($item['url'], '/')
            ];
        }
        $breadcrumbSchema = [
            '@type' => 'BreadcrumbList',
            '@id' => $canonicalUrl . '#breadcrumb',
            'itemListElement' => $items
        ];
    }

    // Build FAQ schema
    $faqSchema = null;
    if ($faqData && is_array($faqData) && count($faqData) > 0) {
        $questions = [];
        foreach ($faqData as $faq) {
            $questions[] = [
                '@type' => 'Question',
                'name' => $faq['question'],
                'acceptedAnswer' => [
                    '@type' => 'Answer',
                    'text' => $faq['answer']
                ]
            ];
        }
        $faqSchema = [
            '@type' => 'FAQPage',
            '@id' => $canonicalUrl . '#faq',
            'mainEntity' => $questions
        ];
    }
@endphp

{{-- ── Meta Title ──────────────────────────────────────────────────── --}}
<title>{{ $metaTitle }}</title>
<meta name="title" content="{{ $metaTitle }}">

{{-- ── Meta Description ────────────────────────────────────────────── --}}
<meta name="description" content="{{ Str::limit($metaDescription, 160) }}">

{{-- ── Robots ──────────────────────────────────────────────────────── --}}
<meta name="robots" content="{{ $robotsValue }}">

{{-- ── Canonical ───────────────────────────────────────────────────── --}}
<link rel="canonical" href="{{ $canonicalUrl }}">

{{-- ── Alternate Language (for future i18n) ─────────────────────── --}}
{{-- <link rel="alternate" hreflang="tr" href="{{ $canonicalUrl }}" /> --}}
{{-- <link rel="alternate" hreflang="en" href="{{ $siteUrl }}/en{{ request()->path() }}" /> --}}
{{-- <link rel="alternate" hreflang="x-default" href="{{ $canonicalUrl }}" /> --}}

{{-- ── Google Search Console verification ────────────────────────── --}}
@if($gscCode)
    <meta name="google-site-verification" content="{{ $gscCode }}">
@endif

{{-- ── Open Graph ──────────────────────────────────────────────────── --}}
<meta property="og:type"        content="{{ $type }}">
<meta property="og:site_name"   content="{{ $siteName }}">
<meta property="og:title"       content="{{ $metaTitle }}">
<meta property="og:description" content="{{ Str::limit($metaDescription, 300) }}">
<meta property="og:url"         content="{{ $canonicalUrl }}">
<meta property="og:locale"      content="tr_TR">
@if($type === 'article')
    <meta property="article:published_time" content="{{ $articleData['published_at'] ?? now()->toAtomString() }}">
    @if(isset($articleData['modified_at']))
    <meta property="article:modified_time" content="{{ $articleData['modified_at'] }}">
    @endif
    @if(isset($articleData['author']))
    <meta property="article:author" content="{{ $articleData['author'] }}">
    @endif
    @if(isset($articleData['category']))
    <meta property="article:section" content="{{ $articleData['category'] }}">
    @endif
@endif
@if($ogImage)
    <meta property="og:image"       content="{{ $ogImage }}">
    <meta property="og:image:alt"   content="{{ $metaTitle }}">
    <meta property="og:image:width" content="1200">
    <meta property="og:image:height"content="630">
    <meta property="og:image:secure_url" content="{{ $ogImage }}">
    <meta property="og:image:type" content="image/jpeg">
@endif

{{-- ── Additional OG Tags from Database ──────────────────────────── --}}
@if(is_array($ogTags) && count($ogTags) > 0)
    @foreach($ogTags as $key => $value)
        <meta property="{{ $key }}" content="{{ $value }}">
    @endforeach
@endif

{{-- ── Twitter Card ────────────────────────────────────────────────── --}}
<meta name="twitter:card"        content="{{ $ogImage ? 'summary_large_image' : 'summary' }}">
<meta name="twitter:site"        content="{{ $twitterHandle ?? '@' . parse_url($siteUrl, PHP_URL_HOST) }}">
<meta name="twitter:creator"     content="{{ $twitterHandle ?? '@' . parse_url($siteUrl, PHP_URL_HOST) }}">
<meta name="twitter:title"       content="{{ $metaTitle }}">
<meta name="twitter:description" content="{{ Str::limit($metaDescription, 200) }}">
<meta name="twitter:url"         content="{{ $canonicalUrl }}">
@if($ogImage)
    <meta name="twitter:image" content="{{ $ogImage }}">
    <meta name="twitter:image:alt" content="{{ $metaTitle }}">
@endif

{{-- ── Schema.org JSON-LD — WebSite + Organization ───────────────── --}}
<script type="application/ld+json">
{
    "@context": "https://schema.org",
    "@graph": [
        {
            "@type": "WebSite",
            "@id": "{{ $siteUrl }}/#website",
            "url": "{{ $siteUrl }}/",
            "name": "{{ $siteName }}",
            "description": "{{ $siteDesc }}",
            "inLanguage": "tr-TR",
            "publisher": { "@id": "{{ $siteUrl }}/#organization" },
            "potentialAction": {
                "@type": "SearchAction",
                "target": {
                    "@type": "EntryPoint",
                    "urlTemplate": "{{ $siteUrl }}/search?q={search_term_string}"
                },
                "query-input": "required name=search_term_string"
            }
        },
        {
            "@type": "Organization",
            "@id": "{{ $siteUrl }}/#organization",
            "name": "{{ $siteName }}",
            "url": "{{ $siteUrl }}/",
            "description": "{{ $siteDesc }}"
            @if($siteLogo)
            ,"logo": {
                "@type": "ImageObject",
                "url": "{{ asset($siteLogo) }}"
            }
            @endif
            @if($contactEmail)
            ,"email": "{{ $contactEmail }}"
            @endif
            @if(!empty($appSettings['contact_phone']))
            ,"telephone": "{{ $appSettings['contact_phone'] }}"
            @endif
            @if(!empty($appSettings['contact_address']))
            ,"address": {
                "@type": "PostalAddress",
                "streetAddress": "{{ $appSettings['contact_address'] }}"
            }
            @endif
            ,"sameAs": [
                @if($twitterUser)
                "{{ $twitterUser }}"
                @endif
            ]
        }
        @if($type === 'article' && $canonicalUrl !== ($siteUrl . '/'))
        ,{
            "@type": "WebPage",
            "@id": "{{ $canonicalUrl }}/#webpage",
            "url": "{{ $canonicalUrl }}",
            "name": "{{ $metaTitle }}",
            "description": "{{ Str::limit($metaDescription, 160) }}",
            "isPartOf": { "@id": "{{ $siteUrl }}/#website" },
            "inLanguage": "tr-TR",
            "about": { "@id": "{{ $siteUrl }}/#organization" }
        }
        @endif
        @if($articleSchema)
        ,{!! json_encode($articleSchema, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) !!}
        @endif
        @if($breadcrumbSchema)
        ,{!! json_encode($breadcrumbSchema, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) !!}
        @endif
        @if($faqSchema)
        ,{!! json_encode($faqSchema, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) !!}
        @endif
    ]
}
</script>

{{-- ── Schema Markup from Database ────────────────────────────────── --}}
@if($schemaMarkup && is_array($schemaMarkup) && count($schemaMarkup) > 0)
    <script type="application/ld+json">
        {!! json_encode($schemaMarkup, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) !!}
    </script>
@endif

{{-- ── Google Analytics 4 ──────────────────────────────────────────── --}}
@if($gaId)
    <script async src="https://www.googletagmanager.com/gtag/js?id={{ $gaId }}"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', '{{ $gaId }}', {
            'anonymize_ip': true,
            'cookie_flags': 'SameSite=None;Secure',
            'send_page_view': true
        });
    </script>
@endif

{{-- ── Additional SEO Meta Tags ───────────────────────────────────── --}}
<meta name="theme-color" content="#2563eb">
<meta name="msapplication-TileColor" content="#2563eb">
<meta name="format-detection" content="telephone=no">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
