'use client';

import React, { useState, useEffect } from 'react';
import { apiRequest } from '@/lib/api';
import { useAuth } from '@/context/auth-context';
import { 
  Copy, 
  Check, 
  Send, 
  Settings, 
  Eye, 
  Code, 
  CheckCircle2, 
  ChevronRight, 
  ChevronLeft,
  Smartphone,
  PhoneCall,
  Search,
  MoreVertical,
  ArrowLeft,
  Paperclip,
  Smile,
  Mic,
  MessageSquare,
  Clock,
  Layers,
  RotateCcw,
  Megaphone,
  User,
  Users,
  Zap
} from 'lucide-react';

interface TemplateConfig {
  id: string;
  name: string;
  category: string;
  businessName: string;
  isVerified: boolean;
  avatarLetter: string;
  avatarBg: string;
  bodyText: string;
  footerText?: string;
  buttons?: string[];
  listButtonLabel?: string;
  listSections?: {
    title: string;
    rows: { id: string; title: string; desc: string }[];
  }[];
  carouselItems?: {
    id: string;
    name: string;
    description: string;
    price: number;
    imageUrl: string;
    button1: string;
    button2: string;
  }[];
}

const DEFAULT_TEMPLATES: Record<string, TemplateConfig> = {
  support: {
    id: 'support',
    name: 'Customer Support',
    category: 'Support & Utility',
    businessName: 'Quatrohaus',
    isVerified: true,
    avatarLetter: 'Q',
    avatarBg: 'bg-purple-600',
    bodyText: 'How would you like to contact Quatrohaus Support?',
    buttons: ['Call Quatrohaus', 'Message Quatrohaus', 'Exit Support'],
  },
  lead: {
    id: 'lead',
    name: 'Lead Generation',
    category: 'Marketing',
    businessName: 'Silver Oak Bank',
    isVerified: true,
    avatarLetter: 'S',
    avatarBg: 'bg-emerald-700',
    bodyText: 'Hello, DFC Bank Welcomes You to WhatsApp Banking.\n\nHow can we assist you?',
    footerText: 'Secured by DFC Banking Group',
    listButtonLabel: 'Select options',
    listSections: [
      {
        title: 'Banking Services',
        rows: [
          { id: 'bank_acc', title: 'Bank Account', desc: 'Check balance & recent transactions' },
          { id: 'credit_card', title: 'Credit Card', desc: 'View statements & pay bills' },
          { id: 'loans', title: 'Loan Services', desc: 'Apply or check application status' },
        ]
      },
      {
        title: 'Other',
        rows: [
          { id: 'agent_support', title: 'Customer Support', desc: 'Connect with a live agent' }
        ]
      }
    ]
  },
  sale: {
    id: 'sale',
    name: 'Sale / Catalog Showcase',
    category: 'Sales & Marketing',
    businessName: 'Leaf & Grain',
    isVerified: true,
    avatarLetter: 'L',
    avatarBg: 'bg-amber-800',
    bodyText: 'Hi Afreen,\nStronger than most hardwoods, yet lightweight. Made of Eco-friendly 100% Natural Bamboo.',
    carouselItems: [
      {
        id: 'c1',
        name: 'Cutlery Set',
        description: 'Reusable premium bamboo utensils',
        price: 18.50,
        imageUrl: 'https://images.unsplash.com/photo-1584269600464-37b1b58a9fe7?q=80&w=400',
        button1: 'Buy Now',
        button2: 'View details'
      },
      {
        id: 'c2',
        name: 'Bamboo Steamer',
        description: 'Authentic cooking bamboo steamer',
        price: 24.99,
        imageUrl: 'https://images.unsplash.com/photo-1591821099447-06225f17a944?q=80&w=400',
        button1: 'Buy Now',
        button2: 'View details'
      },
      {
        id: 'c3',
        name: 'Bamboo Plates',
        description: 'Set of 4 biodegradable plates',
        price: 15.00,
        imageUrl: 'https://images.unsplash.com/photo-1610701596007-11502861dcfa?q=80&w=400',
        button1: 'Buy Now',
        button2: 'View details'
      }
    ]
  },
  feedback: {
    id: 'feedback',
    name: 'Customer Feedback',
    category: 'Utility & Retention',
    businessName: 'Peak Auto Care',
    isVerified: true,
    avatarLetter: 'P',
    avatarBg: 'bg-red-700',
    bodyText: 'Thank you for helping us, your feedback will help us improve our performance. How would you like to rate our services?',
    buttons: ['Review', 'Rating', 'Both'],
  },
  ecocash: {
    id: 'ecocash',
    name: 'EcoCash Payment Prompt',
    category: 'Payments & Checkout',
    businessName: 'EcoStore',
    isVerified: true,
    avatarLetter: 'E',
    avatarBg: 'bg-emerald-600',
    bodyText: 'To pay via EcoCash, please enter your EcoCash mobile number below:',
    footerText: 'Secure EcoCash Push Payment via PesePay',
    buttons: []
  },
  quantity: {
    id: 'quantity',
    name: 'Select Quantity Prompt',
    category: 'Interactive Utility',
    businessName: 'Organic Store',
    isVerified: true,
    avatarLetter: 'O',
    avatarBg: 'bg-emerald-600',
    bodyText: 'Select Quantity\n\n*Organic Coffee Beans*\n$18.50 per unit\n\nConfirm how many units you would like to add to your chat basket.',
    footerText: 'Secure checkout powered by RetailBot',
    buttons: ['Select Quantity', 'Back to Menu']
  }
};

export default function TemplatesPage() {
  const { user } = useAuth();
  const [activeTab, setActiveTab] = useState<'support' | 'lead' | 'sale' | 'feedback' | 'ecocash' | 'quantity'>('support');
  const [panelTab, setPanelTab] = useState<'editor' | 'json' | 'test'>('editor');
  const [showQtySheet, setShowQtySheet] = useState(false);
  const [previewQty, setPreviewQty] = useState(1);
  
  // Custom configurations for the templates
  const [configs, setConfigs] = useState<Record<string, TemplateConfig>>(DEFAULT_TEMPLATES);
  const [copied, setCopied] = useState(false);
  const [testPhone, setTestPhone] = useState('+263779998887');
  const [sendingTest, setSendingTest] = useState(false);

  // Marketing Broadcast mode and states
  const [broadcastMessage, setBroadcastMessage] = useState('');
  const [broadcasting, setBroadcasting] = useState(false);
  const [recipientMode, setRecipientMode] = useState<'all' | 'single'>('all');
  const [customers, setCustomers] = useState<any[]>([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCustomer, setSelectedCustomer] = useState<any | null>(null);

  useEffect(() => {
    const fetchCustomers = async () => {
      if (!user || user.subscriptionStatus === 'UNSUBSCRIBED' || user.subscriptionStatus === 'EXPIRED') {
        return;
      }
      try {
        const data = await apiRequest('api/customers', 'GET');
        if (Array.isArray(data)) {
          setCustomers(data);
        }
      } catch (err) {
        console.error('Failed to fetch customers for broadcast:', err);
      }
    };
    fetchCustomers();
  }, [user?.id, user?.subscriptionStatus]);

  const filteredCustomers = searchQuery.trim() === ''
    ? []
    : customers.filter(cust => {
        const name = (cust.name || '').toLowerCase();
        const phone = (cust.whatsappNumber || '').toLowerCase();
        const query = searchQuery.toLowerCase();
        return name.includes(query) || phone.includes(query);
      });

  useEffect(() => {
    if (user?.phone) {
      setTestPhone(user.phone);
    }
  }, [user]);

  // Phone simulation state
  const [simulatedMessages, setSimulatedMessages] = useState<any[]>([]);
  const [showListSheet, setShowListSheet] = useState(false);
  const [carouselIndex, setCarouselIndex] = useState(0);
  const [previewEcoCashPhone, setPreviewEcoCashPhone] = useState('');

  // Load current template configuration
  const currentConfig = configs[activeTab];

  // Reset chat simulation whenever template changes
  useEffect(() => {
    resetChatSimulation();
    setShowListSheet(false);
    setShowQtySheet(false);
    setPreviewQty(1);
    setCarouselIndex(0);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activeTab]);

  const resetChatSimulation = () => {
    // Generate initial prompt bubble from bot
    let initialMessage = {
      id: 'init',
      direction: 'outbound',
      body: currentConfig.bodyText,
      footer: currentConfig.footerText,
      buttons: currentConfig.buttons,
      listButtonLabel: currentConfig.listButtonLabel,
      carouselItems: currentConfig.carouselItems,
    };
    setSimulatedMessages([initialMessage]);
  };

  const handleEditorChange = (field: keyof TemplateConfig, value: any) => {
    setConfigs(prev => ({
      ...prev,
      [activeTab]: {
        ...prev[activeTab],
        [field]: value
      }
    }));

    // Update the live simulation initial message dynamically
    setSimulatedMessages(prev => {
      if (prev.length > 0 && prev[0].id === 'init') {
        const updated = [...prev];
        updated[0] = {
          ...updated[0],
          body: field === 'bodyText' ? value : currentConfig.bodyText,
          footer: field === 'footerText' ? value : currentConfig.footerText,
          buttons: field === 'buttons' ? value : currentConfig.buttons,
          listButtonLabel: field === 'listButtonLabel' ? value : currentConfig.listButtonLabel,
          carouselItems: field === 'carouselItems' ? value : currentConfig.carouselItems,
        };
        return updated;
      }
      return prev;
    });
  };

  const handleButtonValueChange = (index: number, val: string) => {
    const updatedButtons = [...(currentConfig.buttons || [])];
    updatedButtons[index] = val;
    handleEditorChange('buttons', updatedButtons);
  };

  const handleListRowChange = (sectionIdx: number, rowIdx: number, field: 'title' | 'desc', val: string) => {
    const sections = JSON.parse(JSON.stringify(currentConfig.listSections || []));
    sections[sectionIdx].rows[rowIdx][field] = val;
    handleEditorChange('listSections', sections);
  };

  const handleCarouselItemChange = (itemIdx: number, field: string, val: any) => {
    const items = JSON.parse(JSON.stringify(currentConfig.carouselItems || []));
    items[itemIdx][field] = val;
    handleEditorChange('carouselItems', items);
  };

  // Click handler for buttons inside mockup phone
  const handlePhoneButtonClick = (btnLabel: string) => {
    // 1. Add user reply bubble
    const userMsg = {
      id: `user-${Date.now()}`,
      direction: 'inbound',
      body: btnLabel
    };

    // 2. Add automated bot response after a short delay
    let botReplyText = 'Thanks! Your selection has been received.';
    let responseButtons: string[] | undefined = undefined;

    if (activeTab === 'support') {
      if (btnLabel.toLowerCase().includes('call')) {
        botReplyText = `*Call Quatrohaus Support*\n\nYou can call our support team directly at:\n\n+2637776015100`;
        responseButtons = ['Message Quatrohaus', 'Exit Support'];
      } else if (btnLabel.toLowerCase().includes('message')) {
        botReplyText = `*Message Quatrohaus Support*\n\nYou can chat with us on WhatsApp here:\n\nhttps://wa.me/2637776015100`;
        responseButtons = ['Call Quatrohaus', 'Exit Support'];
      } else if (btnLabel.toLowerCase().includes('exit') || btnLabel === 'Talk to Support') {
        botReplyText = `*Customer Support*\n\nHow would you like to contact Quatrohaus Support?\n\n1. Call Quatrohaus\n2. Message Quatrohaus\n3. Exit Support`;
        responseButtons = ['Call Quatrohaus', 'Message Quatrohaus', 'Exit Support'];
      } else if (btnLabel === 'Shop Now') {
        botReplyText = `*Select a category to browse:*\n\n1. Electronics\n2. Groceries\n3. Clothing`;
        responseButtons = ['Electronics', 'Groceries', 'Clothing', 'Back to Menu'];
      } else if (btnLabel === 'Search Products') {
        botReplyText = `*Search Products*\n\nType the product name or details you are looking for:`;
        responseButtons = ['Back to Menu'];
      } else if (btnLabel === 'View Cart') {
        botReplyText = `*Your Shopping Cart:*\n\nYour cart is empty!\n\nType *1* to browse products, or *menu* to return.`;
        responseButtons = ['Browse Products', 'Back to Menu'];
      } else {
        botReplyText = `Confirmed! We'll see you then at your selected slot: ${btnLabel}.`;
      }
    } else if (activeTab === 'feedback') {
      botReplyText = `Thank you! Your feedback ("${btnLabel}") helps us deliver superior care. We have recorded your rating.`;
    } else if (activeTab === 'sale') {
      botReplyText = `Awesome selection! Added ${btnLabel.replace('Buy ', '')} to your shopping cart. Reply *3* to view cart or checkout!`;
    } else if (activeTab === 'ecocash') {
      botReplyText = `*EcoCash Payment Initiated!*\n\n` +
        `A push payment request of *USD $150.00* has been sent to *${btnLabel}*.\n` +
        `Ref: *PESEPAY-SIM-REF-1092*\n\n` +
        `Please check your EcoCash menu and enter your PIN to approve.\n\n` +
        `_You will receive a WhatsApp confirmation once payment is processed._`;
    } else if (activeTab === 'quantity') {
      if (btnLabel === 'Select Quantity') {
        setShowQtySheet(true);
        return;
      }
      botReplyText = `Confirmed! Added *${btnLabel}* to your shopping cart. Reply *3* to view cart or checkout!`;
    }

    const botMsg = {
      id: `bot-${Date.now()}`,
      direction: 'outbound',
      body: botReplyText,
      buttons: responseButtons
    };

    setSimulatedMessages(prev => [...prev, userMsg, botMsg]);
  };

  const handleSelectOptionsClick = () => {
    setShowListSheet(true);
  };

  const handleListRowSelect = (rowTitle: string) => {
    setShowListSheet(false);
    // Add user message
    const userMsg = {
      id: `user-${Date.now()}`,
      direction: 'inbound',
      body: rowTitle
    };
    
    // Add bot response
    const botMsg = {
      id: `bot-${Date.now()}`,
      direction: 'outbound',
      body: `Hello! You selected *${rowTitle}* from our list. How can we help you with this? Please type your query.`
    };
    setSimulatedMessages(prev => [...prev, userMsg, botMsg]);
  };

  // Generate WhatsApp Cloud API JSON Payload
  const generateJsonPayload = (): string => {
    const recipient = '{{customer_phone}}';
    
    if (activeTab === 'ecocash') {
      return JSON.stringify({
        messaging_product: 'whatsapp',
        recipient_type: 'individual',
        to: recipient,
        type: 'interactive',
        interactive: {
          type: 'flow',
          header: {
            type: 'text',
            text: currentConfig.businessName
          },
          body: {
            text: currentConfig.bodyText
          },
          footer: currentConfig.footerText ? {
            text: currentConfig.footerText
          } : undefined,
          action: {
            name: 'flow',
            parameters: {
              flow_token: 'ecocash_payment_flow_token',
              flow_id: '1092779560579318',
              flow_cta: 'Enter EcoCash Number',
              flow_action: 'navigate',
              flow_action_payload: {
                screen: 'PHONE_INPUT'
              }
            }
          }
        }
      }, null, 2);
    }
    
    if (activeTab === 'quantity') {
      return JSON.stringify({
        messaging_product: 'whatsapp',
        recipient_type: 'individual',
        to: recipient,
        type: 'interactive',
        interactive: {
          type: 'flow',
          header: {
            type: 'text',
            text: currentConfig.businessName
          },
          body: {
            text: currentConfig.bodyText
          },
          footer: currentConfig.footerText ? {
            text: currentConfig.footerText
          } : undefined,
          action: {
            name: 'flow',
            parameters: {
              flow_token: 'quantity_selection_flow_token',
              flow_id: '1092779560579420',
              flow_cta: 'Select Quantity',
              flow_action: 'navigate',
              flow_action_payload: {
                screen: 'QTY_SELECTOR'
              }
            }
          }
        }
      }, null, 2);
    }

    if (activeTab === 'support' || activeTab === 'feedback') {
      return JSON.stringify({
        messaging_product: 'whatsapp',
        recipient_type: 'individual',
        to: recipient,
        type: 'interactive',
        interactive: {
          type: 'button',
          header: {
            type: 'text',
            text: currentConfig.businessName
          },
          body: {
            text: currentConfig.bodyText
          },
          action: {
            buttons: (currentConfig.buttons || []).map((btn, idx) => ({
              type: 'reply',
              reply: {
                id: `btn_${idx + 1}`,
                title: btn
              }
            }))
          }
        }
      }, null, 2);
    }

    if (activeTab === 'lead') {
      return JSON.stringify({
        messaging_product: 'whatsapp',
        recipient_type: 'individual',
        to: recipient,
        type: 'interactive',
        interactive: {
          type: 'list',
          header: {
            type: 'text',
            text: currentConfig.businessName
          },
          body: {
            text: currentConfig.bodyText
          },
          footer: currentConfig.footerText ? {
            text: currentConfig.footerText
          } : undefined,
          action: {
            button: currentConfig.listButtonLabel || 'Select options',
            sections: (currentConfig.listSections || []).map((sec, sIdx) => ({
              title: sec.title,
              rows: sec.rows.map((row, rIdx) => ({
                id: row.id,
                title: row.title,
                description: row.desc
              }))
            }))
          }
        }
      }, null, 2);
    }

    // Carousel Multi-Product Template
    return JSON.stringify({
      messaging_product: 'whatsapp',
      recipient_type: 'individual',
      to: recipient,
      type: 'interactive',
      interactive: {
        type: 'carousel',
        header: {
          type: 'text',
          text: `${currentConfig.businessName} Catalog`
        },
        body: {
          text: currentConfig.bodyText
        },
        action: {
          cards: (currentConfig.carouselItems || []).map((item, idx) => ({
            header: {
              type: 'image',
              image: {
                link: item.imageUrl
              }
            },
            body: {
              text: `*${item.name}* - $${item.price.toFixed(2)}\n\n${item.description}`
            },
            action: {
              buttons: [
                {
                  type: 'reply',
                  reply: {
                    id: `buy_${item.id}`,
                    title: item.button1
                  }
                },
                {
                  type: 'reply',
                  reply: {
                    id: `view_${item.id}`,
                    title: item.button2
                  }
                }
              ]
            }
          }))
        }
      }
    }, null, 2);
  };

  const handleCopyPayload = () => {
    navigator.clipboard.writeText(generateJsonPayload());
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  const handleSendSimulatedTemplate = async () => {
    if (!testPhone.trim() || !user || sendingTest) return;

    setSendingTest(true);
    try {
      await apiRequest('api/whatsapp/templates/simulate', 'POST', {
        whatsappNumber: testPhone,
        templateType: currentConfig.name,
        bodyText: currentConfig.bodyText,
        payload: JSON.parse(generateJsonPayload())
      });
      alert(`Template simulated successfully! Go to the 'WhatsApp Bot Simulator' page to check the logged message for ${testPhone}.`);
    } catch (err: any) {
      alert(`Simulation error: ${err.message}`);
    } finally {
      setSendingTest(false);
    }
  };

  const handleSendBroadcast = async () => {
    if (!broadcastMessage.trim() || broadcasting) return;
    if (recipientMode === 'single' && !selectedCustomer) {
      alert("Please select a customer first.");
      return;
    }

    const confirmText = recipientMode === 'all'
      ? "Are you sure you want to send this broadcast message to ALL of your customers?"
      : `Are you sure you want to send this notification to ${selectedCustomer.name || 'this customer'}?`;

    const confirmSend = window.confirm(confirmText);
    if (!confirmSend) return;

    setBroadcasting(true);
    try {
      const payload: any = { message: broadcastMessage };
      if (recipientMode === 'single' && selectedCustomer) {
        payload.recipientPhone = selectedCustomer.whatsappNumber;
      }

      const res = await apiRequest('api/whatsapp/broadcast', 'POST', payload);
      alert(res.message || 'Notification sent successfully!');
      setBroadcastMessage('');
      setSelectedCustomer(null);
      setSearchQuery('');
    } catch (err: any) {
      alert(`Failed to send notification: ${err.message}`);
    } finally {
      setBroadcasting(false);
    }
  };

  return (
    <div className="space-y-8 font-sans pb-16">
      {/* Header section */}
      <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
        <div>
          <h1 className="text-3xl font-extrabold tracking-tight text-white Outfit flex items-center gap-2.5">
            <Layers className="h-7 w-7 text-emerald-400" />
            WhatsApp Message Templates
          </h1>
          <p className="text-sm text-gray-400 mt-1">
            Build, test, and retrieve API structures for interactive marketing and support messages
          </p>
        </div>
      </div>

      {/* Marketing Broadcast Section */}
      <div className="bg-white rounded-2xl p-6 border border-gray-200 shadow-md">
        <div className="flex items-center gap-2.5 border-b border-gray-100 pb-4">
          <div className="bg-emerald-100 p-2 rounded-xl text-emerald-600">
            <Megaphone className="h-6 w-6" />
          </div>
          <div>
            <h2 className="text-xl font-bold text-gray-900 Outfit">
              Customer Broadcast & Notifications
            </h2>
            <p className="text-xs text-gray-500 mt-0.5">
              Send marketing announcements or single notifications to your WhatsApp chatbot customers.
            </p>
          </div>
        </div>

        <div className="mt-6 space-y-6">
          {/* Recipient Mode Selection */}
          <div>
            <label className="text-xs font-bold text-gray-700 uppercase tracking-wider block mb-2 font-sans">
              Recipient Target
            </label>
            <div className="flex gap-4">
              <button
                onClick={() => {
                  setRecipientMode('all');
                  setSelectedCustomer(null);
                  setSearchQuery('');
                }}
                className={`flex-1 py-3 px-4 rounded-xl border-2 transition-all flex items-center justify-center gap-2 font-bold text-sm cursor-pointer select-none ${
                  recipientMode === 'all'
                    ? 'border-emerald-500 bg-emerald-50 text-emerald-700 shadow-sm'
                    : 'border-gray-200 bg-white text-gray-600 hover:border-gray-300 hover:bg-gray-50'
                }`}
              >
                <Users className="h-4 w-4" />
                <span>All Customers</span>
              </button>
              <button
                onClick={() => setRecipientMode('single')}
                className={`flex-1 py-3 px-4 rounded-xl border-2 transition-all flex items-center justify-center gap-2 font-bold text-sm cursor-pointer select-none ${
                  recipientMode === 'single'
                    ? 'border-emerald-500 bg-emerald-50 text-emerald-700 shadow-sm'
                    : 'border-gray-200 bg-white text-gray-600 hover:border-gray-300 hover:bg-gray-50'
                }`}
              >
                <User className="h-4 w-4" />
                <span>Single Customer</span>
              </button>
            </div>
          </div>

          {/* Single Customer Search Panel */}
          {recipientMode === 'single' && (
            <div className="space-y-3 bg-gray-50 p-4 rounded-xl border border-gray-100">
              <label className="text-xs font-bold text-gray-700 uppercase tracking-wider block">
                Select Customer
              </label>

              {selectedCustomer ? (
                <div className="flex items-center justify-between bg-white border border-emerald-100 rounded-xl p-3.5 shadow-sm">
                  <div className="flex items-center gap-3">
                    <div className="h-9 w-9 rounded-full bg-emerald-100 flex items-center justify-center text-emerald-700 font-bold">
                      {selectedCustomer.name ? selectedCustomer.name[0].toUpperCase() : 'C'}
                    </div>
                    <div>
                      <p className="font-extrabold text-sm text-gray-900">{selectedCustomer.name || 'WhatsApp Customer'}</p>
                      <p className="text-xs text-gray-500 font-mono">+{selectedCustomer.whatsappNumber}</p>
                    </div>
                  </div>
                  <button
                    onClick={() => setSelectedCustomer(null)}
                    className="text-xs font-bold text-red-600 hover:text-red-700 hover:underline cursor-pointer"
                  >
                    Change
                  </button>
                </div>
              ) : (
                <div className="relative">
                  <div className="relative">
                    <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
                    <input
                      type="text"
                      placeholder="Search by customer name or phone..."
                      value={searchQuery}
                      onChange={(e) => setSearchQuery(e.target.value)}
                      className="w-full bg-white border border-gray-300 rounded-xl pl-10 pr-4 py-2.5 text-sm text-gray-900 placeholder-gray-400 focus:border-emerald-500 focus:outline-none focus:ring-1 focus:ring-emerald-500 transition-all font-sans"
                    />
                  </div>

                  {searchQuery.trim() !== '' && (
                    <div className="absolute w-full mt-1 bg-white border border-gray-200 rounded-xl shadow-lg z-50 max-h-48 overflow-y-auto divide-y divide-gray-50">
                      {filteredCustomers.length > 0 ? (
                        filteredCustomers.map((cust) => (
                          <button
                            key={cust.id}
                            onClick={() => {
                              setSelectedCustomer(cust);
                              setSearchQuery('');
                            }}
                            className="w-full text-left p-3 hover:bg-emerald-50/50 flex items-center justify-between transition-colors cursor-pointer"
                          >
                            <div>
                              <p className="font-bold text-sm text-gray-950">{cust.name || 'WhatsApp Customer'}</p>
                              <p className="text-xs text-gray-500 font-mono">+{cust.whatsappNumber}</p>
                            </div>
                            <ChevronRight className="h-4 w-4 text-gray-400" />
                          </button>
                        ))
                      ) : (
                        <div className="p-3 text-xs text-gray-500 text-center">No customers match your search</div>
                      )}
                    </div>
                  )}
                </div>
              )}
            </div>
          )}

          {/* Message Textbox */}
          <div>
            <label className="text-xs font-bold text-gray-700 uppercase tracking-wider block mb-2 font-sans">
              Message Content
            </label>
            <textarea
              rows={3}
              value={broadcastMessage}
              onChange={(e) => setBroadcastMessage(e.target.value)}
              placeholder="Type your notice or marketing message here... (e.g. 'Flash Sale! Get 20% off all paintings today on our WhatsApp Shop. Reply with 'shop' to browse our catalog!')"
              className="w-full bg-gray-50 border border-gray-300 rounded-xl p-3.5 text-sm text-gray-900 placeholder-gray-400 focus:border-emerald-500 focus:bg-white focus:outline-none focus:ring-1 focus:ring-emerald-500 transition-all font-sans"
            />
          </div>

          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 border-t border-gray-100 pt-4">
            <div className="text-xs text-gray-500">
              <span>
                {recipientMode === 'all'
                  ? `This will send messages to all active customer profiles.`
                  : selectedCustomer
                  ? `Message will be sent only to +${selectedCustomer.whatsappNumber}.`
                  : `Please select a recipient customer.`}
              </span>
            </div>

            <button
              onClick={handleSendBroadcast}
              disabled={broadcasting || !broadcastMessage.trim() || (recipientMode === 'single' && !selectedCustomer)}
              className={`flex items-center gap-2 px-6 py-2.5 rounded-xl font-bold text-sm transition-all select-none cursor-pointer ${
                broadcasting || !broadcastMessage.trim() || (recipientMode === 'single' && !selectedCustomer)
                  ? 'bg-gray-100 text-gray-400 border border-gray-200 cursor-not-allowed'
                  : 'bg-emerald-500 hover:bg-emerald-600 text-black shadow-lg shadow-emerald-500/10 active:scale-95'
              }`}
            >
              {broadcasting ? (
                <>
                  <div className="h-4 w-4 animate-spin rounded-full border-2 border-black border-t-transparent"></div>
                  <span>Sending...</span>
                </>
              ) : (
                <>
                  <Send className="h-4 w-4" />
                  <span>Send Notification</span>
                </>
              )}
            </button>
          </div>
        </div>
      </div>

      {/* Grid of Templates Quick Selectors */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6 gap-4">
        {(['support', 'lead', 'sale', 'feedback', 'ecocash', 'quantity'] as const).map((key) => {
          const templ = DEFAULT_TEMPLATES[key];
          const isSelected = activeTab === key;
          return (
            <button
              key={key}
              onClick={() => setActiveTab(key)}
              className={`text-left p-5 rounded-2xl border transition-all cursor-pointer relative overflow-hidden flex flex-col justify-between h-32 ${
                isSelected
                  ? 'bg-emerald-500/10 border-emerald-500 shadow-lg shadow-emerald-500/5'
                  : 'bg-white dark:bg-[#0e0f14]/80 border-slate-200 dark:border-white/5 hover:border-slate-300 dark:hover:border-white/10 hover:bg-slate-50 dark:hover:bg-white/2 shadow-sm'
              }`}
            >
              <div>
                <span className="text-[10px] uppercase font-bold tracking-widest text-[#6B7280]" style={{ color: '#6B7280' }}>
                  {templ.category}
                </span>
                <h3 className="font-extrabold text-base font-sans mt-1 text-[#6B7280]" style={{ color: '#6B7280' }}>
                  {templ.name}
                </h3>
              </div>
              <div className="flex items-center justify-between mt-3 text-xs w-full">
                <span className="font-mono text-[10px] text-[#6B7280]" style={{ color: '#6B7280' }}>
                  @{templ.businessName.toLowerCase().replace(/\s/g, '')}
                </span>
                {isSelected && (
                  <span className="h-1.5 w-1.5 rounded-full bg-[#6B7280]" style={{ backgroundColor: '#6B7280' }}></span>
                )}
              </div>
            </button>
          );
        })}
      </div>

      {/* Main Split Panel Workspace */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start">
        {/* Left Column: Mobile phone live mockup */}
        <div className="lg:col-span-5 flex flex-col items-center">
          <div className="text-center mb-3">
            <span className="text-xs text-gray-500 font-mono">Live Interactive Mockup (Light Theme)</span>
          </div>
          
          {/* Mobile Phone outer container */}
          <div className="h-[600px] w-[320px] rounded-[38px] border-8 border-gray-800 bg-[#efeae2] shadow-2xl relative flex flex-col overflow-hidden select-none">
            {/* Phone notch/camera */}
            <div className="absolute top-2 left-1/2 -translate-x-1/2 w-28 h-4 bg-gray-800 rounded-full z-30 flex items-center justify-center">
              <div className="w-2 h-2 rounded-full bg-black/40 ml-4"></div>
            </div>

            {/* Simulated WhatsApp App Header */}
            <div className="bg-[#008069] pt-8 pb-3.5 px-4 flex items-center justify-between shadow-md text-white shrink-0 z-20">
              <div className="flex items-center gap-1.5">
                <ArrowLeft className="h-4.5 w-4.5 cursor-pointer" />
                
                {/* Brand Avatar */}
                <div className={`h-8 w-8 rounded-full ${currentConfig.avatarBg} flex items-center justify-center font-bold text-white text-sm shadow-inner`}>
                  {currentConfig.avatarLetter}
                </div>
                
                <div className="leading-tight">
                  <div className="flex items-center gap-1">
                    <span className="font-bold text-xs max-w-[120px] truncate !text-white" style={{ color: '#ffffff' }}>{currentConfig.businessName}</span>
                    {currentConfig.isVerified && (
                      <CheckCircle2 className="h-3 w-3 fill-emerald-500 text-white shrink-0" />
                    )}
                  </div>
                  <span className="text-[9px] text-emerald-100 block opacity-90">online</span>
                </div>
              </div>
              
              <div className="flex items-center gap-3">
                <PhoneCall className="h-3.5 w-3.5 opacity-90 cursor-pointer" />
                <MoreVertical className="h-4.5 w-4.5 opacity-90 cursor-pointer" />
              </div>
            </div>

            {/* Chat Body (scrollable) */}
            <div className="flex-1 overflow-y-auto p-3.5 space-y-3 flex flex-col justify-start relative bg-[#efeae2]">
              {/* Subtle WhatsApp doodle background */}
              <div className="absolute inset-0 bg-repeat bg-center opacity-60 pointer-events-none" style={{ backgroundImage: `url('/whatsapp-bg.jpg')`, backgroundSize: '280px' }}></div>

              <div className="text-center my-1.5 z-10">
                <span className="bg-white/80 backdrop-blur-sm px-2 py-0.5 rounded shadow-sm text-[8px] text-gray-500 font-mono uppercase tracking-wider">Today</span>
              </div>

              {simulatedMessages.map((msg) => {
                const isBot = msg.direction === 'outbound';
                return (
                  <div key={msg.id} className={`flex ${isBot ? 'justify-start' : 'justify-end'} z-10`}>
                    <div className={`max-w-[90%] rounded-lg px-2.5 py-1.5 shadow-sm text-xs leading-relaxed relative ${
                      isBot ? 'bg-white text-black rounded-tl-none' : 'bg-[#e2f9d3] text-black rounded-tr-none'
                    }`}>
                      {/* Message Body */}
                      <p className="whitespace-pre-wrap select-text pr-4">{msg.body}</p>

                      {/* Footer text if available */}
                      {msg.footer && (
                        <p className="text-[9px] text-gray-400 mt-1 uppercase tracking-wider font-semibold border-t border-gray-100 pt-1">
                          {msg.footer}
                        </p>
                      )}

                      {/* Bot EcoCash Phone Input Textbox Simulator */}
                      {isBot && activeTab === 'ecocash' && msg.id === 'init' && (
                        <div className="mt-3 border-t border-gray-100 pt-3 space-y-2 shrink-0">
                          <div className="flex gap-2">
                            <input
                              type="text"
                              placeholder="e.g. 0771234567"
                              value={previewEcoCashPhone}
                              onChange={(e) => setPreviewEcoCashPhone(e.target.value)}
                              className="flex-1 bg-gray-50 border border-gray-200 rounded px-2.5 py-1 text-xs text-gray-700 outline-none focus:border-emerald-500 font-mono"
                            />
                            <button
                              onClick={() => {
                                if (!previewEcoCashPhone.trim()) return;
                                handlePhoneButtonClick(previewEcoCashPhone);
                                setPreviewEcoCashPhone('');
                              }}
                              className="bg-[#008069] hover:bg-[#006e5a] text-white text-[10px] font-bold px-3 py-1.5 rounded transition-colors cursor-pointer"
                            >
                              Submit
                            </button>
                          </div>
                        </div>
                      )}

                      {/* Bot Interactive Quick Reply Buttons */}
                      {isBot && msg.buttons && msg.buttons.length > 0 && (
                        <div className="mt-2.5 border-t border-gray-100 pt-1 space-y-1.5 shrink-0">
                          {msg.buttons.map((btn: string, bIdx: number) => (
                            <button
                              key={bIdx}
                              onClick={() => handlePhoneButtonClick(btn)}
                              className="w-full bg-white hover:bg-gray-50 active:bg-gray-100 text-[#008069] text-xs font-semibold py-2 px-3 rounded-md border border-gray-100 shadow-sm transition-all text-center flex items-center justify-center cursor-pointer"
                            >
                              {btn}
                            </button>
                          ))}
                        </div>
                      )}

                      {/* Bot List Message Select Button */}
                      {isBot && msg.listButtonLabel && (
                        <div className="mt-2.5 border-t border-gray-100 pt-1 shrink-0">
                          <button
                            onClick={handleSelectOptionsClick}
                            className="w-full bg-white hover:bg-gray-50 active:bg-gray-100 text-[#008069] text-xs font-bold py-2 px-3 rounded-md border border-gray-100 shadow-sm transition-all text-center flex items-center justify-center gap-1.5 cursor-pointer"
                          >
                            <span className="text-gray-400">☰</span>
                            {msg.listButtonLabel}
                          </button>
                        </div>
                      )}

                      {/* Bot Carousel Layout */}
                      {isBot && msg.carouselItems && (
                        <div className="mt-3 overflow-hidden relative max-w-[260px] shrink-0">
                          <div 
                            className="flex transition-transform duration-300 ease-out"
                            style={{ transform: `translateX(-${carouselIndex * 100}%)` }}
                          >
                            {msg.carouselItems.map((item: any, itemIdx: number) => (
                              <div 
                                key={item.id} 
                                className="w-full shrink-0 p-1 select-none"
                              >
                                <div className="bg-white rounded-lg border border-gray-200 shadow-sm overflow-hidden flex flex-col">
                                  {/* Item Image */}
                                  <div className="h-24 w-full bg-gray-100 relative">
                                    {/* eslint-disable-next-line @next/next/no-img-element */}
                                    <img 
                                      src={item.imageUrl} 
                                      alt={item.name}
                                      className="h-full w-full object-cover" 
                                    />
                                    <span className="absolute bottom-2 right-2 bg-black/60 text-white text-[9px] font-bold px-1.5 py-0.5 rounded font-mono">
                                      ${item.price.toFixed(2)}
                                    </span>
                                  </div>
                                  
                                  {/* Item Info */}
                                  <div className="p-2 space-y-1">
                                    <h4 className="font-bold text-xs text-gray-800">{item.name}</h4>
                                    <p className="text-[10px] text-gray-500 line-clamp-2 leading-relaxed">
                                      {item.description}
                                    </p>
                                  </div>

                                  {/* Item Action Buttons */}
                                  <div className="border-t border-gray-100 bg-gray-50/50 p-1.5 space-y-1 flex flex-col">
                                    <button
                                      onClick={() => handlePhoneButtonClick(`Buy ${item.name}`)}
                                      className="w-full bg-[#008069] hover:bg-[#006e5a] text-white text-[10px] font-bold py-1 px-2 rounded text-center transition-colors cursor-pointer"
                                    >
                                      {item.button1}
                                    </button>
                                    <button
                                      onClick={() => handlePhoneButtonClick(`View ${item.name}`)}
                                      className="w-full bg-white hover:bg-gray-100 text-gray-700 text-[10px] font-medium py-1 px-2 rounded border border-gray-200 text-center transition-colors cursor-pointer"
                                    >
                                      {item.button2}
                                    </button>
                                  </div>
                                </div>
                              </div>
                            ))}
                          </div>
                          
                          {/* Carousel Navigation Indicators */}
                          <div className="flex justify-between items-center mt-2 px-1 text-[10px] text-gray-500 font-mono">
                            <button
                              disabled={carouselIndex === 0}
                              onClick={() => setCarouselIndex(prev => Math.max(0, prev - 1))}
                              className="disabled:opacity-20 cursor-pointer p-0.5"
                            >
                              <ChevronLeft className="h-3 w-3" />
                            </button>
                            <span>{carouselIndex + 1} / {msg.carouselItems.length}</span>
                            <button
                              disabled={carouselIndex === msg.carouselItems.length - 1}
                              onClick={() => setCarouselIndex(prev => Math.min(msg.carouselItems.length - 1, prev + 1))}
                              className="disabled:opacity-20 cursor-pointer p-0.5"
                            >
                              <ChevronRight className="h-3 w-3" />
                            </button>
                          </div>
                        </div>
                      )}

                      {/* Small receipt timestamp */}
                      <span className="text-[7.5px] text-gray-400 block text-right mt-1 font-mono">
                        {new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                      </span>
                    </div>
                  </div>
                );
              })}
            </div>

            {/* Bottom Sheet List View (triggers when Select Options is clicked) */}
            {showListSheet && (
              <div className="absolute inset-0 bg-black/40 z-40 flex flex-col justify-end">
                <div className="bg-white rounded-t-2xl shadow-xl max-h-[70%] flex flex-col overflow-hidden animate-slide-up">
                  {/* Sheet Header */}
                  <div className="p-3.5 border-b border-gray-100 flex items-center justify-between bg-gray-50 shrink-0">
                    <span className="font-bold text-xs text-gray-800">{currentConfig.listButtonLabel || 'Select options'}</span>
                    <button 
                      onClick={() => setShowListSheet(false)}
                      className="text-gray-400 text-xs font-semibold cursor-pointer px-2 py-0.5 rounded hover:bg-gray-200"
                    >
                      Close
                    </button>
                  </div>
                  
                  {/* Sheet Scroll Area */}
                  <div className="overflow-y-auto p-2.5 space-y-4">
                    {currentConfig.listSections?.map((sec, secIdx) => (
                      <div key={secIdx} className="space-y-1.5">
                        <h5 className="text-[9px] font-bold text-[#008069] uppercase tracking-wider px-2">
                          {sec.title}
                        </h5>
                        <div className="space-y-0.5 bg-gray-50/50 rounded-lg border border-gray-100 overflow-hidden">
                          {sec.rows.map((row) => (
                            <button
                              key={row.id}
                              onClick={() => handleListRowSelect(row.title)}
                              className="w-full text-left px-3 py-2 hover:bg-emerald-50/40 active:bg-emerald-50 border-b border-gray-100/50 last:border-b-0 flex flex-col justify-start cursor-pointer transition-colors"
                            >
                              <span className="text-xs font-bold text-gray-800">{row.title}</span>
                              <span className="text-[9px] text-gray-500">{row.desc}</span>
                            </button>
                          ))}
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            )}

            {/* Bottom Sheet Quantity Selector View */}
            {showQtySheet && (
              <div className="absolute inset-0 bg-black/40 z-40 flex flex-col justify-end">
                <div className="bg-white rounded-t-3xl p-5 text-gray-900 animate-slide-up max-h-[90%] flex flex-col overflow-hidden relative select-none">
                  {/* Drag Handle */}
                  <div className="w-10 h-1 bg-gray-200 rounded-full mx-auto mb-4" />

                  {/* Header */}
                  <div className="flex justify-between items-center mb-4">
                    <span className="font-extrabold text-sm text-gray-800">Select Quantity</span>
                    <button 
                      onClick={() => setShowQtySheet(false)}
                      className="text-gray-400 text-xs font-semibold cursor-pointer border-0 bg-transparent p-1"
                    >
                      Close
                    </button>
                  </div>

                  {/* Product Card */}
                  <div className="flex gap-3 p-3 rounded-xl bg-gray-50 border border-gray-100 mb-4 items-center">
                    <div className="w-12 h-12 bg-emerald-500 rounded-lg flex items-center justify-center text-white text-xs font-bold font-mono">
                      ☕
                    </div>
                    <div className="flex-1 min-w-0">
                      <h5 className="font-bold text-xs text-gray-800 truncate">Organic Coffee Beans</h5>
                      <p className="text-[10px] text-gray-500 mt-0.5">$18.50 per unit</p>
                      <div className="flex items-center gap-1 mt-1">
                        <span className="w-3 h-3 rounded-full bg-blue-50 text-blue-500 flex items-center justify-center text-[7px] font-bold border border-blue-200">✓</span>
                        <span className="text-[8px] text-blue-500 font-extrabold tracking-tight">In Stock</span>
                      </div>
                    </div>
                  </div>

                  {/* Quantity selector */}
                  <div className="flex flex-col items-center justify-center py-4 mb-4">
                    <div className="flex items-center gap-6">
                      <button
                        onClick={() => setPreviewQty(Math.max(1, previewQty - 1))}
                        disabled={previewQty <= 1}
                        className="w-10 h-10 rounded-full border border-gray-200 bg-white text-gray-600 flex items-center justify-center text-lg hover:bg-gray-50 disabled:opacity-40 cursor-pointer"
                      >
                        —
                      </button>
                      <div className="text-center w-12">
                        <span className="text-4xl font-extrabold text-gray-900">{previewQty}</span>
                        <span className="block text-[8px] font-bold text-gray-400 uppercase tracking-wider mt-0.5">Units</span>
                      </div>
                      <button
                        onClick={() => setPreviewQty(previewQty + 1)}
                        className="w-10 h-10 rounded-full border border-[#16a34a] bg-white text-[#16a34a] flex items-center justify-center text-lg hover:bg-emerald-50 cursor-pointer"
                      >
                        +
                      </button>
                    </div>

                    <div className="mt-4 bg-emerald-50 text-emerald-700 px-3 py-1 rounded-full text-[10px] font-bold border border-emerald-100">
                      Subtotal: <span className="font-mono">${(18.50 * previewQty).toFixed(2)}</span>
                    </div>
                  </div>

                  {/* Action button */}
                  <button
                    onClick={() => {
                      const selectedVal = previewQty;
                      setShowQtySheet(false);
                      handlePhoneButtonClick(`${selectedVal} Units`);
                    }}
                    className="w-full bg-[#16a34a] hover:bg-[#15803d] text-white font-bold py-3 px-4 rounded-xl text-xs flex items-center justify-center gap-1.5 cursor-pointer shadow border-0"
                  >
                    Confirm Quantity
                  </button>

                  <p className="text-[8px] text-gray-400 text-center mt-3 max-w-xs mx-auto leading-normal font-medium">
                    Secure checkout powered by RetailBot. Your order will be added to your chat basket.
                  </p>
                </div>
              </div>
            )}

            {/* Bottom Input Area */}
            <div className="bg-[#f0f2f5] p-2 flex items-center gap-2 border-t border-gray-200 shrink-0 z-20">
              <Smile className="h-5 w-5 text-gray-500 shrink-0 cursor-pointer" />
              <div className="flex-1 bg-white rounded-full px-3.5 py-1.5 border border-gray-200 flex items-center text-[10px] text-gray-400">
                Type a message...
              </div>
              <Paperclip className="h-4.5 w-4.5 text-gray-500 shrink-0 cursor-pointer rotate-45" />
              <div className="h-8 w-8 rounded-full bg-[#00a884] flex items-center justify-center text-white shrink-0 cursor-pointer shadow-sm">
                <Mic className="h-4 w-4" />
              </div>
            </div>
          </div>
          
          {/* Reset Preview Button */}
          <button
            onClick={resetChatSimulation}
            className="mt-4 flex items-center gap-1.5 text-xs text-emerald-400 hover:text-emerald-300 font-medium cursor-pointer transition-colors bg-white/3 border border-white/5 px-4 py-2 rounded-full"
          >
            <RotateCcw className="h-3.5 w-3.5" />
            Reset Chat Simulation
          </button>
        </div>

        {/* Right Column: Code viewer & parameters panel */}
        <div className="lg:col-span-7 space-y-6">
          {/* Panel Tabs */}
          <div className="flex bg-white dark:bg-[#0e0f14]/80 p-1.5 rounded-xl border border-slate-200 dark:border-white/5 gap-1 select-none shadow-sm">
            <button
              onClick={() => setPanelTab('editor')}
              className={`flex-1 flex items-center justify-center gap-1.5 py-2.5 px-4 rounded-lg text-xs font-bold transition-all cursor-pointer ${
                panelTab === 'editor'
                  ? 'bg-emerald-500 text-white shadow-md'
                  : 'text-slate-600 dark:text-gray-400 hover:text-slate-900 dark:hover:text-white'
              }`}
            >
              <Settings className="h-3.5 w-3.5" />
              Visual Editor
            </button>
            <button
              onClick={() => setPanelTab('json')}
              className={`flex-1 flex items-center justify-center gap-1.5 py-2.5 px-4 rounded-lg text-xs font-bold transition-all cursor-pointer ${
                panelTab === 'json'
                  ? 'bg-emerald-500 text-white shadow-md'
                  : 'text-slate-600 dark:text-gray-400 hover:text-slate-900 dark:hover:text-white'
              }`}
            >
              <Code className="h-3.5 w-3.5" />
              API Payload (JSON)
            </button>
            <button
              onClick={() => setPanelTab('test')}
              className={`flex-1 flex items-center justify-center gap-1.5 py-2.5 px-4 rounded-lg text-xs font-bold transition-all cursor-pointer ${
                panelTab === 'test'
                  ? 'bg-emerald-500 text-white shadow-md'
                  : 'text-slate-600 dark:text-gray-400 hover:text-slate-900 dark:hover:text-white'
              }`}
            >
              <Send className="h-3.5 w-3.5" />
              Sandbox Simulator
            </button>
          </div>

          {/* Visual Editor Panel */}
          {panelTab === 'editor' && (
            <div className="glass-panel rounded-2xl p-6 border border-white/5 space-y-5 animate-fade-in">
              <h3 className="font-bold text-white text-base font-sans">Template Customization</h3>
              
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {/* Branding/Sender Name */}
                <div className="space-y-1.5">
                  <label className="text-[10px] font-bold uppercase tracking-wider text-gray-400">Business Sender Name</label>
                  <input
                    type="text"
                    value={currentConfig.businessName}
                    onChange={(e) => handleEditorChange('businessName', e.target.value)}
                    className="w-full glass-input bg-[#0e1511] px-3.5 py-2 text-xs"
                  />
                </div>

                {/* Verified Badge Toggle */}
                <div className="space-y-1.5 flex flex-col justify-end">
                  <div className="flex items-center gap-3 bg-[#0e1511]/40 p-2.5 rounded-lg border border-white/5 h-[38px]">
                    <input
                      type="checkbox"
                      id="verified-checkbox"
                      checked={currentConfig.isVerified}
                      onChange={(e) => handleEditorChange('isVerified', e.target.checked)}
                      className="accent-emerald-500 h-4 w-4 cursor-pointer"
                    />
                    <label htmlFor="verified-checkbox" className="text-xs text-gray-300 font-semibold cursor-pointer select-none">
                      Show official verification badge
                    </label>
                  </div>
                </div>
              </div>

              {/* Body Copy */}
              <div className="space-y-1.5">
                <label className="text-[10px] font-bold uppercase tracking-wider text-gray-400">Message Body Copy</label>
                <textarea
                  rows={4}
                  value={currentConfig.bodyText}
                  onChange={(e) => handleEditorChange('bodyText', e.target.value)}
                  className="w-full glass-input bg-[#0e1511] p-3 text-xs font-sans leading-relaxed"
                />
              </div>

              {/* Context-Specific Fields */}
              {/* 1. BUTTONS (Support / Feedback) */}
              {currentConfig.buttons && (
                <div className="space-y-3 pt-3 border-t border-white/5">
                  <label className="text-[10px] font-bold uppercase tracking-wider text-gray-400 block">Quick Reply Buttons (Max 3)</label>
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                    {currentConfig.buttons.map((btn, idx) => (
                      <div key={idx} className="space-y-1">
                        <span className="text-[9px] text-gray-500 font-mono">Button {idx + 1} Label</span>
                        <input
                          type="text"
                          value={btn}
                          onChange={(e) => handleButtonValueChange(idx, e.target.value)}
                          maxLength={25}
                          className="w-full glass-input bg-[#0e1511] px-3.5 py-2 text-xs font-semibold text-emerald-400"
                        />
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* 2. LIST OPTIONS (Lead Generation) */}
              {activeTab === 'lead' && (
                <div className="space-y-4 pt-3 border-t border-white/5">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="space-y-1.5">
                      <label className="text-[10px] font-bold uppercase tracking-wider text-gray-400">Trigger Button Label</label>
                      <input
                        type="text"
                        value={currentConfig.listButtonLabel}
                        onChange={(e) => handleEditorChange('listButtonLabel', e.target.value)}
                        className="w-full glass-input bg-[#0e1511] px-3.5 py-2 text-xs text-cyan-400 font-bold"
                      />
                    </div>
                    <div className="space-y-1.5">
                      <label className="text-[10px] font-bold uppercase tracking-wider text-gray-400">Footer Note</label>
                      <input
                        type="text"
                        value={currentConfig.footerText || ''}
                        onChange={(e) => handleEditorChange('footerText', e.target.value)}
                        className="w-full glass-input bg-[#0e1511] px-3.5 py-2 text-xs"
                      />
                    </div>
                  </div>

                  {/* List Rows Editor */}
                  <div className="space-y-3">
                    <span className="text-[10px] font-bold uppercase tracking-wider text-gray-400 block">List Options Rows</span>
                    {currentConfig.listSections?.map((sec, secIdx) => (
                      <div key={secIdx} className="bg-black/30 p-4 rounded-xl border border-white/5 space-y-3">
                        <span className="text-[10px] text-emerald-400 font-bold tracking-wider">{sec.title}</span>
                        {sec.rows.map((row, rIdx) => (
                          <div key={row.id} className="grid grid-cols-1 md:grid-cols-2 gap-3 pb-3 border-b border-white/5 last:border-b-0 last:pb-0">
                            <div className="space-y-1">
                              <span className="text-[9px] text-gray-500 font-mono">Row Title</span>
                              <input
                                type="text"
                                value={row.title}
                                onChange={(e) => handleListRowChange(secIdx, rIdx, 'title', e.target.value)}
                                className="w-full glass-input bg-[#0e1511] px-3 py-1.5 text-xs text-white"
                              />
                            </div>
                            <div className="space-y-1">
                              <span className="text-[9px] text-gray-500 font-mono">Description</span>
                              <input
                                type="text"
                                value={row.desc}
                                onChange={(e) => handleListRowChange(secIdx, rIdx, 'desc', e.target.value)}
                                className="w-full glass-input bg-[#0e1511] px-3 py-1.5 text-xs text-gray-400"
                              />
                            </div>
                          </div>
                        ))}
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* 3. CAROUSEL ITEMS (Sales) */}
              {activeTab === 'sale' && (
                <div className="space-y-4 pt-3 border-t border-white/5">
                  <span className="text-[10px] font-bold uppercase tracking-wider text-gray-400 block">Carousel Product Cards</span>
                  
                  {currentConfig.carouselItems?.map((item, idx) => (
                    <div key={item.id} className="bg-black/30 p-4 rounded-xl border border-white/5 space-y-3">
                      <div className="flex items-center justify-between border-b border-white/5 pb-2">
                        <span className="text-xs text-emerald-400 font-bold">Product Card #{idx + 1}</span>
                        <div className="flex items-center gap-1">
                          <span className="text-[9px] text-gray-500 font-mono">Price:</span>
                          <input
                            type="number"
                            step="0.01"
                            value={item.price}
                            onChange={(e) => handleCarouselItemChange(idx, 'price', parseFloat(e.target.value) || 0)}
                            className="bg-[#0e1511] border border-white/10 rounded px-1.5 py-0.5 text-[10px] text-white w-14 text-right outline-none"
                          />
                        </div>
                      </div>
                      
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <div className="space-y-1">
                          <span className="text-[9px] text-gray-500 font-mono">Product Name</span>
                          <input
                            type="text"
                            value={item.name}
                            onChange={(e) => handleCarouselItemChange(idx, 'name', e.target.value)}
                            className="w-full glass-input bg-[#0e1511] px-2.5 py-1.5 text-xs text-white"
                          />
                        </div>
                        <div className="space-y-1">
                          <span className="text-[9px] text-gray-500 font-mono">Image URL</span>
                          <input
                            type="text"
                            value={item.imageUrl}
                            onChange={(e) => handleCarouselItemChange(idx, 'imageUrl', e.target.value)}
                            className="w-full glass-input bg-[#0e1511] px-2.5 py-1.5 text-xs text-gray-400 font-mono truncate"
                          />
                        </div>
                      </div>

                      <div className="space-y-1">
                        <span className="text-[9px] text-gray-500 font-mono">Description Content</span>
                        <input
                          type="text"
                          value={item.description}
                          onChange={(e) => handleCarouselItemChange(idx, 'description', e.target.value)}
                          className="w-full glass-input bg-[#0e1511] px-2.5 py-1.5 text-xs text-gray-300"
                        />
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* API Payload JSON Tab */}
          {panelTab === 'json' && (
            <div className="glass-panel rounded-2xl p-6 border border-white/5 space-y-4 animate-fade-in">
              <div className="flex justify-between items-center">
                <h3 className="font-bold text-white text-base font-sans">WhatsApp API Body JSON</h3>
                
                {/* Copy to Clipboard */}
                <button
                  onClick={handleCopyPayload}
                  className={`flex items-center gap-1.5 text-xs font-semibold px-3 py-1.5 rounded-lg border transition-all cursor-pointer ${
                    copied
                      ? 'bg-emerald-500/10 text-emerald-400 border-emerald-500/20'
                      : 'bg-white/3 text-gray-300 border-white/5 hover:bg-white/5 hover:text-white'
                  }`}
                >
                  {copied ? (
                    <>
                      <Check className="h-3.5 w-3.5 text-emerald-400" />
                      Payload Copied!
                    </>
                  ) : (
                    <>
                      <Copy className="h-3.5 w-3.5 text-gray-400" />
                      Copy Payload
                    </>
                  )}
                </button>
              </div>

              <p className="text-xs text-gray-400 leading-relaxed">
                Send a POST request to the Meta Graph API endpoint below with this JSON body to dispatch this interactive message:
              </p>
              
              <div className="bg-[#0e1511] p-3 rounded-lg border border-white/5 font-mono text-[10px] text-emerald-400 overflow-x-auto select-all">
                POST https://graph.facebook.com/v18.0/&lt;YOUR_PHONE_NUMBER_ID&gt;/messages
              </div>

              {/* JSON codeblock syntax look */}
              <div className="relative">
                <pre className="bg-[#050508] p-5 rounded-xl border border-white/5 font-mono text-[10px] text-cyan-300 overflow-x-auto select-text leading-normal max-h-[380px]">
                  {generateJsonPayload()}
                </pre>
              </div>
            </div>
          )}

          {/* Sandbox Simulator Testing Tab */}
          {panelTab === 'test' && (
            <div className="glass-panel rounded-2xl p-6 border border-white/5 space-y-4 animate-fade-in">
              <h3 className="font-bold text-white text-base font-sans">Simulate Delivery in Sandbox</h3>
              <p className="text-xs text-gray-400 leading-relaxed">
                Dispatch this interactive template to a test number. This will inject the template into your active local chatbot session log, simulating how the message appears inside the **WhatsApp Bot Simulator** tab.
              </p>

              <div className="bg-[#0e1511]/40 p-4 rounded-xl border border-white/5 space-y-4">
                <div className="space-y-1.5">
                  <label className="text-[10px] font-bold uppercase tracking-wider text-gray-400">Recipient Phone Number</label>
                  <input
                    type="text"
                    value={testPhone}
                    onChange={(e) => setTestPhone(e.target.value)}
                    placeholder="e.g. +263779998887"
                    className="w-full glass-input bg-[#0e1511] px-3.5 py-2.5 text-xs font-mono text-white"
                  />
                  <span className="text-[9px] text-gray-500 block leading-tight">
                    Must match the number selected in your Bot Simulator chat.
                  </span>
                </div>

                <button
                  onClick={handleSendSimulatedTemplate}
                  disabled={sendingTest || !testPhone.trim()}
                  className="w-full bg-emerald-500 hover:bg-emerald-600 text-white font-semibold py-2.5 px-4 rounded-xl text-xs flex items-center justify-center gap-1.5 shadow-lg shadow-emerald-500/10 cursor-pointer disabled:opacity-55 disabled:pointer-events-none transition-colors"
                >
                  <Send className={`h-3.5 w-3.5 ${sendingTest ? 'animate-pulse' : ''}`} />
                  {sendingTest ? 'Sending simulated template...' : 'Send Simulated Template'}
                </button>
              </div>

              {/* Sandbox verification hint */}
              <div className="bg-emerald-500/5 border border-emerald-500/10 rounded-xl p-4 flex gap-3 items-start text-xs text-emerald-400">
                <CheckCircle2 className="h-4.5 w-4.5 mt-0.5 shrink-0" />
                <div>
                  <p className="font-bold">Where does it go?</p>
                  <p className="text-gray-400 text-[11px] leading-relaxed mt-0.5">
                    This triggers an outbound template dispatch. You can view the output directly on your WhatsApp client for phone number <strong>{testPhone}</strong>.
                  </p>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
