// QR Menü — Admin panel etkileşimleri
(function () {
    'use strict';

    // Silme onayı
    document.querySelectorAll('[data-confirm]').forEach((el) => {
        el.addEventListener('click', (e) => {
            if (!confirm(el.getAttribute('data-confirm'))) { e.preventDefault(); }
        });
    });

    // Sekmeler (ayarlar)
    const tabs = document.querySelectorAll('.tab');
    if (tabs.length) {
        tabs.forEach((t) => {
            t.addEventListener('click', () => {
                const name = t.getAttribute('data-tab');
                tabs.forEach((x) => x.classList.remove('active'));
                t.classList.add('active');
                document.querySelectorAll('.tab-panel').forEach((p) => {
                    p.classList.toggle('active', p.getAttribute('data-panel') === name);
                });
            });
        });
    }

    // Tema renk canlı önizleme
    const cp = {
        primary: document.getElementById('c_primary'),
        secondary: document.getElementById('c_secondary'),
        bg: document.getElementById('c_bg'),
        surface: document.getElementById('c_surface'),
        text: document.getElementById('c_text'),
        muted: document.getElementById('c_muted'),
    };
    const preview = document.getElementById('themePreview');
    function updatePreview() {
        if (!preview || !cp.primary) return;
        const card = preview.querySelector('.tp-card');
        const title = preview.querySelector('.tp-title');
        const muted = preview.querySelector('.tp-muted');
        const btn = preview.querySelector('.tp-btn');
        preview.style.background = cp.bg.value;
        preview.style.padding = '20px';
        preview.style.borderRadius = '16px';
        card.style.background = cp.surface.value;
        card.style.border = '1px solid rgba(255,255,255,.08)';
        title.style.color = cp.text.value;
        muted.style.color = cp.muted.value;
        btn.style.background = 'linear-gradient(100deg,' + cp.primary.value + ',' + cp.secondary.value + ')';
        btn.style.color = '#1a1408';
    }
    Object.values(cp).forEach((inp) => inp && inp.addEventListener('input', updatePreview));
    updatePreview();

    // Hazır tema seçimi
    document.querySelectorAll('.preset').forEach((btn) => {
        btn.addEventListener('click', () => {
            if (cp.primary) cp.primary.value = btn.dataset.p;
            if (cp.secondary) cp.secondary.value = btn.dataset.p2;
            if (cp.bg) cp.bg.value = btn.dataset.bg;
            if (cp.surface) cp.surface.value = btn.dataset.surface;
            if (cp.text) cp.text.value = btn.dataset.text;
            if (cp.muted) cp.muted.value = btn.dataset.muted;
            updatePreview();
        });
    });

    // Yapay zeka ile besin doldurma
    const aiBtn = document.getElementById('aiBtn');
    if (aiBtn) {
        aiBtn.addEventListener('click', async () => {
            const name = (document.getElementById('prodName') || {}).value || '';
            const desc = (document.getElementById('prodDesc') || {}).value || '';
            const status = document.getElementById('aiStatus');
            const url = (document.getElementById('aiUrl') || {}).value;
            if (!name.trim()) {
                status.className = 'ai-status err';
                status.textContent = 'Önce ürün adını girin.';
                return;
            }
            aiBtn.disabled = true;
            status.className = 'ai-status';
            status.textContent = 'Analiz ediliyor...';
            try {
                const fd = new FormData();
                fd.append('name', name);
                fd.append('description', desc);
                const csrfEl = document.getElementById('aiCsrf');
                if (csrfEl) fd.append('_csrf', csrfEl.value);
                const res = await fetch(url, { method: 'POST', body: fd, headers: { 'X-Requested-With': 'fetch' } });
                const json = await res.json();
                if (!json.ok) throw new Error(json.error || 'Hata');
                const d = json.data;
                const set = (id, val) => { const el = document.getElementById(id); if (el && (el.value === '' || el.value === '0')) el.value = val; };
                const force = (id, val) => { const el = document.getElementById(id); if (el) el.value = val; };
                force('f_calories', d.calories);
                force('f_protein', d.protein);
                force('f_carbs', d.carbs);
                force('f_fat', d.fat);
                force('f_sugar', d.sugar);
                force('f_caffeine', d.caffeine);
                force('f_allergens', d.allergens);
                force('f_notes', d.notes);
                const descEl = document.getElementById('prodDesc');
                if (descEl && !descEl.value.trim()) descEl.value = d.description;
                status.className = 'ai-status ok';
                status.textContent = '✓ Dolduruldu (güven: ' + d.confidence + '). Değerleri düzenleyebilirsiniz.';
            } catch (err) {
                status.className = 'ai-status err';
                status.textContent = 'Hata: ' + err.message;
            } finally {
                aiBtn.disabled = false;
            }
        });
    }
})();
