<div class="p-8 max-w-4xl mx-auto space-y-8">

    <!-- Header -->
    <div class="flex items-center justify-between">
        <div>
            <div class="flex items-center space-x-2">
                <span class="text-xs bg-purple-500/20 text-purple-300 border border-purple-500/30 px-2.5 py-1 rounded-full font-bold">Local Test Bench</span>
                <h1 class="text-2xl font-bold text-white tracking-tight">WhatsApp Webhook Simulator</h1>
            </div>
            <p class="text-slate-400 text-xs mt-1">Test two-way live messaging, auto-responders, lead creation, and delivery receipts without needing an active Meta Business account.</p>
        </div>
        <a href="/chat" class="bg-emerald-500 hover:bg-emerald-600 text-slate-950 text-xs font-bold px-4 py-2 rounded-xl transition flex items-center space-x-1.5 shadow-lg shadow-emerald-500/20">
            <i class="fa-brands fa-whatsapp text-sm"></i>
            <span>Back to Live Chat</span>
        </a>
    </div>

    <!-- Simulator Form Grid -->
    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">

        <!-- 1. Simulate Incoming WhatsApp Customer Message -->
        <div class="bg-slate-900 border border-slate-800 rounded-3xl p-6 shadow-xl space-y-5">
            <div class="flex items-center space-x-3 border-b border-slate-800 pb-3">
                <div class="w-9 h-9 rounded-xl bg-emerald-500/10 border border-emerald-500/20 flex items-center justify-center text-emerald-400">
                    <i class="fa-solid fa-mobile-screen"></i>
                </div>
                <div>
                    <h3 class="font-bold text-white text-sm">Simulate Customer WhatsApp</h3>
                    <p class="text-[10px] text-slate-400">Simulates user sending a message from WhatsApp app</p>
                </div>
            </div>

            <form id="simulator-message-form" onsubmit="Simulator.sendMessage(event)" class="space-y-4">
                <div>
                    <label class="block text-xs text-slate-400 mb-1">Customer Phone Number</label>
                    <input type="text" name="phone_number" id="sim-phone" value="+15550192834" required class="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-xs text-white focus:outline-none focus:border-emerald-500">
                </div>

                <div>
                    <label class="block text-xs text-slate-400 mb-1">Customer Profile Name</label>
                    <input type="text" name="name" id="sim-name" value="Alex Reynolds" required class="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-xs text-white focus:outline-none focus:border-emerald-500">
                </div>

                <div>
                    <label class="block text-xs text-slate-400 mb-1">Message Type</label>
                    <select name="message_type" id="sim-type" class="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-xs text-white focus:outline-none focus:border-emerald-500">
                        <option value="text">💬 Text Message</option>
                        <option value="image">🖼️ Image Attachment</option>
                    </select>
                </div>

                <div>
                    <label class="block text-xs text-slate-400 mb-1">Message Text / Trigger Keyword</label>
                    <textarea name="message" id="sim-message" rows="3" required class="w-full bg-slate-950 border border-slate-800 rounded-xl p-3 text-xs text-white focus:outline-none focus:border-emerald-500 resize-none">Hello! Can you send me the price details and demo schedule?</textarea>
                </div>

                <div class="space-y-1.5">
                    <span class="text-[10px] text-slate-500 block">⚡ Quick Sample Prompts:</span>
                    <div class="flex flex-wrap gap-1.5">
                        <button type="button" onclick="Simulator.fillPrompt('What is your pricing?', 'Alex Reynolds', '+15550192834')" class="text-[10px] bg-slate-950 hover:bg-slate-800 text-slate-300 px-2 py-1 rounded-lg border border-slate-800">
                            💰 "pricing" trigger
                        </button>
                        <button type="button" onclick="Simulator.fillPrompt('I want to book a demo call', 'David Kim', '+15550394856')" class="text-[10px] bg-slate-950 hover:bg-slate-800 text-slate-300 px-2 py-1 rounded-lg border border-slate-800">
                            📅 "demo" trigger
                        </button>
                        <button type="button" onclick="Simulator.fillPrompt('Hi, I am a new customer from Instagram!', 'Brand New Lead', '+15550998877')" class="text-[10px] bg-slate-950 hover:bg-slate-800 text-slate-300 px-2 py-1 rounded-lg border border-slate-800">
                            👋 "new lead" trigger
                        </button>
                    </div>
                </div>

                <button type="submit" class="w-full bg-emerald-500 hover:bg-emerald-600 text-slate-950 font-bold py-2.5 px-4 rounded-xl transition flex items-center justify-center space-x-2">
                    <i class="fa-solid fa-paper-plane text-xs"></i>
                    <span>Send Simulated WhatsApp Message</span>
                </button>
            </form>
        </div>

        <!-- 2. Simulate Delivery & Read Receipts -->
        <div class="bg-slate-900 border border-slate-800 rounded-3xl p-6 shadow-xl space-y-5 flex flex-col justify-between">
            <div class="space-y-4">
                <div class="flex items-center space-x-3 border-b border-slate-800 pb-3">
                    <div class="w-9 h-9 rounded-xl bg-blue-500/10 border border-blue-500/20 flex items-center justify-center text-blue-400">
                        <i class="fa-solid fa-check-double"></i>
                    </div>
                    <div>
                        <h3 class="font-bold text-white text-sm">Simulate Delivery / Read Status</h3>
                        <p class="text-[10px] text-slate-400">Test checkmark status transitions (sent $\rightarrow$ delivered $\rightarrow$ read)</p>
                    </div>
                </div>

                <form id="simulator-status-form" onsubmit="Simulator.sendStatusUpdate(event)" class="space-y-4">
                    <div>
                        <label class="block text-xs text-slate-400 mb-1">Meta Message ID</label>
                        <input type="text" name="meta_message_id" id="sim-meta-id" placeholder="wamid.MOCK_..." required class="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-xs font-mono text-white focus:outline-none focus:border-blue-500">
                    </div>

                    <div>
                        <label class="block text-xs text-slate-400 mb-1">New Status Event</label>
                        <select name="status" class="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-xs text-white focus:outline-none focus:border-blue-500">
                            <option value="delivered">Double Grey Tick (Delivered)</option>
                            <option value="read">Double Blue Tick (Read by Customer)</option>
                            <option value="failed">Exclamation Mark (Failed)</option>
                        </select>
                    </div>

                    <button type="submit" class="w-full bg-blue-500 hover:bg-blue-600 text-white font-bold py-2.5 px-4 rounded-xl transition">
                        Dispatch Status Webhook
                    </button>
                </form>
            </div>

            <!-- Simulation Log Output -->
            <div class="bg-slate-950 p-4 rounded-2xl border border-slate-800 space-y-2">
                <div class="text-[10px] font-bold text-slate-400 uppercase tracking-wider">Simulator Event Log</div>
                <div id="sim-log" class="text-xs font-mono text-emerald-400 max-h-32 overflow-y-auto custom-scrollbar">
                    Ready to simulate WhatsApp webhook events.
                </div>
            </div>
        </div>

    </div>

</div>

<script>
const Simulator = {
    fillPrompt(text, name, phone) {
        document.getElementById('sim-message').value = text;
        document.getElementById('sim-name').value = name;
        document.getElementById('sim-phone').value = phone;
    },

    async sendMessage(e) {
        e.preventDefault();
        const formData = new FormData(e.target);
        this.log('Sending message to Webhook engine...');

        try {
            const res = await fetch('/api/settings/simulator/incoming', {
                method: 'POST',
                body: formData,
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            });
            const data = await res.json();

            if (data.success) {
                this.log(`[SUCCESS] Webhook event received! Message ID: ${data.data.id}`);
                App.toast('Simulated WhatsApp message dispatched!', 'success');
            } else {
                this.log(`[ERROR] ${data.error}`);
                App.toast(data.error, 'error');
            }
        } catch (err) {
            this.log('[ERROR] Failed to contact server');
        }
    },

    async sendStatusUpdate(e) {
        e.preventDefault();
        const formData = new FormData(e.target);
        this.log('Dispatching status webhook update...');

        try {
            const res = await fetch('/api/settings/simulator/status', {
                method: 'POST',
                body: formData,
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            });
            const data = await res.json();

            if (data.success) {
                this.log('[SUCCESS] Status receipt webhook processed.');
                App.toast('Status receipt updated!', 'success');
            } else {
                this.log(`[ERROR] ${data.error}`);
            }
        } catch (err) {
            this.log('[ERROR] Failed to send status');
        }
    },

    log(msg) {
        const el = document.getElementById('sim-log');
        if (el) {
            el.innerHTML += `<div class="mt-1">&gt; ${msg}</div>`;
            el.scrollTop = el.scrollHeight;
        }
    }
};
</script>
