// ── CONFIGURACIÓN DE PLANTILLAS DE CLIENTES ──
export const clientTemplates = {
    'Esp': {
        'Generico': 'images/AF Generico Esp.png',
        'Claro': 'images/AF Claro Esp.png',
        'Colgate': 'images/GLM Colgate Esp.png',
        'KitchenAid': 'images/AF KitchenAid Esp.png',
        'Kraft': 'images/AF Kraft Esp.png',
        'Motorola': 'images/AF Motorola Esp.png',
        'Nestle': 'images/AF Nestle Esp.png',
        'P&G': 'images/AF P&G Esp.png',
        'Philip Morris': 'images/AF Philip Morris Esp.png',
        'Whirlpool': 'images/AF Whirlpool Esp.png'
    },
    'Ing': {
        'Generico': 'images/AF Generico Ing.png',
        'Claro': 'images/AF Claro Ing.png',
        'Colgate': 'images/GLM Colgate Ing.png',
        'KitchenAid': 'images/AF KitchenAid Ing.png',
        'Kraft': 'images/AF Kraft Ing.png',
        'Motorola': 'images/AF Motorola Ing.png',
        'Nestle': 'images/AF Nestle Ing.png',
        'P&G': 'images/AF P&G Ing.png',
        'Philip Morris': 'images/AF Philip Morris Ing.png',
        'Whirlpool': 'images/AF Whirlpool Ing.png'
    }
};

// ── INYECTORES DINÁMICOS DE DEPENDENCIAS ──
function loadScript(src, globalKey) {
    return new Promise((resolve) => {
        if (window[globalKey]) return resolve(window[globalKey]);
        const s = document.createElement('script');
        s.src = src;
        s.onload = () => resolve(window[globalKey]);
        document.head.appendChild(s);
    });
}

const getQRLib = () => loadScript('https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js', 'QRCode');
const getHtml2Canvas = () => loadScript('https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js', 'html2canvas');

// ── GENERADOR DE QR NATIVO (REACT RENDERING) ──
export async function renderQRCode(employeeId, canvasElement) {
    if (!canvasElement) return;
    const text = (employeeId || '').trim();
    const ctx = canvasElement.getContext('2d');
    ctx.clearRect(0, 0, canvasElement.width, canvasElement.height);

    if (text.length <= 2) return;

    const QRCodeLib = await getQRLib();
    const tmp = document.createElement('div');
    tmp.style.display = 'none';
    document.body.appendChild(tmp);

    new QRCodeLib(tmp, {
        text: `http://localhost:5173/employee/${text}`,
        width: 55,
        height: 55,
        colorDark: '#000000',
        colorLight: '#ffffff',
        correctLevel: QRCodeLib.CorrectLevel.M
    });

    setTimeout(() => {
        const img = tmp.querySelector('img') || tmp.querySelector('canvas');

        const drawIt = (src) => {
            const i = new Image();
            i.onload = () => {
                ctx.fillStyle = '#ffffff';
                ctx.fillRect(0, 0, 55, 55);
                ctx.drawImage(i, 0, 0, 55, 55);
                if (tmp.parentNode) document.body.removeChild(tmp);
            };
            i.src = src;
        };

        if (img && img.tagName === 'CANVAS') {
            drawIt(img.toDataURL());
        } else if (img) {
            if (img.complete) drawIt(img.src);
            else img.onload = () => drawIt(img.src);
        } else {
            if (tmp.parentNode) document.body.removeChild(tmp);
        }
    }, 50);
}

// ── ENGINE DE PROCESAMIENTO ULTRA MAX QUALITY (650x1004) ──
export async function downloadIDCards(config) {
    const { name, role, selectedClient, language, photoSrc, baseUrl, qrCanvas, onStateChange } = config;

    if (onStateChange) onStateChange({ processing: true, text: 'Procesando...' });

    const html2canvasLib = await getHtml2Canvas();
    const cleanName = name.trim().replace(/\s+/g, '') || 'Empleado';

    // Resolver rutas absolutas
    const frontBgUrl = `${baseUrl}images/AF GLM Frente.png`;
    const currentGroup = clientTemplates[language] || clientTemplates['Esp'];
    const backBgFile = currentGroup[selectedClient] || 'images/AF Generico Esp.png';
    const backBgUrl = `${baseUrl}${backBgFile}`;

    // Sandbox virtual aislado
    const sandbox = document.createElement('div');
    sandbox.style.position = 'fixed';
    sandbox.style.top = '-9999px';
    sandbox.style.left = '-9999px';
    sandbox.style.width = '1400px';
    document.body.appendChild(sandbox);

    const cardStyleBase = `
        position: relative;
        width: 650px;
        height: 1004px;
        border-radius: 16px;
        background-size: cover;
        background-position: center;
        background-repeat: no-repeat;
        display: inline-block;
        margin-right: 50px;
        overflow: hidden;
        font-family: Arial, Helvetica, sans-serif;
    `;

    // 1. Frente Virtual en tamaño real
    const vFront = document.createElement('div');
    vFront.style.cssText = cardStyleBase;
    vFront.style.backgroundImage = `url('${frontBgUrl}')`;

    let photoStyleHtml = `background: #e1e9ee; display: flex; align-items: center; justify-content: center;`;
    let innerPhotoContent = `<svg style="width:100px; height:100px; opacity:0.3; color:#4F758B;" viewBox="0 0 28 28" fill="none"><circle cx="14" cy="10" r="5.5" stroke="currentColor" stroke-width="1.5"/><path d="M3 24c0-6 22-6 22 0" stroke="currentColor" stroke-width="1.5"/></svg>`;

    if (photoSrc) {
        photoStyleHtml = `
            background-image: url('${photoSrc}') !important;
            background-size: cover !important;
            background-position: center center !important;
            background-repeat: no-repeat !important;
        `;
        innerPhotoContent = '';
    }

    vFront.innerHTML = `
        <div style="position:absolute; top:260.5px; left:131.5px; width:384px; height:384px; border-radius:50%; overflow:hidden; z-index:5; ${photoStyleHtml}">
            ${innerPhotoContent}
        </div>
        <div style="position:absolute; top:715px; left:20px; right:20px; font-size:38px; font-weight:900; color:#FFFFFF; text-align:center; text-transform:uppercase; letter-spacing:1px; word-break:break-word; z-index:5;">
            ${name.toUpperCase() || 'NOMBRE APELLIDO'}
        </div>
        <div style="position:absolute; bottom:32px; right:15px; font-size:26px; font-weight:700; color:#6B8499; text-align:right; text-transform:uppercase; letter-spacing:1px; max-width:550px; white-space:nowrap; z-index:5;">
            ${role.toUpperCase() || 'PUESTO'}
        </div>
    `;

    // 2. Reverso Virtual en tamaño real
    const vBack = document.createElement('div');
    vBack.style.cssText = cardStyleBase;
    vBack.style.backgroundImage = `url('${backBgUrl}')`;

    const vQRZone = document.createElement('div');
    vQRZone.style.cssText = `
        position: absolute;
        bottom: 27px;
        right: 27px;
        background: #ffffff;
        padding: 11px;
        border-radius: 16px;
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 5;
    `;

    const vQRCanvas = document.createElement('canvas');
    vQRCanvas.width = 149;
    vQRCanvas.height = 149;
    vQRCanvas.style.width = '100px';
    vQRCanvas.style.height = '100px';
    const vQRContext = vQRCanvas.getContext('2d');

    if (vQRContext && qrCanvas) {
        vQRContext.imageSmoothingEnabled = false;
        vQRContext.drawImage(qrCanvas, 0, 0, 149, 149);
    }
    vQRZone.appendChild(vQRCanvas);
    vBack.appendChild(vQRZone);

    sandbox.appendChild(vFront);
    sandbox.appendChild(vBack);

    const renderOpts = {
        scale: 1,
        useCORS: true,
        allowTaint: false,
        backgroundColor: null,
        logging: false,
        width: 650,
        height: 1004
    };

    try {
        const frontCanvas = await html2canvasLib(vFront, renderOpts);
        executeFileDownload(frontCanvas.toDataURL('image/png'), `${cleanName}Frente.png`);

        const backCanvas = await html2canvasLib(vBack, renderOpts);
        executeFileDownload(backCanvas.toDataURL('image/png'), `${cleanName}Reverso.png`);
    } catch (error) {
        console.error('Error generando las vistas en alta resolución:', error);
    } finally {
        if (sandbox.parentNode) document.body.removeChild(sandbox);
        if (onStateChange) onStateChange({ processing: false, text: '⬇ Descargar' });
    }
}

function executeFileDownload(dataUrl, fileName) {
    const link = document.createElement('a');
    link.href = dataUrl;
    link.download = fileName;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}