<?php

/**
 * WhatsApp Messaging Distribution Queue View
 *
 * Provides manual template queue management, message clipboard copying,
 * direct WhatsApp deep links, status markers, and queue regeneration actions.
 *
 * Variables:
 *   $title         — string — Page title.
 *   $queue         — array — Compiled list of guest messaging templates.
 *   $search        — string — Active search filter query.
 *   $status        — string — Filter selection ('not_sent' | 'sent' | 'all').
 *   $pending_count — int — Number of guests remaining to be sent.
 *   $sent_count    — int — Number of guests marked sent.
 *
 * @package Inveetaire
 * @ref     RC-014
 */

$role = \App\Core\Session::get('role_snapshot') === 'crew' ? 'crew' : 'couple';
?>

<div class="max-w-6xl mx-auto space-y-6" x-data="{ queueLoading: false, resetModalOpen: false }">
     <!-- Header -->
    <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
        <div>
            <div class="page-breadcrumb">
                <a href="<?= url('/app/couple/dashboard') ?>">Dashboard</a>
                <span class="sep">/</span>
                <span>Messaging Queue</span>
            </div>
            <h1 class="page-h1">
                <span class="page-header-icon">
                    <i class="fa-brands fa-whatsapp"></i>
                </span>
                <?= escape_html($title) ?>
            </h1>
            <p class="page-subtitle">Review personalized templates, launch direct WhatsApp chats, and mark invitations as delivered.</p>
        </div>
        <div class="flex items-center gap-2">
            <!-- Regenerate / Reset Queue Control (RC-015 Standardized Confirmation Dialog) -->
            <div>
                <button type="button" @click="resetModalOpen = true" class="btn btn-secondary btn-md">
                    🔄 Regenerate Queue
                </button>

                <!-- Standardized Reset Modal Overlay -->
                <div 
                    class="fixed inset-0 bg-slate-900/60 backdrop-blur-sm z-50 flex items-center justify-center p-4" 
                    style="display: none;" 
                    x-show="resetModalOpen"
                    @keydown.escape.window="resetModalOpen = false"
                    @click.self="resetModalOpen = false"
                    x-transition:enter="transition ease-out duration-200"
                    x-transition:enter-start="opacity-0 scale-95"
                    x-transition:enter-end="opacity-100 scale-100"
                    x-transition:leave="transition ease-in duration-150"
                    x-transition:leave-start="opacity-100 scale-100"
                    x-transition:leave-end="opacity-0 scale-95"
                    role="dialog"
                    aria-modal="true"
                    aria-labelledby="modal-title-reset"
                >
                    <div class="bg-white rounded-2xl max-w-sm w-full p-6 shadow-2xl space-y-6">
                        <div class="text-center space-y-2">
                            <span class="text-4xl block">⚠️</span>
                            <h3 id="modal-title-reset" class="text-sm font-bold text-slate-800">Regenerate Queue?</h3>
                            <p class="text-xs text-slate-500 leading-relaxed">This resets the invitation delivery status of ALL guests back to Pending. Are you sure you want to proceed?</p>
                        </div>
                        
                        <form method="POST" action="<?= url("/app/{$role}/engagement/whatsapp-queue/reset") ?>" class="flex gap-3 m-0">
                            <input type="hidden" name="_csrf" value="<?= escape_html(\App\Core\Csrf::getToken()) ?>">
                            <button type="button" @click="resetModalOpen = false" class="btn btn-secondary flex-1 py-2 text-xs font-bold">
                                Cancel
                            </button>
                            <button type="submit" class="btn btn-primary flex-1 py-2 text-xs font-bold text-white">
                                Confirm Reset
                            </button>
                        </form>
                    </div>
                </div>
            </div>
            <?php if ($role !== 'crew'): ?>
                <a href="<?= url('/app/couple/messaging/template') ?>" class="btn btn-secondary flex items-center gap-1.5">
                    <i class="fa-solid fa-pen"></i> Edit Wording Template
                </a>
            <?php endif; ?>
        </div>
    </div>

    <!-- Status Tabs & Summary counts -->
    <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 bg-white border border-slate-100 rounded-2xl p-4 shadow-sm">
        <div class="flex gap-2">
            <a 
                href="<?= url("/app/{$role}/engagement/whatsapp-queue?status=not_sent") ?>" 
                @click="queueLoading = true"
                class="px-4 py-2 text-xs font-semibold rounded-lg <?= $status === 'not_sent' ? 'bg-purple-100 text-purple-700 font-bold' : 'text-slate-500 hover:bg-slate-50' ?>"
            >
                ⏳ Pending Delivery (<?= $pending_count ?>)
            </a>
            <a 
                href="<?= url("/app/{$role}/engagement/whatsapp-queue?status=sent") ?>" 
                @click="queueLoading = true"
                class="px-4 py-2 text-xs font-semibold rounded-lg <?= $status === 'sent' ? 'bg-purple-100 text-purple-700 font-bold' : 'text-slate-500 hover:bg-slate-50' ?>"
            >
                ✅ Sent (<?= $sent_count ?>)
            </a>
            <a 
                href="<?= url("/app/{$role}/engagement/whatsapp-queue?status=all") ?>" 
                @click="queueLoading = true"
                class="px-4 py-2 text-xs font-semibold rounded-lg <?= $status === 'all' ? 'bg-purple-100 text-purple-700 font-bold' : 'text-slate-500 hover:bg-slate-50' ?>"
            >
                All Guests
            </a>
        </div>
        
        <!-- Quick search in queue -->
        <form method="GET" action="<?= url("/app/{$role}/engagement/whatsapp-queue") ?>" @submit="queueLoading = true" class="flex gap-2 w-full sm:w-auto">
            <input type="hidden" name="_status" value="<?= escape_html($status) ?>">
            <input 
                type="text" 
                name="search" 
                value="<?= escape_html($search) ?>" 
                placeholder="Search queue..." 
                class="form-input text-xs py-1.5 px-3 w-full sm:w-48"
            >
            <button type="submit" class="btn btn-primary text-xs py-1.5 px-3">Filter</button>
        </form>
    </div>

    <!-- Main Flex Columns layout: Left column Queue lists, Right column Premium placeholder -->
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        
        <!-- Queue Candidate Lists (Left 2 columns) -->
        <div class="lg:col-span-2 space-y-4">
            
            <!-- Loading skeletons visual overlay (RC-015) -->
            <div class="space-y-3" x-show="queueLoading" style="display: none;">
                <div class="skeleton-pulse skeleton-card bg-slate-50 border border-slate-100 rounded-2xl" style="height: 100px;"></div>
                <div class="skeleton-pulse skeleton-card bg-slate-50 border border-slate-100 rounded-2xl" style="height: 100px;"></div>
                <div class="skeleton-pulse skeleton-card bg-slate-50 border border-slate-100 rounded-2xl" style="height: 100px;"></div>
            </div>

            <div x-show="!queueLoading" class="space-y-4">
                <?php if (empty($queue)): ?>
                    <div class="empty-state-elegant">
                        <div class="empty-state-icon">✉️</div>
                        <h3 class="empty-state-title">No guests in this queue</h3>
                        <p class="empty-state-text">Either all invitations have been successfully sent, or no pending items match your filters.</p>
                        <div class="mt-4">
                            <a href="<?= url("/app/{$role}/guests") ?>" class="btn btn-primary btn-sm font-bold inline-flex items-center gap-1.5 px-4 py-2">
                                <i class="fa-solid fa-users"></i> Manage Guest List
                            </a>
                        </div>
                    </div>
                <?php else: ?>
                    <div class="space-y-3">
                    <?php foreach ($queue as $item): ?>
                        <div class="bg-white border border-slate-100 rounded-2xl p-5 shadow-sm hover:shadow-md transition duration-200 flex flex-col md:flex-row md:items-center justify-between gap-4">
                            <div class="space-y-1">
                                <div class="flex items-center gap-2">
                                    <h4 class="font-bold text-slate-800"><?= escape_html($item['full_name']) ?></h4>
                                    <span class="badge badge-neutral text-[10px]">
                                        <?= escape_html(ucfirst($item['guest_group'] ?? 'others')) ?>
                                    </span>
                                    <?php if ($item['invitation_status'] === 'sent'): ?>
                                        <span class="badge bg-purple-100 text-purple-700 text-[10px]">Sent</span>
                                    <?php endif; ?>
                                </div>
                                <div class="text-xs text-slate-400 font-mono flex items-center gap-3">
                                    <span>📞 <?= escape_html($item['phone_number'] ?? 'No number') ?></span>
                                    <span>👥 <?= (int) $item['invited_pax'] ?> seats</span>
                                </div>
                            </div>
                            
                            <!-- Action Control buttons -->
                            <div class="flex items-center gap-2 whitespace-nowrap self-end md:self-auto">
                                <!-- Preview Modal Trigger -->
                                <button 
                                    type="button" 
                                    onclick='openPreviewModal("<?= escape_javascript($item['full_name']) ?>", <?= json_encode($item['message'], JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>, "<?= escape_javascript($item['whatsapp_url'] ?? '') ?>")'
                                    class="btn btn-secondary btn-sm text-xs py-1.5 px-3"
                                >
                                    👁️ Preview
                                </button>
                                
                                <!-- Copy Message -->
                                <button 
                                    type="button" 
                                    onclick='copyText(<?= json_encode($item['message'], JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>)'
                                    class="btn btn-secondary btn-sm text-xs py-1.5 px-3"
                                >
                                    📋 Copy
                                </button>

                                <!-- WhatsApp Web link -->
                                <?php if (!empty($item['whatsapp_url'])): ?>
                                    <a 
                                        href="<?= escape_html($item['whatsapp_url']) ?>" 
                                        target="_blank" 
                                        onclick="openWhatsAppLink(<?= $item['id'] ?>)"
                                        class="btn btn-sm bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg text-xs py-1.5 px-3 flex items-center gap-1.5"
                                    >
                                        💬 Send WhatsApp
                                    </a>
                                <?php else: ?>
                                    <button 
                                        type="button" 
                                        disabled 
                                        class="btn btn-secondary btn-sm text-xs py-1.5 px-3 opacity-50 cursor-not-allowed"
                                    >
                                        💬 Send WhatsApp
                                    </button>
                                <?php endif; ?>

                                <!-- Manual Mark as Sent form -->
                                <?php if ($item['invitation_status'] === 'not_sent'): ?>
                                    <form id="mark-sent-form-<?= $item['id'] ?>" method="POST" action="<?= url("/app/{$role}/engagement/whatsapp-queue/mark-sent/" . $item['id']) ?>" class="inline m-0">
                                        <input type="hidden" name="_csrf" value="<?= escape_html(\App\Core\Csrf::getToken()) ?>">
                                        <button type="submit" class="btn btn-secondary btn-sm text-xs py-1.5 px-3" title="Mark as invitation sent">
                                            ✓ Mark Sent
                                        </button>
                                    </form>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
            
        </div>

        <!-- Premium Feature Broadcast Placeholder (Right 1 column) -->
        <div class="space-y-4">
            <div class="bg-white border border-slate-100 rounded-2xl p-6 shadow-sm relative overflow-hidden" style="background-image: linear-gradient(135deg, #faf5ff 0%, #f5f3ff 100%);">
                <!-- Coming Soon premium ribbon -->
                <div class="absolute top-4 right-4 bg-purple-600 text-white font-bold text-[9px] uppercase tracking-widest px-2.5 py-1 rounded-full shadow-sm">
                    Premium Feature
                </div>
                
                <div class="text-3xl mb-4 mt-2">📡</div>
                <h3 class="font-bold text-slate-800 text-base">Automated Broadcast Center</h3>
                <p class="text-xs text-slate-500 mt-2 leading-relaxed">
                    Automate invitation distribution without clicking. Import lists and broadcast to hundreds of guests simultaneously using our off-site webhook channels.
                </p>

                <!-- Disabled form mock widgets -->
                <div class="mt-6 space-y-3 opacity-60 pointer-events-none">
                    <div>
                        <label class="text-[10px] font-bold uppercase tracking-wider text-slate-400">Broadcast Channel</label>
                        <select class="form-input text-xs w-full mt-1 bg-slate-50" disabled>
                            <option>Inveetaire Gateway Shared (Default)</option>
                        </select>
                    </div>
                    <div>
                        <label class="text-[10px] font-bold uppercase tracking-wider text-slate-400">Schedule Delivery</label>
                        <input type="text" class="form-input text-xs w-full mt-1 bg-slate-50" value="Instant (As soon as possible)" disabled>
                    </div>
                    <button type="button" disabled class="btn btn-primary w-full text-xs py-2 mt-2 bg-purple-400 cursor-not-allowed">
                        🚀 Schedule Automated Broadcast
                    </button>
                </div>
            </div>
        </div>

    </div>
</div>

<!-- Modal Popup for Wording Template Review -->
<div id="preview-modal" class="hidden fixed inset-0 z-50 overflow-y-auto flex items-center justify-center p-4 bg-slate-900/60 backdrop-blur-sm">
    <div class="card max-w-md w-full overflow-hidden shadow-2xl p-0">
        <div class="p-6 border-b border-slate-100 flex items-center justify-between bg-slate-50/50">
            <div>
                <h3 class="text-sm font-bold text-slate-800" id="modal-guest-name">Personalized Wording</h3>
                <p class="text-[10px] text-slate-400 mt-0.5">Wording pre-filled for direct sending</p>
            </div>
            <button type="button" onclick="closePreviewModal()" class="text-slate-400 hover:text-slate-650 text-sm font-bold">✕</button>
        </div>
        <div class="p-6 space-y-4">
            <textarea id="modal-message-body" readonly class="form-textarea w-full font-mono h-64 text-xs"></textarea>
            
            <div class="flex gap-2 justify-end pt-2 border-t border-slate-100">
                <button type="button" onclick="closePreviewModal()" class="btn btn-secondary btn-sm text-xs">
                    Close
                </button>
                <a id="modal-whatsapp-link" href="#" target="_blank" class="btn btn-sm bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg text-xs py-1.5 px-3 flex items-center gap-1.5">
                    💬 Send via WhatsApp
                </a>
            </div>
        </div>
    </div>
</div>

<script>
    function openPreviewModal(guestName, messageBody, whatsappUrl) {
        document.getElementById('modal-guest-name').textContent = "Wording for " + guestName;
        document.getElementById('modal-message-body').value = messageBody;
        
        const waBtn = document.getElementById('modal-whatsapp-link');
        if (whatsappUrl) {
            waBtn.href = whatsappUrl;
            waBtn.style.display = 'inline-flex';
        } else {
            waBtn.style.display = 'none';
        }
        
        document.getElementById('preview-modal').classList.remove('hidden');
    }

    function closePreviewModal() {
        document.getElementById('preview-modal').classList.add('hidden');
    }

    // Add Escape key listener to close modal (RC-015 Accessibility)
    window.addEventListener('keydown', function(event) {
        if (event.key === 'Escape') {
            closePreviewModal();
        }
    });

    // Add Backdrop click listener to close modal (RC-015 Backdrop Configurable)
    document.getElementById('preview-modal').addEventListener('click', function(event) {
        if (event.target === this) {
            closePreviewModal();
        }
    });

    function copyText(text) {
        navigator.clipboard.writeText(text).then(() => {
            alert('Personalized invitation message copied to clipboard!');
        }).catch(err => {
            console.error('Failed to copy text: ', err);
        });
    }

    function openWhatsAppLink(guestId) {
        // Automatically submit the mark-sent form for this guest when they trigger deep link
        setTimeout(() => {
            const form = document.getElementById('mark-sent-form-' + guestId);
            if (form) {
                form.submit();
            }
        }, 1000);
    }
</script>
