<div>
    @php($blockers = $this->esignBlockers)

    @if($blockers)
        <div class="alert alert-warning border-0 border-start border-warning border-4 shadow-sm mb-3" role="alert">
            <div class="d-flex align-items-start">
                <i class="mdi mdi-alert-circle-outline fs-3 me-2 text-warning"></i>
                <div>
                    <strong class="d-block mb-1">Application not ready for e-signature</strong>
                    <ul class="mb-0 ps-3 small">
                        @foreach($blockers as $blocker)
                            <li>{{ $blocker }}</li>
                        @endforeach
                    </ul>
                </div>
            </div>
        </div>
    @endif

    <!-- Main Card: Contract Requests History -->
    <div class="card shadow-sm mb-4">
        <div class="card-header bg-white d-flex justify-content-between align-items-center">
            <h5 class="mb-0">Contract Requests</h5>
            @can('claims.request.send')
            <button type="button"
                    class="btn btn-primary btn-sm"
                    @if($blockers) disabled title="Resolve the blockers above before creating a request"
                    @else data-bs-toggle="modal" data-bs-target="#newRequestModal" @endif>
                Create New Request
            </button>
            @endcan
        </div>
        <div class="card-body">
            <livewire:client.esign-timeline :client="$client" wire:key="esign-tl-{{ $client->id }}"/>
        </div>
    </div>

    <!-- Modal 1: Create New Request -->
    <div class="modal fade" id="newRequestModal" tabindex="-1" aria-labelledby="newRequestModalLabel" aria-hidden="true" wire:ignore.self>
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header bg-light">
                    <h5 class="modal-title" id="newRequestModalLabel">Select Contracts to Send</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0">
                            <thead class="table-light">
                            <tr>
                                <th scope="col" style="width: 50px;"></th>
                                <th scope="col">Contract Name</th>
                            </tr>
                            </thead>
                            <tbody>
                            @foreach($contracts as $contract)
                                <tr>
                                    <td>
                                        <input class="form-check-input" type="checkbox" wire:model.live="selectedContractIds" value="{{ $contract['id'] }}">
                                    </td>
                                    <td>{{ $contract['name'] }}</td>
                                </tr>
                            @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="modal-footer d-flex justify-content-between">
                    <div class="text-muted small">
                        Selected: {{ count($selectedContractIds) }} contract(s)
                    </div>
                    <div>
                        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                        @can('claims.request.send')
                        <button wire:click="processSignature"
                                class="btn btn-primary"
                                @disabled($blockers)
                                @if($blockers) title="Resolve the application blockers before sending" @endif>
                            Process Signatures
                            <div wire:loading wire:target="processSignature" class="spinner-border spinner-border-sm ms-2" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                        </button>
                        @endcan
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal 2: Review & Preview (PDF.js) -->
    <div class="modal fade" id="contractPreviewModal" tabindex="-1" data-bs-backdrop="static" aria-labelledby="previewModalLabel" aria-hidden="true" wire:ignore.self>
        <div class="modal-dialog modal-lg modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header bg-light">
                    <h5 class="modal-title" id="previewModalLabel">Review Contracts Before Sending</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body text-center bg-secondary" id="pdf-container" style="--bs-bg-opacity: .1;">
                    <!-- PDF.js Canvases will be injected here dynamically -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" wire:click="cancelDraft" data-bs-dismiss="modal">Cancel</button>
                    <!-- Confirm action fires Livewire method directly -->
                    @can('claims.request.send')
                    <button type="button" class="btn btn-success" wire:click="confirmAndSend">
                        Confirm & Send
                        <div wire:loading wire:target="confirmAndSend" class="spinner-border spinner-border-sm ms-2" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                    </button>
                    @endcan
                </div>
            </div>
        </div>
    </div>

    <script>
        // Generic copy to clipboard function for the table rows
        function copyToClipboard(text, buttonElement) {
            navigator.clipboard.writeText(text).then(() => {
                const originalText = buttonElement.innerText;
                buttonElement.innerText = 'Copied!';
                buttonElement.classList.replace('btn-outline-secondary', 'btn-success');

                setTimeout(() => {
                    buttonElement.innerText = originalText;
                    buttonElement.classList.replace('btn-success', 'btn-outline-secondary');
                }, 2000);
            }).catch(err => {
                console.error('Failed to copy text: ', err);
            });
        }
    </script>

    @script
    <script>
        pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';

        // Listen for the Livewire event to open the modal
        $wire.on('show-preview-modal', async ({ previews }) => {

            // Hide the New Request modal if it's open to prevent overlay issues
            const newReqModalEl = document.getElementById('newRequestModal');
            const newReqModal = bootstrap.Modal.getInstance(newReqModalEl);
            if (newReqModal) {
                newReqModal.hide();
            }

            const container = document.getElementById('pdf-container');
            container.innerHTML = ''; // Clear previous renders

            // Show Bootstrap Preview Modal
            const previewModalEl = document.getElementById('contractPreviewModal');
            const previewModal = new bootstrap.Modal(previewModalEl);
            previewModal.show();

            // Render each PDF passed from Livewire
            for (const preview of previews) {
                // Add a title separator for multiple documents
                const title = document.createElement('h6');
                title.className = "text-start mt-3 mb-2 fw-bold text-dark";
                title.innerText = `Preview: ${preview.name} (${preview.id})`;
                container.appendChild(title);

                // Decode base64 to binary for PDF.js
                const pdfData = atob(preview.pdf_data);

                try {
                    // Load the PDF Document
                    const loadingTask = pdfjsLib.getDocument({ data: pdfData });
                    const pdf = await loadingTask.promise;

                    // Loop through all pages in the PDF
                    for (let pageNum = 1; pageNum <= pdf.numPages; pageNum++) {
                        // Fetch the current page
                        const page = await pdf.getPage(pageNum);

                        // Scale the viewport to look good in the modal
                        const scale = 1.2;
                        const viewport = page.getViewport({ scale: scale });

                        // Create a wrapper for the canvas to add page numbering if desired (optional)
                        const pageWrapper = document.createElement('div');
                        pageWrapper.className = 'position-relative mb-4';

                        // Create canvas
                        const canvas = document.createElement('canvas');
                        canvas.className = 'border shadow-sm bg-white mx-auto d-block';
                        canvas.style.maxWidth = '100%';
                        canvas.style.height = 'auto';

                        const context = canvas.getContext('2d');
                        canvas.height = viewport.height;
                        canvas.width = viewport.width;

                        const renderContext = {
                            canvasContext: context,
                            viewport: viewport
                        };

                        // Render page to canvas
                        await page.render(renderContext).promise;

                        // Add page number text
                        const pageLabel = document.createElement('div');
                        pageLabel.className = 'text-muted small mt-1';
                        pageLabel.innerText = `Page ${pageNum} of ${pdf.numPages}`;

                        pageWrapper.appendChild(canvas);
                        pageWrapper.appendChild(pageLabel);
                        container.appendChild(pageWrapper);
                    }

                } catch (error) {
                    console.error("Error rendering PDF: ", error);
                    const errorMsg = document.createElement('div');
                    errorMsg.className = "alert alert-danger";
                    errorMsg.innerText = `Failed to load preview for ${preview.name}.`;
                    container.appendChild(errorMsg);
                }
            }
        });

        // Listen for the event to close the modal after successful submission
        $wire.on('close-preview-modal', () => {
            const modalEl = document.getElementById('contractPreviewModal');
            const modal = bootstrap.Modal.getInstance(modalEl);
            if (modal) {
                modal.hide();
            }
        });
    </script>
    @endscript
</div>