<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}" data-bs-theme="{{ session('theme', 'light') }}">
    <head>
        @hook('AdminAreaHeadStart')
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="csrf-token" content="{{ csrf_token() }}">
        <meta name="api-token" content="{{ $apiToken ?? '' }}">

        <title>@yield('title') - {{ $appName }}</title>

        <!-- Early Theme Check — admin_theme key (store ile karışmasın) -->
        <script>
            (function() {
                // Geriye uyum: eski 'theme' key'i varsa migrate et, sonra sil
                if (! localStorage.getItem('admin_theme') && localStorage.getItem('theme')) {
                    localStorage.setItem('admin_theme', localStorage.getItem('theme'));
                }
                const theme = localStorage.getItem('admin_theme') || 'light';
                document.documentElement.setAttribute('data-bs-theme', theme);
                if (theme === 'dark') {
                    document.documentElement.classList.add('dark-theme');
                }
            })();
        </script>

        <!-- Global Translations -->
        <script>
            window.translations = {
                fields: {
                    date_range: '{{ __('admin/clients.fields_date_range') }}',
                    city_select: '{{ __('admin/clients.fields_city_select') }}',
                },
                common: {
                    yes: '{{ __('common.yes') }}',
                    no: '{{ __('common.no') }}'
                },
                notifications: {
                    title: '{{ __('admin/notifications.title') }}',
                    mark_all_read: '{{ __('admin/notifications.mark_all_read') }}',
                    empty: '{{ __('admin/notifications.empty') }}',
                    just_now: '{{ __('admin/notifications.just_now') }}',
                    minutes_ago: '{{ __('admin/notifications.minutes_ago') }}',
                    hours_ago: '{{ __('admin/notifications.hours_ago') }}',
                    yesterday: '{{ __('admin/notifications.yesterday') }}',
                    days_ago: '{{ __('admin/notifications.days_ago') }}'
                },
                search: {
                    placeholder: '{{ __('admin/search.placeholder') }}',
                    no_results: '{{ __('admin/search.no_results') }}',
                    menu_items: '{{ __('admin/search.menu_items') }}',
                    clients: '{{ __('admin/search.clients') }}',
                    invoices: '{{ __('admin/search.invoices') }}',
                    domains: '{{ __('admin/search.domains') }}',
                    products: '{{ __('admin/search.products') }}',
                    loading: '{{ __('admin/search.loading') }}',
                    min_chars: '{{ __('admin/search.min_chars') }}'
                },
                types: {
                    input: '{{ __('admin/client-custom-fields.types_input') }}',
                    select: '{{ __('admin/client-custom-fields.types_select') }}'
                },
                buttons: {
                    edit: '{{ __('common.edit') }}',
                    delete: '{{ __('common.delete') }}',
                    save: '{{ __('common.save') }}',
                    cancel: '{{ __('common.cancel') }}',
                    confirm: '{{ __('common.confirm') }}',
                    close: '{{ __('common.close') }}',
                    back: '{{ __('common.back') }}',
                    clear: '{{ __('admin/clients.buttons_clear') }}'
                },
                messages: {
                    delete_confirm: '{{ __('common.delete_confirm') }}',
                    delete_success: '{{ __('common.delete_success') }}',
                    delete_error: '{{ __('common.delete_error') }}',
                    save_success: '{{ __('common.save_success') }}',
                    save_error: '{{ __('common.save_error') }}',
                    update_success: '{{ __('common.update_success') }}',
                    update_error: '{{ __('common.update_error') }}',
                    token_error: '{{ __('common.token_error') }}',
                    url_not_available: '{{ __('admin/menu.url_not_available') }}'
                },
                placeholders:{
                    select_cycle: '{{ __('admin/orders.placeholders_select_cycle') }}',
                },
                errors: {
                    session_expired: '{{ __('common.session_expired') }}',
                    validation_error: '{{ __('common.validation_error') }}',
                    server_error: '{{ __('common.server_error') }}',
                    not_found: '{{ __('common.not_found') }}'
                },
                status: {
                    active: '{{ __('common.active') }}',
                    inactive: '{{ __('common.inactive') }}',
                    pending: '{{ __('common.pending') }}',
                    completed: '{{ __('common.completed') }}',
                    cancelled: '{{ __('common.cancelled') }}'
                },
                admin: {
                    clients: {
                        title: '{{ __('admin/clients.title') }}',
                        status: {
                            active: '{{ __('admin/clients.status_active') }}',
                            inactive: '{{ __('admin/clients.status_inactive') }}'
                        },
                        type: {
                            individual: '{{ __('admin/clients.type_individual') }}',
                            corporate: '{{ __('admin/clients.type_corporate') }}'
                        },
                        buttons: {
                            save: '{{ __('admin/clients.buttons_save') }}',
                            cancel: '{{ __('admin/clients.buttons_cancel') }}'
                        },
                        messages: {
                            loading: '{{ __('admin/clients.messages_loading') }}',
                            success: '{{ __('admin/clients.messages_success') }}',
                            error: '{{ __('admin/clients.messages_error') }}'
                        }
                    }
                }
            };

            // Global API Routes
            window.apiRoutes = {
                theme: {
                    update: '{{ route("api.admin.theme.update") }}'
                },
                translations: {
                    get: '{{ route("api.admin.translations.get", [":modelType", ":modelId", ":field"]) }}',
                    save: '{{ route("api.admin.translations.save", [":modelType", ":modelId", ":field"]) }}'
                },
                notifications: {
                    index: '{{ route("api.admin.notifications.index") }}',
                    unreadCount: '{{ route("api.admin.notifications.unread-count") }}',
                    read: '{{ route("api.admin.notifications.read", ":id") }}',
                    readAll: '{{ route("api.admin.notifications.read-all") }}'
                },
                search: {
                    index: '{{ route("api.admin.search") }}'
                }
            };

            window.routes = {
                productGroups: {
                    edit: '{{ route("admin.product-groups.edit", ":id") }}',
                    update: '{{ route("admin.product-groups.update", ":id") }}',
                    destroy: '{{ route("api.admin.product-groups.destroy", ":id") }}'
                },
                productCategories: {
                    edit: '{{ route("admin.product-categories.edit", ":id") }}',
                    update: '{{ route("admin.product-categories.update", ":id") }}',
                    destroy: '{{ route("api.admin.product-categories.destroy", ":id") }}'
                }
            };

            window.datatableTranslations = {
                forbidden: '{{ __("admin/common.permission_denied") }}',
                unauthorized: '{{ __("admin/common.session_expired") }}',
                error: '{{ __("admin/common.ajax_error") }}'
            };
        </script>

        <!-- API Token Management -->
        <script>
            (function() {
                const tokenMeta = document.querySelector('meta[name="api-token"]');
                if (tokenMeta) {
                    const token = tokenMeta.content;
                    if (token) {
                        localStorage.setItem('api_token', token);
                    }
                }

                // Token yönetimi için global fonksiyonlar
                window.getApiToken = function() {
                    return localStorage.getItem('api_token');
                };

                window.setApiToken = function(token) {
                    localStorage.setItem('api_token', token);
                };

                window.removeApiToken = function() {
                    localStorage.removeItem('api_token');
                };

                window.refreshApiToken = async function() {
                    try {
                        const response = await fetch('/sanctum/token', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'Accept': 'application/json',
                                'Authorization': 'Bearer ' + document.querySelector('meta[name="api-token"]').getAttribute('content')
                            }
                        });

                        if (!response.ok) throw new Error('Token alınamadı');

                        const data = await response.json();
                        setApiToken(data.token);
                        return data.token;
                    } catch (error) {
                        console.error('Token yenileme hatası:', error);
                        return null;
                    }
                };

                // API istekleri için interceptor
                window.apiRequest = async function(url, options = {}) {
                    let token = getApiToken();

                    if (!token) {
                        token = await refreshApiToken();
                        if (!token) {
                            throw new Error('API token alınamadı');
                        }
                    }

                    const defaultOptions = {
                        headers: {
                            'Authorization': `Bearer ${token}`,
                            'Content-Type': 'application/json',
                            'Accept': 'application/json'
                        }
                    };

                    const response = await fetch(url, { ...defaultOptions, ...options });

                    if (response.status === 401) {
                        // Token geçersiz, yenilemeyi dene
                        token = await refreshApiToken();
                        if (!token) {
                            throw new Error('Token yenilenemedi');
                        }

                        // İsteği yeni token ile tekrarla
                        defaultOptions.headers.Authorization = `Bearer ${token}`;
                        return fetch(url, { ...defaultOptions, ...options });
                    }

                    if (response.status === 403) {
                        const msg = window.datatableTranslations?.forbidden || 'Bu işlem için yetkiniz bulunmamaktadır.';
                        if (typeof window.showError === 'function') {
                            window.showError(msg);
                        }
                        throw new Error(msg);
                    }

                    return response;
                };
            })();
        </script>
        @stack('styles')

        @vite(['resources/css/admin/app.css', 'resources/js/admin/app.js', 'resources/js/common/password-toggle.js'])

        <script>
            // Notification system initialization
            document.addEventListener('DOMContentLoaded', function() {
                if (window.bootstrap && window.bootstrap.Toast) {
                    console.log('Bootstrap toast system ready');
                } else {
                    console.warn('Bootstrap not available, using alert fallback');
                }
            });
        </script>

        <style>
            /* Modern Admin Panel Layout */
            .admin-container {
                max-width: 100% !important;
                padding-left: 1.5rem;
                padding-right: 1.5rem;
            }

            /* Responsive düzenlemeler */
            @media (min-width: 1400px) {
                .admin-container {
                    padding-left: 2rem;
                    padding-right: 2rem;
                }
            }

            @media (min-width: 1600px) {
                .admin-container {
                    padding-left: 3rem;
                    padding-right: 3rem;
                }
            }

            /* Modern Content Area */
            main.flex-grow-1 {
                background-color: var(--body-bg);
                min-height: calc(100vh - 140px);
            }

            /* Compact Card Styles */
            .card {
                border-radius: 0.75rem;
                border: 1px solid var(--card-border);
                box-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.05);
                margin-bottom: 1.5rem;
            }

            .card-header {
                background-color: var(--card-bg);
                border-bottom: 1px solid var(--card-border);
                padding: 1rem 1.25rem;
                font-weight: 600;
                font-size: 1rem;
            }

            .card-body {
                padding: 1.25rem;
            }

            /* Compact Form Controls */
            .form-control,
            .form-select {
                font-size: 0.875rem;
                padding: 0.5rem 0.75rem;
                border-radius: 0.5rem;
            }

            .form-label {
                font-size: 0.875rem;
                font-weight: 500;
                margin-bottom: 0.5rem;
                color: var(--body-color);
            }

            .form-group,
            .mb-3 {
                margin-bottom: 1rem !important;
            }

            /* Compact Buttons */
            .btn {
                font-size: 0.875rem;
                padding: 0.5rem 1rem;
                border-radius: 0.5rem;
                font-weight: 500;
                transition: all var(--transition-duration) var(--transition-ease);
            }

            .btn-sm {
                padding: 0.375rem 0.75rem;
                font-size: 0.8125rem;
            }

            /* Modern Alerts */
            .alert {
                border-radius: 0.5rem;
                border: none;
                padding: 0.875rem 1rem;
                font-size: 0.875rem;
            }
        </style>
        <link rel="apple-touch-icon" sizes="180x180" href="{{ asset('apple-touch-icon.png') }}">
        <link rel="icon" type="image/png" sizes="32x32" href="{{ asset('favicon-32x32.png') }}">
        <link rel="icon" type="image/png" sizes="16x16" href="{{ asset('favicon-16x16.png') }}">
        <link rel="shortcut icon" href="{{ asset('favicon.ico') }}">
        <link rel="manifest" href="{{ asset('site.webmanifest') }}">
        @hook('AdminAreaHeadOutput')
    </head>
    <body class="font-sans antialiased @stack('body_class')">
        @hook('AdminAreaHeaderOutput')
        <div class="wrapper d-flex flex-column min-vh-100">
            @include('admin.layouts.navigation')

            <!-- Page Content -->
            <main class="flex-grow-1">
                <div class="container admin-container py-4">
                    <!-- Flash Mesajları - Toast'a dönüştürülecekler -->
                    @if (session('success'))
                    <div class="alert alert-toast-success alert-dismissible fade show" role="alert" style="display: none;">
                        {{ session('success') }}
                    </div>
                    @elseif (session('error'))
                    <div class="alert alert-toast-danger alert-dismissible fade show" role="alert" style="display: none;">
                        {{ session('error') }}
                    </div>
                    @elseif (session('warning'))
                    <div class="alert alert-toast-warning alert-dismissible fade show" role="alert" style="display: none;">
                        {{ session('warning') }}
                    </div>
                    @elseif (session('info'))
                    <div class="alert alert-toast-info alert-dismissible fade show" role="alert" style="display: none;">
                        {{ session('info') }}
                    </div>
                    @else
                        @if ($errors->any())
                            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                <h6><i class="fas fa-exclamation-triangle me-2"></i>{{__('admin/general.validation_errors')}}</h6>
                                <ul class="mb-0">
                                    @foreach ($errors->all() as $error)
                                        <li>{{ $error }}</li>
                                    @endforeach
                                </ul>
                                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                            </div>
                        @endif
                    @endif

                    @yield('content')
                </div>
            </main>

            <!-- Footer -->
            @include('admin.layouts.footer')
        </div>

        <!-- Toast Container -->
        <div id="toast-container" class="toast-container position-fixed top-0 end-0 p-3" style="z-index: 9999;"></div>

        @stack('scripts')
        @stack('captcha-scripts')
        @hook('AdminAreaFooterOutput')
    </body>
</html>
