/**
 * FATE 後台新增店家：台灣縣市二級選單、OSM 預覽 GPS、Google 格式營業時間
 */
(function () {
    'use strict';

    var cfg = window.FATE_ADD_STORE_CFG || {};
    var citiesApi = cfg.citiesApi || 'cities_api.php';
    var geocodeApi = cfg.geocodeApi || 'geocode_api.php';

    function $(id) {
        return document.getElementById(id);
    }

    /**
     * @param {string} url
     * @param {{allowOkEnvelope?: boolean}} opts allowOkEnvelope：含 ok/error 欄位時不拋錯（geocode_api）
     */
    function fetchJson(url, opts) {
        opts = opts || {};
        return fetch(url, { credentials: 'same-origin' })
            .then(function (r) {
                return r.text().then(function (text) {
                    var data = null;
                    try {
                        data = text ? JSON.parse(text) : null;
                    } catch (e) {
                        if (!r.ok) {
                            throw new Error('HTTP ' + r.status);
                        }
                        throw new Error('回應不是 JSON（可能路徑錯誤或未登入）');
                    }
                    if (!r.ok) {
                        var errMsg = (data && data.error) ? String(data.error) : ('HTTP ' + r.status);
                        throw new Error(errMsg);
                    }
                    if (
                        data &&
                        typeof data === 'object' &&
                        !Array.isArray(data) &&
                        data.error &&
                        !(opts.allowOkEnvelope && typeof data.ok === 'boolean')
                    ) {
                        throw new Error(String(data.error));
                    }
                    return data;
                });
            });
    }

    function setCityStatus(msg, isError) {
        var el = $('cityDistrictStatus');
        if (!el) {
            return;
        }
        el.textContent = msg || '';
        el.style.color = isError ? 'var(--bad)' : 'var(--muted)';
    }

    function initCityDistrict() {
        var citySel = $('citySelector');
        var distSel = $('districtSelector');
        var zipInput = $('zipCode');
        if (!citySel || !distSel) {
            return;
        }

        var initialCity = cfg.initialCity || '';
        var initialDistrict = cfg.initialDistrict || '';

        citySel.disabled = true;
        setCityStatus('正在載入城市…', false);
        fetchJson(citiesApi + '?action=getCities')
            .then(function (cities) {
                if (!Array.isArray(cities)) {
                    throw new Error('城市列表格式錯誤');
                }
                citySel.innerHTML = '<option value="">請選擇城市</option>';
                cities.forEach(function (city) {
                    var opt = document.createElement('option');
                    opt.value = city;
                    opt.textContent = city;
                    if (initialCity && city === initialCity) {
                        opt.selected = true;
                    }
                    citySel.appendChild(opt);
                });
                citySel.disabled = false;
                setCityStatus('', false);
                if (initialCity) {
                    loadDistricts(initialCity, initialDistrict);
                }
            })
            .catch(function (err) {
                var msg = (err && err.message) ? err.message : '載入城市失敗';
                citySel.innerHTML = '<option value="">載入城市失敗</option>';
                citySel.disabled = false;
                setCityStatus(msg, true);
            });

        function loadDistricts(city, selectDistrict) {
            distSel.disabled = true;
            distSel.innerHTML = '<option value="">載入中…</option>';
            fetchJson(citiesApi + '?action=getDistricts&city=' + encodeURIComponent(city))
                .then(function (districts) {
                    if (!Array.isArray(districts)) {
                        throw new Error('地區列表格式錯誤');
                    }
                    distSel.innerHTML = '<option value="">請選擇地區</option>';
                    districts.forEach(function (d) {
                        var name = d.district_name || d;
                        var opt = document.createElement('option');
                        opt.value = name;
                        opt.textContent = name;
                        if (d.zip_code) {
                            opt.dataset.zipCode = d.zip_code;
                        }
                        if (selectDistrict && name === selectDistrict) {
                            opt.selected = true;
                            if (zipInput && d.zip_code) {
                                zipInput.value = d.zip_code;
                            }
                        }
                        distSel.appendChild(opt);
                    });
                    distSel.disabled = false;
                })
                .catch(function (err) {
                    var msg = (err && err.message) ? err.message : '載入地區失敗';
                    distSel.innerHTML = '<option value="">載入地區失敗</option>';
                    distSel.disabled = false;
                    setCityStatus(msg, true);
                });
        }

        citySel.addEventListener('change', function () {
            var city = citySel.value;
            if (!city) {
                distSel.innerHTML = '<option value="">請先選擇城市</option>';
                distSel.disabled = true;
                if (zipInput) {
                    zipInput.value = '';
                }
                return;
            }
            loadDistricts(city, '');
        });

        distSel.addEventListener('change', function () {
            var opt = distSel.options[distSel.selectedIndex];
            if (zipInput && opt && opt.dataset.zipCode) {
                zipInput.value = opt.dataset.zipCode;
            }
        });
    }

    function initGeocodePreview() {
        var btn = $('btnGeocodePreview');
        var statusEl = $('geocodeStatus');
        var gps = $('gpsLocation');
        var placeFmt = $('placeFormattedAddress');
        if (!btn) {
            return;
        }

        btn.addEventListener('click', function () {
            var citySel = $('citySelector');
            var distSel = $('districtSelector');
            var street = ($('streetAddress') || {}).value || '';
            var zip = ($('zipCode') || {}).value || '';
            var city = citySel ? citySel.value : '';
            var district = distSel ? distSel.value : '';
            if (!city || !district || !street.trim()) {
                if (statusEl) {
                    statusEl.textContent = '請先選擇城市、地區並填寫街道';
                    statusEl.style.color = 'var(--bad)';
                }
                return;
            }
            if (statusEl) {
                statusEl.textContent = '查詢中…';
                statusEl.style.color = 'var(--muted)';
            }
            btn.disabled = true;
            var url = geocodeApi
                + '?city=' + encodeURIComponent(city)
                + '&district=' + encodeURIComponent(district)
                + '&street=' + encodeURIComponent(street)
                + '&zip=' + encodeURIComponent(zip);
            fetchJson(url, { allowOkEnvelope: true })
                .then(function (d) {
                    btn.disabled = false;
                    if (!d || d.ok === false) {
                        if (statusEl) {
                            statusEl.textContent = (d && d.error) ? d.error : '查詢失敗';
                            statusEl.style.color = 'var(--bad)';
                        }
                        return;
                    }
                    if (gps) {
                        gps.value = d.google_map_location || '';
                    }
                    if (placeFmt && !placeFmt.value.trim() && d.display_name) {
                        placeFmt.value = d.display_name;
                    }
                    if (statusEl) {
                        var provider = (d.provider === 'google') ? 'Google' : ((d.provider === 'osm') ? 'OSM' : '');
                        var okMsg;
                        if (d.google_fallback && d.google_error) {
                            okMsg = 'Google 未成功（' + d.google_error + '）→ 已改用 OSM';
                            if (d.precision === 'district') {
                                okMsg += '：僅行政區近似座標，請核對或手動微調 GPS';
                            }
                            statusEl.style.color = 'var(--warn)';
                        } else {
                            okMsg = provider ? ('已取得座標（' + provider + '）') : '已取得座標';
                            if (d.precision === 'district') {
                                okMsg = (provider ? provider + '：' : '') + '已取得行政區近似座標（建議核對或手動微調 GPS）';
                            }
                            statusEl.style.color = d.precision === 'district' ? 'var(--warn)' : 'var(--ok)';
                        }
                        statusEl.textContent = okMsg;
                    }
                })
                .catch(function (err) {
                    btn.disabled = false;
                    if (statusEl) {
                        statusEl.textContent = (err && err.message) ? err.message : '無法連線伺服器';
                        statusEl.style.color = 'var(--bad)';
                    }
                });
        });
    }

    function initBusinessHours() {
        var dialog = $('multiHoursModal');
        var hidden = $('multiHoursJson');
        var openBtn = $('btnOpenHoursModal');
        var saveBtn = $('btnSaveMultiHours');
        var cancelBtn = $('btnCancelMultiHours');
        var summary = $('hoursSummary');

        if (!dialog || !hidden) {
            return;
        }

        if (cfg.multiHoursJson) {
            hidden.value = cfg.multiHoursJson;
        }

        function updateSummary() {
            if (!summary) {
                return;
            }
            try {
                var h = JSON.parse(hidden.value || '{}');
                var parts = [];
                var labels = { Monday: '一', Tuesday: '二', Wednesday: '三', Thursday: '四', Friday: '五', Saturday: '六', Sunday: '日' };
                Object.keys(labels).forEach(function (day) {
                    var v = (h[day] || '').trim();
                    if (v) {
                        parts.push('週' + labels[day] + ' ' + v);
                    }
                });
                summary.textContent = parts.length ? parts.join('；') : '尚未設定（可留空）';
            } catch (e) {
                summary.textContent = '尚未設定';
            }
        }

        document.querySelectorAll('.hours-set-closed').forEach(function (btn) {
            btn.addEventListener('click', function () {
                var day = btn.getAttribute('data-day');
                var inp = document.querySelector('.multi-hours-input[data-day="' + day + '"]');
                if (inp) {
                    inp.value = 'Closed';
                }
            });
        });

        document.querySelectorAll('.hours-set-24h').forEach(function (btn) {
            btn.addEventListener('click', function () {
                var day = btn.getAttribute('data-day');
                var inp = document.querySelector('.multi-hours-input[data-day="' + day + '"]');
                if (inp) {
                    inp.value = '00:00-00:00';
                }
            });
        });

        var set24 = $('btnSetSimple24Hours');
        if (set24) {
            set24.addEventListener('click', function () {
                var st = $('businessHoursStart');
                var en = $('businessHoursEnd');
                if (st) {
                    st.value = '00:00';
                }
                if (en) {
                    en.value = '00:00';
                }
            });
        }

        if (openBtn) {
            openBtn.addEventListener('click', function () {
                try {
                    var h = JSON.parse(hidden.value || '{}');
                    document.querySelectorAll('.multi-hours-input').forEach(function (inp) {
                        var day = inp.getAttribute('data-day');
                        if (day && h[day] !== undefined) {
                            inp.value = h[day];
                        }
                    });
                } catch (e) { /* ignore */ }
                if (typeof dialog.showModal === 'function') {
                    dialog.showModal();
                }
            });
        }

        function closeDialog() {
            if (typeof dialog.close === 'function') {
                dialog.close();
            }
        }

        if (cancelBtn) {
            cancelBtn.addEventListener('click', closeDialog);
        }
        var cancelFoot = $('btnCancelMultiHoursFoot');
        if (cancelFoot) {
            cancelFoot.addEventListener('click', closeDialog);
        }

        if (saveBtn) {
            saveBtn.addEventListener('click', function () {
                var hours = {};
                document.querySelectorAll('.multi-hours-input').forEach(function (inp) {
                    var day = inp.getAttribute('data-day');
                    if (day) {
                        hours[day] = inp.value.trim();
                    }
                });
                hidden.value = JSON.stringify(hours);
                updateSummary();
                dialog.close();
            });
        }

        updateSummary();
    }

    function initPhotoPreview() {
        var coverInput = $('coverPhotoInput');
        var coverBox = $('coverPhotoPreview');
        var intInput = $('interiorImagesInput');
        var intBox = $('interiorPhotoPreview');
        var maxInterior = 4;

        function showBox(box, show) {
            if (!box) {
                return;
            }
            if (show) {
                box.hidden = false;
            } else {
                box.hidden = true;
                box.innerHTML = '';
            }
        }

        function appendThumb(container, file, label) {
            if (!window.FileReader || !file.type.match(/^image\//)) {
                return;
            }
            var wrap = document.createElement('figure');
            wrap.className = 'photo-preview__item';
            var cap = document.createElement('figcaption');
            cap.className = 'photo-preview__cap';
            cap.textContent = label || file.name || '';
            var img = document.createElement('img');
            img.alt = label || '預覽';
            wrap.appendChild(img);
            wrap.appendChild(cap);
            container.appendChild(wrap);
            var reader = new FileReader();
            reader.onload = function (e) {
                img.src = e.target && e.target.result ? e.target.result : '';
            };
            reader.readAsDataURL(file);
        }

        if (coverInput && coverBox) {
            coverInput.addEventListener('change', function () {
                var file = coverInput.files && coverInput.files[0];
                if (!file) {
                    showBox(coverBox, false);
                    return;
                }
                coverBox.innerHTML = '';
                showBox(coverBox, true);
                appendThumb(coverBox, file, '封面');
            });
        }

        if (intInput && intBox) {
            intInput.addEventListener('change', function () {
                var files = intInput.files;
                if (!files || files.length === 0) {
                    showBox(intBox, false);
                    return;
                }
                intBox.innerHTML = '';
                showBox(intBox, true);
                var n = Math.min(maxInterior, files.length);
                for (var i = 0; i < n; i++) {
                    appendThumb(intBox, files[i], '店內 ' + (i + 1));
                }
                if (files.length > maxInterior) {
                    var note = document.createElement('p');
                    note.className = 'sub photo-preview__note';
                    note.textContent = '已選 ' + files.length + ' 張，送出時僅上傳前 ' + maxInterior + ' 張。';
                    intBox.appendChild(note);
                }
            });
        }
    }

    document.addEventListener('DOMContentLoaded', function () {
        initCityDistrict();
        initGeocodePreview();
        initBusinessHours();
        initPhotoPreview();
    });
})();
