<x-app-layout>

    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 dark:text-gray-200 leading-tight">
            {{ __('Metaverse Cards') }}
        </h2>
    </x-slot>

    <style type="text/css">
        @font-face {
            font-family: "Primary";
            src: url("{{ url('/theme/fonts') }}/{{ $card->theme->font_primary }}");
        }

        @font-face {
            font-family: "Secondary";
            src: url("{{ url('/theme/fonts') }}/{{ $card->theme->font_secondary }}");
        }

        #print-docs {
            font-family: Arial, Helvetica, sans-serif;
        }

        .design-page {
            color: {{ $card->theme->color }};
        }

        .design-text-primary {
            font-family: "Primary";
            text-transform: {{ $card->theme->style_primary }};
        }

        .design-text-secondary {
            font-family: "Secondary";
        }

        #print-docs h1 {
            font-size: 72px;
        }

        #print-docs h2 {
            font-size: 64px;
        }

        #print-docs h3 {
            font-size: 48px;
        }

        #print-docs h4 {
            font-size: 36px;
        }

        #print-docs h5 {
            font-size: 24px;
        }

        #print-docs p {
            font-size: 18px;
        }
    </style>

    <!-- QRCode -->
    <script src="{{ url('/js/qrcode.js') }}"></script>
    <!-- HTML2Canvas -->
    <script src="{{ url('/js/html2canvas.js') }}"></script>
    <!-- Dom To Image -->
    <script src="{{ url('/js/dom-to-image.min.js') }}"></script>

    <script src="https://supereggbert.github.io/aframe-htmlembed-component/dist/build.js"></script>

    <div class="py-12">
        <div class="w-full p-0 lg:p-12">

            <div class="overflow-hidden h-0 w-0" id="print-docs">
                <div class="relative aspect-[4/6] bg-white" style="width: 1080px" id="front-card">
                    <img src="{{ url('/theme/' . $card->theme_code . '/bg_primary.jpg') }}" class="w-full">
                    <div class="absolute top-0 left-0 w-full h-full flex items-center justify-center"
                        style="padding: 274px 140px;">
                        <div
                            class="w-full h-full flex flex-col justify-center items-center design-text-secondary design-page">
                            <h3 class="mb-6">
                                @if ($card->title != null)
                                    {{ $card->title }}
                                @else
                                    WALIMATULURUS
                                @endif
                            </h3>
                            <h1 class="design-text-primary">{{ $card->male_short_name }}</h1>
                            <h4>&amp;</h4>
                            <h1 class="design-text-primary">{{ $card->female_short_name }}</h1>
                            <h3 class="mt-6">{{ date('d/m/Y', strtotime($card->date_masihi)) }}</h3>
                            <h4 class="mb-6">{{ $card->date_hijrah }}</h4>
                            <h3 class="text-center max-w-xl">
                                {{ $card->location_name }}
                            </h3>
                        </div>
                    </div>
                </div>
                <div class="aspect-[4/6] bg-white p-20" style="width: 1080px" id="back-card">

                    <div class="h-full flex flex-col justify-center items-center">
                        <p>Assalamualaikum w.b.t</p>
                        <h4 class="design-text-primary">{{ $card->father_name }}</h4>
                        @if ($card->mother_name != '' && $card->mother_name != null && $card->father_name != '' && $card->father_name != null)
                            <h4>&amp;</h4>
                        @endif
                        <h4 class="design-text-primary">{{ $card->mother_name }}</h4>
                        <p class="my-6 text-center max-w-xl">
                            DENGAN SEGALA HORMATNYA MEMPERSILAKAN Y.B. / Y.BHG. TAN SRI / PUAN SRI / DATUK / DATO’/
                            DATIN / TUAN / PUAN / SAUDARA / SAUDARI KE MAJLIS PERKAHWINAN
                        </p>
                        <h4 class="design-text-primary">{{ $card->male_full_name }}</h4>
                        <h4>&amp;</h4>
                        <h4 class="design-text-primary">{{ $card->female_full_name }}</h4>
                        <div class="flex-grow"></div>
                        <div class="py-6 w-full max-w-xl">
                            <p class="font-bold mb-1">TEMPAT:</p>
                            <div class="mb-6">
                                <h5>{{ $card->location_name }}</h5>
                                @if ($card->location_address != null)
                                    <p>{{ $card->location_address }}</p>
                                @endif
                            </div>
                            <p class="font-bold mb-1">TARIKH:</p>
                            <h5 class="mb-6">{{ date('d/m/Y', strtotime($card->date_masihi)) }}</h5>
                            <p class="font-bold mb-1">ATURCARA:</p>
                            <h5>
                                <table class="table table-borderless mb-6">
                                    <tbody>
                                        <tr>
                                            <td class="text-right pb-3">{{ $card->program_time_1 }}</td>
                                            <td class="pl-6 pb-3">{{ $card->program_name_1 }}</td>
                                        </tr>
                                        <tr>
                                            <td class="text-right pb-3">{{ $card->program_time_2 }}</td>
                                            <td class="pl-6 pb-3">{{ $card->program_name_2 }}</td>
                                        </tr>
                                        <tr>
                                            <td class="text-right">{{ $card->program_time_3 }}</td>
                                            <td class="pl-6">{{ $card->program_name_3 }}</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </h5>
                            <p class="mb-6 text-justify">
                                "Ya Allah Yang Maha Mencipta, Jadikanlah majlis ini majlis yang mendapat
                                keberkatan dan keredhaanMu, kekalkanlah ikatan perkahwinan mereka
                                sepanjang hayat, tetapkanlah kasih sayang antara mereka selagi tidak
                                melebihi kasih padaMu."
                            </p>
                            <p class="">Aamin, Ya Rabbal A'lamin</p>
                        </div>
                        <div class="flex-grow"></div>
                        <div class="flex gap-6 w-full max-w-xl">
                            <div class="aspect-square w-40 h-40" id="kkd-qrcode"></div>
                            <div class="flex flex-col flex-grow">
                                <p>IMBAS KOD QR SEKARANG</p>
                                <h5 class="font-bold">Kad Kahwin Digital + Chat AI</h5>
                                <div class="flex-grow"></div>
                                <p>{{ $card->male_short_name }} & {{ $card->female_short_name }}</p>
                                <p>{{ route('cards.show', $card->id) }}</p>
                            </div>
                        </div>
                    </div>
                </div>

            </div>

            <div class="grid lg:grid-cols-1">

                <div class="mx-6 lg:mx-0">
                    {{-- <p class="text-sm mb-2 w-full text-center">Metaverse Kad Kahwin</p> --}}
                    <div id="aframe-container" class="bg-white w-full aspect-[9/16] lg:aspect-video overflow-hidden shadow-lg border rounded-lg">
                        <!-- A-Frame scene will be injected here after images are ready -->
                        <div class="w-full h-full flex items-center justify-center text-gray-400">
                            <p>Loading metaverse...</p>
                        </div>
                    </div>
                </div>

                <div class="mx-6 lg:mx-0 overflow-hidden w-0 h-0">
                    <img id="preview-full-card" class="w-full my-auto" style="width: 1080px">
                    <div id="full-card" class="grid lg:grid-cols-2 bg-white" style="width: 1080px">
                        <div class="flex items-center justify-center">
                            <a href="#" class="w-full h-full">
                                <img id="preview-front-card" class="w-full my-auto">
                            </a>
                        </div>
                        <div class="flex items-center justify-center relative">
                            <a href="#" class="w-full">
                                <img id="preview-back-card" class="w-full my-auto">
                            </a>
                        </div>
                    </div>
                </div>

            </div>

        </div>
    </div>

    <script type="text/javascript">
        // Store blob URLs globally so A-Frame can access them
        let cardFrontBlobUrl = null;
        let cardBackBlobUrl = null;

        async function generateCardImages() {
            console.log('Generating card images...');
            
            // Generate front card
            await domtoimage.toBlob(document.getElementById('front-card'))
                .then(function(blob) {
                    cardFrontBlobUrl = URL.createObjectURL(blob);
                    document.getElementById('preview-front-card').src = cardFrontBlobUrl;
                    console.log('card front generated');
                });
            
            // Generate back card
            await domtoimage.toBlob(document.getElementById('back-card'))
                .then(function(blob) {
                    cardBackBlobUrl = URL.createObjectURL(blob);
                    document.getElementById('preview-back-card').src = cardBackBlobUrl;
                    console.log('card back generated');
                });
            
            // Generate full card preview
            await domtoimage.toBlob(document.getElementById('full-card'))
                .then(function(blob) {
                    document.getElementById('preview-full-card').src = URL.createObjectURL(blob);
                    console.log('card full generated');
                });
            
            console.log('All card images generated!');
        }

        function injectAframeScene() {
            const container = document.getElementById('aframe-container');
            
            // Create the A-Frame scene HTML with blob URLs already set
            const sceneHTML = `
                <a-scene embedded loading-screen="dotsColor: red; backgroundColor: black">
                    <a-assets>
                        <img id="metaverse-card-1" src="${cardFrontBlobUrl}" crossorigin="anonymous" />
                        <img id="metaverse-card-2" src="${cardBackBlobUrl}" crossorigin="anonymous" />
                        <img id="skybox" src="{{asset('models/skybox.png')}}" crossorigin="anonymous" />
                        <a-asset-item id="apartment" src="{{ asset('models/apartment.glb') }}"></a-asset-item>
                    </a-assets>

                    <a-entity id="room" position="0 0 -.5">
                        <a-sky src="#skybox"></a-sky>

                        <!--
                        <a-entity animation="property: rotation; to: 0 360 0; dur: 80000; easing: linear; loop: true">
                            <a-plane width="1" height="1.6" side="double" position="0 1.4 -3"
                                rotation="-15 0 0" src="#metaverse-card-1"></a-plane>
                            <a-plane width="1" height="1.6" side="double" position="3 1.4 0"
                                rotation="-15 -90 0" src="#metaverse-card-2"></a-plane>
                            <a-plane width="1" height="1.6" side="double" position="0 1.4 3"
                                rotation="-15 180 0" src="#metaverse-card-1"></a-plane>
                            <a-plane width="1" height="1.6" side="double" position="-3 1.4 0"
                                rotation="-15 90 0" src="#metaverse-card-2"></a-plane>
                        </a-entity>
                        -->

                        <a-entity position="3 0 .4" animation="property: rotation; to: 0 -360 0; dur: 20000; easing: linear; loop: true">
                            <!-- Cat by Quaternius (https://poly.pizza/m/qKICY6xla2) -->
                            <a-entity
                                gltf-model="https://cdn.glitch.global/e4ab7d94-4a08-4cab-9904-cecd4299a2c1/Cat.glb?v=1718304004599"
                                scale=".3 .3 .3" position="0 0 -1.5" rotation="0 90 0"
                                animation-mixer="clip:AnimalArmature|AnimalArmature|AnimalArmature|Walk; loop:100000000000000; timeScale: 1; crossFadeDuration: 1"></a-entity>
                        </a-entity>

                        <!-- Ceiling -->
                        <a-plane position="-1.3 3 1.6" rotation="90 0 0" color="#fff" material="side: double" geometry="height: 12; width: 14"></a-plane>

                        <!-- Apartment 2 by Gabriele Romagnoli [CC-BY] (https://creativecommons.org/licenses/by/3.0/) via Poly Pizza (https://poly.pizza/m/dtgO5dwwtkk) -->
                        <a-entity gltf-model="#apartment" position="-0.4 0.93 0.85" rotation="0 0 0" scale="8 8 8">
                            <a-plane side="double" position="0.43 0.01 -0.345" color="#fff" geometry="height: 0.1; width: 0.2">
                                <a-plane width="0.2" height="0.1" side="double" position="0 0 0.0001"
                                    rotation="" src="{{ asset('images/vr_tv.png') }}"></a-plane>
                            </a-plane>
                        </a-entity>

                        <a-entity
                            scale=".1 .1 .1" position="0 0.12 0" rotation="0 0 0">
                            <a-entity position="2.2 8.8 1" scale="2 2 2" rotation="-40 0 0" grabbable>
                                <a-plane width="1" height="1.6" side="double" position="-0.5 0 0"
                                    rotation="" src="#metaverse-card-1"
                                    obb-collider="centerModel: true"></a-plane>
                                <a-plane width="1" height="1.6" side="double" position="0.5 0 0"
                                    rotation="" src="#metaverse-card-2"
                                    obb-collider="centerModel: true"></a-plane>
                            </a-entity>
                            <!-- Orchid by Poly by Google [CC-BY] (https://creativecommons.org/licenses/by/3.0/) via Poly Pizza (https://poly.pizza/m/59BuDmuEYIZ)-->
                            <a-entity
                                gltf-model="https://cdn.glitch.global/e4ab7d94-4a08-4cab-9904-cecd4299a2c1/Orchid.glb?v=1718331915797"
                                scale=".1 .1 .1" position="-3 8 -3" rotation="0 0 0"></a-entity>
                            <!-- Book Stack by Danni Bittman [CC-BY] (https://creativecommons.org/licenses/by/3.0/) via Poly Pizza (https://poly.pizza/m/1WggoIFq8tx)-->
                            <a-entity
                                gltf-model="https://cdn.glitch.global/e4ab7d94-4a08-4cab-9904-cecd4299a2c1/Book%20Stack.glb?v=1718332241489"
                                scale="5 5 5" position="3 9 -2" rotation="0 30 0"></a-entity>
                            <!-- Phone by jeremy [CC-BY] (https://creativecommons.org/licenses/by/3.0/) via Poly Pizza (https://poly.pizza/m/8F1Of9426Ue) -->
                            <a-entity
                                gltf-model="https://cdn.glitch.global/e4ab7d94-4a08-4cab-9904-cecd4299a2c1/Phone.glb?v=1718333148727"
                                scale="0.25 0.25 0.25" position="-2 7.7 4" rotation="-90 30 0" grabbable>
                                <a-plane width="4.7" height="8.8" side="double" position="0 0 0.2"
                                    rotation="" src="#metaverse-card-1"
                                    obb-collider="centerModel: true"></a-plane>
                            </a-entity>
                        </a-entity>

                        <!-- 
                        <a-cylinder color="white" segments-radial="8" radius="4" height=".02"
                            side="double" position="0 -.01 0" rotation="0 90 0"
                            src="https://cdn.glitch.global/e4ab7d94-4a08-4cab-9904-cecd4299a2c1/kkd_2019.png?v=1718334005745">
                            <a-cylinder color="white" segments-radial="8" radius="4.2" height=".02"
                                side="double" position="0 -.01 0" rotation="0 0 0"></a-cylinder>
                        </a-cylinder> -->
                    </a-entity>

                    <a-camera position="1 1.6 0" wasd-controls="enabled:true"></a-camera>

                    <a-light position="2 3 0" color="#fff" intensity="5" type="point"></a-light>
                    <a-light position="-2 3 2" color="#fff" intensity="5" type="point"></a-light>
                    <a-light position="0 3 -1.5" color="#fff" intensity=".25" type="ambient"></a-light>
                    

                    <a-entity id="leftHand" hand-tracking-grab-controls="hand: left;"></a-entity>
                    <a-entity id="rightHand" hand-tracking-grab-controls="hand: right;"></a-entity>
                </a-scene>
            `;
            
            container.innerHTML = sceneHTML;
            console.log('A-Frame scene injected!');
        }

        // Initialize QR Code
        new QRCode(document.getElementById("kkd-qrcode"), {
            text: "{{ route('cards.show', $card->id) }}",
            width: 160,
            height: 160,
            colorDark: "#000000",
            colorLight: "#ffffff",
            correctLevel: QRCode.CorrectLevel.H
        });

        // Wait for DOM to be ready, then generate images and init A-Frame
        document.addEventListener('DOMContentLoaded', async function() {
            // Wait a bit for fonts and images to load
            await new Promise(resolve => setTimeout(resolve, 2000));
            
            // Generate card images first
            await generateCardImages();
            
            // Now inject A-Frame scene with the blob URLs already set
            injectAframeScene();
        });
    </script>

</x-app-layout>
