<x-app-layout>
    <x-slot name="header">
        <div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
            <div>
                <p class="text-sm font-semibold uppercase tracking-wide text-blue-600 dark:text-blue-400">Shareable Report</p>
                <h2 class="mt-1 text-2xl font-bold text-slate-950 dark:text-white">{{ $report['type'] === 'weekly' ? 'Weekly Trade Report' : 'Monthly Trade Report' }}</h2>
            </div>
            <a href="{{ route('reports.share.index') }}" class="rounded-lg border border-blue-100 px-4 py-2 text-sm font-bold text-blue-700 dark:border-blue-900 dark:text-blue-300">Change Options</a>
        </div>
    </x-slot>

    @php
        $previewMinWidth = match ($imageSize) {
            'story' => 320,
            'facebook' => 430,
            default => 360,
        };
    @endphp

    <div class="grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]">
        <section class="rounded-lg border border-blue-100 bg-white p-3 shadow-sm dark:border-blue-900/50 dark:bg-slate-900 sm:p-6">
            <div class="overflow-x-auto overscroll-x-contain pb-3 [scrollbar-width:thin] [scrollbar-color:theme(colors.blue.300)_transparent] dark:[scrollbar-color:theme(colors.blue.800)_transparent]">
                <div class="mx-auto w-full max-w-[520px]" style="min-width: {{ $previewMinWidth }}px; aspect-ratio: {{ $size['ratio'] }};">
                    @include('reports.share.template')
                </div>
            </div>
            <p class="mt-3 text-center text-xs font-semibold text-slate-500 dark:text-slate-400 sm:hidden">
                Swipe sideways to preview the full report design.
            </p>
        </section>

        <aside class="rounded-lg border border-blue-100 bg-white p-6 shadow-sm dark:border-blue-900/50 dark:bg-slate-900">
            <h3 class="text-lg font-black text-slate-950 dark:text-white">Export image</h3>
            <p class="mt-2 text-sm leading-6 text-slate-600 dark:text-slate-300">
                Size: <strong>{{ $size['width'] }}x{{ $size['height'] }}</strong>. Download uses browser-side html2canvas, so it works well on cPanel without server Node/Browsershot.
            </p>

            <div class="mt-5 space-y-3">
                <button
                    id="download-share-report"
                    data-width="{{ $size['width'] }}"
                    data-height="{{ $size['height'] }}"
                    data-name="vizutrade-{{ $report['type'] }}-{{ $imageSize }}-{{ $imageTheme }}-report.png"
                    class="w-full rounded-lg bg-blue-600 px-4 py-3 text-sm font-black text-white hover:bg-blue-700"
                >
                    Download PNG
                </button>
                <button id="native-share-report" class="w-full rounded-lg border border-blue-100 px-4 py-3 text-sm font-black text-blue-700 hover:bg-blue-50 dark:border-blue-900 dark:text-blue-300 dark:hover:bg-blue-950/50">
                    Share Image
                </button>
            </div>

            <div class="mt-6 rounded-lg bg-blue-50 p-4 text-sm text-blue-900 dark:bg-blue-950/40 dark:text-blue-100">
                Profit display: <strong>{{ $showProfit ? 'Visible' : 'Hidden' }}</strong>
            </div>
        </aside>
    </div>

    <script>
        async function waitForShareReportAssets(card) {
            if (document.fonts?.ready) {
                await document.fonts.ready;
            }

            const images = Array.from(card.querySelectorAll('img'));
            await Promise.all(images.map((image) => {
                if (image.complete) {
                    return Promise.resolve();
                }

                if (image.decode) {
                    return image.decode().catch(() => Promise.resolve());
                }

                return new Promise((resolve) => {
                    image.onload = resolve;
                    image.onerror = resolve;
                });
            }));
        }

        async function renderShareReportCanvas() {
            const card = document.getElementById('share-report-card');
            const button = document.getElementById('download-share-report');
            const targetWidth = Number(button.dataset.width);
            const targetHeight = Number(button.dataset.height);
            const rect = card.getBoundingClientRect();
            const scale = Math.max(targetWidth / rect.width, targetHeight / rect.height);

            await waitForShareReportAssets(card);

            const renderedCanvas = await window.html2canvas(card, {
                backgroundColor: null,
                scale: scale,
                useCORS: true,
                logging: false,
                width: rect.width,
                height: rect.height,
                windowWidth: document.documentElement.scrollWidth,
                windowHeight: document.documentElement.scrollHeight,
            });

            if (renderedCanvas.width === targetWidth && renderedCanvas.height === targetHeight) {
                return renderedCanvas;
            }

            const outputCanvas = document.createElement('canvas');
            outputCanvas.width = targetWidth;
            outputCanvas.height = targetHeight;
            outputCanvas
                .getContext('2d')
                .drawImage(renderedCanvas, 0, 0, renderedCanvas.width, renderedCanvas.height, 0, 0, targetWidth, targetHeight);

            return outputCanvas;
        }

        document.getElementById('download-share-report')?.addEventListener('click', async (event) => {
            const button = event.currentTarget;
            button.disabled = true;
            button.textContent = 'Generating...';

            try {
                const canvas = await renderShareReportCanvas();
                const link = document.createElement('a');
                link.download = button.dataset.name;
                link.href = canvas.toDataURL('image/png');
                link.click();
            } finally {
                button.disabled = false;
                button.textContent = 'Download PNG';
            }
        });

        document.getElementById('native-share-report')?.addEventListener('click', async () => {
            if (!navigator.canShare || !navigator.share) {
                alert('Your browser does not support direct image sharing. Use Download PNG instead.');
                return;
            }

            const canvas = await renderShareReportCanvas();
            canvas.toBlob(async (blob) => {
                const file = new File([blob], 'vizutrade-report.png', { type: 'image/png' });
                if (navigator.canShare({ files: [file] })) {
                    await navigator.share({ files: [file], title: 'ViZuTrade Report', text: 'Generated by ViZuTrade' });
                }
            }, 'image/png');
        });
    </script>
</x-app-layout>
