<div>
    <!-- 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>
            <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#newRequestModal">
                Create New Request
            </button>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover align-middle">
                    <thead class="table-light">
                    <tr>
                        <th scope="col">ID</th>
                        <th scope="col">Status</th>
                        <th scope="col">Date Sent</th>
                        <th scope="col">Link</th>
                    </tr>
                    </thead>
                    <tbody>
                    @forelse($client->contractRequests ?? [] as $request)
                        <tr>
                            <td>#{{ $request->id }}</td>
                            <td>
                                    <span class="badge bg-{{ $request->status === 'sent' ? 'success' : 'secondary' }}">
                                        {{ ucfirst($request->status) }}
                                    </span>
                            </td>
                            <td>{{ $request->created_at->format('M d, Y H:i') }}</td>
                            <td>
                                @if($request->link)
                                    <a href="{{ $request->link }}" target="_blank" class="btn btn-sm btn-link text-decoration-none">View</a>
                                    <button class="btn btn-sm btn-outline-secondary" onclick="copyToClipboard('{{ $request->link }}', this)">
                                        Copy Link
                                    </button>
                                @else
                                    <span class="text-muted">N/A</span>
                                @endif
                            </td>
                        </tr>
                    @empty
                        <!-- Empty State -->
                        <tr>
                            <td colspan="4" class="text-center py-5 text-muted">
                                <div class="mb-3">
                                    <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="text-secondary opacity-50">
                                        <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
                                        <polyline points="14 2 14 8 20 8"></polyline>
                                        <line x1="16" y1="13" x2="8" y2="13"></line>
                                        <line x1="16" y1="17" x2="8" y2="17"></line>
                                        <polyline points="10 9 9 9 8 9"></polyline>
                                    </svg>
                                </div>
                                <h6 class="text-dark">No Contract Requests Found</h6>
                                <p class="small mb-3">Get started by creating a new contract request for this client.</p>
                                <button type="button" class="btn btn-outline-primary btn-sm" data-bs-toggle="modal" data-bs-target="#newRequestModal">
                                    Create New Request
                                </button>
                            </td>
                        </tr>
                    @endforelse
                    </tbody>
                </table>
            </div>
        </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="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>
                        <button wire:click="processSignature" class="btn btn-primary">
                            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>
                    </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" data-bs-dismiss="modal">Cancel</button>
                    <!-- Confirm action fires Livewire method directly -->
                    <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>
                </div>
            </div>
        </div>
    </div>

    <!-- Include PDF.js from CDN -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"></script>

    <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>