(function () {
    const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content || '';

    function showToast(message) {
        const stack = document.querySelector('[data-toast-stack]');
        if (!stack) return;
        const toast = document.createElement('div');
        toast.className = 'app-toast';
        toast.textContent = message;
        stack.appendChild(toast);
        window.setTimeout(() => toast.remove(), 3200);
    }

    function parseData(el, key, fallback = []) {
        try {
            return JSON.parse(el.dataset[key] || JSON.stringify(fallback));
        } catch {
            return fallback;
        }
    }

    function installTheme() {
        const saved = localStorage.getItem('civigo-theme');
        if (saved === 'dark') {
            document.body.dataset.theme = 'dark';
        }

        document.querySelectorAll('[data-theme-toggle]').forEach((button) => {
            button.addEventListener('click', () => {
                const dark = document.body.dataset.theme !== 'dark';
                document.body.dataset.theme = dark ? 'dark' : '';
                localStorage.setItem('civigo-theme', dark ? 'dark' : 'light');
                button.querySelector('i')?.classList.toggle('bi-sun', dark);
                button.querySelector('i')?.classList.toggle('bi-moon', !dark);
            });
        });
    }

    function installSidebar() {
        const sidebar = document.querySelector('#sidebar');
        document.querySelectorAll('[data-sidebar-toggle]').forEach((button) => {
            button.addEventListener('click', () => sidebar?.classList.toggle('open'));
        });
    }

    function initTooltips() {
        if (!window.bootstrap) return;
        document.querySelectorAll('[data-bs-toggle="tooltip"]').forEach((el) => {
            new bootstrap.Tooltip(el);
        });
    }

    function statusColor(status) {
        if (status === 'solved') return '#18B76A';
        if (status === 'in_progress') return '#F59E0B';
        return '#EF4444';
    }

    function initMap(id) {
        const el = document.getElementById(id);
        if (!el || !window.L) return;

        const reports = parseData(el, 'reports');
        const map = L.map(el, {
            zoomControl: true,
            scrollWheelZoom: false,
        }).setView([42.62, 25.2], id === 'fullMap' ? 7 : 6);

        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            maxZoom: 19,
            attribution: '&copy; OpenStreetMap',
        }).addTo(map);

        reports.forEach((report) => {
            if (!report.lat || !report.lng) return;
            L.circleMarker([report.lat, report.lng], {
                radius: 11,
                color: '#fff',
                weight: 3,
                fillColor: statusColor(report.status),
                fillOpacity: 0.96,
            })
                .addTo(map)
                .bindPopup(`<strong>#${report.id} ${report.title}</strong><br>${report.address}<br>${report.institution}`);
        });

        window.setTimeout(() => map.invalidateSize(), 120);
    }

    function initCharts() {
        if (!window.Chart) return;

        document.querySelectorAll('[data-chart]').forEach((canvas) => {
            const labels = parseData(canvas, 'labels');
            const values = parseData(canvas, 'values');
            const type = canvas.dataset.chart;

            new Chart(canvas, {
                type,
                data: {
                    labels,
                    datasets: [{
                        data: values,
                        borderRadius: 10,
                        backgroundColor: type === 'doughnut'
                            ? ['#18B76A', '#2563EB', '#7C3AED', '#F97316', '#EF4444']
                            : '#18B76A',
                        borderWidth: 0,
                    }],
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: {
                            display: type === 'doughnut',
                            position: 'bottom',
                        },
                    },
                    scales: type === 'bar' ? {
                        x: { grid: { display: false } },
                        y: { grid: { color: 'rgba(102,112,133,.16)' }, ticks: { precision: 0 } },
                    } : {},
                },
            });
        });
    }

    function installGps() {
        document.querySelectorAll('[data-gps]').forEach((button) => {
            button.addEventListener('click', () => {
                const output = document.querySelector('[data-gps-output]');
                if (!navigator.geolocation) {
                    if (output) output.textContent = 'Геолокацията не се поддържа.';
                    return;
                }

                navigator.geolocation.getCurrentPosition((position) => {
                    if (output) {
                        output.textContent = `${position.coords.latitude.toFixed(5)}, ${position.coords.longitude.toFixed(5)}`;
                    }
                }, () => {
                    if (output) output.textContent = 'GPS достъпът е отказан.';
                });
            });
        });
    }

    async function requestJson(url, options) {
        const response = await fetch(url, {
            headers: {
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRF-Token': csrfToken,
                ...(options?.headers || {}),
            },
            ...options,
        });

        return response.json();
    }

    function installReportForm() {
        const form = document.querySelector('.js-report-form');
        if (!form) return;

        const output = document.querySelector('.js-document-output');
        const proof = document.querySelector('.js-delivery-proof');

        form.addEventListener('submit', async (event) => {
            event.preventDefault();
            const result = await requestJson(form.action, {
                method: 'POST',
                body: new FormData(form),
            });

            if (result.ok && output) {
                output.textContent = result.document.text;
                if (proof && result.delivery) {
                    proof.innerHTML = renderDeliveryProof(result.delivery);
                }
                showToast(`Готов сигнал ${result.report.tracking_number}`);
            } else {
                showToast(result.message || 'Неуспешна заявка.');
            }
        });

        document.querySelector('[data-ai-polish]')?.addEventListener('click', async () => {
            const description = form.querySelector('[name="description"]');
            if (!description?.value) return;
            const body = new FormData();
            body.append('_csrf', csrfToken);
            body.append('message', description.value);
            const result = await requestJson('/api/assistant/suggest', { method: 'POST', body });
            if (result.ok) {
                description.value = result.result.official_text.split('\n\n')[3] || description.value;
                showToast('AI предложи по-официален текст.');
            }
        });
    }

    function renderDeliveryProof(delivery) {
        const evidence = delivery.evidence || {};
        const status = delivery.delivery_status || 'unknown';
        const channel = delivery.channel === 'edelivery' ? 'ССЕВ / портал' : 'Email';
        const messageId = delivery.message_id || evidence.message_id || 'Очаква се входящ номер';
        const note = evidence.note || evidence.next_step || evidence.reason || 'Запазете това доказателство към историята на сигнала.';
        const portal = evidence.portal || evidence.edelivery || '';

        return `
            <h3>Доказателство за доставка</h3>
            <dl class="proof-grid">
                <div><dt>Канал</dt><dd>${escapeHtml(channel)}</dd></div>
                <div><dt>Статус</dt><dd>${escapeHtml(status)}</dd></div>
                <div><dt>Получател</dt><dd>${escapeHtml(delivery.recipient_name || delivery.recipient_email || 'Компетентна институция')}</dd></div>
                <div><dt>Message ID</dt><dd>${escapeHtml(messageId)}</dd></div>
                ${portal ? `<div><dt>Портал</dt><dd>${escapeHtml(portal)}</dd></div>` : ''}
                <div><dt>Бележка</dt><dd>${escapeHtml(note)}</dd></div>
            </dl>
        `;
    }

    function installAiForm() {
        const form = document.querySelector('.js-ai-form');
        if (!form) return;

        const thread = document.querySelector('.js-chat-thread');
        const resultBox = document.querySelector('.js-ai-result');

        form.addEventListener('submit', async (event) => {
            event.preventDefault();
            const data = new FormData(form);
            const message = data.get('message');
            if (!message) return;

            thread?.insertAdjacentHTML('beforeend', `<div class="citizen-message"><p>${escapeHtml(String(message))}</p></div>`);
            const result = await requestJson(form.action, { method: 'POST', body: data });

            if (!result.ok) {
                showToast(result.message || 'AI заявката не успя.');
                return;
            }

            const ai = result.result;
            thread?.insertAdjacentHTML('beforeend', `<div class="assistant-message"><span class="avatar small">AI</span><p>Предлагам институция: <strong>${escapeHtml(ai.institution)}</strong>. Подготвих официален текст и следващи действия.</p></div>`);

            if (resultBox) {
                resultBox.innerHTML = `
                    <h3>Институция</h3>
                    <p>${escapeHtml(ai.institution)}</p>
                    <h3>Уточняващи въпроси</h3>
                    <ul>${ai.questions.map((item) => `<li>${escapeHtml(item)}</li>`).join('')}</ul>
                    <h3>Правни препратки</h3>
                    <ul>${ai.legal_references.map((item) => `<li>${escapeHtml(item)}</li>`).join('')}</ul>
                    <h3>Официален текст</h3>
                    <div class="document-preview">${escapeHtml(ai.official_text)}</div>
                    <h3>Следващи действия</h3>
                    <ul>${ai.next_actions.map((item) => `<li>${escapeHtml(item)}</li>`).join('')}</ul>
                `;
            }

            form.reset();
        });
    }

    function installDocForms() {
        document.querySelectorAll('.js-doc-form').forEach((form) => {
            form.addEventListener('submit', async (event) => {
                event.preventDefault();
                const result = await requestJson(form.action, {
                    method: 'POST',
                    body: new FormData(form),
                });
                const output = document.querySelector(form.dataset.output || '.document-preview');
                if (result.ok && output) {
                    output.textContent = result.document.text;
                    showToast('Документът е генериран.');
                }
            });
        });
    }

    function installPetitionForm() {
        const form = document.querySelector('.js-petition-form');
        if (!form) return;

        form.addEventListener('submit', async (event) => {
            event.preventDefault();
            const result = await requestJson(form.action, {
                method: 'POST',
                body: new FormData(form),
            });
            showToast(result.ok ? 'Петицията е създадена.' : 'Неуспешно създаване.');
        });
    }

    function installTrackingForm() {
        const form = document.querySelector('.js-track-form');
        if (!form) return;

        form.addEventListener('submit', async (event) => {
            event.preventDefault();
            const result = await requestJson(form.action, {
                method: 'POST',
                body: new FormData(form),
            });
            const output = document.querySelector('.js-track-output');
            if (result.ok && output) {
                const report = result.report;
                output.innerHTML = `<h2>#${report.id} ${escapeHtml(report.title)}</h2><p>${escapeHtml(report.address)}</p><span class="status-pill ${statusClass(report.status)}">${statusLabel(report.status)}</span>`;
                const enforcement = result.enforcement;
                if (enforcement?.actions?.length) {
                    output.insertAdjacentHTML('beforeend', `<div class="deadline-list mt-3">${enforcement.actions.map((item) => `<div><span>${escapeHtml(item)}</span></div>`).join('')}</div>`);
                }
                showToast('Статусът е обновен.');
            }
        });
    }

    function installTemplateButtons() {
        document.querySelectorAll('[data-template]').forEach((button) => {
            button.addEventListener('click', () => {
                const type = button.dataset.template || 'Сигнал';
                const hidden = document.querySelector('.js-doc-form [name="type"]');
                const output = document.querySelector('.js-generator-output');
                if (hidden) hidden.value = type.toLowerCase().includes('жалба') ? 'appeal' : 'signal';
                if (output) output.textContent = `Избран шаблон: ${type}. Попълни полетата и генерирай преглед.`;
            });
        });
    }

    function escapeHtml(value) {
        return value.replace(/[&<>"']/g, (char) => ({
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;',
        }[char]));
    }

    function statusClass(status) {
        if (status === 'solved') return 'success';
        if (status === 'in_progress') return 'warning';
        return 'danger';
    }

    function statusLabel(status) {
        if (status === 'solved') return 'Решен';
        if (status === 'in_progress') return 'В процес';
        if (status === 'late') return 'Просрочен';
        return 'Нерешен';
    }

    function installPwa() {
        if ('serviceWorker' in navigator) {
            navigator.serviceWorker.register('/sw.js').catch(() => {});
        }
    }

    document.addEventListener('DOMContentLoaded', () => {
        installTheme();
        installSidebar();
        initTooltips();
        initMap('dashboardMap');
        initMap('fullMap');
        initCharts();
        installGps();
        installReportForm();
        installAiForm();
        installDocForms();
        installPetitionForm();
        installTrackingForm();
        installTemplateButtons();
        installPwa();
    });
})();
