// wwwroot/js/converters/image-ocr-converter.js
// Implementação específica para conversor de imagem para texto (OCR)

async function performConversion(formData) {
    const fileInput = formData.get('file');

    if (!fileInput || fileInput.size === 0) {
        throw new Error('Por favor, selecione uma imagem');
    }

    // Validar tipo de arquivo
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/bmp', 'application/pdf'];
    if (!allowedTypes.includes(fileInput.type)) {
        throw new Error('Formato de arquivo não suportado. Use JPG, PNG, GIF, BMP ou PDF.');
    }

    // Validar tamanho (15MB)
    if (fileInput.size > 15 * 1024 * 1024) {
        throw new Error('Arquivo muito grande. Tamanho máximo: 15MB');
    }

    const requestData = new FormData();
    requestData.append('inputType', 'file');
    requestData.append('fileInput', fileInput);
    requestData.append('language', document.documentElement.lang || 'pt');

    // Adicionar opções de OCR se houver
    const ocrLanguage = formData.get('ocrLanguage') || 'por';
    const options = { ocrLanguage: ocrLanguage };
    requestData.append('options', JSON.stringify(options));

    const response = await fetch('/converter/api/convert/image-ocr', {
        method: 'POST',
        body: requestData
    });

    if (!response.ok) {
        const error = await response.json();
        throw new Error(error.message || 'Erro no processamento da imagem');
    }

    const result = await response.json();

    // Mostrar resultado do OCR
    showOcrResult(result.outputText, fileInput);
}

function showOcrResult(extractedText, originalFile) {
    const outputTextElement = document.getElementById('outputText');
    const successActions = document.getElementById('successActions');

    if (outputTextElement) {
        outputTextElement.value = extractedText;
        document.getElementById('outputArea').style.display = 'block';
        successActions.style.display = 'block';

        // Mostrar preview da imagem
        showImagePreview(originalFile);

        // Adicionar botão para salvar texto
        addSaveTextButton(extractedText);
    }
}

function showImagePreview(file) {
    const previewContainer = document.getElementById('imagePreview');
    if (previewContainer && file.type.startsWith('image/')) {
        const reader = new FileReader();
        reader.onload = function (e) {
            previewContainer.innerHTML = `
                <div class="mt-3">
                    <small class="text-muted">Imagem processada:</small><br>
                    <img src="${e.target.result}" alt="Preview" class="img-thumbnail mt-1" style="max-height: 200px;">
                </div>
            `;
        };
        reader.readAsDataURL(file);
    }
}

function addSaveTextButton(text) {
    const successActions = document.getElementById('successActions');

    if (document.getElementById('saveTextBtn')) return;

    const saveBtn = document.createElement('button');
    saveBtn.id = 'saveTextBtn';
    saveBtn.type = 'button';
    saveBtn.className = 'btn btn-sm btn-outline-success';
    saveBtn.innerHTML = '<i class="fas fa-save me-1"></i> Salvar Texto';

    saveBtn.addEventListener('click', () => {
        const blob = new Blob([text], { type: 'text/plain;charset=utf-8' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'texto-extraido.txt';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    });

    successActions.appendChild(saveBtn);
}

function initializeConverter() {
    setupAdvancedOcrOptions();
    setupImagePreview();
}

function setupAdvancedOcrOptions() {
    const advancedContainer = document.getElementById('advancedSettings');
    if (advancedContainer) {
        advancedContainer.innerHTML = `
            <div class="row">
                <div class="col-md-6">
                    <label class="form-label">Idioma do OCR</label>
                    <select name="ocrLanguage" class="form-select">
                        <option value="por">Português</option>
                        <option value="eng">English</option>
                        <option value="spa">Español</option>
                        <option value="fra">Français</option>
                        <option value="deu">Deutsch</option>
                    </select>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Qualidade</label>
                    <select name="quality" class="form-select">
                        <option value="balanced">Balanceada</option>
                        <option value="fast">Rápida</option>
                        <option value="accurate">Precisa</option>
                    </select>
                </div>
            </div>
        `;
    }
}

function setupImagePreview() {
    const fileInput = document.getElementById('fileInput');
    if (fileInput) {
        fileInput.addEventListener('change', function (e) {
            const file = e.target.files[0];
            if (file && file.type.startsWith('image/')) {
                const reader = new FileReader();
                reader.onload = function (event) {
                    let previewContainer = document.getElementById('imagePreview');
                    if (!previewContainer) {
                        previewContainer = document.createElement('div');
                        previewContainer.id = 'imagePreview';
                        fileInput.parentNode.appendChild(previewContainer);
                    }

                    previewContainer.innerHTML = `
                        <div class="mt-2">
                            <img src="${event.target.result}" alt="Preview" class="img-thumbnail" style="max-height: 150px;">
                        </div>
                    `;
                };
                reader.readAsDataURL(file);
            }
        });
    }
}