@extends('agency.layouts.app')

@section('title', $tour->name . ' - Pazaryeri Çevirileri')
@section('page_title', 'Pazaryeri Çevirileri')

@php
    $breadcrumbs = [
        ['title' => 'Ana Sayfa', 'url' => route('agency.dashboard')],
        ['title' => 'Kültür Turları', 'url' => route('agency.products.kultur-turlari.index')],
        ['title' => $tour->name, 'url' => route('agency.products.kultur-turlari.show', $tour)],
        ['title' => 'Pazaryeri Çevirileri', 'url' => '']
    ];
@endphp

@push('styles')
    <!-- Quill Rich Text Editor CSS -->
    <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
    <style>
        .tour-detail-container {
            max-width: 1200px;
            margin: 0 auto;
        }

        .tour-header {
            background: linear-gradient(135deg, var(--primary-color), var(--primary-light));
            color: white;
            padding: 2rem;
            border-radius: var(--radius-xl);
            margin-bottom: 2rem;
            position: relative;
            overflow: hidden;
        }

        .tour-header::before {
            content: '';
            position: absolute;
            top: 0;
            right: 0;
            width: 200px;
            height: 200px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 50%;
            transform: translate(50%, -50%);
        }

        .tour-header-content {
            position: relative;
            z-index: 2;
        }

        .tour-title {
            font-size: 28px;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }

        .tour-code {
            font-size: 14px;
            opacity: 0.9;
            margin-bottom: 1rem;
        }

        .tour-meta {
            display: flex;
            gap: 2rem;
            flex-wrap: wrap;
        }

        .tour-meta-item {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 14px;
        }

        .tour-meta-icon {
            font-size: 16px;
            opacity: 0.8;
        }

        .tabs-container {
            background: white;
            border: 1px solid var(--gray-200);
            border-radius: var(--radius-xl);
            overflow: hidden;
            margin-bottom: 2rem;
            position: relative;
        }

        .nav-tabs {
            background: var(--gray-50);
            border-bottom: 1px solid var(--gray-200);
            padding: 0 1rem;
            margin: 0;
        }

        .nav-tabs .nav-link {
            border: none;
            border-radius: 0;
            color: var(--gray-600);
            font-weight: 500;
            padding: 1rem 1.5rem;
            position: relative;
            transition: var(--transition);
        }

        .nav-tabs .nav-link:hover {
            color: var(--primary-color);
            background: transparent;
            border-color: transparent;
        }

        .nav-tabs .nav-link.active {
            color: var(--primary-color);
            background: transparent;
            border-color: transparent;
            font-weight: 600;
        }

        .nav-tabs .nav-link.active::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            height: 3px;
            background: var(--primary-color);
            border-radius: 3px 3px 0 0;
        }

        .tab-content {
            padding: 2rem;
        }

        /* Modern Translation Styles */
        .marketplace-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
            gap: 1rem;
            margin-bottom: 1.5rem;
        }

        .marketplace-select-card {
            background: white;
            border: 2px solid var(--gray-200);
            border-radius: var(--radius-lg);
            padding: 1.25rem;
            cursor: pointer;
            transition: all 0.25s ease;
            position: relative;
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .marketplace-select-card:hover {
            border-color: var(--primary-color);
            transform: translateY(-2px);
            box-shadow: var(--shadow-md);
        }

        .marketplace-select-card.active {
            border-color: var(--primary-color);
            background-color: rgba(37, 99, 235, 0.06); /* Soft premium light blue tint */
        }

        .marketplace-select-card .card-icon {
            width: 42px;
            height: 42px;
            border-radius: var(--radius-md);
            background: var(--gray-100);
            color: var(--gray-700);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.25rem;
            font-weight: 700;
            transition: all 0.25s ease;
        }

        .marketplace-select-card.active .card-icon {
            background: var(--primary-color);
            color: white;
        }

        .marketplace-select-card .card-info {
            display: flex;
            flex-direction: column;
        }

        .marketplace-select-card .card-title {
            font-size: 15px;
            font-weight: 700;
            color: var(--gray-900);
            margin: 0;
        }

        .marketplace-select-card .card-meta {
            font-size: 11px;
            color: var(--gray-500);
            margin-top: 0.15rem;
        }

        .language-pills-container {
            margin-bottom: 1.5rem;
            padding: 1rem;
            background: var(--gray-50);
            border-radius: var(--radius-lg);
            border: 1px solid var(--gray-200);
        }

        .language-pills-title {
            font-size: 12px;
            font-weight: 700;
            text-transform: uppercase;
            color: var(--gray-500);
            margin-bottom: 0.75rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .language-pills {
            display: flex;
            gap: 0.5rem;
            flex-wrap: wrap;
        }

        .language-pill {
            background: white;
            color: var(--gray-700);
            border: 1px solid var(--gray-300);
            border-radius: 50px;
            padding: 0.4rem 1rem;
            cursor: pointer;
            font-weight: 600;
            font-size: 13px;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .language-pill:hover {
            border-color: var(--primary-color);
            color: var(--primary-color);
        }

        .language-pill.active {
            background: var(--primary-color);
            color: white;
            border-color: var(--primary-color);
        }

        .translation-layout {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1.5rem;
        }

        @media (max-width: 992px) {
            .translation-layout {
                grid-template-columns: 1fr;
            }
        }

        .translation-column-title {
            font-size: 15px;
            font-weight: 700;
            color: var(--gray-800);
            padding-bottom: 0.5rem;
            margin-bottom: 1rem;
            border-bottom: 2px solid var(--gray-100);
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .translation-field-container {
            background: white;
            border: 1px solid var(--gray-200);
            border-radius: var(--radius-lg);
            padding: 1.25rem;
            margin-bottom: 1.25rem;
            transition: all 0.2s ease;
        }

        .translation-field-container:hover {
            border-color: var(--gray-300);
            box-shadow: var(--shadow-sm);
        }

        .translation-field-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 0.5rem;
        }

        .translation-field-label {
            font-weight: 700;
            color: var(--gray-900);
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .readonly-preview-box {
            background: var(--gray-50);
            border: 1px solid var(--gray-200);
            border-radius: var(--radius-md);
            padding: 0.75rem 1rem;
            min-height: 38px;
            font-size: 13.5px;
            color: var(--gray-700);
            word-break: break-word;
        }

        .readonly-preview-rich {
            background: var(--gray-50);
            border: 1px solid var(--gray-200);
            border-radius: var(--radius-md);
            padding: 0.75rem 1rem;
            min-height: 120px;
            max-height: 250px;
            overflow-y: auto;
            font-size: 13.5px;
            color: var(--gray-700);
        }

        .btn-copy-default {
            background: transparent;
            border: none;
            color: var(--primary-color);
            font-size: 11px;
            font-weight: 700;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 0.25rem;
            padding: 0.25rem 0.5rem;
            border-radius: var(--radius-sm);
            transition: all 0.2s ease;
        }

        .btn-copy-default:hover {
            background: var(--primary-light);
            color: var(--primary-color);
        }

        .workspace-loader {
            display: none;
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255, 255, 255, 0.8);
            z-index: 100;
            align-items: center;
            justify-content: center;
            flex-direction: column;
            gap: 1rem;
            backdrop-filter: blur(2px);
        }

        .workspace-loader.active {
            display: flex;
        }

        .quill-editor-container {
            background: white;
            border: 1px solid var(--gray-300);
            border-radius: var(--radius-md);
        }

        .ql-toolbar {
            border: none !important;
            border-bottom: 1px solid var(--gray-200) !important;
            background: var(--gray-50);
            border-radius: var(--radius-md) var(--radius-md) 0 0;
        }

        .ql-container {
            border: none !important;
            min-height: 120px;
            font-size: 13.5px;
            border-radius: 0 0 var(--radius-md) var(--radius-md);
        }

        .empty-state {
            text-align: center;
            padding: 3rem 2rem;
            color: var(--gray-500);
        }

        .empty-state-icon {
            font-size: 3rem;
            color: var(--gray-300);
            margin-bottom: 1rem;
        }

        .empty-state-title {
            font-size: 18px;
            font-weight: 700;
            color: var(--gray-700);
            margin-bottom: 0.5rem;
        }

        .actions-bar {
            position: sticky;
            bottom: 0;
            background: white;
            border-top: 2px solid var(--gray-200);
            padding: 1.25rem 2rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin: 2rem -2rem -2rem;
            border-radius: 0 0 var(--radius-xl) var(--radius-xl);
            z-index: 50;
        }
    </style>
@endpush

@section('content')
    <div class="tour-detail-container">
        <!-- Tour Header -->
        <div class="tour-header">
            <div class="tour-header-content">
                <div class="tour-code">Tur Kodu: {{ $tour->code }}</div>
                <h1 class="tour-title">{{ $tour->name }}</h1>
                <div class="tour-meta">
                    <div class="tour-meta-item">
                        <i class="fas fa-map-marker-alt tour-meta-icon"></i>
                        {{ $tour->departureCity->city ?? 'Belirtilmemiş' }}
                        → {{ $tour->arrivalCity->city ?? 'Belirtilmemiş' }}
                    </div>
                    @if($tour->duration_days)
                        <div class="tour-meta-item">
                            <i class="fas fa-calendar-day tour-meta-icon"></i>
                            {{ $tour->duration_days }} Gün
                        </div>
                    @endif
                    <div class="tour-meta-item">
                        <i class="fas fa-dollar-sign tour-meta-icon"></i>
                        {{ number_format($tour->base_price, 0) }} {{ $tour->currency }}
                    </div>
                </div>
            </div>
        </div>

        <!-- Tabs Container -->
        <div class="tabs-container">
            <!-- Loading Overlay -->
            <div class="workspace-loader" id="workspaceLoader">
                <div class="spinner-border text-primary" role="status"></div>
                <span class="fw-bold text-gray-700" id="loaderMessage">Yükleniyor...</span>
            </div>

            <!-- Tab Navigation -->
            @include('agency.products.kultur-turlari._nav', ['active' => 'translations'])

            <!-- Tab Content -->
            <div class="tab-content">
                @if($marketplaces->isEmpty())
                    <div class="empty-state">
                        <i class="fas fa-store-alt-slash empty-state-icon"></i>
                        <h4 class="empty-state-title">Aktif Pazar Yeri Bulunmuyor</h4>
                        <p class="mb-4">Bu tura tanımlanmış aktif bir pazar yeri bulunmamaktadır. Çeviri yapabilmek için önce tura pazar yeri tanımlamalısınız.</p>
                        <a href="{{ route('agency.products.kultur-turlari.settings', $tour) }}" class="btn btn-primary">
                            <i class="fas fa-cog me-2"></i>Pazaryeri Ayarlarına Git
                        </a>
                    </div>
                @else
                    <!-- 1. Marketplace Selection -->
                    <h5 class="fw-bold mb-3 text-gray-800">
                        <i class="fas fa-store text-primary me-2"></i>Pazar Yeri Seçin
                    </h5>
                    <div class="marketplace-grid">
                        @foreach($marketplaces as $mp)
                            <div class="marketplace-select-card" data-id="{{ $mp->id }}" onclick="selectMarketplace({{ $mp->id }})">
                                <div class="card-icon">
                                    {{ mb_strtoupper(mb_substr($mp->name, 0, 2, 'UTF-8'), 'UTF-8') }}
                                </div>
                                <div class="card-info">
                                    <h4 class="card-title">{{ $mp->name }}</h4>
                                    <div class="card-meta">
                                        {{ $mp->languages->count() }} Dil • {{ $mp->currencies->count() }} Para Birimi
                                    </div>
                                </div>
                            </div>
                        @endforeach
                    </div>

                    <!-- 2. Language Selection (Populated by JS) -->
                    <div class="language-pills-container" id="languageContainer" style="display: none;">
                        <div class="language-pills-title">
                            <i class="fas fa-globe"></i> Desteklenen Diller
                        </div>
                        <div class="language-pills" id="languagePills"></div>
                    </div>

                    <!-- 3. Translation Workspace Form -->
                    <form id="translationForm" style="display: none;" method="POST">
                        @csrf
                        <input type="hidden" name="marketplace_id" id="marketplaceIdInput">
                        <input type="hidden" name="language_id" id="languageIdInput">

                        <div class="translation-layout">
                            <!-- Left Column: Default Values (Read Only) -->
                            <div class="translation-column">
                                <div class="translation-column-title">
                                    <i class="fas fa-file-alt text-secondary"></i> Orijinal İçerik (Varsayılan)
                                </div>

                                <!-- Name -->
                                <div class="translation-field-container">
                                    <div class="translation-field-header">
                                        <span class="translation-field-label">Tur Adı</span>
                                    </div>
                                    <div class="readonly-preview-box" id="default-name">{{ $tour->name }}</div>
                                </div>

                                <!-- Short Description -->
                                <div class="translation-field-container">
                                    <div class="translation-field-header">
                                        <span class="translation-field-label">Kısa Açıklama</span>
                                    </div>
                                    <div class="readonly-preview-box" style="white-space: pre-wrap;" id="default-short_description">{{ $tour->short_description }}</div>
                                </div>

                                <!-- Description -->
                                <div class="translation-field-container">
                                    <div class="translation-field-header">
                                        <span class="translation-field-label">Detaylı Açıklama</span>
                                    </div>
                                    <div class="readonly-preview-rich" id="default-description">{!! $tour->description !!}</div>
                                </div>

                                <!-- Gezilecek Yerler (places_to_visit) -->
                                <div class="translation-field-container">
                                    <div class="translation-field-header">
                                        <span class="translation-field-label">Gezilecek Yerler</span>
                                    </div>
                                    <div class="readonly-preview-rich" id="default-places_to_visit">{!! $tour->places_to_visit !!}</div>
                                </div>

                                <!-- Dahil Olan Hizmetler -->
                                <div class="translation-field-container">
                                    <div class="translation-field-header">
                                        <span class="translation-field-label">Dahil Olan Hizmetler</span>
                                    </div>
                                    <div class="readonly-preview-rich" id="default-inclusions">{!! $tour->inclusions !!}</div>
                                </div>

                                <!-- Dahil Olmayan Hizmetler -->
                                <div class="translation-field-container">
                                    <div class="translation-field-header">
                                        <span class="translation-field-label">Dahil Olmayan Hizmetler</span>
                                    </div>
                                    <div class="readonly-preview-rich" id="default-exclusions">{!! $tour->exclusions !!}</div>
                                </div>

                                <!-- İptal Politikası -->
                                <div class="translation-field-container">
                                    <div class="translation-field-header">
                                        <span class="translation-field-label">İptal Politikası</span>
                                    </div>
                                    <div class="readonly-preview-rich" id="default-cancellation_policy">{!! $tour->cancellation_policy !!}</div>
                                </div>

                                <!-- SEO Title -->
                                <div class="translation-field-container">
                                    <div class="translation-field-header">
                                        <span class="translation-field-label">SEO Başlığı (Meta Title)</span>
                                    </div>
                                    <div class="readonly-preview-box" id="default-meta_title">{{ $tour->meta_title }}</div>
                                </div>

                                <!-- SEO Description -->
                                <div class="translation-field-container">
                                    <div class="translation-field-header">
                                        <span class="translation-field-label">SEO Açıklaması (Meta Description)</span>
                                    </div>
                                    <div class="readonly-preview-box" style="white-space: pre-wrap;" id="default-meta_description">{{ $tour->meta_description }}</div>
                                </div>
                            </div>

                            <!-- Right Column: Translatable Input Fields -->
                            <div class="translation-column">
                                <div class="translation-column-title" id="translationColumnTitle">
                                    <i class="fas fa-language text-primary"></i> Çeviri İçeriği
                                </div>

                                <!-- Name -->
                                <div class="translation-field-container">
                                    <div class="translation-field-header">
                                        <label class="translation-field-label" for="input-name">Tur Adı</label>
                                        <button type="button" class="btn-copy-default" onclick="copyDefault('name')">
                                            <i class="fas fa-copy"></i> Varsayılandan Kopyala
                                        </button>
                                    </div>
                                    <input type="text" name="name" id="input-name" class="form-control">
                                </div>

                                <!-- Short Description -->
                                <div class="translation-field-container">
                                    <div class="translation-field-header">
                                        <label class="translation-field-label" for="input-short_description">Kısa Açıklama</label>
                                        <button type="button" class="btn-copy-default" onclick="copyDefault('short_description')">
                                            <i class="fas fa-copy"></i> Varsayılandan Kopyala
                                        </button>
                                    </div>
                                    <textarea name="short_description" id="input-short_description" class="form-control" rows="3"></textarea>
                                </div>

                                <!-- Description -->
                                <div class="translation-field-container">
                                    <div class="translation-field-header">
                                        <label class="translation-field-label">Detaylı Açıklama</label>
                                        <button type="button" class="btn-copy-default" onclick="copyDefaultRich('description')">
                                            <i class="fas fa-copy"></i> Varsayılandan Kopyala
                                        </button>
                                    </div>
                                    <div class="quill-editor-container">
                                        <div id="editor-description"></div>
                                    </div>
                                    <input type="hidden" name="description" id="input-description">
                                </div>

                                <!-- Gezilecek Yerler (highlights) -->
                                <div class="translation-field-container">
                                    <div class="translation-field-header">
                                        <label class="translation-field-label">Gezilecek Yerler</label>
                                        <button type="button" class="btn-copy-default" onclick="copyDefaultRich('places_to_visit', 'highlights')">
                                            <i class="fas fa-copy"></i> Varsayılandan Kopyala
                                        </button>
                                    </div>
                                    <div class="quill-editor-container">
                                        <div id="editor-highlights"></div>
                                    </div>
                                    <input type="hidden" name="highlights" id="input-highlights">
                                </div>

                                <!-- Inclusions -->
                                <div class="translation-field-container">
                                    <div class="translation-field-header">
                                        <label class="translation-field-label">Dahil Olan Hizmetler</label>
                                        <button type="button" class="btn-copy-default" onclick="copyDefaultRich('inclusions')">
                                            <i class="fas fa-copy"></i> Varsayılandan Kopyala
                                        </button>
                                    </div>
                                    <div class="quill-editor-container">
                                        <div id="editor-inclusions"></div>
                                    </div>
                                    <input type="hidden" name="inclusions" id="input-inclusions">
                                </div>

                                <!-- Exclusions -->
                                <div class="translation-field-container">
                                    <div class="translation-field-header">
                                        <label class="translation-field-label">Dahil Olmayan Hizmetler</label>
                                        <button type="button" class="btn-copy-default" onclick="copyDefaultRich('exclusions')">
                                            <i class="fas fa-copy"></i> Varsayılandan Kopyala
                                        </button>
                                    </div>
                                    <div class="quill-editor-container">
                                        <div id="editor-exclusions"></div>
                                    </div>
                                    <input type="hidden" name="exclusions" id="input-exclusions">
                                </div>

                                <!-- Cancellation Policy -->
                                <div class="translation-field-container">
                                    <div class="translation-field-header">
                                        <label class="translation-field-label">İptal Politikası</label>
                                        <button type="button" class="btn-copy-default" onclick="copyDefaultRich('cancellation_policy')">
                                            <i class="fas fa-copy"></i> Varsayılandan Kopyala
                                        </button>
                                    </div>
                                    <div class="quill-editor-container">
                                        <div id="editor-cancellation_policy"></div>
                                    </div>
                                    <input type="hidden" name="cancellation_policy" id="input-cancellation_policy">
                                </div>

                                <!-- SEO Title -->
                                <div class="translation-field-container">
                                    <div class="translation-field-header">
                                        <label class="translation-field-label" for="input-meta_title">SEO Başlığı (Meta Title)</label>
                                        <button type="button" class="btn-copy-default" onclick="copyDefault('meta_title')">
                                            <i class="fas fa-copy"></i> Varsayılandan Kopyala
                                        </button>
                                    </div>
                                    <input type="text" name="meta_title" id="input-meta_title" class="form-control">
                                </div>

                                <!-- SEO Description -->
                                <div class="translation-field-container">
                                    <div class="translation-field-header">
                                        <label class="translation-field-label" for="input-meta_description">SEO Açıklaması (Meta Description)</label>
                                        <button type="button" class="btn-copy-default" onclick="copyDefault('meta_description')">
                                            <i class="fas fa-copy"></i> Varsayılandan Kopyala
                                        </button>
                                    </div>
                                    <textarea name="meta_description" id="input-meta_description" class="form-control" rows="3"></textarea>
                                </div>
                            </div>
                        </div>

                        <!-- Actions Bar -->
                        <div class="actions-bar">
                            <div class="actions-bar-info">
                                <i class="fas fa-info-circle text-primary me-2"></i>
                                Seçili pazar yeri ve dil için çevirileri düzenliyorsunuz.
                            </div>
                            <div class="d-flex gap-2">
                                <button type="button" class="btn btn-outline-secondary" onclick="window.history.back()">
                                    İptal
                                </button>
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save me-2"></i> Çevirileri Kaydet
                                </button>
                            </div>
                        </div>
                    </form>
                @endif
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <!-- Quill Rich Text Editor JS -->
    <script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
    <script>
        // Store marketplace structure
        const marketplaces = @json($marketplaces);
        let selectedMarketplaceId = null;
        let selectedLanguageId = null;
        let editors = {};

        document.addEventListener('DOMContentLoaded', function () {
            if (marketplaces.length > 0) {
                // Initialize Quill editors
                const toolbarOptions = [
                    ['bold', 'italic', 'underline', 'strike'],
                    [{'list': 'ordered'}, {'list': 'bullet'}],
                    [{'color': []}, {'background': []}],
                    ['link', 'clean']
                ];

                const editorFields = ['description', 'highlights', 'inclusions', 'exclusions', 'cancellation_policy'];
                editorFields.forEach(field => {
                    editors[field] = new Quill(`#editor-${field}`, {
                        theme: 'snow',
                        modules: { toolbar: toolbarOptions },
                        placeholder: 'Çeviri içeriğini buraya yazın veya varsayılandan kopyalayın...'
                    });

                    // Sync Quill HTML content to hidden input on change
                    editors[field].on('text-change', function() {
                        document.getElementById(`input-${field}`).value = editors[field].root.innerHTML;
                    });
                });

                // Auto-select first marketplace
                selectMarketplace(marketplaces[0].id);
            }
        });

        function selectMarketplace(id) {
            selectedMarketplaceId = id;
            selectedLanguageId = null;

            // Update Active Class on Card
            document.querySelectorAll('.marketplace-select-card').forEach(card => {
                card.classList.remove('active');
                if (parseInt(card.dataset.id) === id) {
                    card.classList.add('active');
                }
            });

            // Find selected marketplace object
            const marketplace = marketplaces.find(m => m.id === id);
            
            // Build language pills
            const languagePills = document.getElementById('languagePills');
            languagePills.innerHTML = '';
            
            if (marketplace && marketplace.languages && marketplace.languages.length > 0) {
                marketplace.languages.forEach(lang => {
                    const pill = document.createElement('div');
                    pill.className = 'language-pill';
                    pill.dataset.langId = lang.id;
                    pill.innerHTML = `
                        <i class="fas fa-globe-americas"></i> ${lang.name} (${lang.code.toUpperCase()})
                    `;
                    pill.onclick = () => selectLanguage(lang.id, lang.name);
                    languagePills.appendChild(pill);
                });

                document.getElementById('languageContainer').style.display = 'block';
                document.getElementById('translationForm').style.display = 'none';

                // Auto-select first language
                selectLanguage(marketplace.languages[0].id, marketplace.languages[0].name);
            } else {
                document.getElementById('languageContainer').style.display = 'none';
                document.getElementById('translationForm').style.display = 'none';
                alert('Bu pazar yerine tanımlanmış bir dil bulunmuyor.');
            }
        }

        function selectLanguage(id, name) {
            selectedLanguageId = id;

            // Update active pill
            document.querySelectorAll('.language-pill').forEach(pill => {
                pill.classList.remove('active');
                if (parseInt(pill.dataset.langId) === id) {
                    pill.classList.add('active');
                }
            });

            // Set Form Hidden Inputs
            document.getElementById('marketplaceIdInput').value = selectedMarketplaceId;
            document.getElementById('languageIdInput').value = selectedLanguageId;

            // Update column title
            document.getElementById('translationColumnTitle').innerHTML = `
                <i class="fas fa-language text-primary"></i> Çeviri İçeriği (${name})
            `;

            // Load translations
            fetchTranslations();
        }

        function showLoader(message = 'Yükleniyor...') {
            document.getElementById('loaderMessage').textContent = message;
            document.getElementById('workspaceLoader').classList.add('active');
        }

        function hideLoader() {
            document.getElementById('workspaceLoader').classList.remove('active');
        }

        function fetchTranslations() {
            showLoader('Çeviriler getiriliyor...');

            const url = `{{ route('agency.products.kultur-turlari.translations.fetch', $tour) }}?marketplace_id=${selectedMarketplaceId}&language_id=${selectedLanguageId}`;
            
            fetch(url, {
                headers: {
                    'Accept': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                hideLoader();
                if (data.success) {
                    // Populate Form
                    const trans = data.translation || {};
                    
                    document.getElementById('input-name').value = trans.name || '';
                    document.getElementById('input-short_description').value = trans.short_description || '';
                    document.getElementById('input-meta_title').value = trans.meta_title || '';
                    document.getElementById('input-meta_description').value = trans.meta_description || '';

                    // Quill Content
                    editors.description.root.innerHTML = trans.description || '';
                    editors.highlights.root.innerHTML = trans.highlights || '';
                    editors.inclusions.root.innerHTML = trans.inclusions || '';
                    editors.exclusions.root.innerHTML = trans.exclusions || '';
                    editors.cancellation_policy.root.innerHTML = trans.cancellation_policy || '';

                    // Sync hidden inputs
                    document.getElementById('input-description').value = trans.description || '';
                    document.getElementById('input-highlights').value = trans.highlights || '';
                    document.getElementById('input-inclusions').value = trans.inclusions || '';
                    document.getElementById('input-exclusions').value = trans.exclusions || '';
                    document.getElementById('input-cancellation_policy').value = trans.cancellation_policy || '';

                    // Show form
                    document.getElementById('translationForm').style.display = 'block';
                } else {
                    alert('Çeviriler alınırken hata oluştu: ' + data.message);
                }
            })
            .catch(err => {
                hideLoader();
                console.error(err);
                alert('Sistem hatası. Çeviriler yüklenemedi.');
            });
        }

        // Copy default helper
        function copyDefault(fieldName) {
            const defaultValue = document.getElementById(`default-${fieldName}`).textContent.trim();
            document.getElementById(`input-${fieldName}`).value = defaultValue;
        }

        function copyDefaultRich(sourceField, targetField = null) {
            const target = targetField || sourceField;
            const defaultValue = document.getElementById(`default-${sourceField}`).innerHTML;
            editors[target].root.innerHTML = defaultValue;
            document.getElementById(`input-${target}`).value = defaultValue;
        }

        // Form Submission
        document.getElementById('translationForm').addEventListener('submit', function (e) {
            e.preventDefault();
            
            showLoader('Çeviriler kaydediliyor...');
            
            const formData = new FormData(this);

            fetch('{{ route('agency.products.kultur-turlari.translations.save', $tour) }}', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('[name="_token"]').value,
                    'Accept': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                hideLoader();
                if (data.success) {
                    // Create and show success alert
                    document.querySelectorAll('.alert').forEach(a => a.remove());

                    const alertDiv = document.createElement('div');
                    alertDiv.className = 'alert alert-success alert-dismissible fade show';
                    alertDiv.innerHTML = `
                        <i class="fas fa-check-circle me-2"></i> ${data.message}
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    `;
                    
                    const tabContent = document.querySelector('.tab-content');
                    tabContent.insertBefore(alertDiv, tabContent.firstChild);
                    
                    // Scroll to notification
                    tabContent.scrollIntoView({ behavior: 'smooth', block: 'start' });

                    setTimeout(() => {
                        alertDiv.remove();
                    }, 4000);
                } else {
                    alert('Kaydedilirken hata oluştu: ' + data.message);
                }
            })
            .catch(err => {
                hideLoader();
                console.error(err);
                alert('Sistem hatası. Kaydedilemedi.');
            });
        });
    </script>
@endpush
