@props([
    'label' => '',
    'field' => '',
    'model' => '',
    'modelId' => '',
    'fieldName' => '',
    'target' => '',
    'type' => 'text',
    'name' => '',
    'value' => '',
    'required' => false,
    'placeholder' => '',
    'rows' => null,
    'class' => 'form-control',
    'helpText' => null,
    'labelClass' => 'col-md-3 col-form-label text-md-end',
    'inputClass' => 'col-md-9',
    'languages' => [],
    'existingTranslations' => []
])

@php
   // // Dil verilerini al (default olarak TR ve EN)
   // $languages = $languages ?? [
   //     ['code' => 'tr', 'name' => 'Türkçe', 'site_default' => true],
   //     ['code' => 'en', 'name' => 'English', 'site_default' => false]
   // ];

    // Mevcut çevirileri al (edit modunda)
    $existingTranslations = $existingTranslations ?? [];
@endphp

<div class="row mb-3">
    <label class="{{ $labelClass }}">{{ $label }}</label>
    <div class="{{ $inputClass }}">
        <!-- Language Tabs -->
        <ul class="nav nav-tabs" role="tablist" id="languageTabs_{{ $field }}">
            @foreach($languages as $index => $language)
                @php
                    $isActive = $index === 0 ? 'active' : '';
                    $isDefault = $language['site_default'];
                    $tabClass = $isDefault ? 'nav-link fw-bold' : 'nav-link';
                @endphp
                <li class="nav-item" role="presentation">
                    <button class="{{ $tabClass }} {{ $isActive }}"
                            data-bs-toggle="tab"
                            data-bs-target="#tab_{{ $field }}_{{ $language['code'] }}"
                            type="button"
                            role="tab">
                        {{ $language['name'] }}
                        @if($isDefault)
                            <span class="badge bg-primary ms-2"
                                  data-bs-toggle="tooltip"
                                  data-bs-placement="top"
                                  title="{{ __('admin/common.translations_default_language_info') }}">
                                {{ __('admin/common.translations_default_badge') }}
                            </span>
                        @endif
                    </button>
                </li>
            @endforeach
        </ul>

        <!-- Tab Content -->
        <div class="tab-content mt-0" id="languageTabContent_{{ $field }}">
            @foreach($languages as $index => $language)
                @php
                    $isActive = $index === 0 ? 'show active' : '';
                    $isDefault = $language['site_default'];

                    // Değeri belirle
                    $currentValue = '';
                    if ($isDefault) {
                        // Default dil için ana input değerini kullan
                        $currentValue = $value;
                    } else {
                        // Diğer diller için mevcut çevirileri kullan
                        $currentValue = $existingTranslations[$language['code']] ?? '';
                    }
                @endphp

                <div class="tab-pane fade {{ $isActive }}"
                     id="tab_{{ $field }}_{{ $language['code'] }}"
                     role="tabpanel">

                    @if($type === 'textarea')
                        <textarea class="form-control translation-input"
                                  name="translations[{{ $language['code'] }}][{{ $field }}]"
                                  data-lang="{{ $language['code'] }}"
                                  data-field="{{ $field }}"
                                  data-is-default="{{ $isDefault ? 'true' : 'false' }}"
                                  rows="{{ $rows ?? 4 }}"
                                  placeholder="{{ $placeholder }}"
                                  @if($required && $isDefault) required @endif>{{ $currentValue }}</textarea>
                    @else
                        <input type="{{ $type }}"
                               class="form-control translation-input"
                               name="translations[{{ $language['code'] }}][{{ $field }}]"
                               data-lang="{{ $language['code'] }}"
                               data-field="{{ $field }}"
                               data-is-default="{{ $isDefault ? 'true' : 'false' }}"
                               value="{{ $currentValue }}"
                               placeholder="{{ $placeholder }}"
                               @if($required && $isDefault) required @endif>
                    @endif


                </div>
            @endforeach
        </div>

        @if($helpText)
            <small class="form-text text-muted mt-2">{{ $helpText }}</small>
        @endif
    </div>
</div>

<!-- Hidden input for main field (default language value) -->
@php
    $defaultLang = collect($languages)->firstWhere('site_default', true);
@endphp
@if($defaultLang)
    @if($type === 'textarea')
        <textarea name="{{ $name }}"
                  id="hidden_{{ $name }}"
                  style="display: none;">{{ $value }}</textarea>
    @else
        <input type="hidden"
               name="{{ $name }}"
               id="hidden_{{ $name }}"
               value="{{ $value }}">
    @endif
@endif

@push('scripts')
<script>
// Translation tabbed group functionality
if (!window.translationTabbedGroups) {
    window.translationTabbedGroups = {};
}

if (!window.translationTabbedGroups['{{ $field }}']) {
    window.translationTabbedGroups['{{ $field }}'] = {
        initialized: false,
        field: '{{ $field }}',
        defaultLangCode: '{{ $defaultLang['code'] ?? '' }}',

        init: function() {
            if (this.initialized) return;

            // Default dil input'una event listener ekle
            this.setupDefaultLanguageListener();

            // Tooltip'leri başlat
            this.initializeTooltips();

            this.initialized = true;
        },

        // Default dil input'una event listener ekle
        setupDefaultLanguageListener: function() {
            const defaultInput = document.querySelector(`[data-field="${this.field}"][data-is-default="true"]`);
            const hiddenInput = document.getElementById(`hidden_{{ $name }}`);

            if (defaultInput && hiddenInput) {
                defaultInput.addEventListener('input', (e) => {
                    // Hidden input'u güncelle (form submit için)
                    hiddenInput.value = e.target.value;

                    // Input event'ini tetikle ki diğer listener'lar çalışsın
                    const event = new Event('input', { bubbles: true });
                    hiddenInput.dispatchEvent(event);
                });

                // İlk yüklemede değeri senkronize et
                hiddenInput.value = defaultInput.value;
            }
        },

        // Tooltip'leri başlat
        initializeTooltips: function() {
            const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');
            [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl, {
                boundary: document.body
            }));
        },

        // Form submit için translation verilerini al
        getTranslationData: function() {
            const inputs = document.querySelectorAll(`[data-field="${this.field}"].translation-input`);
            const translations = {};

            inputs.forEach(input => {
                const lang = input.getAttribute('data-lang');
                const value = input.value;

                if (!translations[lang]) {
                    translations[lang] = {};
                }
                translations[lang][this.field] = value;
            });

            return translations;
        }
    };

    // Initialize when DOM is ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function() {
            window.translationTabbedGroups['{{ $field }}'].init();
        });
    } else {
        window.translationTabbedGroups['{{ $field }}'].init();
    }
}
</script>
@endpush
