document.addEventListener('DOMContentLoaded', () => {
    const picker = document.querySelector('#address-picker');
    if (!picker) return;

    const province = picker.querySelector('#province');
    const district = picker.querySelector('#district');
    const neighborhood = picker.querySelector('#neighborhood');
    const districtManual = picker.querySelector('#district-manual-wrap');
    const neighborhoodManual = picker.querySelector('#neighborhood-manual-wrap');
    const apiBase = 'https://api.turkiyeapi.dev/v2';
    const oldDistrict = picker.dataset.oldDistrict || '';
    const oldNeighborhood = picker.dataset.oldNeighborhood || '';

    const resetSelect = (select, text) => {
        select.innerHTML = `<option value="">${text}</option>`;
        select.disabled = true;
    };

    const showManual = (level) => {
        if (level === 'district') {
            district.disabled = true;
            district.required = false;
            districtManual.hidden = false;
            districtManual.querySelector('input').required = true;
        }
        neighborhood.disabled = true;
        neighborhood.required = false;
        neighborhoodManual.hidden = false;
        neighborhoodManual.querySelector('input').required = true;
    };

    const fillOptions = (select, items, placeholder, oldValue = '') => {
        select.innerHTML = `<option value="">${placeholder}</option>`;
        items.sort((a, b) => a.name.localeCompare(b.name, 'tr'));
        items.forEach((item) => {
            const option = document.createElement('option');
            option.value = item.name;
            option.textContent = item.name;
            option.dataset.id = item.id;
            if (item.postalCode) option.dataset.postalCode = item.postalCode;
            if (item.name === oldValue) option.selected = true;
            select.appendChild(option);
        });
        select.disabled = false;
        select.required = true;
    };

    const request = async (path) => {
        const response = await fetch(`${apiBase}${path}`, { headers: { Accept: 'application/json' } });
        if (!response.ok) throw new Error('Adres listesi yüklenemedi');
        const json = await response.json();
        return Array.isArray(json.data) ? json.data : [];
    };

    const loadNeighborhoods = async (districtId, selected = '') => {
        resetSelect(neighborhood, 'Mahalleler yükleniyor…');
        neighborhoodManual.hidden = true;
        neighborhoodManual.querySelector('input').required = false;
        try {
            const items = await request(`/districts/${districtId}/neighborhoods`);
            if (!items.length) throw new Error('Mahalle bulunamadı');
            fillOptions(neighborhood, items, 'Mahalle seçin', selected);
            if (selected) neighborhood.dispatchEvent(new Event('change'));
        } catch (_) {
            showManual('neighborhood');
        }
    };

    const loadDistricts = async (provinceId, selectedDistrict = '', selectedNeighborhood = '') => {
        resetSelect(district, 'İlçeler yükleniyor…');
        resetSelect(neighborhood, 'Önce ilçe seçin');
        districtManual.hidden = true;
        districtManual.querySelector('input').required = false;
        neighborhoodManual.hidden = true;
        neighborhoodManual.querySelector('input').required = false;
        try {
            const items = await request(`/provinces/${provinceId}/districts`);
            if (!items.length) throw new Error('İlçe bulunamadı');
            fillOptions(district, items, 'İlçe seçin', selectedDistrict);
            if (selectedDistrict) {
                const selected = district.options[district.selectedIndex];
                if (selected?.dataset.id) await loadNeighborhoods(selected.dataset.id, selectedNeighborhood);
            }
        } catch (_) {
            showManual('district');
        }
    };

    province.addEventListener('change', () => {
        const selected = province.options[province.selectedIndex];
        if (!selected?.dataset.id) {
            resetSelect(district, 'Önce il seçin');
            resetSelect(neighborhood, 'Önce ilçe seçin');
            return;
        }
        loadDistricts(selected.dataset.id);
    });

    district.addEventListener('change', () => {
        const selected = district.options[district.selectedIndex];
        if (!selected?.dataset.id) {
            resetSelect(neighborhood, 'Önce ilçe seçin');
            return;
        }
        loadNeighborhoods(selected.dataset.id);
    });

    neighborhood.addEventListener('change', () => {
        const selected = neighborhood.options[neighborhood.selectedIndex];
        const postal = document.querySelector('#postal_code');
        if (postal && selected?.dataset.postalCode && !postal.value) postal.value = selected.dataset.postalCode;
    });

    const initialProvince = province.options[province.selectedIndex];
    if (initialProvince?.dataset.id) {
        loadDistricts(initialProvince.dataset.id, oldDistrict, oldNeighborhood);
    }
});
