document.addEventListener('DOMContentLoaded', () => {

    // --- 1. CORE VISIBILITY LOGIC ---
    function setupVisibility(radioName, targetId, showValue = 'yes') {
        const radios = document.querySelectorAll(`input[name="${radioName}"]`);
        const target = document.getElementById(targetId);
        if (!target) return;

        const update = () => {
            const selected = document.querySelector(`input[name="${radioName}"]:checked`);
            if (selected && selected.value === showValue) {
                target.classList.remove('hidden');
            } else {
                target.classList.add('hidden');
            }
        };
        radios.forEach(r => r.addEventListener('change', update));
        update();
    }

    setupVisibility('isReferred', 'refereeFields', 'yes');

    // --- 2. PINCODE LOGIC ---
    let pincodeMap = new Map();
    async function loadPincodeData() {
        if (pincodeMap.size > 0) return;
        try {
            const resp = await fetch('assets/data/PINCODES.csv');
            if (resp.ok) {
                const text = await resp.text();
                text.split('\n').slice(1).forEach(line => {
                    const parts = line.split(',');
                    if (parts.length >= 4) {
                        pincodeMap.set(parts[0].trim(), { 
                            city: parts[2].trim(), 
                            state: parts[1].trim() 
                        });
                    }
                });
            }
        } catch (e) { console.error("Pincode load error", e); }
    }

    function bindPincode(pinId, cityInpName) {
        const pin = document.getElementById(pinId);
        if (!pin) return;
        pin.addEventListener('input', async () => {
            if (pin.value.length === 6) {
                await loadPincodeData();
                const data = pincodeMap.get(pin.value);
                if (data) {
                    const cityInp = document.querySelector(`input[name="${cityInpName}"]`);
                    if (cityInp) cityInp.value = data.city;
                }
            }
        });
    }
    bindPincode('residentPincode', 'residentCity');
    bindPincode('permPincode', 'permCity');

    const sameAsResident = document.getElementById('sameAsResident');
    if (sameAsResident) {
        sameAsResident.addEventListener('change', () => {
            const container = document.getElementById('permAddressContainer');
            if (sameAsResident.checked) {
                container.classList.add('opacity-40', 'pointer-events-none');
                document.getElementById('permHouse').value = document.querySelector('input[name="residentHouse"]').value;
                document.getElementById('permArea').value = document.querySelector('input[name="residentAddress"]').value;
                document.getElementById('permPincode').value = document.getElementById('residentPincode').value;
                document.getElementById('permCity').value = document.querySelector('input[name="residentCity"]').value;
            } else {
                container.classList.remove('opacity-40', 'pointer-events-none');
            }
        });
    }

    // --- 3. EMI TABLE LOGIC ---
    let emiCount = 1;
    const emiTableBody = document.getElementById('emiTableBody');
    const addEmiRowBtn = document.getElementById('addEmiRowBtn');

    if (addEmiRowBtn && emiTableBody) {
        addEmiRowBtn.addEventListener('click', () => {
            emiCount++;
            const tr = document.createElement('tr');
            tr.className = "group hover:bg-slate-50 transition-colors";
            tr.innerHTML = `
                <td class="px-6 py-4 font-bold text-slate-400">${emiCount}</td>
                <td class="px-4 py-4">
                    <div class="space-y-1">
                        <input type="text" name="loan_type_${emiCount}" class="text-xs font-bold text-slate-800 bg-transparent outline-none w-full" placeholder="Personal Loan">
                        <input type="text" name="bank_name_${emiCount}" class="text-[10px] text-slate-400 bg-transparent outline-none w-full" placeholder="Bank Name">
                    </div>
                </td>
                <td class="px-4 py-4">
                    <input type="date" name="loan_date_${emiCount}" class="text-xs font-medium text-slate-600 bg-transparent outline-none">
                </td>
                <td class="px-4 py-4">
                    <div class="space-y-1">
                        <div class="flex items-center gap-1">
                            <span class="text-[10px] font-bold text-slate-300">₹</span>
                            <input type="number" name="emi_amt_${emiCount}" class="text-xs font-bold text-slate-800 bg-transparent outline-none w-20" placeholder="0">
                        </div>
                        <div class="flex items-center gap-1">
                            <input type="number" name="total_tenure_${emiCount}" class="text-[10px] font-medium text-slate-400 bg-transparent outline-none w-10 text-right" placeholder="0">
                            <span class="text-[10px] font-medium text-slate-300">Mo.</span>
                        </div>
                    </div>
                </td>
                <td class="px-4 py-4">
                    <div class="flex items-center gap-1">
                        <span class="text-[10px] font-bold text-slate-300">₹</span>
                        <input type="number" name="outstanding_${emiCount}" class="text-xs font-bold text-slate-800 bg-transparent outline-none w-full" placeholder="Total Pending">
                    </div>
                </td>
                <td class="px-6 py-4 text-xs font-bold">
                    <select name="history_${emiCount}" class="text-emerald-500 bg-transparent outline-none cursor-pointer">
                        <option value="On-time">Regular</option>
                        <option value="Delay">Delay</option>
                        <option value="Settled">Settled</option>
                    </select>
                </td>
                <td class="px-6 py-4 text-center">
                    <button type="button" class="text-slate-300 hover:text-red-500 transition-colors delete-row"><i class="fas fa-trash-can"></i></button>
                </td>
            `;
            emiTableBody.appendChild(tr);
            tr.querySelector('.delete-row').addEventListener('click', () => {
                tr.remove();
                reorderEmi();
            });
        });
    }

    function reorderEmi() {
        const rows = emiTableBody.querySelectorAll('tr');
        rows.forEach((r, i) => {
            r.querySelector('td:first-child').textContent = i + 1;
        });
        emiCount = rows.length;
    }

    document.querySelectorAll('.delete-row').forEach(b => {
        b.addEventListener('click', (e) => {
            e.target.closest('tr').remove();
            reorderEmi();
        });
    });

    // --- 4. FILE UPLOAD PREVIEW ---
    const fileInput = document.getElementById('multiDocUpload');
    const fileList = document.getElementById('fileList');

    if (fileInput && fileList) {
        fileInput.addEventListener('change', (e) => {
            fileList.innerHTML = '';
            Array.from(e.target.files).forEach(file => {
                const div = document.createElement('div');
                div.className = "flex items-center justify-between p-3 bg-white rounded-xl border border-slate-100 shadow-sm animate-in fade-in slide-in-from-left-4";
                div.innerHTML = `
                    <div class="flex items-center gap-3">
                        <i class="fas fa-file-pdf text-red-500"></i>
                        <div>
                            <p class="text-[11px] font-bold text-slate-800 line-clamp-1">${file.name}</p>
                            <p class="text-[9px] text-slate-400 font-bold uppercase">${(file.size / 1024).toFixed(0)} KB</p>
                        </div>
                    </div>
                    <button type="button" class="text-slate-300 hover:text-red-500 remove-file"><i class="fas fa-times"></i></button>
                `;
                fileList.appendChild(div);
                div.querySelector('.remove-file').addEventListener('click', () => div.remove());
            });
        });
    }

    // --- 5. MULTI-VOICE RECORDING ---
    let mediaRecorder;
    let audioChunks = [];
    let recordedFiles = []; // Array of Blobs

    const startBtn = document.getElementById('startVoiceBtn');
    const stopBtn = document.getElementById('stopVoiceBtn');
    const voiceGallery = document.getElementById('voiceGallery');
    const recPulse = document.getElementById('recPulse');
    const recText = document.getElementById('recText');

    if (startBtn && stopBtn && voiceGallery) {
        startBtn.addEventListener('click', async () => {
            try {
                const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                mediaRecorder = new MediaRecorder(stream);
                audioChunks = [];

                mediaRecorder.ondataavailable = (e) => audioChunks.push(e.data);
                mediaRecorder.onstop = () => {
                    const audioBlob = new Blob(audioChunks, { type: 'audio/webm' });
                    addVoiceToGallery(audioBlob);
                    stream.getTracks().forEach(track => track.stop());
                };

                mediaRecorder.start();
                toggleRecState(true);
            } catch (err) {
                alert("Microphone access denied or not available.");
                console.error(err);
            }
        });

        stopBtn.addEventListener('click', () => {
            if (mediaRecorder && mediaRecorder.state === "recording") {
                mediaRecorder.stop();
                toggleRecState(false);
            }
        });

        function toggleRecState(isRecording) {
            if (isRecording) {
                startBtn.classList.add('hidden');
                stopBtn.classList.remove('hidden');
                stopBtn.classList.add('flex');
                recPulse.classList.remove('hidden');
                recText.textContent = "Recording...";
            } else {
                startBtn.classList.remove('hidden');
                stopBtn.classList.add('hidden');
                stopBtn.classList.remove('flex');
                recPulse.classList.add('hidden');
                recText.textContent = "Tap to Record Again";
            }
        }

        function addVoiceToGallery(blob) {
            const id = Date.now();
            recordedFiles.push({ id, blob });
            
            const url = URL.createObjectURL(blob);
            const item = document.createElement('div');
            item.className = "recording-item";
            item.innerHTML = `
                <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary">
                    <i class="fas fa-volume-high"></i>
                </div>
                <div class="flex-1">
                    <p class="text-[10px] font-black text-slate-400 uppercase tracking-widest">Voice Note ${recordedFiles.length}</p>
                    <audio src="${url}" controls class="h-8 w-full mt-1"></audio>
                </div>
                <button type="button" class="w-8 h-8 rounded-lg hover:bg-red-50 text-slate-300 hover:text-red-500 transition-colors delete-voice">
                    <i class="fas fa-trash-can"></i>
                </button>
            `;
            voiceGallery.appendChild(item);

            item.querySelector('.delete-voice').addEventListener('click', () => {
                recordedFiles = recordedFiles.filter(f => f.id !== id);
                item.remove();
            });
        }
    }

    // --- 6. SUBMISSION ---
    const form = document.getElementById('loanForm');
    if (form) {
        form.addEventListener('submit', async (e) => {
            e.preventDefault();
            const btn = form.querySelector('button[type="submit"]');
            const originalText = btn.innerHTML;

            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-circle-notch fa-spin"></i> Securing Data...';

            const formData = new FormData(form);
            const payload = Object.fromEntries(formData);

            // Fetch EMI Table Data
            const emiData = [];
            emiTableBody.querySelectorAll('tr').forEach((r, i) => {
                const idx = i + 1;
                emiData.push({
                    type: r.querySelector(`[name="loan_type_${idx}"]`)?.value,
                    bank: r.querySelector(`[name="bank_name_${idx}"]`)?.value,
                    emi: r.querySelector(`[name="emi_amt_${idx}"]`)?.value,
                    outstanding: r.querySelector(`[name="outstanding_${idx}"]`)?.value
                });
            });
            payload.emiDetails = emiData;
            payload.voiceNotesCount = recordedFiles.length;

            console.log("Submitting Premium Loan Request:", payload);

            try {
                // In a real scenario, we'd upload blobs to cloud storage here
                await API.Leads.create({
                    ...payload,
                    lead_type: 'personal_loan_premium',
                    status: 'New'
                });

                btn.innerHTML = '<i class="fas fa-check-circle"></i> Request Received';
                btn.classList.replace('bg-primary', 'bg-emerald-500');
                
                setTimeout(() => {
                    alert("Your application has been received. Our executive will contact you shortly.");
                    window.location.href = 'index.html';
                }, 1500);
            } catch (err) {
                alert("Submission error. Please try again.");
                btn.disabled = false;
                btn.innerHTML = originalText;
            }
        });
    }
});
