(() => {
    const app = document.getElementById('report-app');
    if (!app) return;

    const bootstrap = window.reportBootstrap || {};
    const agentDirectory = bootstrap.agentDirectory || {};
    const saveStatus = document.getElementById('saveStatus');
    const persistForms = [...document.querySelectorAll('.persist-local')];
    const hasPersistedReport = () => !!(app.dataset.reportId && app.dataset.reportId !== '0');
    let webcamStream = null;

    const setStatus = (message, type = 'info') => {
        if (!saveStatus) return;
        saveStatus.className = `alert alert-${type} py-2 small`;
        saveStatus.textContent = message;
    };

    const storageKeyFor = (formId, reportId) => `db-report-draft-${formId}-${reportId || 'new'}`;

    const persistForm = (form) => {
        if (!form) return;
        const data = {};
        new FormData(form).forEach((value, keyName) => {
            if (value instanceof File) return;
            if (Object.prototype.hasOwnProperty.call(data, keyName)) {
                if (!Array.isArray(data[keyName])) data[keyName] = [data[keyName]];
                data[keyName].push(value);
            } else {
                data[keyName] = value;
            }
        });
        localStorage.setItem(form.dataset.localKey, JSON.stringify(data));
    };

    const updateReportId = (reportId) => {
        const previousId = app.dataset.reportId && app.dataset.reportId !== '0' ? app.dataset.reportId : 'new';
        app.dataset.reportId = reportId;
        document.querySelectorAll('input[name="report_id"]').forEach(input => input.value = reportId);

        persistForms.forEach((form) => {
            const oldKey = form.dataset.localKey || storageKeyFor(form.id, previousId);
            const newKey = storageKeyFor(form.id, reportId);
            if (oldKey !== newKey) {
                const oldValue = localStorage.getItem(oldKey);
                const newValue = localStorage.getItem(newKey);
                if (oldValue && !newValue) {
                    localStorage.setItem(newKey, oldValue);
                }
                localStorage.removeItem(oldKey);
            }
            form.dataset.localKey = newKey;
        });

        const url = new URL(window.location.href);
        url.searchParams.set('id', reportId);
        window.history.replaceState({}, '', url);
    };

    const restoreForm = (form) => {
        if (hasPersistedReport()) return;
        const saved = localStorage.getItem(form.dataset.localKey);
        if (!saved) return;
        try {
            const data = JSON.parse(saved);
            Object.entries(data).forEach(([name, value]) => {
                const nodes = form.querySelectorAll(`[name="${CSS.escape(name)}"]`);
                if (!nodes.length) return;
                if (nodes.length > 1) {
                    nodes.forEach((node, idx) => {
                        if (Array.isArray(value) && typeof value[idx] !== 'undefined' && node.type !== 'file') {
                            node.value = value[idx];
                        }
                    });
                } else if (nodes[0].type !== 'file') {
                    nodes[0].value = value;
                }
            });
        } catch (err) {
            console.warn('Unable to restore local draft', err);
        }
    };

    persistForms.forEach((form) => {
        form.dataset.localKey = storageKeyFor(form.id, app.dataset.reportId && app.dataset.reportId !== '0' ? app.dataset.reportId : 'new');
        restoreForm(form);
        form.addEventListener('input', () => persistForm(form));
        form.addEventListener('change', () => persistForm(form));
    });

    const clearLocalDraft = (form) => {
        if (form?.dataset?.localKey) {
            localStorage.removeItem(form.dataset.localKey);
        }
    };

    const computeSalesRows = () => {
        document.querySelectorAll('#salesSnapshotTable tbody tr').forEach((row) => {
            const target = parseFloat(row.querySelector('.sales-target').value || '0');
            const achievement = parseFloat(row.querySelector('.sales-achievement').value || '0');
            const variance = achievement - target;
            row.querySelector('.sales-variance').value = variance.toFixed(2);
            let status = 'Needs attention';
            if (target <= 0 && achievement <= 0) status = 'No activity';
            else if (achievement >= target) status = 'Achieved / On track';
            else if (achievement >= target * 0.75) status = 'Moderate gap';
            row.querySelector('.sales-status').value = status;
        });
    };

    const updateStockVariance = (row) => {
        const stock = parseInt(row.querySelector('.stock-level')?.value || '0', 10);
        const system = parseInt(row.querySelector('.system-stock')?.value || '0', 10);
        const varianceInput = row.querySelector('.stock-variance');
        if (varianceInput) varianceInput.value = stock - system;
    };

    document.addEventListener('input', (e) => {
        if (e.target.matches('.sales-target, .sales-achievement')) computeSalesRows();
        if (e.target.matches('.stock-level, .system-stock')) updateStockVariance(e.target.closest('tr'));
    });
    computeSalesRows();
    document.querySelectorAll('#stockStatusTable tbody tr').forEach(updateStockVariance);

    const addRow = (tableBody, html) => {
        const tr = document.createElement('tr');
        tr.innerHTML = html.trim();
        tableBody.appendChild(tr.firstElementChild);
    };

    document.getElementById('addStockRow')?.addEventListener('click', () => {
        addRow(document.querySelector('#stockStatusTable tbody'), `
            <tr>
                <td><input name="product_name[]" class="form-control form-control-sm"></td>
                <td><input type="number" step="1" name="stock_level[]" class="form-control form-control-sm stock-level"></td>
                <td><input type="number" step="1" name="system_stock[]" class="form-control form-control-sm system-stock"></td>
                <td><input type="number" step="1" name="stock_variance[]" class="form-control form-control-sm stock-variance" readonly></td>
                <td><input name="variance_comment[]" class="form-control form-control-sm"></td>
                <td><button type="button" class="btn btn-sm btn-outline-danger remove-row">×</button></td>
            </tr>`);
        persistForm(document.getElementById('form4'));
    });

    document.getElementById('addIssueRow')?.addEventListener('click', () => {
        addRow(document.querySelector('#issuesTable tbody'), `
            <tr>
                <td><select name="issue_type[]" class="form-select form-select-sm"><option>Sales</option><option>Stock</option><option>Distribution</option><option>Team Discipline</option></select></td>
                <td><input name="issue_description[]" class="form-control form-control-sm"></td>
                <td><select name="severity[]" class="form-select form-select-sm"><option>N/A</option><option>Low</option><option>Medium</option><option>High</option></select></td>
                <td><button type="button" class="btn btn-sm btn-outline-danger remove-row">×</button></td>
            </tr>`);
        persistForm(document.getElementById('form5'));
    });

    document.getElementById('addFollowRow')?.addEventListener('click', () => {
        addRow(document.querySelector('#followTable tbody'), `
            <tr>
                <td><input name="follow_action[]" class="form-control form-control-sm"></td>
                <td><input name="follow_responsible[]" class="form-control form-control-sm"></td>
                <td><select name="follow_deadline[]" class="form-select form-select-sm"><option>1 month</option><option>3 months</option><option>6 months</option></select></td>
                <td><button type="button" class="btn btn-sm btn-outline-danger remove-row">×</button></td>
            </tr>`);
        persistForm(document.getElementById('form7'));
    });

    document.addEventListener('click', (e) => {
        if (e.target.classList.contains('remove-row')) {
            const form = e.target.closest('form');
            e.target.closest('tr')?.remove();
            if (form) persistForm(form);
        }
    });

    const routeMapSelect = document.getElementById('territory_route_map');
    const routeMapUpload = document.querySelector('.route-map-upload');
    const routeMapRemove = document.getElementById('territory_route_map_remove');
    const existingRouteMapPreview = document.getElementById('existingRouteMapPreview');
    const webcamPreview = document.getElementById('webcamPreview');
    const webcamRouteMap = document.getElementById('webcam_route_map');

    const syncRouteMapState = () => {
        const enabled = routeMapSelect?.value === 'Yes';
        routeMapUpload?.classList.toggle('d-none', !enabled);
        if (!enabled) {
            if (routeMapRemove) routeMapRemove.value = '1';
            if (webcamRouteMap) webcamRouteMap.value = '';
            if (existingRouteMapPreview) existingRouteMapPreview.classList.add('d-none');
            if (webcamPreview) {
                webcamPreview.src = '';
                webcamPreview.classList.add('d-none');
            }
        } else if (routeMapRemove) {
            routeMapRemove.value = '0';
        }
    };
    routeMapSelect?.addEventListener('change', syncRouteMapState);
    syncRouteMapState();

    const startWebcam = document.getElementById('startWebcam');
    const captureWebcam = document.getElementById('captureWebcam');
    const webcamVideo = document.getElementById('webcamVideo');

    startWebcam?.addEventListener('click', async () => {
        try {
            webcamStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' }, audio: false });
            webcamVideo.srcObject = webcamStream;
            setStatus('Camera started. Capture image when ready.', 'info');
        } catch (err) {
            setStatus('Unable to access camera. Use normal file upload instead.', 'warning');
        }
    });

    captureWebcam?.addEventListener('click', () => {
        if (!webcamVideo || !webcamStream) {
            setStatus('Open camera first.', 'warning');
            return;
        }
        const canvas = document.createElement('canvas');
        canvas.width = webcamVideo.videoWidth || 640;
        canvas.height = webcamVideo.videoHeight || 480;
        const ctx = canvas.getContext('2d');
        ctx.drawImage(webcamVideo, 0, 0, canvas.width, canvas.height);
        const dataUrl = canvas.toDataURL('image/png');
        if (webcamRouteMap) webcamRouteMap.value = dataUrl;
        if (webcamPreview) {
            webcamPreview.src = dataUrl;
            webcamPreview.classList.remove('d-none');
        }
        if (existingRouteMapPreview) existingRouteMapPreview.classList.add('d-none');
        if (routeMapRemove) routeMapRemove.value = '0';
        if (webcamStream) {
            webcamStream.getTracks().forEach((track) => track.stop());
            webcamStream = null;
        }
        persistForm(document.getElementById('form2'));
        setStatus('Webcam image captured. Save Form 02 to upload it.', 'success');
    });

    const signaturePads = {};
    document.querySelectorAll('.signature-pad').forEach((canvas) => {
        const ratio = window.devicePixelRatio || 1;
        const rect = canvas.getBoundingClientRect();
        canvas.width = Math.max(rect.width * ratio, 300);
        canvas.height = 160 * ratio;
        const ctx = canvas.getContext('2d');
        ctx.scale(ratio, ratio);
        ctx.lineWidth = 2;
        ctx.lineCap = 'round';
        ctx.strokeStyle = '#111827';
        let drawing = false;
        let hasDrawn = false;
        const getPoint = (event) => {
            const r = canvas.getBoundingClientRect();
            const point = event.touches ? event.touches[0] : event;
            return { x: point.clientX - r.left, y: point.clientY - r.top };
        };
        const start = (event) => {
            drawing = true;
            hasDrawn = true;
            const point = getPoint(event);
            ctx.beginPath();
            ctx.moveTo(point.x, point.y);
        };
        const move = (event) => {
            if (!drawing) return;
            event.preventDefault();
            const point = getPoint(event);
            ctx.lineTo(point.x, point.y);
            ctx.stroke();
        };
        const stop = () => { drawing = false; };
        ['mousedown', 'touchstart'].forEach((ev) => canvas.addEventListener(ev, start, { passive: false }));
        ['mousemove', 'touchmove'].forEach((ev) => canvas.addEventListener(ev, move, { passive: false }));
        ['mouseup', 'mouseleave', 'touchend', 'touchcancel'].forEach((ev) => canvas.addEventListener(ev, stop));
        signaturePads[canvas.id] = {
            canvas,
            hasDrawn: () => hasDrawn,
            clear: () => {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                hasDrawn = false;
            }
        };
    });

    const signatureRemoveMap = {
        prepared_signature_canvas: { removeInput: 'prepared_signature_remove', existingPreview: 'prepared_signature_existing', dataInput: 'prepared_signature_data' },
        distributor_signature_canvas: { removeInput: 'distributor_signature_remove', existingPreview: 'distributor_signature_existing', dataInput: 'distributor_signature_data' },
        employee_signature_canvas: { removeInput: 'employee_signature_remove', existingPreview: 'employee_signature_existing', dataInput: 'employee_signature_data' },
    };

    document.querySelectorAll('.clear-signature').forEach((btn) => {
        btn.addEventListener('click', () => {
            const target = btn.dataset.target;
            const config = signatureRemoveMap[target];
            signaturePads[target]?.clear();
            if (config) {
                const removeInput = document.getElementById(config.removeInput);
                const existingPreview = document.getElementById(config.existingPreview);
                const dataInput = document.getElementById(config.dataInput);
                if (removeInput) removeInput.value = '1';
                if (dataInput) dataInput.value = '';
                if (existingPreview) existingPreview.classList.add('d-none');
            }
            persistForm(document.getElementById('form8'));
        });
    });

    const attachSignatureData = () => {
        Object.entries(signatureRemoveMap).forEach(([canvasId, config]) => {
            const pad = signaturePads[canvasId];
            const input = document.getElementById(config.dataInput);
            const removeInput = document.getElementById(config.removeInput);
            if (pad && input) {
                if (pad.hasDrawn()) {
                    input.value = pad.canvas.toDataURL('image/png');
                    if (removeInput) removeInput.value = '0';
                } else if ((removeInput?.value || '0') !== '1') {
                    input.value = '';
                }
            }
        });
    };

    const agentInput = document.getElementById('agent_name');
    const ownerContact = document.getElementById('owner_contact');
    const coverageArea = document.getElementById('coverage_area');
    const agentContactText = document.getElementById('agentContactText');
    const agentTerritoryText = document.getElementById('agentTerritoryText');
    const agentRegionText = document.getElementById('agentRegionText');
    const agentAddressText = document.getElementById('agentAddressText');

    const findAgentDetails = (name) => {
        if (!name) return null;
        if (agentDirectory[name]) return agentDirectory[name];
        const exactKey = Object.keys(agentDirectory).find((key) => key.toLowerCase() === name.toLowerCase());
        return exactKey ? agentDirectory[exactKey] : null;
    };

    const syncAgentDetails = () => {
        const details = findAgentDetails(agentInput?.value || '');
        agentContactText.textContent = details?.dbcontact || '-';
        agentTerritoryText.textContent = details?.territory_name || '-';
        agentRegionText.textContent = details?.region || '-';
        agentAddressText.textContent = details?.dbaddres || '-';
        if (!details) return;

        if (ownerContact && !ownerContact.value.trim()) {
            ownerContact.value = details.dbcontact || '';
        }
        if (coverageArea && !coverageArea.value.trim()) {
            const parts = [details.territory_name, details.sub_region, details.region].filter(Boolean);
            coverageArea.value = parts.join(' / ');
        }
        persistForm(document.getElementById('form2'));
    };

    agentInput?.addEventListener('change', syncAgentDetails);
    agentInput?.addEventListener('input', syncAgentDetails);
    syncAgentDetails();

    document.querySelectorAll('.save-section').forEach((button) => {
        button.addEventListener('click', async () => {
            const form = document.getElementById(button.dataset.form);
            if (!form) return;

            if (button.dataset.captureLocation === 'start') {
                const pos = await new Promise((resolve) => {
                    if (!navigator.geolocation) return resolve({ lat: '', lng: '' });
                    navigator.geolocation.getCurrentPosition(
                        (geo) => resolve({ lat: geo.coords.latitude, lng: geo.coords.longitude }),
                        () => resolve({ lat: '', lng: '' }),
                        { enableHighAccuracy: true, timeout: 8000, maximumAge: 0 }
                    );
                });
                const lat = form.querySelector('[name="start_lat"]');
                const lng = form.querySelector('[name="start_lng"]');
                if (lat) lat.value = pos.lat;
                if (lng) lng.value = pos.lng;
            }

            if (button.dataset.captureLocation === 'end') {
                const pos = await new Promise((resolve) => {
                    if (!navigator.geolocation) return resolve({ lat: '', lng: '' });
                    navigator.geolocation.getCurrentPosition(
                        (geo) => resolve({ lat: geo.coords.latitude, lng: geo.coords.longitude }),
                        () => resolve({ lat: '', lng: '' }),
                        { enableHighAccuracy: true, timeout: 8000, maximumAge: 0 }
                    );
                });
                const lat = form.querySelector('[name="end_lat"]');
                const lng = form.querySelector('[name="end_lng"]');
                if (lat) lat.value = pos.lat;
                if (lng) lng.value = pos.lng;
                attachSignatureData();
            }

            const reportId = app.dataset.reportId;
            if (button.dataset.action !== 'save_form1' && (!reportId || reportId === '0')) {
                setStatus('Please save Form 01 first.', 'warning');
                return;
            }

            const formData = new FormData(form);
            formData.set('action', button.dataset.action);
            if (reportId && reportId !== '0') {
                formData.set('report_id', reportId);
            }

            button.disabled = true;
            setStatus('Saving, please wait...', 'info');
            try {
                const response = await fetch('report_save.php', { method: 'POST', body: formData });
                const result = await response.json();
                if (!response.ok || !result.ok) throw new Error(result.message || 'Save failed.');
                if (result.report_id) updateReportId(result.report_id);
                clearLocalDraft(form);
                setStatus(result.message, 'success');
            } catch (err) {
                setStatus(err.message || 'Unable to save form.', 'danger');
            } finally {
                button.disabled = false;
            }
        });
    });
})();
