import { useState } from 'react';
import type { DashboardData, ChatWidgetData } from './types';
import {
  MessageCircle,
  Share2,
  BarChart3,
  Plus,
  Trash2,
  Edit2,
  Upload,
  TrendingUp,
  Eye,
  Users,
  Smartphone,
  Clock,
  Globe,
  Monitor,
  AlertCircle,
  Layout,
  Palette,
  CheckCircle2,
  MousePointer2,
  Heading,
  MessageSquare,
  User,
  RefreshCw,
  Tag,
  Circle,
  Square,
  CircleDot
} from 'lucide-react'
import { PhoneInput } from './components/ui/PhoneInput'
import { SearchableSelect } from './components/ui/searchable-select'
import { Separator } from './components/ui/separator'
import { toast } from "sonner"
import { cn } from "@/lib/utils"
import { motion, AnimatePresence } from 'framer-motion'
import {
  SettingCard,
  FlatTabs,
  SettingInput,
  SettingsLayout,
  SettingsHeader,
  AdminButton,
  ModernCardHeader,
  SnapshotStat,
  FeatSection,
  ColorInput,
} from './components/ui/settings-ui';
import { CompactSettingCard } from './components/ui/CompactSettingCard';
import { MultiSelectTagify } from './components/ui/multi-select-tagify';

// ─── Types ────────────────────────────────────────────────────────────────────

interface SocialLink {
  link: string;
  icon: string;
}

interface ChatWidgetSettings {
  wawp_enable_button: 'yes' | 'no';
  wawp_whatsapp_numbers: string[];
  wawp_whatsapp_messages: string[];
  wawp_user_names: string[];
  wawp_user_roles: string[];
  wawp_user_avatars: string[];
  wawp_whatsapp_header: string;
  wawp_welcome_message: string;
  wawp_reply_time_text: string;
  wawp_avatar_url: string;
  wawp_social_intro_text: string;
  wawp_social_icons: SocialLink[];
  wawp_social_button_style: 'round' | 'square' | 'outline' | 'brand';
  wawp_social_layout: 'vertical' | 'horizontal';
  wawp_whatsapp_icon_class: string;
  wawp_button_bg_color: string;
  wawp_icon_color: string;
  wawp_button_size: string;
  wawp_corner_radius: string;
  wawp_button_position: 'left' | 'right';
  wawp_button_bottom_offset: string;
  wawp_display_desktop: 'yes' | 'no';
  wawp_display_mobile: 'yes' | 'no';
  wawp_trigger_on_all_pages: 'yes' | 'no';
  wawp_page_conditions: (string | number)[];
}

// ─── Sub-Components ──────────────────────────────────────────────────────────

import { memo } from 'react';

const FloatingPreview = memo(({ 
  settings, 
  data, 
  rootData, 
  isWindowOpen, 
  setIsWindowOpen,
  activeNumbers 
}: { 
  settings: ChatWidgetSettings, 
  data: ChatWidgetData, 
  rootData: DashboardData, 
  isWindowOpen: boolean, 
  setIsWindowOpen: (open: boolean) => void,
  activeNumbers: string[]
}) => {
  return (
    <div id="wawp-chat-wrapper" style={{ 
      right: settings.wawp_button_position === 'right' ? '32px' : 'auto', 
      left: settings.wawp_button_position === 'left' ? '32px' : 'auto', 
      bottom: `${settings.wawp_button_bottom_offset || 32}px`, 
      position: 'fixed',
      zIndex: 99999
    }}>
      <AnimatePresence>
        {isWindowOpen && (
          <motion.div
            initial={{ opacity: 0, scale: 0, transformOrigin: settings.wawp_button_position === 'left' ? 'bottom left' : 'bottom right' }}
            animate={{ opacity: 1, scale: 1 }}
            exit={{ opacity: 0, scale: 0 }}
            id="wawp-chat-window"
            className="wawp-chat-window scale-toggle"
            style={{
              background: 'linear-gradient(135deg, #044449 50%, #00c66b)',
              position: 'relative',
              display: 'flex',
              flexDirection: 'column',
              width: '350px',
              height: 'auto',
              transform: 'none',
              bottom: '12px',
              marginBottom: '0'
            }}
          >
            <div className="wawp-chat-header">
              <img
                src={settings.wawp_avatar_url || rootData.icons.baseUrl + 'WhatsApp_avatar.png'}
                alt="Avatar"
                className="wawp-header-avatar"
              />
              <div>
                <div className="wawp-widget-title">{settings.wawp_whatsapp_header || "Let's chat"}</div>
                <div className="wawp-widget-message">{settings.wawp_welcome_message || "How may we help you?"}</div>
              </div>
              <i
                className="ri-close-line wawp-minimize-icon"
                onClick={() => setIsWindowOpen(false)}
                style={{ [rootData.global.isRtl ? 'left' : 'right']: '12px' }}
              ></i>
            </div>

            <div className="wawp-chat-data">
              <div className="wawp-reply-time-container">
                <div className="wawp-reply-time-bubble">
                  <i className="ri-time-line"></i>
                  {settings.wawp_reply_time_text || "Typically replies within minutes"}
                </div>
              </div>

              <div className="wawp-chat-content" id="wawp-contact-list">
                {activeNumbers.length > 0 ? (
                  activeNumbers.map((_, i: number) => (
                    <div key={i}>
                      <div className="wawp-contact-item">
                        <div className="wawp-avatar-wrapper">
                          <img
                            src={settings.wawp_user_avatars[i] || settings.wawp_avatar_url || rootData.icons.baseUrl + 'WhatsApp_avatar.png'}
                            alt="Avatar"
                          />
                          <span className="wawp-online-dot"></span>
                        </div>
                        <div className="wawp-contact-info">
                          <span className="wawp-contact-name">{settings.wawp_user_names[i] || "Support Agent"}</span>
                          <span className="wawp-contact-role">{settings.wawp_user_roles[i] || "Online"}</span>
                        </div>
                        <div className="btns-group">
                          <a href="#"><i className="ri-whatsapp-line wawp-wa-chat-icon"></i></a>
                          <i className="ri-qr-code-line wawp-qr-chat-icon"></i>
                        </div>
                      </div>
                      <hr style={{ width: '100%', margin: 0, border: 0, borderTop: '1px solid #ededed' }} />
                    </div>
                  ))
                ) : (
                  <div className="p-8 text-center text-slate-400 text-xs italic">
                    Add a number to preview
                  </div>
                )}
              </div>
            </div>

            <div className="wawp-chat-footer">
              {settings.wawp_social_icons.length > 0 && (
                <div className={cn(
                  "wawp-social-section wawp-social-container",
                  `wawp-layout-${settings.wawp_social_layout}`
                )}>
                  <div className="wawp-social-intro">{settings.wawp_social_intro_text || "Reach us on:"}</div>
                  <div className={cn(
                    "wawp-social-icons",
                    `wawp-style-${settings.wawp_social_button_style}`
                  )}>
                    {settings.wawp_social_icons.map((item, idx) => {
                      const isBrand = settings.wawp_social_button_style === 'brand';
                      const remixIcons = data.remix_icons as Record<string, { label?: string, color: string }>;
                      const iconConfig = remixIcons?.[item.icon];

                      return (
                        <a
                          key={idx}
                          href="#"
                          className="wawp-social-icon"
                          style={{
                            color: isBrand ? (iconConfig?.color || 'white') : 'white'
                          }}
                        >
                          <i className={item.icon}></i>
                        </a>
                      );
                    })}
                  </div>
                </div>
              )}
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      <div
        id="wawp-whatsapp-button"
        className="wawp-whatsapp-button"
        onClick={() => setIsWindowOpen(!isWindowOpen)}
        style={{
          width: `${settings.wawp_button_size}px`,
          height: `${settings.wawp_button_size}px`,
          borderRadius: `${settings.wawp_corner_radius}%`,
          background: settings.wawp_button_bg_color || 'linear-gradient(135deg, #2ee168, #00c66b)',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          cursor: 'pointer',
          float: settings.wawp_button_position === 'right' ? 'right' : 'left'
        }}
      >
        {settings.wawp_whatsapp_icon_class ? (
          <i
            className={settings.wawp_whatsapp_icon_class}
            style={{
              fontSize: `${Math.floor(parseInt(settings.wawp_button_size) * 0.6)}px`,
              color: settings.wawp_icon_color || '#fff'
            }}
          ></i>
        ) : (
          <img
            src={rootData.icons.baseUrl + 'WhatsApp_icon.png'}
            alt="WhatsApp"
            style={{ width: '100%', height: 'auto', borderRadius: 'inherit' }}
          />
        )}
      </div>
    </div>
  );
});

FloatingPreview.displayName = 'FloatingPreview';

export default function ChatWidget({ data: rootData }: { data: DashboardData }) {
  const data = rootData?.chatWidgetData || null;
  const [settings, setSettings] = useState<ChatWidgetSettings | null>(() => {
    if (!data?.settings) return null;
    const s = JSON.parse(JSON.stringify(data.settings));
    // Ensure arrays exist to prevent .length / .map errors
    if (!Array.isArray(s.wawp_whatsapp_numbers)) s.wawp_whatsapp_numbers = [];
    if (!Array.isArray(s.wawp_whatsapp_messages)) s.wawp_whatsapp_messages = [];
    if (!Array.isArray(s.wawp_user_names)) s.wawp_user_names = [];
    if (!Array.isArray(s.wawp_user_roles)) s.wawp_user_roles = [];
    if (!Array.isArray(s.wawp_user_avatars)) s.wawp_user_avatars = [];
    if (!Array.isArray(s.wawp_social_icons)) s.wawp_social_icons = [];
    if (!Array.isArray(s.wawp_page_conditions)) s.wawp_page_conditions = [];
    if (!s.wawp_button_bottom_offset) s.wawp_button_bottom_offset = '32';
    if (!s.wawp_social_layout) s.wawp_social_layout = 'vertical';
    return s;
  });
  const [activeTab, setActiveTab] = useState('whatsapp');
  const [isSaving, setIsSaving] = useState(false);
  const [saveStatus, setSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle');
  const [editingAgent, setEditingAgent] = useState<number | null>(null);
  const [isWindowOpen, setIsWindowOpen] = useState(false);

  const [prevData, setPrevData] = useState(data);
  if (data !== prevData) {
    setPrevData(data);
    if (data?.settings) {
      const s = JSON.parse(JSON.stringify(data.settings));
      if (!Array.isArray(s.wawp_whatsapp_numbers)) s.wawp_whatsapp_numbers = [];
      if (!Array.isArray(s.wawp_whatsapp_messages)) s.wawp_whatsapp_messages = [];
      if (!Array.isArray(s.wawp_user_names)) s.wawp_user_names = [];
      if (!Array.isArray(s.wawp_user_roles)) s.wawp_user_roles = [];
      if (!Array.isArray(s.wawp_user_avatars)) s.wawp_user_avatars = [];
      if (!Array.isArray(s.wawp_social_icons)) s.wawp_social_icons = [];
      if (!Array.isArray(s.wawp_page_conditions)) s.wawp_page_conditions = [];
      if (!s.wawp_button_bottom_offset) s.wawp_button_bottom_offset = '32';
      if (!s.wawp_social_layout) s.wawp_social_layout = 'vertical';
      setSettings(s);
    }
  }


  if (!data || !settings) return null;

  const handleSave = async () => {
    setIsSaving(true);
    setSaveStatus('saving');

    try {
      const settingsToSave: Record<string, unknown> = {};

      // Map frontend keys to database option names via optionNames map
      Object.keys(settings).forEach(key => {
        const dbKey = data?.optionNames?.[key] || key;
        settingsToSave[dbKey] = settings[key as keyof ChatWidgetSettings];
      });

      const response = await fetch(rootData.global.settingsRestUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': rootData.global.wpRestNonce
        },
        body: JSON.stringify({
          settings: settingsToSave
        })
      });

      if (!response.ok) {
        throw new Error(`Server responded with ${response.status}`);
      }

      const result = await response.json();
      const resultMsg = result.message || (result.data && result.data.message);

      if (result.success) {
        toast.success(typeof resultMsg === 'string' ? resultMsg : "Settings saved successfully!");
        setSaveStatus('saved');
        window.dispatchEvent(new CustomEvent('wawp-refresh-data'));
      } else {
        toast.error(typeof resultMsg === 'string' ? resultMsg : "Failed to save settings");
        setSaveStatus('error');
      }
    } catch (e: unknown) {
      console.error('ChatWidget save error:', e);
      toast.error("Network error saving settings");
      setSaveStatus('error');
    } finally {
      setIsSaving(false);
      setTimeout(() => setSaveStatus('idle'), 3000);
    }
  };

  const updateSetting = <K extends keyof ChatWidgetSettings>(key: K, value: ChatWidgetSettings[K]) => {
    setSettings(prev => prev ? { ...prev, [key]: value } : null);
    setSaveStatus('idle');
  };

  // ─── WhatsApp Contacts Handlers ──────────────────────────────────────────────

  const addContact = () => {
    const next = { ...settings };
    next.wawp_whatsapp_numbers.push('');
    next.wawp_whatsapp_messages.push('Hello!');
    next.wawp_user_names.push('John Doe');
    next.wawp_user_roles.push('Support');
    next.wawp_user_avatars.push(settings.wawp_avatar_url || '');
    setSettings(next);
  };

  const removeContact = (idx: number) => {
    const next = { ...settings };
    next.wawp_whatsapp_numbers.splice(idx, 1);
    next.wawp_whatsapp_messages.splice(idx, 1);
    next.wawp_user_names.splice(idx, 1);
    next.wawp_user_roles.splice(idx, 1);
    next.wawp_user_avatars.splice(idx, 1);
    setSettings(next);
  };

  const updateContact = (idx: number, field: string, value: string) => {
    const next = { ...settings };
    if (field === 'number') next.wawp_whatsapp_numbers[idx] = value;
    if (field === 'name') next.wawp_user_names[idx] = value;
    if (field === 'message') next.wawp_whatsapp_messages[idx] = value;
    if (field === 'role') next.wawp_user_roles[idx] = value;
    if (field === 'avatar') next.wawp_user_avatars[idx] = value;
    setSettings(next);
  };

  const openMediaLibrary = (idx: number | 'main') => {
    const frame = (window as unknown as {
      wp: {
        media: (args: Record<string, unknown>) => {
          on: (event: string, cb: () => void) => void;
          state: () => { get: (id: string) => { first: () => { toJSON: () => { url: string } } } };
          open: () => void;
        }
      }
    }).wp.media({
      title: 'Select Avatar',
      button: { text: 'Use this image' },
      multiple: false
    });

    frame.on('select', () => {
      const attachment = frame.state().get('selection').first().toJSON();
      if (idx === 'main') {
        updateSetting('wawp_avatar_url', attachment.url);
      } else {
        updateContact(idx as number, 'avatar', attachment.url);
      }
    });

    frame.open();
  };

  // ─── Social Links Handlers ───────────────────────────────────────────────────

  const addSocialLink = () => {
    const next = { ...settings };
    next.wawp_social_icons.push({ link: '', icon: 'ri-facebook-circle-fill' });
    setSettings(next);
  };

  const removeSocialLink = (idx: number) => {
    const next = { ...settings };
    next.wawp_social_icons.splice(idx, 1);
    setSettings(next);
  };

  const updateSocialLink = (idx: number, field: 'link' | 'icon', value: string) => {
    const next = { ...settings };
    next.wawp_social_icons[idx][field] = value;
    setSettings(next);
  };

  // ─── Render Helpers ──────────────────────────────────────────────────────────

  const stats = data?.stats || {};

  const tabs = [
    { id: 'whatsapp', label: 'WhatsApp', icon: MessageCircle },
    { id: 'social', label: 'Social Links', icon: Share2 },
    { id: 'analytics', label: 'Analytics', icon: BarChart3 },
    { id: 'settings', label: 'Appearance', icon: Palette },
    { id: 'conditions', label: 'Conditions', icon: Globe },
  ];

  const activeNumbers = settings.wawp_whatsapp_numbers.filter(num => num);

  return (
    <SettingsLayout>
      <div className="flex flex-col xl:flex-row min-h-screen">
        {/* ─── Main Content Area ─── */}
        <div className="flex-1 space-y-6">
          <SettingsHeader
            title={data.i18n.chatWidget.title}
            description="Add direct WhatsApp chat, social media links, and more with interaction tracking."
          >
            <div className="flex items-center gap-2">
              {saveStatus === 'saved' && (
                <motion.div
                  initial={{ opacity: 0, scale: 0.9 }} animate={{ opacity: 1, scale: 1 }} exit={{ opacity: 0 }}
                  className="hidden md:flex items-center gap-2 px-3 py-1.5 bg-emerald-50 text-emerald-600 rounded-[5px] text-[10px] font-black uppercase tracking-widest border border-emerald-100/50"
                >
                  <CheckCircle2 size={14} />
                  Changes Deployed
                </motion.div>
              )}
              <AdminButton
                onClick={handleSave}
                disabled={isSaving}
                className="shadow-sm"
              >
                {isSaving ? <RefreshCw className="mr-2 h-4 w-4 animate-spin" /> : <CheckCircle2 className="mr-2 h-4 w-4" />}
                {isSaving ? 'Saving...' : 'Save Settings'}
              </AdminButton>
            </div>
          </SettingsHeader>

          <FlatTabs
            tabs={tabs}
            activeTab={activeTab}
            onTabChange={setActiveTab}
          />

          <div className="mt-4">
            <AnimatePresence mode="wait">
              <motion.div
                key={activeTab}
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -10 }}
                transition={{ duration: 0.2 }}
              >
                {/* ─── WhatsApp Tab ─── */}
                {activeTab === 'whatsapp' && (
                  <div className="space-y-8 outline-none border-none p-0">
                    <div className="grid grid-cols-1 gap-6">
                      <CompactSettingCard
                        icon={MessageCircle}
                        title="WhatsApp Widget Status"
                        description="General toggle to display or hide the chat widget across your site."
                        checked={settings.wawp_enable_button === 'yes'}
                        onChange={(checked: boolean) => updateSetting('wawp_enable_button', checked ? 'yes' : 'no')}
                        statusMessage={settings.wawp_enable_button === 'yes' ? "The WhatsApp floating button is currently active on your website." : "The WhatsApp floating button is currently hidden from your visitors."}
                        statusType={settings.wawp_enable_button === 'yes' ? 'active' : 'inactive'}
                      />
                    </div>

                    <SettingCard className="p-0 overflow-hidden">
                      <ModernCardHeader
                        title="Account Configuration"
                        description="Configure your primary WhatsApp account details and display settings."
                        icon={MessageCircle}
                      />

                      <div className="p-6 md:p-8 space-y-6">
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                          <SettingInput
                            label="Widget Headline"
                            value={settings.wawp_whatsapp_header}
                            onChange={(val) => updateSetting('wawp_whatsapp_header', val)}
                            placeholder=""
                            icon={Heading}
                            showEmoji={true}
                            showFormatting={true}
                          />
                          <SettingInput
                            label="Reply Time Text"
                            value={settings.wawp_reply_time_text}
                            onChange={(val) => updateSetting('wawp_reply_time_text', val)}
                            placeholder="e.g. Typically replies in minutes"
                            icon={Clock}
                            showEmoji={true}
                            showFormatting={false}
                          />
                        </div>

                        <SettingInput
                          label="Welcome Message"
                          value={settings.wawp_welcome_message}
                          onChange={(val) => updateSetting('wawp_welcome_message', val)}
                          placeholder=""
                          icon={MessageSquare}
                          showEmoji={true}
                          showFormatting={true}
                        />

                        <div className="flex flex-col md:flex-row items-center gap-6 p-4 bg-gray-50 border border-[#dcdcde] rounded-[5px]">
                          <div className="relative group overflow-hidden w-20 h-20 rounded-full border-2 border-white shadow-sm flex-shrink-0 bg-white flex items-center justify-center">
                            <img
                              src={settings.wawp_avatar_url || 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMDAgMTAwIj48Y2lyY2xlIGN4PSI1MCIgY3k9IjUwIiByPSI1MCIgZmlsbD0iI2NjYyIvPjwvc3ZnPg=='}
                              className="w-[85%] h-[85%] object-contain"
                            />
                            <button
                              onClick={() => openMediaLibrary('main')}
                              className="absolute inset-0 bg-black/40 text-white opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center cursor-pointer"
                            >
                              <Upload size={16} />
                            </button>
                          </div>
                          <div className="flex-1 space-y-1">
                            <h4 className="font-bold text-gray-900 text-sm">Header Avatar</h4>
                            <p className="text-xs text-gray-500 font-medium leading-relaxed">This image appears at the top of the chat window. Recommended size 100x100px.</p>
                            <div className="flex gap-2 mt-2">
                              <button
                                onClick={() => openMediaLibrary('main')}
                                className="bg-white border border-[#dcdcde] hover:bg-gray-50 text-gray-700 px-3 py-1.5 rounded-[5px] text-[11px] font-bold transition-all shadow-sm"
                              >
                                Change Photo
                              </button>
                            </div>
                          </div>
                        </div>
                      </div>
                    </SettingCard>

                    <SettingCard className="p-0 overflow-hidden">
                      <ModernCardHeader
                        title="Support Agents"
                        description="Manage multiple WhatsApp numbers and support roles."
                        icon={Users}
                        rightAction={
                          <AdminButton
                            onClick={addContact}
                            icon={Plus}
                            className="bg-emerald-600 hover:bg-emerald-700"
                          >
                            Add New Agent
                          </AdminButton>
                        }
                      />

                      <div className="p-6 md:p-8 space-y-4">
                        {settings.wawp_whatsapp_numbers.map((_, i) => (
                          <motion.div
                            layout
                            initial={{ opacity: 0, scale: 0.98 }}
                            animate={{ opacity: 1, scale: 1 }}
                            key={i}
                          >
                            {editingAgent === i ? (
                              <SettingCard className="group relative overflow-visible p-5 md:p-6 border-emerald-500/30 bg-emerald-50/10 shadow-lg shadow-emerald-500/5">
                                <div className="flex items-start gap-4">
                                  <div className="relative group/avatar w-12 h-12 rounded-full overflow-hidden border border-gray-200 flex-shrink-0 bg-white flex items-center justify-center">
                                    <img src={settings.wawp_user_avatars[i]} className="w-[85%] h-[85%] object-contain" />
                                    <div
                                      onClick={() => openMediaLibrary(i)}
                                      className="absolute inset-0 bg-black/40 text-white opacity-0 group-hover/avatar:opacity-100 transition-opacity flex items-center justify-center cursor-pointer"
                                    >
                                      <Edit2 size={12} />
                                    </div>
                                  </div>

                                  <div className="flex-1 grid grid-cols-1 md:grid-cols-3 gap-4">
                                    <SettingInput
                                      label="Name"
                                      value={settings.wawp_user_names[i]}
                                      onChange={(val) => updateContact(i, 'name', val)}
                                      className="bg-white"
                                      icon={User}
                                      showEmoji={true}
                                    />
                                    <div className="space-y-2">
                                      <label className="text-[11px] font-black uppercase text-gray-400 tracking-widest leading-none">WhatsApp Number</label>
                                      <PhoneInput
                                        value={settings.wawp_whatsapp_numbers[i]}
                                        onChange={(val) => updateContact(i, 'number', val)}
                                        className="h-11 border-slate-200 rounded-[5px] bg-white transition-all"
                                        placeholder="+1234567890"
                                        hideMessage
                                      />
                                    </div>
                                    <SettingInput
                                      label="Role / Title"
                                      value={settings.wawp_user_roles[i]}
                                      onChange={(val) => updateContact(i, 'role', val)}
                                      className="bg-white"
                                      placeholder="e.g. Sales"
                                      icon={Tag}
                                      showEmoji={true}
                                    />
                                  </div>
                                </div>

                                <div className="mt-4 pt-4 border-t border-gray-100 space-y-4">
                                  <SettingInput
                                    label="Pre-filled Message"
                                    value={settings.wawp_whatsapp_messages[i]}
                                    onChange={(val) => updateContact(i, 'message', val)}
                                    className="bg-white"
                                    placeholder="I have a question about..."
                                    icon={MessageSquare}
                                    showEmoji={true}
                                  />

                                  <div className="wawp-field">
                                    <label className="text-[11px] font-black uppercase text-gray-400 tracking-widest leading-none mb-2 block"><i className="ri-image-line mr-1"></i> Avatar</label>
                                    <div className="flex items-center gap-4 p-4 bg-white border border-[#dcdcde] rounded-[5px]">
                                      <div className="relative group overflow-hidden w-12 h-12 rounded-full border-2 border-white shadow-sm flex-shrink-0 bg-white flex items-center justify-center">
                                        <img
                                          src={settings.wawp_user_avatars[i] || 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMDAgMTAwIj48Y2lyY2xlIGN4PSI1MCIgY3k9IjUwIiByPSI1MCIgZmlsbD0iI2NjYyIvPjwvc3ZnPg=='}
                                          className="w-[85%] h-[85%] object-contain"
                                        />
                                        <button
                                          onClick={() => openMediaLibrary(i)}
                                          className="absolute inset-0 bg-black/40 text-white opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center cursor-pointer"
                                        >
                                          <Upload size={14} />
                                        </button>
                                      </div>
                                      <div className="flex-1 min-w-0">
                                        <p className="text-[10px] text-gray-500 font-bold truncate">{settings.wawp_user_avatars[i]}</p>
                                      </div>
                                      <AdminButton
                                        onClick={() => openMediaLibrary(i)}
                                        className="h-8 px-3 text-[11px]"
                                      >
                                        Upload
                                      </AdminButton>
                                    </div>
                                  </div>

                                  <div className="flex items-center justify-between pt-2">
                                    <button
                                      onClick={() => {
                                        removeContact(i);
                                        setEditingAgent(null);
                                      }}
                                      className="flex items-center gap-2 text-[12px] font-bold text-red-500 hover:text-red-600 transition-colors"
                                    >
                                      <Trash2 size={14} /> Remove Agent
                                    </button>
                                    <AdminButton
                                      onClick={() => setEditingAgent(null)}
                                      className="bg-emerald-600 hover:bg-emerald-700"
                                    >
                                      <CheckCircle2 className="mr-2 h-4 w-4" /> Done
                                    </AdminButton>
                                  </div>
                                </div>
                              </SettingCard>
                            ) : (
                              <div className="wawp-contact-collapsed flex items-center gap-4 p-5 bg-white border border-[#dcdcde] rounded-[5px] hover:border-[#004449]/20 hover:shadow-md hover:shadow-[#004449]/5 transition-all group">
                                <img
                                  src={settings.wawp_user_avatars[i] || settings.wawp_avatar_url}
                                  className="wawp-summary-avatar w-14 h-14 rounded-[10px] object-cover border border-gray-100"
                                />

                                <div className="wawp-summary-info flex-1 grid grid-cols-1 md:grid-cols-3 gap-2">
                                  <span className="wawp-summary-name flex items-center gap-2 text-[13px] font-bold text-gray-800">
                                    <i className="ri-user-3-line text-[#004449]"></i>
                                    Name: <span className="font-medium text-gray-600">{settings.wawp_user_names[i]}</span>
                                  </span>
                                  <span className="wawp-summary-number flex items-center gap-2 text-[13px] font-bold text-gray-800">
                                    <i className="ri-whatsapp-line text-[#25D366]"></i>
                                    Number: <span className="font-medium text-gray-600">{settings.wawp_whatsapp_numbers[i]}</span>
                                  </span>
                                  <span className="wawp-summary-role flex items-center gap-2 text-[13px] font-bold text-gray-800">
                                    <i className="ri-briefcase-line text-orange-500"></i>
                                    Role: <span className="font-medium text-gray-600">{settings.wawp_user_roles[i]}</span>
                                  </span>
                                </div>

                                <div className="wawp-summary-actions flex items-center gap-2">
                                  <button
                                    type="button"
                                    onClick={() => setEditingAgent(i)}
                                    className="wawp-btn flex items-center gap-2 px-4 py-2 border border-[#dcdcde] rounded-[5px] text-[12px] font-bold text-[#004449] hover:bg-gray-50 transition-all"
                                  >
                                    <Edit2 size={14} /> Edit
                                  </button>
                                  <button
                                    type="button"
                                    onClick={() => removeContact(i)}
                                    className="wawp-btn flex items-center gap-2 px-4 py-2 border border-[#dcdcde] rounded-[5px] text-[12px] font-bold text-red-500 hover:bg-red-50 hover:border-red-100 transition-all"
                                  >
                                    <Trash2 size={14} /> Delete
                                  </button>
                                </div>
                              </div>
                            )}
                          </motion.div>
                        ))}

                        {settings.wawp_whatsapp_numbers.length === 0 && (
                          <div className="p-12 text-center border-2 border-dashed border-gray-200 rounded-[5px] bg-white">
                            <div className="w-12 h-12 bg-gray-50 rounded-full flex items-center justify-center mx-auto mb-4">
                              <Users className="text-gray-300" size={24} />
                            </div>
                            <h3 className="text-sm font-bold text-gray-900">No agents added</h3>
                            <p className="text-xs text-gray-500 mt-1">Add at least one WhatsApp number to show the widget.</p>
                          </div>
                        )}

                      </div>
                    </SettingCard>
                  </div>
                )}

                {/* ─── Social Links Tab ─── */}
                {activeTab === 'social' && (
                  <div className="space-y-8 outline-none border-none p-0">
                    <SettingCard className="p-0 overflow-hidden">
                      <ModernCardHeader
                        title="Social Channels"
                        description="Connect your other social platforms to provide more ways to reach you."
                        icon={Share2}
                        rightAction={
                          <AdminButton
                            onClick={addSocialLink}
                            icon={Plus}
                          >
                            Add Social Link
                          </AdminButton>
                        }
                      />

                      <div className="p-6 md:p-8 space-y-4">
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                          {settings.wawp_social_icons.map((link, i) => (
                            <div key={i} className="flex flex-col gap-4 p-5 bg-gray-50 border border-[#dcdcde] rounded-[5px] group relative">
                              <button
                                onClick={() => removeSocialLink(i)}
                                className="absolute top-4 right-4 p-2 text-gray-400 hover:text-red-500 transition-colors"
                              >
                                <Trash2 size={16} />
                              </button>

                              <div className="space-y-2">
                                <label className="text-[11px] font-black uppercase text-gray-400 tracking-widest leading-none">Icon / Platform</label>
                                <SearchableSelect
                                  options={Object.entries(data?.remix_icons || {}).map(([cls, info]: [string, { label?: string; color?: string }]) => ({
                                    value: cls,
                                    label: info?.label || cls.replace('ri-', '').replace(/-/g, ' '),
                                    icon: <i className={cn(cls, "text-lg")} style={{ color: info?.color }}></i>
                                  }))}
                                  value={link.icon}
                                  onChange={(val) => updateSocialLink(i, 'icon', val)}
                                  className="h-11 bg-white border-slate-200 text-slate-700 font-bold text-[13px] hover:border-[#004449]/30 transition-all rounded-[5px]"
                                />
                              </div>
                              <SettingInput
                                label="Profile Link URL"
                                value={link.link}
                                onChange={(val) => updateSocialLink(i, 'link', val)}
                                placeholder="https://facebook.com/..."
                                icon={Globe}
                                className="bg-white"
                                showEmoji={false}
                              />
                            </div>
                          ))}

                          {settings.wawp_social_icons.length === 0 && (
                            <div className="md:col-span-2 p-12 text-center border-2 border-dashed border-gray-200 rounded-[5px] bg-white">
                              <Share2 className="w-8 h-8 text-gray-300 mx-auto mb-3" />
                              <h3 className="text-sm font-bold text-gray-900">No social links added</h3>
                              <p className="text-xs text-gray-500 mt-1">Add links to your social profiles to show them in the widget.</p>
                            </div>
                          )}
                        </div>
                      </div>
                    </SettingCard>

                    <SettingCard className="p-0 overflow-hidden">
                      <ModernCardHeader
                        title="Display Styles"
                        description="Choose how your social icons should appear in the widget."
                        icon={Palette}
                      />
                      <div className="p-6 md:p-8 space-y-6">
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                          <div className="space-y-3">
                            <label className="text-[12px] font-bold text-gray-700 flex items-center gap-2">
                              <Palette size={14} className="text-[#004449]" /> Icon Shape & Style
                            </label>
                            <div className="grid grid-cols-2 gap-3">
                              {[
                                { id: 'round', label: 'Round White', icon: Circle },
                                { id: 'square', label: 'Square White', icon: Square },
                                { id: 'outline', label: 'Outline', icon: CircleDot },
                                { id: 'brand', label: 'Brand Colors', icon: Palette },
                              ].map((style) => (
                                <button
                                  key={style.id}
                                  onClick={() => updateSetting('wawp_social_button_style', style.id as 'round' | 'square' | 'outline' | 'brand')}
                                  className={`flex flex-col items-center justify-center p-3 rounded-[8px] border-2 transition-all gap-1.5 ${settings.wawp_social_button_style === style.id
                                    ? 'border-[#004449] bg-[#004449]/5 text-[#004449]'
                                    : 'border-gray-100 bg-gray-50 text-gray-500 hover:border-gray-200'
                                    }`}
                                >
                                  <style.icon size={16} />
                                  <span className="text-[10px] font-bold uppercase tracking-wider">{style.label}</span>
                                </button>
                              ))}
                            </div>
                          </div>

                          <div className="space-y-3">
                            <label className="text-[12px] font-bold text-gray-700 flex items-center gap-2">
                              <Layout size={14} className="text-[#004449]" /> Social Layout
                            </label>
                            <div className="grid grid-cols-2 gap-3 h-[calc(100%-27px)]">
                              {[
                                { id: 'vertical', label: 'Vertical (Above)', icon: MousePointer2, desc: 'Text above icons' },
                                { id: 'horizontal', label: 'Horizontal (Inline)', icon: Share2, desc: 'Text before icons' },
                              ].map((layout) => (
                                <button
                                  key={layout.id}
                                  onClick={() => updateSetting('wawp_social_layout', layout.id as 'vertical' | 'horizontal')}
                                  className={`flex flex-col items-center justify-center p-3 rounded-[8px] border-2 transition-all gap-1.5 ${settings.wawp_social_layout === layout.id
                                    ? 'border-[#004449] bg-[#004449]/5 text-[#004449]'
                                    : 'border-gray-100 bg-gray-50 text-gray-500 hover:border-gray-200'
                                    }`}
                                >
                                  <layout.icon size={16} />
                                  <span className="text-[10px] font-bold uppercase tracking-wider">{layout.label}</span>
                                  <span className="text-[9px] opacity-60 font-medium">{layout.desc}</span>
                                </button>
                              ))}
                            </div>
                          </div>
                        </div>

                        <SettingInput
                          label="Social Intro Text"
                          value={settings.wawp_social_intro_text}
                          onChange={(val) => updateSetting('wawp_social_intro_text', val)}
                          placeholder=""
                          icon={Heading}
                          showEmoji={true}
                          showFormatting={true}
                        />
                      </div>
                    </SettingCard>
                  </div>
                )}

                {/* ─── Analytics Tab ─── */}
                {activeTab === 'analytics' && (
                  <div className="space-y-8 outline-none border-none p-0">
                    <FeatSection
                      title="Engagement Analytics"
                      description="Insights into how visitors are interacting with your chat widget."
                      icon={BarChart3}
                      gridCols="sm:grid-cols-4"
                    >
                      <SnapshotStat
                        value={(stats.total_views || 0).toString()}
                        label="Total Views"
                        sub="Total widget impressions across your site."
                        badge="Views"
                        percent={100}
                        barColor="bg-blue-500"
                        icon={Eye}
                      />
                      <SnapshotStat
                        value={(stats.total_clicks || 0).toString()}
                        label="Widget Opens"
                        sub="Number of times visitors clicked to see agents."
                        badge="Clicks"
                        percent={((stats.total_clicks || 0) / (stats.total_views || 1)) * 100}
                        barColor="bg-emerald-500"
                        icon={MousePointer2}
                      />
                      <SnapshotStat
                        value={(stats.open_whatsapp || 0).toString()}
                        label="WhatsApp Chats"
                        sub="Direct redirections to the WhatsApp API."
                        badge="Leads"
                        percent={((stats.open_whatsapp || 0) / (stats.total_clicks || 1)) * 100}
                        barColor="bg-orange-500"
                        icon={TrendingUp}
                      />
                      <SnapshotStat
                        value={Object.keys(stats.social_clicks || {}).length.toString()}
                        label="Social Engagement"
                        sub="Total clicks on external social link icons."
                        badge="Social"
                        percent={100}
                        barColor="bg-purple-500"
                        icon={Share2}
                      />
                    </FeatSection>

                    <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
                      <SettingCard className="lg:col-span-2 p-0 overflow-hidden">
                        <ModernCardHeader
                          title="Interaction Activity"
                          description="Peak engagement times and days."
                          icon={Clock}
                        />
                        <div className="p-6 md:p-8 space-y-8">
                          <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                            <div className="space-y-4">
                              <h4 className="text-[11px] font-black text-gray-400 uppercase tracking-widest">Active Days</h4>
                              <div className="space-y-2">
                                {['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'].map(day => {
                                  const val = (stats.day_stats?.[day] || 0) as number;
                                  const max = Math.max(...Object.values(stats.day_stats || {}).map(v => Number(v)), 1);
                                  const pct = (val / max) * 100;
                                  return (
                                    <div key={day} className="flex items-center gap-3">
                                      <span className="text-[10px] font-bold text-gray-500 w-16">{day.substring(0, 3)}</span>
                                      <div className="flex-1 h-2 bg-gray-100 rounded-full overflow-hidden">
                                        <div className="h-full bg-emerald-500 transition-all duration-1000" style={{ width: `${pct}%` }} />
                                      </div>
                                      <span className="text-[10px] font-black text-gray-900 w-8 text-right">{val}</span>
                                    </div>
                                  );
                                })}
                              </div>
                            </div>

                            <div className="space-y-4">
                              <h4 className="text-[11px] font-black text-gray-400 uppercase tracking-widest">Hourly Trends</h4>
                              <div className="h-[140px] flex items-end gap-1 px-2">
                                {Array.from({ length: 24 }).map((_, h) => {
                                  const hour = h.toString().padStart(2, '0');
                                  const val = (stats.hour_stats?.[hour] || 0) as number;
                                  const max = Math.max(...Object.values(stats.hour_stats || {}).map(v => Number(v)), 1);
                                  const height = (val / max) * 100;
                                  return (
                                    <div key={h} className="flex-1 group relative">
                                      <div
                                        className="w-full bg-blue-500/20 group-hover:bg-blue-500 transition-all rounded-t-[2px]"
                                        style={{ height: `${height}%` }}
                                      />
                                      <div className="absolute bottom-full left-1/2 -translate-x-1/2 mb-1 hidden group-hover:block bg-gray-900 text-white text-[8px] px-1 rounded">
                                        {val}
                                      </div>
                                    </div>
                                  );
                                })}
                              </div>
                              <div className="flex justify-between px-2 text-[8px] font-black text-gray-400 uppercase tracking-widest">
                                <span>00:00</span>
                                <span>12:00</span>
                                <span>23:59</span>
                              </div>
                            </div>
                          </div>

                          <div className="pt-6 border-t border-gray-100">
                            <h4 className="text-[11px] font-black text-gray-400 uppercase tracking-widest mb-4">Top Performing Pages</h4>
                            <div className="space-y-2">
                              {Object.entries(stats.page_stats || {}).slice(0, 5).sort(([, a], [, b]) => (b.chat_clicks || 0) - (a.chat_clicks || 0)).map(([pid, pstats]) => {
                                const page = (data?.pages || []).find((p) => p.ID.toString() === pid);
                                return (
                                  <div key={pid} className="flex items-center justify-between p-3 bg-gray-50 rounded-[5px] border border-gray-100">
                                    <span className="text-[12px] font-bold text-gray-700 truncate max-w-[200px]">{page?.post_title || `Page ID: ${pid}`}</span>
                                    <div className="flex items-center gap-4">
                                      <div className="text-right">
                                        <p className="text-[8px] font-black text-gray-400 uppercase">Clicks</p>
                                        <p className="text-[11px] font-black text-gray-900">{pstats.chat_clicks || 0}</p>
                                      </div>
                                      <div className="text-right">
                                        <p className="text-[8px] font-black text-gray-400 uppercase">WA Open</p>
                                        <p className="text-[11px] font-black text-emerald-600">{pstats.open_whatsapp || 0}</p>
                                      </div>
                                    </div>
                                  </div>
                                );
                              })}
                              {Object.keys(stats.page_stats || {}).length === 0 && (
                                <p className="text-center py-4 text-[11px] text-gray-400 font-bold uppercase">No page-specific data yet</p>
                              )}
                            </div>
                          </div>

                          <div className="pt-6 border-t border-gray-100">
                            <h4 className="text-[11px] font-black text-gray-400 uppercase tracking-widest mb-4">Top Support Agents</h4>
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                              {Object.entries(stats.contact_stats || {}).slice(0, 4).sort(([, a], [, b]) => (b.chat_clicks || 0) - (a.chat_clicks || 0)).map(([phone, cstats]) => (
                                <div key={phone} className="flex items-center gap-4 p-4 bg-white border border-gray-100 rounded-[5px] shadow-sm">
                                  <div className="w-10 h-10 rounded-full bg-emerald-50 text-emerald-600 flex items-center justify-center font-bold text-[12px] border border-emerald-100">
                                    {cstats.name?.substring(0, 2).toUpperCase() || '??'}
                                  </div>
                                  <div className="flex-1 min-w-0">
                                    <p className="text-[12px] font-bold text-gray-800 truncate">{cstats.name}</p>
                                    <p className="text-[10px] text-gray-400 font-medium">+{phone}</p>
                                  </div>
                                  <div className="text-right">
                                    <p className="text-[14px] font-black text-emerald-600">{cstats.open_whatsapp || 0}</p>
                                    <p className="text-[8px] font-black text-gray-400 uppercase">Leads</p>
                                  </div>
                                </div>
                              ))}
                              {Object.keys(stats.contact_stats || {}).length === 0 && (
                                <p className="md:col-span-2 text-center py-4 text-[11px] text-gray-400 font-bold uppercase">No agent activity recorded yet</p>
                              )}
                            </div>
                          </div>
                        </div>
                      </SettingCard>

                      <SettingCard className="p-0 overflow-hidden">
                        <ModernCardHeader
                          title="Device Distribution"
                          description="User traffic split by device type."
                          icon={Monitor}
                        />
                        <div className="p-6 md:p-8 space-y-6">
                          {(() => {
                            const deviceStats = stats.device_stats || {};
                            const total = Object.values(deviceStats).reduce((acc: number, curr: number) => acc + curr, 0) || 1;
                            return [
                              { label: 'Desktop', key: 'Desktop', icon: Monitor, color: 'bg-blue-500' },
                              { label: 'Mobile', key: 'Mobile', icon: Smartphone, color: 'bg-emerald-500' },
                              { label: 'Tablet', key: 'Tablet', icon: Layout, color: 'bg-orange-500' }
                            ].map((device, i) => {
                              const val = (deviceStats[device.key] || 0) as number;
                              const pct = Math.round((val / total) * 100);
                              return (
                                <div key={i} className="space-y-2">
                                  <div className="flex items-center justify-between">
                                    <div className="flex items-center gap-2">
                                      <device.icon size={14} className="text-gray-400" />
                                      <span className="text-[12px] font-bold text-gray-700">{device.label}</span>
                                    </div>
                                    <span className="text-[12px] font-black text-gray-900">{pct}%</span>
                                  </div>
                                  <div className="w-full h-1.5 bg-gray-100 rounded-full overflow-hidden">
                                    <div className={cn("h-full rounded-full transition-all duration-1000", device.color)} style={{ width: `${pct}%` }} />
                                  </div>
                                </div>
                              );
                            });
                          })()}
                        </div>
                      </SettingCard>
                    </div>
                  </div>
                )}

                {/* ─── Appearance Tab ─── */}
                {activeTab === 'settings' && (
                  <div className="space-y-8 outline-none border-none p-0">
                    <SettingCard className="p-0 overflow-hidden">
                      <ModernCardHeader
                        title="Button Appearance"
                        description="Customize the look and feel of your floating WhatsApp button."
                        icon={Palette}
                      />

                      <div className="p-6 md:p-8">
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                          <div className="space-y-4">
                            <label className="text-[11px] font-black uppercase text-gray-400 tracking-widest">Button Icon</label>
                            <SearchableSelect
                              options={Object.entries(data?.chat_icons || {}).map(([cls, label]) => ({
                                value: cls,
                                label: label ? String(label) : cls,
                                icon: <i className={cn(cls, "mr-2")}></i>
                              }))}
                              value={settings.wawp_whatsapp_icon_class}
                              onChange={(val) => updateSetting('wawp_whatsapp_icon_class', val)}
                              className="h-11 bg-white border-slate-200 text-slate-700 font-bold text-[13px] hover:border-[#004449]/30 transition-all rounded-[5px]"
                            />
                          </div>

                          <div className="space-y-4">
                            <label className="text-[11px] font-black uppercase text-gray-400 tracking-widest">Button Position</label>
                            <div className="flex p-1 bg-gray-100 rounded-[5px] border border-[#dcdcde]">
                              <button
                                onClick={() => updateSetting('wawp_button_position', 'left')}
                                className={cn(
                                  "flex-1 py-1.5 text-[12px] font-bold rounded-[3px] transition-all",
                                  settings.wawp_button_position === 'left' ? "bg-white text-emerald-600 shadow-sm" : "text-gray-500 hover:text-gray-700 hover:bg-white/50"
                                )}
                              >
                                Left Side
                              </button>
                              <button
                                onClick={() => updateSetting('wawp_button_position', 'right')}
                                className={cn(
                                  "flex-1 py-1.5 text-[12px] font-bold rounded-[3px] transition-all",
                                  settings.wawp_button_position === 'right' ? "bg-white text-emerald-600 shadow-sm" : "text-gray-500 hover:text-gray-700 hover:bg-white/50"
                                )}
                              >
                                Right Side
                              </button>
                            </div>
                          </div>

                          <div className="space-y-2">
                            <div className="flex items-center justify-between">
                              <label className="text-[11px] font-black uppercase text-gray-400 tracking-widest">Button Size ({settings.wawp_button_size}px)</label>
                            </div>
                            <input
                              type="range" min="40" max="100" step="1"
                              value={settings.wawp_button_size}
                              onChange={(e) => updateSetting('wawp_button_size', e.target.value)}
                              className="w-full h-1.5 bg-gray-100 rounded-lg appearance-none cursor-pointer accent-[#004449]"
                            />
                          </div>

                          <div className="space-y-2">
                            <div className="flex items-center justify-between">
                              <label className="text-[11px] font-black uppercase text-gray-400 tracking-widest">Corner Radius ({settings.wawp_corner_radius}px)</label>
                            </div>
                            <input
                              type="range" min="0" max="50" step="1"
                              value={settings.wawp_corner_radius}
                              onChange={(e) => updateSetting('wawp_corner_radius', e.target.value)}
                              className="w-full h-1.5 bg-gray-100 rounded-lg appearance-none cursor-pointer accent-[#004449]"
                            />
                          </div>

                          <div className="space-y-2">
                            <div className="flex items-center justify-between">
                              <label className="text-[11px] font-black uppercase text-gray-400 tracking-widest">Vertical Offset ({settings.wawp_button_bottom_offset}px)</label>
                            </div>
                            <input
                              type="range" min="0" max="200" step="1"
                              value={settings.wawp_button_bottom_offset}
                              onChange={(e) => updateSetting('wawp_button_bottom_offset', e.target.value)}
                              className="w-full h-1.5 bg-gray-100 rounded-lg appearance-none cursor-pointer accent-[#004449]"
                            />
                          </div>

                          <div className="space-y-4">
                            <ColorInput
                              label="Background Color"
                              value={settings.wawp_button_bg_color}
                              onChange={(val) => updateSetting('wawp_button_bg_color', val)}
                            />
                          </div>

                          <div className="space-y-4">
                            <ColorInput
                              label="Icon Color"
                              value={settings.wawp_icon_color}
                              onChange={(val) => updateSetting('wawp_icon_color', val)}
                            />
                          </div>
                        </div>

                        <Separator className="my-8" />

                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                          <CompactSettingCard
                            icon={Monitor}
                            title="Show on Desktop"
                            description="Show widget for computer visitors"
                            checked={settings.wawp_display_desktop === 'yes'}
                            onChange={(checked: boolean) => updateSetting('wawp_display_desktop', checked ? 'yes' : 'no')}
                            className="bg-gray-50/30"
                          />
                          <CompactSettingCard
                            icon={Smartphone}
                            title="Show on Mobile"
                            description="Show widget for mobile visitors"
                            checked={settings.wawp_display_mobile === 'yes'}
                            onChange={(checked: boolean) => updateSetting('wawp_display_mobile', checked ? 'yes' : 'no')}
                            className="bg-gray-50/30"
                          />
                        </div>
                      </div>
                    </SettingCard>
                  </div>
                )}

                {/* ─── Conditions Tab ─── */}
                {activeTab === 'conditions' && (
                  <div className="space-y-8 outline-none border-none p-0">
                    <CompactSettingCard
                      icon={Eye}
                      title="Visibility Rules"
                      description="Control exactly which pages your chat button appears on."
                      checked={settings.wawp_trigger_on_all_pages === 'yes'}
                      onChange={(checked: boolean) => updateSetting('wawp_trigger_on_all_pages', checked ? 'yes' : 'no')}
                      statusMessage={settings.wawp_trigger_on_all_pages === 'yes' ? "The widget is currently active on all public pages." : `Hidden on ${settings.wawp_page_conditions.length} restricted page(s).`}
                      statusType={settings.wawp_trigger_on_all_pages === 'yes' ? 'active' : 'warning'}
                    >
                      {settings.wawp_trigger_on_all_pages === 'no' && (
                        <motion.div
                          initial={{ opacity: 0, height: 0 }}
                          animate={{ opacity: 1, height: 'auto' }}
                          className="space-y-4"
                        >
                          <MultiSelectTagify
                            label="Exclusion List"
                            placeholder="Search and select pages to hide widget on..."
                            options={(data?.pages || []).map((page: { ID: number, post_title: string }) => ({
                              value: page.ID.toString(),
                              label: page.post_title
                            }))}
                            selected={(settings.wawp_page_conditions || []).map((id: string | number) => id.toString())}
                            onChange={(next) => updateSetting('wawp_page_conditions', next.map(id => parseInt(id)))}
                          />

                          <div className="flex items-center gap-3 p-4 bg-orange-50 border border-orange-100 rounded-[5px]">
                            <AlertCircle className="w-4 h-4 text-orange-600" />
                            <p className="text-[11px] text-orange-900 font-bold uppercase tracking-tight">
                              Visitors won't see the chat widget on the selected pages above.
                            </p>
                          </div>
                        </motion.div>
                      )}
                    </CompactSettingCard>

                  </div>
                )}
              </motion.div>
            </AnimatePresence>
          </div>
        </div>

        {/* ─── Floating Live Preview (Memoized) ─── */}
        <FloatingPreview 
          settings={settings}
          data={data}
          rootData={rootData}
          isWindowOpen={isWindowOpen}
          setIsWindowOpen={setIsWindowOpen}
          activeNumbers={activeNumbers}
        />
      </div>
    </SettingsLayout>
  );
}
