<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>@yield('title', 'Acente Paneli') - {{ auth()->user()?->agency?->name ?? 'Acente Pro Max' }}</title>

    {{-- Tema başlatıcı: sayfa boyanmadan ÖNCE çalışır (FOUC/flaş önlenir).
         Kayıtlı tercih yoksa açık tema varsayılandır; kullanıcı seçimi localStorage('theme') ile saklanır. --}}
    <script>
        (function () {
            try {
                if (localStorage.getItem('theme') === 'dark') {
                    document.documentElement.setAttribute('data-theme', 'dark');
                    document.documentElement.setAttribute('data-bs-theme', 'dark');
                }
            } catch (e) { /* localStorage erişilemezse açık tema */ }
        })();
    </script>

    <!-- Favicon -->
    <link rel="icon" type="image/svg+xml" href="{{ asset('favicon.svg') }}">
    <link rel="icon" type="image/png" sizes="32x32" href="{{ asset('favicon-32.png') }}">
    <link rel="icon" type="image/png" sizes="16x16" href="{{ asset('favicon-16.png') }}">
    <link rel="alternate icon" href="{{ asset('favicon.ico') }}">
    <link rel="apple-touch-icon" href="{{ asset('apple-touch-icon.png') }}">

    <!-- Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap"
          rel="stylesheet">

    <!-- Icons -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

    <!-- Bootstrap -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

    <!-- Agency Panel CSS -->
    <link rel="stylesheet" href="{{ asset('assets/agency/css/app.css') }}?v={{ filemtime(public_path('assets/agency/css/app.css')) }}">

    <!-- Koyu Tema (yalnızca html[data-theme="dark"] iken etkili; açık temaya dokunmaz) -->
    <link rel="stylesheet" href="{{ asset('assets/agency/css/dark-theme.css') }}?v={{ filemtime(public_path('assets/agency/css/dark-theme.css')) }}">

    <!-- Global Tarih & Saat Seçici (tüm date/time/datetime-local alanlarını otomatik sarar) -->
    <link rel="stylesheet" href="{{ asset('assets/agency/css/datetime-picker.css') }}?v={{ filemtime(public_path('assets/agency/css/datetime-picker.css')) }}">
    <script defer src="{{ asset('assets/agency/js/datetime-picker.js') }}?v={{ filemtime(public_path('assets/agency/js/datetime-picker.js')) }}"></script>
    <script defer src="{{ asset('assets/agency/js/numeric-fields.js') }}?v={{ filemtime(public_path('assets/agency/js/numeric-fields.js')) }}"></script>

    <!-- Aranabilir Liste Seçici (uyruk/ülke gibi kısa kodlu alanlar; data-lookup ile) -->
    <link rel="stylesheet" href="{{ asset('assets/agency/css/lookup-picker.css') }}?v={{ filemtime(public_path('assets/agency/css/lookup-picker.css')) }}">
    {{-- Uç adresi route'tan gelir: acente ön eki değişirse betiği düzeltmek gerekmesin --}}
    <script>window.__lookupUrl = @json(route('agency.lookups.show', ['kind' => '__KIND__']));</script>
    <script defer src="{{ asset('assets/agency/js/lookup-picker.js') }}?v={{ filemtime(public_path('assets/agency/js/lookup-picker.js')) }}"></script>

    <!-- Aurora Bildirim Sistemi (özel toast + onay modalı; Swal köprüsü dahil) -->
    @include('components.app-alerts')

    <!-- Quill Rich Text Editor (free, MIT) -->
    <link href="https://cdn.jsdelivr.net/npm/quill@2.0.3/dist/quill.snow.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/quill@2.0.3/dist/quill.js"></script>
    <style>
        /* Ortak zengin metin (Quill) görünümü */
        .rte-wrap { background:#fff; border:1.5px solid #e2e8f0; border-radius:10px; overflow:hidden; }
        .rte-wrap .ql-toolbar.ql-snow { border:none; border-bottom:1px solid #e2e8f0; background:#f8fafc; border-radius:10px 10px 0 0; }
        .rte-wrap .ql-container.ql-snow { border:none; font-size:.875rem; font-family:inherit; }
        .rte-wrap .ql-editor { min-height:120px; }
        .rte-wrap .ql-editor.ql-blank::before { color:#94a3b8; font-style:normal; }
        /* Kayıtlı zengin metnin salt-okunur gösterimi */
        .rte-content { font-size:.85rem; line-height:1.6; color:#334155; word-break:break-word; }
        .rte-content p { margin-bottom:.4rem; }
        .rte-content:last-child > *:last-child { margin-bottom:0; }
        .rte-content ul, .rte-content ol { padding-left:1.25rem; margin-bottom:.4rem; }
    </style>

    @stack('styles')
</head>
<body class="agency-layout">
@include('agency.layouts.partials.sidebar')

<!-- Main Content -->
<div class="main-content">
    <!-- Header -->
    <header class="main-header">
        <div class="header-left">
            <button class="mobile-sidebar-toggle d-lg-none" id="mobileSidebarToggle">
                <i class="fas fa-bars"></i>
            </button>

            <div class="page-title">
                <h4>@yield('page_title', 'Dashboard')</h4>
                @if(isset($breadcrumbs))
                    <nav aria-label="breadcrumb">
                        <ol class="breadcrumb">
                            @foreach($breadcrumbs as $breadcrumb)
                                @if($loop->last)
                                    <li class="breadcrumb-item active">{{ $breadcrumb['title'] ?? $breadcrumb['name'] ?? '' }}</li>
                                @else
                                    <li class="breadcrumb-item">
                                        <a href="{{ $breadcrumb['url'] ?? '#' }}">{{ $breadcrumb['title'] ?? $breadcrumb['name'] ?? '' }}</a>
                                    </li>
                                @endif
                            @endforeach
                        </ol>
                    </nav>
                @endif
            </div>
        </div>

        {{-- Global Arama (Ctrl+K) --}}
        @include('agency.layouts.partials.global-search')

        {{-- Global Hızlı Ekle (+) --}}
        @include('agency.layouts.partials.quick-add')

        <div class="header-right">
            <!-- Görevler Toolbar -->
            @include('agency.layouts.partials.header-tasks')

            <!-- Notifications -->
            <div class="dropdown">
                <button class="btn btn-light btn-sm position-relative" data-bs-toggle="dropdown">
                    <i class="fas fa-bell"></i>
                    <span
                        class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger">3</span>
                </button>
                <div class="dropdown-menu dropdown-menu-end notification-dropdown">
                    <h6 class="dropdown-header">Bildirimler</h6>
                    <div class="notification-item">
                        <div class="notification-content">
                            <div class="notification-title">Yeni Rezervasyon</div>
                            <div class="notification-desc">İstanbul Turu için yeni rezervasyon</div>
                            <div class="notification-time">2 dakika önce</div>
                        </div>
                    </div>
                    <div class="dropdown-divider"></div>
                    <a class="dropdown-item text-center" href="#">Tüm Bildirimleri Gör</a>
                </div>
            </div>

            <!-- User Menu -->
            <div class="dropdown">
                <button class="btn btn-light btn-sm d-flex align-items-center" data-bs-toggle="dropdown">
                    <img
                        src="https://ui-avatars.com/api/?name={{ auth()->user()->full_name }}&background=gradient&color=fff"
                        alt="Avatar" class="rounded-circle me-2" width="24" height="24">
                    <span class="d-none d-md-inline">{{ auth()->user()->first_name }}</span>
                    <i class="fas fa-chevron-down ms-1"></i>
                </button>
                <ul class="dropdown-menu dropdown-menu-end">
                    <li><a class="dropdown-item" href="{{ route('agency.profile') }}">
                            <i class="fas fa-user"></i> Profil
                        </a></li>
                    @if(auth()->user()->agencies()->count() > 1 || auth()->user()->isSuperAdmin())
                        <li><a class="dropdown-item" href="{{ route('agency.switch') }}">
                                <i class="fas fa-exchange-alt"></i> Acente Değiştir
                            </a></li>
                    @endif
                    <li><a class="dropdown-item" href="{{ route('agency.settings') }}">
                            <i class="fas fa-cog"></i> Ayarlar
                        </a></li>
                    <li><a class="dropdown-item" href="{{ route('agency.settings.company.pdf') }}">
                            <i class="fas fa-file-pdf"></i> Şirket Bilgilerim (PDF)
                        </a></li>
                    <li>
                        <hr class="dropdown-divider">
                    </li>
                    <li>
                        <button type="button" class="dropdown-item theme-toggle-btn" id="themeToggleBtn">
                            <i class="fas fa-moon"></i>
                            <i class="fas fa-sun"></i>
                            <span id="themeToggleLabel">Koyu Tema</span>
                        </button>
                    </li>
                    <li>
                        <hr class="dropdown-divider">
                    </li>
                    <li>
                        <form method="POST" action="{{ route('agency.logout') }}">
                            @csrf
                            <button type="submit" class="dropdown-item text-danger">
                                <i class="fas fa-sign-out-alt"></i> Çıkış Yap
                            </button>
                        </form>
                    </li>
                </ul>
            </div>
        </div>
    </header>

    <!-- Content Area -->
    <main class="content-area">
        @if (session('success') || session('error') || session('warning'))
            <script>
                document.addEventListener('DOMContentLoaded', function () {
                    @if(session('success'))
                        appToast({ icon: 'success', title: {{ Js::from(session('success')) }}, timer: 4000 });
                    @endif
                    @if(session('error'))
                        appToast({ icon: 'error', title: {{ Js::from(session('error')) }}, timer: 5000 });
                    @endif
                    @if(session('warning'))
                        appToast({ icon: 'warning', title: {{ Js::from(session('warning')) }}, timer: 4500 });
                    @endif
                });
            </script>
        @endif

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

{{-- Global Quick View Drawer --}}
@include('components.quick-view-drawer')

{{-- Satış ürün tipi seçim modalı: global "+" menüsündeki "Satış" da kullanır (@once ile tekil) --}}
@include('agency.sales.partials._new-sale-modal')

{{-- Recent Pages & Quick-View History Sidebar --}}
@include('components.recent-sidebar')

<!-- Mobile Sidebar Backdrop -->
<div class="sidebar-backdrop d-lg-none" id="sidebarBackdrop"></div>

{{-- Global Mesajlaşma Widget'ı --}}
{{-- Chat sayfasında gizli: tam sayfa chat kendi soketini/polling'ini kurar, widget ikinci bir istemci açardı. --}}
@auth
    @unless(request()->routeIs('agency.chat.page'))
        @include('agency.layouts.partials.chat-widget')
    @endunless
@endauth

<!-- Scripts -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="{{ asset('assets/agency/js/app.js') }}"></script>
<script src="{{ asset('assets/agency/js/green-actions.js') }}"></script>

    <script>
        // Auto-hide alerts after 8 seconds (increased for better readability)
        setTimeout(function() {
            let alerts = document.querySelectorAll('.alert-dismissible');
            alerts.forEach(function(alert) {
                let bsAlert = new bootstrap.Alert(alert);
                bsAlert.close();
            });
        }, 8000);

        // Tema geçişi (açık/koyu)
        document.addEventListener('DOMContentLoaded', function () {
            const themeBtn = document.getElementById('themeToggleBtn');
            if (!themeBtn) return;

            const themeLabel = document.getElementById('themeToggleLabel');

            function syncThemeBtn() {
                const dark = document.documentElement.getAttribute('data-theme') === 'dark';
                themeBtn.title = dark ? 'Açık tema' : 'Koyu tema';
                if (themeLabel) themeLabel.textContent = dark ? 'Açık Tema' : 'Koyu Tema';
            }

            themeBtn.addEventListener('click', function () {
                const dark = document.documentElement.getAttribute('data-theme') === 'dark';
                if (dark) {
                    document.documentElement.removeAttribute('data-theme');
                    document.documentElement.removeAttribute('data-bs-theme');
                } else {
                    document.documentElement.setAttribute('data-theme', 'dark');
                    document.documentElement.setAttribute('data-bs-theme', 'dark');
                }
                try { localStorage.setItem('theme', dark ? 'light' : 'dark'); } catch (e) {}
                syncThemeBtn();
            });

            syncThemeBtn();
        });

        // Sidebar Functionality
        document.addEventListener('DOMContentLoaded', function () {
            const sidebar = document.getElementById('agencySidebar');
            const collapseBtn = document.getElementById('sidebarCollapseBtn');
            const mobileToggle = document.getElementById('mobileSidebarToggle');
            const backdrop = document.getElementById('sidebarBackdrop');

            // Restore sidebar state
            const isCollapsed = localStorage.getItem('sidebar-collapsed') === 'true';
            if (isCollapsed && window.innerWidth > 992) {
                sidebar.classList.add('collapsed');
            }

            // Toggle collapse
            if (collapseBtn) {
                collapseBtn.addEventListener('click', function () {
                    sidebar.classList.toggle('collapsed');
                    localStorage.setItem('sidebar-collapsed', sidebar.classList.contains('collapsed'));
                });
            }

            // Mobile toggle
            if (mobileToggle) {
                mobileToggle.addEventListener('click', function () {
                    sidebar.classList.add('show');
                    backdrop.classList.add('show');
                });
            }

            if (backdrop) {
                backdrop.addEventListener('click', function () {
                    sidebar.classList.remove('show');
                    backdrop.classList.remove('show');
                });
            }

            // Dropdowns
            const dropdownLinks = document.querySelectorAll('.nav-item.has-dropdown > .nav-link');
            dropdownLinks.forEach(link => {
                link.addEventListener('click', function (e) {
                    if (sidebar.classList.contains('collapsed') && window.innerWidth > 992) return;

                    const parent = this.parentElement;
                    const isOpen = parent.classList.contains('open');

                    // Close other dropdowns at the same level (optional)
                    // document.querySelectorAll('.nav-item.has-dropdown.open').forEach(item => {
                    //     if (item !== parent) item.classList.remove('open');
                    // });

                    parent.classList.toggle('open');
                });
            });

            // Prevent dropdowns from opening if sidebar is collapsed
            const sidebarNav = document.querySelector('.sidebar-nav');
            if (sidebarNav) {
                sidebarNav.addEventListener('click', (e) => {
                    if (sidebar.classList.contains('collapsed') && window.innerWidth > 992) {
                        const dropdownItem = e.target.closest('.has-dropdown');
                        if (dropdownItem) {
                            e.preventDefault();
                            sidebar.classList.remove('collapsed');
                            dropdownItem.classList.add('open');
                        }
                    }
                });
            }
        });
</script>

@stack('scripts')
</body>
</html>
