// Tab

function showContent(tabIndex) {
    const contents = document.querySelectorAll('.tab-content');
    contents.forEach((content) => content.classList.remove('active-content'));
    const tabs = document.querySelectorAll('.tab');
    tabs.forEach((tab) => tab.classList.remove('active-tab'));
    contents[tabIndex].classList.add('active-content');
    tabs[tabIndex].classList.add('active-tab');
}
// Signature
(function ($) {
    // Check if font is loaded before drawing
    function isFontLoaded() {
        // return document.fonts.check('1em "Style Script"');

        const selectedFont = $('#fontSelect').val();
        return document.fonts.check(`1em "${selectedFont}"`);
    }

    // Try to draw with font, with fallback and retry
    function drawTextWithFont() {
        if (isFontLoaded()) {
            // Font is loaded, draw normally
            textCtx.clearRect(0, 0, textCanvas.width, textCanvas.height);

            const selectedFont = $('#fontSelect').val();
            textCtx.font = `30px "${selectedFont}", cursive`;

            textCtx.fillStyle = textColorPicker.value;
            textCtx.textAlign = 'center';
            textCtx.textBaseline = 'middle';
            textCtx.fillText(
                inputField.value,
                textCanvas.width / 2,
                textCanvas.height / 2
            );
            return true;
        }
        return false;
    }

    // Color picker label updates
    $('#textSignatureColor, #drawSignatureColor').on('input', function () {
        let labelClass =
            $(this).attr('id') === 'textSignatureColor'
                ? '.cv-color-picker-label'
                : '.cv-color-picker-drawlabel';
        $(labelClass).text($(this).val().replace('#', ''));
    });

    // Text-to-Signature
    const textCanvas = document.getElementById('textCanvas');
    const textCtx = textCanvas?.getContext('2d');
    const inputField = document.getElementById('signatureInput');
    const textColorPicker = document.getElementById('textSignatureColor');

    $('#fontSelect').on('change', function () {
        drawTextWithFont();
    });

    // Generate text signature with retry mechanism
    $('#fontOption').click(function () {
        if (drawTextWithFont()) {
            return;
        }

        const loadingMsg = $('<div>Loading font...</div>');
        $(textCanvas).after(loadingMsg);

        setTimeout(function () {
            if (drawTextWithFont()) {
                loadingMsg.remove();
                return;
            }

            const checkInterval = setInterval(function () {
                if (drawTextWithFont()) {
                    clearInterval(checkInterval);
                    loadingMsg.remove();
                }
            }, 200);

            setTimeout(function () {
                clearInterval(checkInterval);
                loadingMsg.text(
                    'Font could not be loaded. Using fallback font.'
                );

                textCtx.clearRect(0, 0, textCanvas.width, textCanvas.height);
                textCtx.font = '30px cursive';
                textCtx.fillStyle = textColorPicker.value;
                textCtx.textAlign = 'center';
                textCtx.textBaseline = 'middle';
                textCtx.fillText(
                    inputField.value,
                    textCanvas.width / 2,
                    textCanvas.height / 2
                );

                setTimeout(() => loadingMsg.remove(), 3000);
            }, 5000);
        }, 500);
    });

    $('#saveTextSignature').click(function () {
        saveSignature(textCanvas.toDataURL('image/png'));
    });

    // Draw Signature
    const drawCanvas = document.getElementById('drawCanvas');
    const drawCtx = drawCanvas?.getContext('2d');
    const drawColorPicker = document.getElementById('drawSignatureColor');
    let isDrawing = false;

    // Function to get touch coordinates
    function getTouchPos(canvas, touchEvent) {
        const rect = canvas.getBoundingClientRect();
        return {
            x: touchEvent.touches[0].clientX - rect.left,
            y: touchEvent.touches[0].clientY - rect.top,
        };
    }

    // Mouse Events
    drawCanvas?.addEventListener('mousedown', (e) => {
        isDrawing = true;
        drawCtx.beginPath();
        drawCtx.moveTo(e.offsetX, e.offsetY);
    });

    drawCanvas?.addEventListener('mousemove', (e) => {
        if (!isDrawing) return;
        drawCtx.lineWidth = 2;
        drawCtx.lineCap = 'round';
        drawCtx.strokeStyle = drawColorPicker.value;
        drawCtx.lineTo(e.offsetX, e.offsetY);
        drawCtx.stroke();
    });

    drawCanvas?.addEventListener('mouseup', () => (isDrawing = false));
    drawCanvas?.addEventListener('mouseout', () => (isDrawing = false));

    // Touch Events for Mobile
    drawCanvas?.addEventListener('touchstart', (e) => {
        e.preventDefault();
        isDrawing = true;
        const pos = getTouchPos(drawCanvas, e);
        drawCtx.beginPath();
        drawCtx.moveTo(pos.x, pos.y);
    });

    drawCanvas?.addEventListener('touchmove', (e) => {
        e.preventDefault();
        if (!isDrawing) return;
        const pos = getTouchPos(drawCanvas, e);
        drawCtx.lineWidth = 2;
        drawCtx.lineCap = 'round';
        drawCtx.strokeStyle = drawColorPicker.value;
        drawCtx.lineTo(pos.x, pos.y);
        drawCtx.stroke();
    });

    drawCanvas?.addEventListener('touchend', () => (isDrawing = false));
    drawCanvas?.addEventListener('touchcancel', () => (isDrawing = false));

    // Clear and Save Buttons
    $('#clearDrawSignature').click(function () {
        drawCtx?.clearRect(0, 0, drawCanvas.width, drawCanvas.height);
    });

    $('#saveDrawSignature').click(function () {
        saveSignature(drawCanvas?.toDataURL('image/png'));
    });

    // Save Signature Function
    function saveSignature(imageData) {
        $.post(
            wpSignatureCombo.ajax_url,
            { 
                action: 'bwdcv_save_signature', 
                security: wpSignatureCombo.nonce,
                image_data: imageData 
            },
            function (response) {
                const result = JSON.parse(response);
                if (result.success) {
                    $('#signatureResponse').html(
                        'Signature saved! <img src="' +
                        result.image_url +
                        '" width="100">'
                    );
                } else {
                    $('#signatureResponse').html('Error saving signature.');
                }
            }
        );
    }

    $('#fontSelect').on('change', function () {
        const selectedFont = $(this).val();

        // Preload selected font
        $('<div>', {
            text: 'Font preloader',
            style: `font-family: "${selectedFont}", cursive; position: absolute; opacity: 0.01; pointer-events: none;`,
        }).appendTo('body');

        // Redraw text
        drawTextWithFont();
    });

    //Custom select option font style
    function textFontSignttre() {
        const selector = document?.getElementById('custom-font-select');
        const selected = selector?.querySelector('.selected-font');
        const options = selector?.querySelectorAll('.font-options li');
        const input = document?.getElementById('fontSelect');

        selected?.addEventListener('click', function () {
            selector?.classList.toggle('open');
        });

        options?.forEach((option) => {
            option?.addEventListener('click', function () {
                const font = this.getAttribute('data-font');
                selected.textContent = font;
                selected.style.fontFamily = font;
                input.value = font;
                selector.classList.remove('open');
            });
        });

        document.addEventListener('click', function (e) {
            if (!selector?.contains(e.target)) {
                selector.classList.remove('open');
            }
        });
    }
    textFontSignttre();
})(jQuery);

(function ($) {
    $(document)?.ready(function () {
        $('#dataTable').DataTable({
            responsive: true,
            info: false,
            ordering: false,
            paging: false,
            searching: false,
        });
    });
})(jQuery);
