{{--
    Standalone print document. Wraps whichever paper layout was asked for in a
    bare HTML page with the right @page size, then triggers the browser print
    dialog. The layouts themselves are shared with the Master Control live
    preview, so what a landlord approves is what comes out of the printer.
--}}
@php
    $isThermal = $paper === 'thermal80';
    $layout = $isThermal ? 'invoices.print.thermal80' : 'invoices.print.a4';
@endphp
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>{{ $doc->number }}</title>
    <style>
        @page {
            @if ($isThermal)
                /* Continuous roll: 80mm stock, 72mm printable. A fixed height
                   would clip a long bill, so the page grows with content. */
                size: 80mm auto;
                margin: 0;
            @else
                size: A4 portrait;
                margin: 0;
            @endif
        }

        html, body { margin: 0; padding: 0; background: #f3f4f6; }

        @media print {
            html, body { background: #fff; }
            .no-print { display: none !important; }
        }

        .toolbar { position: sticky; top: 0; z-index: 10; display: flex; gap: 8px; align-items: center;
            justify-content: center; padding: 10px; background: #1f2937; color: #f9fafb;
            font-family: system-ui, -apple-system, "Segoe UI", sans-serif; font-size: 13px; }
        .toolbar button, .toolbar a { appearance: none; border: 1px solid #4b5563; background: #374151;
            color: #f9fafb; padding: 6px 14px; border-radius: 6px; font: inherit; cursor: pointer;
            text-decoration: none; }
        .toolbar button:hover, .toolbar a:hover { background: #4b5563; }
        .toolbar .spacer { flex: 1 1 auto; max-width: 24px; }

        /* fit-content, so the drop shadow hugs the paper rather than the window:
           each layout declares its own stock width (210mm / 72mm) and centres
           itself inside this. */
        .sheet { width: fit-content; margin: 16px auto; background: #fff;
            box-shadow: 0 1px 3px rgba(0,0,0,.2); }
        @media print { .sheet { width: auto; margin: 0; box-shadow: none; } }
    </style>
</head>
<body>
    <div class="toolbar no-print">
        <span>{{ $isThermal ? '80mm receipt' : 'A4 invoice' }} — {{ $doc->number }}</span>
        <span class="spacer"></span>
        <button type="button" id="printBtn">Print</button>
        <a href="{{ route('invoices.print', ['invoice' => $invoiceKey, 'paper' => $isThermal ? 'a4' : 'thermal80', 'preview' => ($embed ?? false) ? 1 : null]) }}">
            Switch to {{ $isThermal ? 'A4' : '80mm' }}
        </a>
    </div>

    <div class="sheet" id="sheet">
        {{-- Real print: `preview` (the letterhead placeholder flag) is
             deliberately left unset here, distinct from `$embed` above. --}}
        @include($layout, ['doc' => $doc])
    </div>

    @unless(($embed ?? false))
    <script>
        const isThermal = {{ $isThermal ? 'true' : 'false' }};
        const paper = isThermal ? 'thermal80' : 'a4';

        function printDocument(html, paper) {
            if (!html) return;

            const frame = document.createElement('iframe');
            frame.setAttribute('aria-hidden', 'true');

            /*
            * IMPORTANT:
            *
            * Do NOT use:
            *   width: 1px
            *   height: 1px
            *   opacity: 0
            *
            * Chrome can treat the iframe as having no printable layout.
            *
            * Keep the iframe rendered, but place it far outside the viewport.
            */
            const frameWidth = paper === 'thermal80' ? '80mm' : '210mm';

            frame.style.cssText = [
                'position: fixed',
                'left: -10000px',
                'top: 0',
                `width: ${frameWidth}`,
                'height: 100vh',
                'border: 0',
                'visibility: visible',
            ].join(';');

            const page = paper === 'thermal80'
                ? '@page { size: 80mm auto; margin: 0; }'
                : '@page { size: A4 portrait; margin: 0; }';

            let started = false;

            const cleanup = () => {
                if (frame.parentNode) {
                    frame.remove();
                }
            };

            const start = () => {
                if (started) return;
                started = true;

                const printWindow = frame.contentWindow;

                if (!printWindow) {
                    cleanup();
                    return;
                }

                printWindow.focus();
                printWindow.print();

                printWindow.addEventListener(
                    'afterprint',
                    cleanup,
                    { once: true }
                );

                // Fallback for browsers that do not fire afterprint.
                setTimeout(cleanup, 60000);
            };

            document.body.appendChild(frame);

            const doc = frame.contentDocument;

            if (!doc) {
                cleanup();
                return;
            }

            doc.open();

            doc.write(`
                <!DOCTYPE html>
                <html lang="en">
                <head>
                    <meta charset="utf-8">
                    <meta name="viewport" content="width=device-width, initial-scale=1">

                    <base href="${document.baseURI}">

                    <style>
                        ${page}

                        html,
                        body {
                            margin: 0;
                            padding: 0;
                            background: #fff;
                        }

                        html {
                            width: 100%;
                        }

                        body {
                            width: 100%;
                        }

                        @media print {
                            html,
                            body {
                                margin: 0 !important;
                                padding: 0 !important;
                                background: #fff !important;
                            }
                        }
                    </style>
                </head>

                <body>
                    ${html}
                </body>
                </html>
            `);

            doc.close();

            /*
            * document.write() + document.close() does not always produce a
            * reliable load event in every browser, especially for dynamically
            * generated HTML.
            *
            * Give the browser time to:
            *   - parse the receipt
            *   - apply the receipt CSS
            *   - load the logo
            *   - calculate the final receipt height
            */
            const waitForImages = Array.from(
                doc.images || []
            );

            Promise.all(
                waitForImages.map((image) => {
                    if (image.complete) {
                        return Promise.resolve();
                    }

                    return new Promise((resolve) => {
                        image.addEventListener('load', resolve, { once: true });
                        image.addEventListener('error', resolve, { once: true });
                    });
                })
            ).then(() => {
                setTimeout(start, 100);
            });

            /*
            * Absolute fallback.
            */
            setTimeout(start, 2000);
        }

        const sheet = document.getElementById('sheet');
        const printBtn = document.getElementById('printBtn');

        function doPrint() {
            const html = sheet.innerHTML;
            printDocument(html, paper);
        }

        printBtn.addEventListener('click', doPrint);

        // Auto-open the dialog on arrival; the toolbar button covers a cancel.
        // Skip when embedded as a preview (the POS receipt modal) — that context
        // paints the sheet in an iframe and must not hijack the browser.
        window.addEventListener('load', () => window.setTimeout(doPrint, 250));
    </script>
    @endunless
</body>
</html>