import { useState, useEffect } from 'react'
import type { DashboardData } from './types';
import { 
  MessageCircle, 
  Share2, 
  BarChart3, 
  Plus, 
  Trash2, 
  Edit2, 
  Check, 
  Upload, 
  TrendingUp,
  Eye,
  Users,
  Smartphone,
  Clock,
  Globe,
  Monitor,
  AlertCircle,
  Layout,
  Palette,
  Save,
  CheckCircle2,
  Shield,
  MousePointer2
} from 'lucide-react'
import { PhoneInput } from './components/ui/PhoneInput'
import { Switch } from './components/ui/switch'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './components/ui/select'
import { Separator } from './components/ui/separator'
import { Badge } from './components/ui/badge'
import { toast } from "sonner"
import { cn } from "@/lib/utils"
import { motion, AnimatePresence } from 'framer-motion'
import { 
  SettingCard, 
  FlatTabs, 
  SettingInput,
  BannerCard,
  SettingsLayout, 
  SettingsHeader,
  PrimaryButton,
  ModernCardHeader,
  SnapshotStat,
  FeatSection
} from './components/ui/settings-ui';

// ─── 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_enable_powered_by: 'yes' | 'no';
  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';
  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_display_desktop: 'yes' | 'no';
  wawp_display_mobile: 'yes' | 'no';
  wawp_trigger_on_all_pages: 'yes' | 'no';
  wawp_page_conditions: (string | number)[];
}

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 = [];
    return s;
  });
  const [activeTab, setActiveTab] = useState('whatsapp');
  const [isSaving, setIsSaving] = useState(false);
  const [saveStatus, setSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle');

  // Sync settings when data changes
  useEffect(() => {
    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 = [];
      setSettings(s);
    }
  }, [data]);

  const dStat = rootData?.domainStatus || (window as unknown as { wawpDashboardData?: { domainStatus?: string } }).wawpDashboardData?.domainStatus;
  const cSec  = rootData?.global?.section || (window as unknown as { wawpDashboardData?: { currentSection?: string } }).wawpDashboardData?.currentSection;
  if (dStat && dStat !== 'active' && cSec !== 'connector') return null;

  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) {
      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 },
  ];

  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."
        >
          {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>
          )}
          <PrimaryButton
            onClick={handleSave}
            loading={isSaving}
            icon={Save}
            className="h-10 px-10"
          >
            {isSaving ? 'Saving...' : 'Deploy Changes'}
          </PrimaryButton>
        </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">
                  <BannerCard 
                    title="WhatsApp Widget Status"
                    description="General toggle to display or hide the chat widget across your site."
                    badge={settings.wawp_enable_button === 'yes' ? 'Enabled' : 'Disabled'}
                    color={settings.wawp_enable_button === 'yes' ? 'emerald' : 'orange'}
                    icon={MessageCircle}
                  >
                    <div className="flex items-center justify-between gap-4 mt-2">
                      <p className="text-[12px] opacity-70 font-medium">
                        {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."}
                      </p>
                      <Switch 
                        checked={settings.wawp_enable_button === 'yes'}
                        onCheckedChange={(checked) => updateSetting('wawp_enable_button', checked ? 'yes' : 'no')}
                      />
                    </div>
                  </BannerCard>

                  <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="e.g. Chat with us on WhatsApp"
                        />
                        <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"
                        />
                      </div>

                      <SettingInput 
                        label="Welcome Message"
                        value={settings.wawp_welcome_message}
                        onChange={(val) => updateSetting('wawp_welcome_message', val)}
                        placeholder="Hi there! How can we help you today?"
                      />

                      <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">
                          <img 
                            src={settings.wawp_avatar_url || 'https://via.placeholder.com/150'} 
                            className="w-full h-full object-cover" 
                          />
                          <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={
                        <PrimaryButton 
                          onClick={addContact}
                          icon={Plus}
                          className="bg-emerald-600 hover:bg-emerald-700"
                        >
                          Add New Agent
                        </PrimaryButton>
                      }
                    />

                    <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}
                      >
                        <SettingCard className="group relative overflow-visible">
                          <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">
                              <img src={settings.wawp_user_avatars[i]} className="w-full h-full object-cover" />
                              <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-gray-50/50"
                              />
                              <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-gray-50/50 transition-all focus-within:bg-white"
                                  placeholder="+1234567890"
                                  hideMessage
                                />
                              </div>
                              <SettingInput 
                                label="Role / Title"
                                value={settings.wawp_user_roles[i]}
                                onChange={(val) => updateContact(i, 'role', val)}
                                className="bg-gray-50/50"
                                placeholder="e.g. Sales"
                              />
                            </div>
                            
                            <div className="flex flex-col gap-2">
                              <button 
                                onClick={() => removeContact(i)}
                                className="p-2 text-gray-400 hover:text-red-500 transition-colors"
                              >
                                <Trash2 size={16} />
                              </button>
                            </div>
                          </div>
                          
                          <div className="mt-4 pt-4 border-t border-gray-100">
                            <SettingInput 
                              label="Pre-filled Message"
                              value={settings.wawp_whatsapp_messages[i]}
                              onChange={(val) => updateContact(i, 'message', val)}
                              className="bg-gray-50/50"
                              placeholder="I have a question about..."
                            />
                          </div>
                        </SettingCard>
                      </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 className="flex items-center justify-between p-6 bg-white border border-[#dcdcde] rounded-[5px]">
                      <div className="space-y-1">
                        <h4 className="text-sm font-bold text-gray-900">Show "Support WAWP" Branding</h4>
                        <p className="text-xs text-gray-500 font-medium">We'd love if you kept this visible to support us.</p>
                      </div>
                      <Switch 
                        checked={settings.wawp_enable_powered_by === 'yes'}
                        onCheckedChange={(checked) => updateSetting('wawp_enable_powered_by', checked ? 'yes' : 'no')}
                      />
                    </div>
                  </div>
                  </SettingCard>
                </div>
                )}

                {/* ─── Social Links Tab ─── */}
                {activeTab === 'social' && (
                <div className="space-y-8 outline-none border-none p-0">
                  <BannerCard 
                    title="Social Network Integration"
                    badge="Multi-Channel"
                    color="blue"
                    icon={Share2}
                  >
                    <p className="text-[12px] text-blue-900/70 font-medium mt-1">Add other platforms like Messenger, Instagram, or Telegram to expand your reach beyond WhatsApp.</p>
                  </BannerCard>

                  <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={
                        <PrimaryButton 
                          onClick={addSocialLink}
                          icon={Plus}
                        >
                          Add Social Link
                        </PrimaryButton>
                      }
                    />

                    <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>
                              <Select 
                                value={link.icon} 
                                onValueChange={(val) => updateSocialLink(i, 'icon', val)}
                              >
                                <SelectTrigger className="bg-white border-[#dcdcde] h-11 text-[13px] font-medium">
                                  <SelectValue />
                                </SelectTrigger>
                                <SelectContent>
                                  {Object.entries(data?.remix_icons || {}).map(([cls, info]: [string, { name: string, color: string }]) => (
                                    <SelectItem key={cls} value={cls}>
                                      <div className="flex items-center gap-2">
                                        <i className={cls} style={{ color: info.color }}></i>
                                        {info.name}
                                      </div>
                                    </SelectItem>
                                  ))}
                                </SelectContent>
                              </Select>
                            </div>
                            <SettingInput 
                              label="Profile Link URL"
                              value={link.link}
                              onChange={(val) => updateSocialLink(i, 'link', val)}
                              placeholder="https://facebook.com/..."
                              className="bg-white"
                            />
                          </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="Introduction Text" 
                      description="This text appears above your social links in the chat window."
                      icon={Edit2}
                    />
                    <div className="p-6 md:p-8">
                      <SettingInput 
                        label="Social Intro Text"
                        value={settings.wawp_social_intro_text}
                        onChange={(val) => updateSetting('wawp_social_intro_text', val)}
                        placeholder="Reach us on other platforms:"
                      />
                    </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="Interactions"
                      sub="Number of times users clicked the chat button."
                      badge="Clicks"
                      percent={((stats.total_clicks || 0) / (stats.total_views || 1)) * 100}
                      barColor="bg-emerald-500"
                      icon={MousePointer2}
                    />
                    <SnapshotStat 
                      value={`${(( (stats.total_clicks || 0) / (stats.total_views || 1)) * 100).toFixed(1)}%`}
                      label="Engagement Rate"
                      sub="Conversion rate from views to interactions."
                      badge="Rate"
                      percent={((stats.total_clicks || 0) / (stats.total_views || 1)) * 100}
                      barColor="bg-orange-500"
                      icon={TrendingUp}
                    />
                    <SnapshotStat 
                      value={settings.wawp_whatsapp_numbers.length.toString()}
                      label="Support Agents"
                      sub="Active team members available via chat."
                      badge="Staff"
                      percent={100}
                      barColor="bg-purple-500"
                      icon={Users}
                    />
                  </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 Trends" 
                        description="Last 30 days of chat interaction activity."
                        icon={BarChart3}
                      />
                      <div className="p-6 md:p-8">
                        <div className="h-[300px] flex items-center justify-center bg-gray-50 border border-dashed border-[#dcdcde] rounded-[5px]">
                         <div className="text-center">
                            <TrendingUp size={32} className="text-gray-300 mx-auto mb-3" />
                            <p className="text-[11px] text-gray-400 font-bold uppercase tracking-widest">Heatmaps and detailed reports coming soon</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">
                         {[
                           { label: 'Desktop', value: '45%', icon: Monitor, color: 'bg-blue-500' },
                           { label: 'Mobile', value: '52%', icon: Smartphone, color: 'bg-emerald-500' },
                           { label: 'Tablet', value: '3%', icon: Layout, color: 'bg-orange-500' }
                         ].map((device, i) => (
                           <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">{device.value}</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: device.value }} />
                              </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>
                        <Select 
                          value={settings.wawp_whatsapp_icon_class} 
                          onValueChange={(val) => updateSetting('wawp_whatsapp_icon_class', val)}
                        >
                          <SelectTrigger className="bg-white border-[#dcdcde] h-11">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            {Object.entries(data?.chat_icons || {}).map(([cls, label]) => (
                               <SelectItem key={cls} value={cls}>
                                <div className="flex items-center gap-2">
                                  <i className={cls}></i>
                                  {String(label)}
                                </div>
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </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-4">
                        <label className="text-[11px] font-black uppercase text-gray-400 tracking-widest">Background Color</label>
                        <div className="flex items-center gap-4">
                          <input 
                            type="text" 
                            value={settings.wawp_button_bg_color} 
                            onChange={(e) => updateSetting('wawp_button_bg_color', e.target.value)}
                            className="bg-white border border-[#dcdcde] flex-1 px-4 py-2.5 rounded-[5px] text-sm font-medium focus:ring-1 focus:ring-emerald-500 transition-all outline-none"
                          />
                          <div 
                            className="w-10 h-10 rounded-[5px] border border-[#dcdcde] shadow-sm flex-shrink-0 cursor-pointer transition-transform hover:scale-110" 
                            style={{ background: settings.wawp_button_bg_color }}
                          />
                        </div>
                      </div>

                      <div className="space-y-4">
                        <label className="text-[11px] font-black uppercase text-gray-400 tracking-widest">Icon Color</label>
                        <div className="flex items-center gap-4">
                          <input 
                            type="text" 
                            value={settings.wawp_icon_color} 
                            onChange={(e) => updateSetting('wawp_icon_color', e.target.value)}
                            className="bg-white border border-[#dcdcde] flex-1 px-4 py-2.5 rounded-[5px] text-sm font-medium focus:ring-1 focus:ring-emerald-500 transition-all outline-none"
                          />
                           <div 
                            className="w-10 h-10 rounded-[5px] border border-[#dcdcde] shadow-sm flex-shrink-0 cursor-pointer transition-transform hover:scale-110" 
                            style={{ backgroundColor: settings.wawp_icon_color }}
                          />
                        </div>
                      </div>
                    </div>

                    <Separator className="my-8" />

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                       <div className="flex items-center justify-between p-4 bg-gray-50 border border-[#dcdcde] rounded-[5px]">
                          <div className="space-y-0.5">
                            <span className="block text-[13px] font-bold text-slate-900">Show on Desktop</span>
                            <span className="block text-[10px] text-slate-400 font-bold uppercase tracking-tight">Show widget for computer visitors</span>
                          </div>
                          <Switch 
                            checked={settings.wawp_display_desktop === 'yes'}
                            onCheckedChange={(checked) => updateSetting('wawp_display_desktop', checked ? 'yes' : 'no')}
                          />
                       </div>
                       <div className="flex items-center justify-between p-4 bg-gray-50 border border-[#dcdcde] rounded-[5px]">
                          <div className="space-y-0.5">
                            <span className="block text-[13px] font-bold text-slate-900">Show on Mobile</span>
                            <span className="block text-[10px] text-slate-400 font-bold uppercase tracking-tight">Show widget for mobile visitors</span>
                          </div>
                          <Switch 
                            checked={settings.wawp_display_mobile === 'yes'}
                            onCheckedChange={(checked) => updateSetting('wawp_display_mobile', checked ? 'yes' : 'no')}
                          />
                       </div>
                    </div>
                    </div>
                  </SettingCard>
                </div>
                )}

                {/* ─── Conditions Tab ─── */}
                {activeTab === 'conditions' && (
                <div className="space-y-8 outline-none border-none p-0">
                  <SettingCard className="p-0 overflow-hidden">
                    <ModernCardHeader 
                      title="Visibility Rules" 
                      description="Control exactly which pages your chat button appears on."
                      icon={Globe}
                    />

                    <div className="p-6 md:p-8 space-y-6">
                      <div className="flex items-center justify-between p-5 bg-white border border-[#dcdcde] rounded-[5px] transition-all hover:bg-gray-50 shadow-sm">
                        <div className="space-y-1">
                          <h4 className="text-[14px] font-bold text-gray-900">Show on All Pages</h4>
                          <p className="text-[12px] text-gray-500 font-medium">Automatically display the widget on every public page of your site.</p>
                        </div>
                        <Switch 
                          checked={settings.wawp_trigger_on_all_pages === 'yes'}
                          onCheckedChange={(checked) => updateSetting('wawp_trigger_on_all_pages', checked ? 'yes' : 'no')}
                        />
                      </div>

                      {settings.wawp_trigger_on_all_pages === 'no' && (
                        <motion.div 
                          initial={{ opacity: 0, height: 0 }}
                          animate={{ opacity: 1, height: 'auto' }}
                          className="space-y-4"
                        >
                           <label className="text-[11px] font-black uppercase text-gray-400 tracking-widest pl-1">Selected Restricted Pages</label>
                           <div className="grid grid-cols-1 md:grid-cols-2 gap-3 max-h-[400px] overflow-y-auto p-4 bg-white border border-[#dcdcde] rounded-[5px]">
                            {(data?.pages || []).map((page: { ID: number, post_title: string }) => (
                              <div 
                                key={page.ID} 
                                onClick={() => {
                                  const next = [...settings.wawp_page_conditions];
                                  if (next.includes(page.ID)) {
                                    const i = next.indexOf(page.ID);
                                    next.splice(i, 1);
                                  } else {
                                    next.push(page.ID);
                                  }
                                  updateSetting('wawp_page_conditions', next);
                                }}
                                className={cn(
                                  "flex items-center gap-3 p-3 rounded-[5px] border cursor-pointer transition-all",
                                  settings.wawp_page_conditions.includes(page.ID) ? "border-emerald-200 bg-emerald-50/30" : "border-gray-100 bg-gray-50/30 hover:bg-white"
                                )}
                              >
                                <div className={cn(
                                  "w-5 h-5 rounded-[3px] flex items-center justify-center border transition-all",
                                  settings.wawp_page_conditions.includes(page.ID) ? "bg-emerald-500 border-emerald-500 text-white" : "bg-white border-gray-200"
                                )}>
                                  {settings.wawp_page_conditions.includes(page.ID) && <Check className="w-3.5 h-3.5" />}
                                </div>
                                <span className={cn(
                                  "text-xs font-bold truncate",
                                  settings.wawp_page_conditions.includes(page.ID) ? "text-emerald-700" : "text-gray-600"
                                )}>
                                  {page.post_title}
                                </span>
                              </div>
                            ))}
                          </div>
                          
                          <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">
                               Widget will be hidden on {settings.wawp_page_conditions.length} restricted page(s).
                            </p>
                          </div>
                        </motion.div>
                      )}
                    </div>
                  </SettingCard>

                  <BannerCard 
                    title="Domain Restriction"
                    badge="Advanced"
                    color="blue"
                    icon={Shield}
                  >
                    <p className="text-[12px] text-blue-900/70 font-medium mt-1">To use this widget on other domains, you'll need to upgrade to a Multi-Domain license.</p>
                  </BannerCard>
                </div>
                )}
             </motion.div>
          </AnimatePresence>
        </div>
      </div>

      {/* ─── Live Preview Sidebar ─── */}
      <aside className="w-full lg:w-[480px] bg-white border-l border-[#dcdcde] p-8 lg:sticky lg:top-0 h-screen overflow-y-auto hidden xl:flex flex-col">
          <div className="flex items-center justify-between mb-8">
            <h2 className="text-[18px] font-black text-slate-800 flex items-center gap-3 uppercase tracking-tighter">
              <div className="w-10 h-10 bg-emerald-50 text-emerald-600 rounded-[5px] flex items-center justify-center border border-emerald-100">
                <Eye size={20} />
              </div>
              Live Preview
            </h2>
            <Badge variant="outline" className="text-[10px] font-black uppercase tracking-widest bg-emerald-50 border-emerald-100 text-emerald-600/70">Visual Studio</Badge>
          </div>

          <div className="flex-1 rounded-[10px] bg-gray-50 border border-[#dcdcde] p-8 relative min-h-[600px] flex flex-col items-center justify-center overflow-hidden">
             <div className="absolute top-0 inset-x-0 h-1 mt-0 bg-emerald-500/20" />
             <div className="absolute top-4 left-1/2 -translate-x-1/2 w-24 h-6 bg-slate-200/50 rounded-full flex items-center justify-center gap-1.5 px-2">
                 <div className="w-1.5 h-1.5 rounded-full bg-slate-400" />
                 <div className="w-1.5 h-1.5 rounded-full bg-slate-400" />
                 <div className="w-1.5 h-1.5 rounded-full bg-slate-300" />
             </div>

             {/* ─── Mockup Chat Card ─── */}
             <motion.div 
               layout
               className="w-full max-w-[310px] bg-white rounded-[10px] overflow-hidden shadow-[0_20px_60px_-15px_rgba(0,0,0,0.1)] border border-[#dcdcde]"
               style={{ 
                 opacity: settings.wawp_enable_button === 'yes' ? 1 : 0.4 ,
                 filter: settings.wawp_enable_button === 'yes' ? 'none' : 'grayscale(1)'
               }}
             >
                <div 
                  className="p-5 text-white flex items-center gap-4 relative overflow-hidden"
                  style={{ background: settings.wawp_button_bg_color }}
                >
                  <div className="w-12 h-12 rounded-full overflow-hidden bg-white/20 border border-white/30 flex-shrink-0 relative">
                    <img src={settings.wawp_avatar_url} className="w-full h-full object-cover" />
                    <div className="absolute bottom-0 right-0 w-3.5 h-3.5 bg-emerald-400 border-2 border-emerald-800 rounded-full" />
                  </div>
                  <div className="z-10">
                    <h3 className="font-black text-[13px] leading-tight flex items-center gap-2">
                      {settings.wawp_whatsapp_header}
                    </h3>
                    <p className="text-[9px] opacity-80 font-black flex items-center gap-1.5 mt-0.5 uppercase tracking-widest">
                       <Clock size={10} /> {settings.wawp_reply_time_text}
                    </p>
                  </div>
                  <div className="absolute -right-4 -top-4 w-24 h-24 bg-white/10 rounded-full blur-2xl" />
                </div>

                <div className="p-4 bg-gray-50/30">
                   <div className="bg-white p-3 rounded-[5px] border border-[#dcdcde] relative shadow-sm">
                      <p className="text-[12px] text-gray-700 leading-normal font-medium">{settings.wawp_welcome_message}</p>
                      <div className="absolute -left-1 top-2 w-2 h-2 bg-white rotate-45 border-l border-b border-[#dcdcde]" />
                   </div>
                </div>

                <div className="p-4 pt-0 bg-gray-50/30 space-y-2">
                  <p className="text-[9px] font-black uppercase text-gray-400 tracking-widest mb-1 px-1">Active Agents</p>
                  {settings.wawp_whatsapp_numbers.map((_, i) => (
                    <div key={i} className="flex items-center gap-3 p-2 bg-white rounded-[5px] border border-[#dcdcde] hover:border-emerald-300 transition-all cursor-pointer group shadow-sm">
                       <div className="w-9 h-9 rounded-full overflow-hidden bg-white border border-gray-100 flex-shrink-0">
                          <img src={settings.wawp_user_avatars[i]} className="w-full h-full object-cover" />
                       </div>
                       <div className="flex-1 min-w-0">
                          <div className="flex items-center justify-between">
                            <span className="text-[11px] font-black text-gray-800 truncate">{settings.wawp_user_names[i]}</span>
                          </div>
                          <p className="text-[10px] text-gray-400 font-bold uppercase tracking-tight">{settings.wawp_user_roles[i]}</p>
                       </div>
                       <MessageCircle size={14} className="text-emerald-500 opacity-0 group-hover:opacity-100 transition-opacity" />
                    </div>
                  ))}
                </div>

                {settings.wawp_social_icons.length > 0 && (
                   <div className="px-4 py-3 bg-white border-t border-[#dcdcde] space-y-3">
                      <p className="text-[9px] font-black uppercase text-gray-400 tracking-widest text-center">{settings.wawp_social_intro_text}</p>
                      <div className="flex flex-wrap gap-2 justify-center">
                        {settings.wawp_social_icons.map((link, i) => {
                          const iconInfo = data.remix_icons[link.icon];
                          return (
                            <div 
                              key={i} 
                              className={cn(
                                "w-8 h-8 flex items-center justify-center text-white transition-transform hover:scale-110 shadow-sm",
                                settings.wawp_social_button_style === 'round' ? "rounded-full" : "rounded-[5px]"
                              )}
                              style={{ backgroundColor: iconInfo?.color || '#eee' }}
                            >
                              <i className={`${link.icon} text-[14px]`}></i>
                            </div>
                          );
                        })}
                      </div>
                   </div>
                )}

                {settings.wawp_enable_powered_by === 'yes' && (
                  <div className="py-2.5 bg-gray-50 flex items-center justify-center gap-1.5 border-t border-[#dcdcde]">
                    <span className="text-[9px] text-gray-400 font-black uppercase tracking-widest">Support</span>
                    <span className="text-[9px] font-black text-[#004449]">WAWP</span>
                  </div>
                )}
             </motion.div>

             {/* ─── Mockup Floating Button ─── */}
             <div className="mt-12 group relative">
                <div 
                   className={cn(
                     "absolute inset-0 bg-emerald-500/20 blur-xl transition-all group-hover:blur-2xl opacity-0 group-hover:opacity-100",
                     settings.wawp_corner_radius === '50' ? "rounded-full" : "rounded-[5px]"
                   )}
                />
                <motion.div 
                  className="flex items-center justify-center relative transition-all group-hover:scale-110 active:scale-95 cursor-pointer z-10 shadow-xl border border-white/20"
                  style={{ 
                    width: `${settings.wawp_button_size}px`, 
                    height: `${settings.wawp_button_size}px`, 
                    background: settings.wawp_button_bg_color,
                    borderRadius: `${settings.wawp_corner_radius}px`,
                  }}
                >
                  <i className={`${settings.wawp_whatsapp_icon_class}`} style={{ color: settings.wawp_icon_color, fontSize: `${parseInt(settings.wawp_button_size) * 0.45}px` }}></i>
                </motion.div>
             </div>
          </div>

          <div className="mt-8 space-y-4">
             <div className="p-6 bg-gray-50 rounded-[10px] border border-[#dcdcde] shadow-sm">
                <div className="flex items-center gap-3 mb-4">
                  <div className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse" />
                  <span className="text-[10px] font-black text-gray-900 uppercase tracking-widest">Active Configuration</span>
                </div>
                <ul className="space-y-3">
                  <li className="text-[12px] text-gray-600 flex items-center justify-between border-b border-[#dcdcde] pb-2 last:border-0">
                    <span className="font-bold flex items-center gap-2"><Layout size={12} /> Position</span>
                    <span className="font-black text-slate-900 uppercase tracking-tighter">{settings.wawp_button_position}</span>
                  </li>
                  <li className="text-[12px] text-gray-600 flex items-center justify-between border-b border-[#dcdcde] pb-2 last:border-0">
                    <span className="font-bold flex items-center gap-2"><Users size={12} /> Support Agents</span>
                    <span className="font-black text-slate-900">{settings.wawp_whatsapp_numbers.length}</span>
                  </li>
                   <li className="text-[12px] text-gray-600 flex items-center justify-between">
                    <span className="font-bold flex items-center gap-2"><Globe size={12} /> Privacy Settings</span>
                    <Badge variant="outline" className="text-[8px] font-black uppercase tracking-widest border-emerald-100 text-emerald-600 bg-emerald-50">
                      {settings.wawp_enable_powered_by === 'yes' ? 'Public' : 'Private'}
                    </Badge>
                  </li>
                </ul>
             </div>
             
             <div className="flex items-center gap-3 px-5 py-3.5 bg-emerald-50 border border-emerald-100 rounded-[5px]">
                <Shield size={16} className="text-emerald-600" />
                <p className="text-[10px] text-emerald-900 font-black uppercase leading-tight tracking-wider">Preview mode: All changes reflect in real-time before saving.</p>
             </div>
          </div>
       </aside>
    </div>
  </SettingsLayout>
);
}
