document.querySelectorAll('.tab').forEach(tab => {
    tab.addEventListener('click', () => {
        document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
        document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
        tab.classList.add('active');
        document.getElementById(tab.dataset.tab).classList.add('active');
    });
});

const API_BASE = '/schadenprotokoll/api';
let templateFile = null;
let laufzettelFile = null;

function showStatus(id, type, msg) {
    const el = document.getElementById(id);
    if (el) { el.className = 'status visible ' + type; el.textContent = msg; }
}

function checkGenerateReady() {
    document.getElementById('generate-btn').disabled = !(templateFile && laufzettelFile);
}

const templateZone = document.getElementById('template-zone');
const templateInput = document.getElementById('template-input');
templateZone.addEventListener('click', () => templateInput.click());
templateZone.addEventListener('dragover', e => { e.preventDefault(); templateZone.classList.add('dragover'); });
templateZone.addEventListener('dragleave', () => templateZone.classList.remove('dragover'));
templateZone.addEventListener('drop', e => {
    e.preventDefault(); templateZone.classList.remove('dragover');
    if (e.dataTransfer.files.length) { templateInput.files = e.dataTransfer.files; handleTemplateSelect(); }
});
templateInput.addEventListener('change', handleTemplateSelect);

function handleTemplateSelect() {
    if (templateInput.files.length) {
        templateFile = templateInput.files[0];
        document.getElementById('template-info').innerHTML = '<strong>OK: ' + templateFile.name + '</strong>';
        document.getElementById('template-info').classList.add('visible');
        checkGenerateReady();
    }
}

const laufzettelZone = document.getElementById('laufzettel-zone');
const laufzettelInput = document.getElementById('laufzettel-input');
laufzettelZone.addEventListener('click', () => laufzettelInput.click());
laufzettelZone.addEventListener('dragover', e => { e.preventDefault(); laufzettelZone.classList.add('dragover'); });
laufzettelZone.addEventListener('dragleave', () => laufzettelZone.classList.remove('dragover'));
laufzettelZone.addEventListener('drop', e => {
    e.preventDefault(); laufzettelZone.classList.remove('dragover');
    if (e.dataTransfer.files.length) { laufzettelInput.files = e.dataTransfer.files; handleLaufzettelSelect(); }
});
laufzettelInput.addEventListener('change', handleLaufzettelSelect);

function handleLaufzettelSelect() {
    if (laufzettelInput.files.length) {
        laufzettelFile = laufzettelInput.files[0];
        document.getElementById('laufzettel-info').innerHTML = '<strong>OK: ' + laufzettelFile.name + '</strong>';
        document.getElementById('laufzettel-info').classList.add('visible');
        checkGenerateReady();
    }
}

document.getElementById('generate-btn').addEventListener('click', async () => {
    showStatus('generate-status', 'loading', 'Verarbeite...');
    const formData = new FormData();
    formData.append('template', templateFile);
    formData.append('laufzettel', laufzettelFile);

    try {
        const response = await fetch(API_BASE + '/generate', { method: 'POST', body: formData });
        if (!response.ok) throw new Error((await response.json()).error);
        const blob = await response.blob();
        const a = document.createElement('a');
        a.href = URL.createObjectURL(blob);
        a.download = 'Schadenprotokoll_vorbefuellt.pdf';
        document.body.appendChild(a); a.click(); document.body.removeChild(a);
        showStatus('generate-status', 'success', 'PDF erfolgreich generiert!');
    } catch (err) {
        showStatus('generate-status', 'error', 'Fehler: ' + err.message);
    }
});

function setupSimpleUpload(zoneId, inputId, infoId, btnId) {
    const zone = document.getElementById(zoneId);
    const input = document.getElementById(inputId);
    if (!zone || !input) return;
    zone.addEventListener('click', () => input.click());
    zone.addEventListener('dragover', e => { e.preventDefault(); zone.classList.add('dragover'); });
    zone.addEventListener('dragleave', () => zone.classList.remove('dragover'));
    zone.addEventListener('drop', e => {
        e.preventDefault(); zone.classList.remove('dragover');
        if (e.dataTransfer.files.length) { input.files = e.dataTransfer.files; updateInfo(); }
    });
    input.addEventListener('change', updateInfo);
    function updateInfo() {
        if (input.files.length) {
            document.getElementById(infoId).innerHTML = '<strong>OK: ' + input.files[0].name + '</strong>';
            document.getElementById(infoId).classList.add('visible');
            document.getElementById(btnId).disabled = false;
        }
    }
}

setupSimpleUpload('pdf-zone', 'pdf-input', 'pdf-info', 'analyze-btn');
setupSimpleUpload('vorbericht-zone', 'vorbericht-input', 'vorbericht-info', 'vorbericht-btn');

document.getElementById('analyze-btn').addEventListener('click', async () => {
    showStatus('analyze-status', 'loading', 'Analysiere...');
    const formData = new FormData();
    formData.append('file', document.getElementById('pdf-input').files[0]);
    try {
        const response = await fetch(API_BASE + '/analyze', { method: 'POST', body: formData });
        if (!response.ok) throw new Error((await response.json()).error);
        const result = await response.json();
        let html = '';
        for (const [k, v] of Object.entries(result.data.textfields || {})) {
            if (v) html += '<div class="dropdown-item"><strong>' + k + ':</strong> ' + v + '</div>';
        }
        for (const [k, d] of Object.entries(result.data.dropdowns || {})) {
            if (d.selected) html += '<div class="dropdown-item"><strong>' + k + ':</strong> ' + d.selected + '</div>';
        }
        document.getElementById('analyze-data').innerHTML = html || 'Keine Daten';
        document.getElementById('analyze-result').classList.add('visible');
        showStatus('analyze-status', 'success', 'Fertig');
    } catch (err) { showStatus('analyze-status', 'error', 'Fehler: ' + err.message); }
});

document.getElementById('vorbericht-btn').addEventListener('click', async () => {
    showStatus('vorbericht-status', 'loading', 'Erstelle Vorbericht...');
    const formData = new FormData();
    formData.append('file', document.getElementById('vorbericht-input').files[0]);
    try {
        const response = await fetch(API_BASE + '/vorbericht', { method: 'POST', body: formData });
        if (!response.ok) throw new Error((await response.json()).error);
        const blob = await response.blob();
        const a = document.createElement('a');
        a.href = URL.createObjectURL(blob);
        a.download = 'Vorbericht.docx';
        document.body.appendChild(a); a.click(); document.body.removeChild(a);
        showStatus('vorbericht-status', 'success', 'Vorbericht erstellt!');
    } catch (err) { showStatus('vorbericht-status', 'error', 'Fehler: ' + err.message); }
});
