<script>
document.addEventListener('DOMContentLoaded', function () {
    const copySelect = document.getElementById('document-copy-select');
    const copyLabel = document.getElementById('document-copy-label');
    const pdfLink = document.getElementById('debit-note-pdf-download');
    const printLink = document.getElementById('debit-note-print-link');
    const pdfBase = @json(route('admin.debit-notes.pdf', $debitNote));
    const printBase = @json(route('admin.debit-notes.print', $debitNote));
    const canvas = document.getElementById('debit-note-preview-canvas');

    function syncCopyToPdf() {
        const key = copySelect ? (copySelect.value || 'original') : 'original';
        const copyQs = 'copy=' + encodeURIComponent(key);
        if (pdfLink) {
            pdfLink.href = pdfBase + (pdfBase.includes('?') ? '&' : '?') + copyQs;
        }
        if (printLink) {
            printLink.href = printBase + (printBase.includes('?') ? '&' : '?') + copyQs + '&autoprint=1';
        }
    }

    if (copySelect && copyLabel) {
        copySelect.addEventListener('change', function () {
            copyLabel.textContent = this.options[this.selectedIndex].text;
            syncCopyToPdf();
        });
    }
    syncCopyToPdf();

    document.querySelectorAll('.billing-layout-toggle [data-layout]').forEach(btn => {
        btn.addEventListener('click', function () {
            document.querySelectorAll('.billing-layout-toggle [data-layout]').forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            const doc = document.getElementById('debit-note-doc');
            if (doc) doc.dataset.layout = this.dataset.layout;
        });
    });

    document.querySelectorAll('.billing-zoom-toggle [data-zoom]').forEach(btn => {
        btn.addEventListener('click', function () {
            document.querySelectorAll('.billing-zoom-toggle [data-zoom]').forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            if (canvas) canvas.dataset.zoom = this.dataset.zoom;
        });
    });

    const getLinkBtn = document.getElementById('debit-note-get-link-btn');
    const shareModalEl = document.getElementById('debit-note-share-link-modal');
    if (getLinkBtn && shareModalEl) {
        const shareModal = bootstrap.Modal.getOrCreateInstance(shareModalEl);
        const shareUrlInput = document.getElementById('debit-note-share-url');
        const shareError = document.getElementById('debit-note-share-error');
        const shareVisibility = document.getElementById('debit-note-share-visibility');
        const csrf = document.querySelector('meta[name="csrf-token"]');

        getLinkBtn.addEventListener('click', async function () {
            shareError.classList.add('d-none');
            shareUrlInput.value = 'Generating link…';
            shareModal.show();

            try {
                const response = await fetch(getLinkBtn.dataset.shareUrl, {
                    method: 'POST',
                    headers: {
                        'Accept': 'application/json',
                        'X-CSRF-TOKEN': csrf ? csrf.content : '',
                        'X-Requested-With': 'XMLHttpRequest',
                    },
                });
                const data = await response.json();
                if (!response.ok) {
                    throw new Error(data.message || 'Could not generate share link.');
                }
                shareUrlInput.value = data.url;
                if (shareVisibility && data.visibility) {
                    shareVisibility.textContent = data.visibility;
                }
            } catch (error) {
                shareUrlInput.value = '';
                shareError.textContent = error.message || 'Could not generate share link.';
                shareError.classList.remove('d-none');
            }
        });

        const copyBtn = document.getElementById('debit-note-share-copy-btn');
        if (copyBtn) {
            copyBtn.addEventListener('click', async function () {
                const url = shareUrlInput.value;
                if (!url || url.startsWith('Generating')) {
                    return;
                }
                try {
                    await navigator.clipboard.writeText(url);
                    copyBtn.textContent = 'Copied!';
                    setTimeout(function () { copyBtn.textContent = 'Copy'; }, 2000);
                } catch (e) {
                    shareUrlInput.select();
                    document.execCommand('copy');
                    copyBtn.textContent = 'Copied!';
                    setTimeout(function () { copyBtn.textContent = 'Copy'; }, 2000);
                }
            });
        }
    }
});
</script>
