'use client';

import { useState, useEffect } from 'react';
import {
  Bell, Search, Trash2, CheckCheck, Filter, Shield, FileText, Users, Wallet, Wrench,
  Battery, Zap, AlertTriangle, CheckCircle, Info, Eye, Sparkles, PlusCircle, Play, ChevronRight, X,
  Mail, MessageSquare, Send, Calendar, Clock, ArrowRight, EyeOff, UserCheck
} from 'lucide-react';
import Link from 'next/link';
import toast from 'react-hot-toast';

interface Notification {
  id: string;
  category: 'kyc' | 'rental' | 'maintenance' | 'swap_station' | 'investor' | 'system' | 'withdraw';
  priority: 'low' | 'medium' | 'high' | 'critical';
  title: string;
  message: string;
  time: string;
  read: boolean;
  meta?: {
    link?: string;
    actionLabel?: string;
    details?: Record<string, string>;
  };
}

interface Broadcast {
  id: string;
  title: string;
  message: string;
  channels: ('email' | 'sms' | 'push')[];
  targetType: 'all' | 'group' | 'specific';
  targetValue: string; // "All Users", "Biker", "Jamal Uddin"
  sentAt: string;
  status: 'sent' | 'scheduled';
  scheduleTime?: string;
  recipientCount: number;
}

const mockUsersList = [
  { id: 'USR-001', name: 'Rahim Ahmed', role: 'biker', phone: '+8801712345678', email: 'rahim@jaiben.com' },
  { id: 'USR-002', name: 'Karim Hasan', role: 'biker', phone: '+8801812345678', email: 'karim@jaiben.com' },
  { id: 'USR-003', name: 'Jamal Uddin', role: 'biker', phone: '+8801912345678', email: 'jamal@jaiben.com' },
  { id: 'USR-005', name: 'Farid Ahmed', role: 'biker', phone: '+8801612345678', email: 'farid@jaiben.com' },
  { id: 'USR-010', name: 'Tariqul Islam', role: 'investor', phone: '+8801512345678', email: 'tariqul@jaiben.com' },
  { id: 'USR-011', name: 'Sofia Chowdhury', role: 'investor', phone: '+8801312345678', email: 'sofia@jaiben.com' },
  { id: 'USR-020', name: 'Alim Swap Cabinet', role: 'swap-station', phone: '+8801412345678', email: 'alim@jaiben.com' },
  { id: 'USR-030', name: 'Dhaka City Merchant', role: 'merchant', phone: '+8801212345678', email: 'merchant@jaiben.com' }
];

const initialNotifications: Notification[] = [
  {
    id: 'notif-inv-002',
    category: 'withdraw',
    priority: 'high',
    title: 'New Withdrawal Request',
    message: 'Investor Md. Hasan Mahmud (inv1) submitted a withdrawal request of ৳15,000 to bank account Islami Bank Bangladesh Ltd.',
    time: '2026-05-19T09:30:00Z',
    read: false,
    meta: {
      link: '/admin/investors/inv1?tab=financial',
      actionLabel: 'Review Withdrawal',
      details: {
        'Investor': 'Md. Hasan Mahmud (inv1)',
        'Withdrawal Amount': '৳15,000',
        'Method': 'Bank Transfer (Islami Bank)',
        'Available Balance': '৳69,250',
        'Status': 'Awaiting Verification'
      }
    }
  },
  {
    id: 'notif-inv-001',
    category: 'investor',
    priority: 'high',
    title: 'Profile Financial Info Update Request',
    message: 'Investor Md. Hasan Mahmud (inv1) submitted new bank accounts and mobile banking credentials for administrative verification.',
    time: '2026-05-18T10:15:00Z',
    read: false,
    meta: {
      link: '/admin/investors/inv1?tab=financial',
      actionLabel: 'Verify Financial Info',
      details: {
        'Investor': 'Md. Hasan Mahmud (inv1)',
        'Proposed Bank': 'Islami Bank, Dutch-Bangla Bank',
        'Proposed Mobile': 'bKash, Nagad',
        'Status': 'Awaiting Verification'
      }
    }
  },
  {
    id: 'notif-001',
    category: 'kyc',
    priority: 'high',
    title: 'New KYC Request Submitted',
    message: 'Biker application USR-002 (Karim Hasan) uploaded NID and driving license for review.',
    time: '2026-05-17T22:30:00Z',
    read: false,
    meta: {
      link: '/admin/kyc',
      actionLabel: 'Review Documents',
      details: {
        'Applicant': 'Karim Hasan',
        'Type': 'Biker',
        'Submitted At': 'Today, 10:30 PM',
        'Documents': 'NID Front, NID Back, License'
      }
    }
  },
  {
    id: 'notif-002',
    category: 'rental',
    priority: 'critical',
    title: 'Rental Overdue Alert - Bike Lock Pending',
    message: 'Rental transaction RNT-002 (Karim Hasan) is 5 days overdue. Payment of ৳3,500 is pending.',
    time: '2026-05-17T21:15:00Z',
    read: false,
    meta: {
      link: '/admin/rentals',
      actionLabel: 'Manage Overdue',
      details: {
        'Rental ID': 'RNT-002',
        'Rider': 'Karim Hasan',
        'Vehicle': 'Yadea DT3 (BIKE-002)',
        'Dues Pending': '৳3,500',
        'Overdue Days': '5 Days',
        'Next Action': 'Automatic lock trigger in 12 hours'
      }
    }
  },
  {
    id: 'notif-003',
    category: 'maintenance',
    priority: 'medium',
    title: 'High Temperature Battery Warning',
    message: 'EV BIKE-005 reported battery cell temperature at 52°C. Investigation recommended.',
    time: '2026-05-17T19:40:00Z',
    read: false,
    meta: {
      link: '/admin/maintenance',
      actionLabel: 'Schedule Repair',
      details: {
        'EV ID': 'BIKE-005',
        'Battery SOC': '45%',
        'Reported Temp': '52°C (Warning)',
        'Location': 'Uttara Area',
        'Status': 'Operational'
      }
    }
  },
  {
    id: 'notif-004',
    category: 'swap_station',
    priority: 'high',
    title: 'Low Battery Inventory Alert',
    message: 'Swap Station "Gulshan Hub Cabinets" has only 1 fully charged battery remaining in cabinets.',
    time: '2026-05-17T17:00:00Z',
    read: false,
    meta: {
      link: '/admin/swap-stations',
      actionLabel: 'Restock Station',
      details: {
        'Station Name': 'Gulshan Hub Station',
        'Capacity': '8 Cabinets',
        'Available Charged': '1 Battery',
        'Empty Compartments': '5 Compartments',
        'Operator': 'JAIBEN Gulshan Staff'
      }
    }
  },
  {
    id: 'notif-005',
    category: 'investor',
    priority: 'low',
    title: 'New Investment Plan Subscribed',
    message: 'Investor USR-003 (Jamal Uddin) successfully subscribed to "5 Bike Plan" Tier. Deposited ৳900,000.',
    time: '2026-05-17T14:20:00Z',
    read: true,
    meta: {
      link: '/admin/investors',
      actionLabel: 'View Investment',
      details: {
        'Investor': 'Jamal Uddin',
        'Plan': '5 Bike FICO Plan',
        'Base EV Price': '৳180,000 per EV',
        'Total Investment': '৳900,000',
        'Monthly ROI': '50% share'
      }
    }
  },
];

const initialBroadcasts: Broadcast[] = [
  {
    id: 'broad-001',
    title: 'System Maintenance Scheduled',
    message: 'Dear riders, our swap cabinet network will undergo a scheduled database upgrade on Saturday from 2:00 AM to 4:00 AM.',
    channels: ['email', 'push'],
    targetType: 'all',
    targetValue: 'All Users',
    sentAt: '2026-05-16T10:00:00Z',
    status: 'sent',
    recipientCount: 450
  },
  {
    id: 'broad-002',
    title: 'New Rental Subscriptions Active',
    message: 'Exciting news! We have added high capacity battery swap add-ons. Rent a battery for only ৳1,500/month additional.',
    channels: ['sms'],
    targetType: 'group',
    targetValue: 'biker',
    sentAt: '2026-05-15T12:00:00Z',
    status: 'sent',
    recipientCount: 320
  }
];

const messageTemplates = [
  { id: 'welcome', type: 'email', name: 'Welcome Email', subject: 'Welcome to JAIBEN Mobility - Your Journey Starts Here!', body: 'Dear {name},\n\nWelcome to JAIBEN Mobility!\n\nWe\'re thrilled to have you join our community of eco-friendly commuters.\n\nBest regards,\nJAIBEN Mobility Team' },
  { id: 'rental_confirmation', type: 'email', name: 'Rental Confirmation', subject: 'Rental Confirmed - Your EV is Ready!', body: 'Dear {name},\n\nYour rental has been confirmed!\n\nBooking Details:\n- Bike: {bike}\n- Plan: {plan}\n- Start Date: {start_date}\n\nEnjoy your ride!\n\nJAIBEN Mobility Team' },
  { id: 'payment_reminder', type: 'email', name: 'Payment Reminder', subject: 'Payment Due Soon - {amount}', body: 'Dear {name},\n\nThis is a friendly reminder that your payment of {amount} is due on {due_date}.\n\nJAIBEN Mobility Team' },
  { id: 'due_notice', type: 'email', name: 'Due Notice', subject: 'Payment Overdue - Action Required', body: 'Dear {name},\n\nYour payment for the rental of {bike} is overdue. Overdue Amount: {amount}.\n\nJAIBEN Mobility Team' },
  { id: 'kyc_verification', type: 'email', name: 'KYC Verification Status', subject: 'KYC Verification Approved', body: 'Dear {name},\n\nYour KYC verification has been Approved. You can now access all features and rent EVs!\n\nJAIBEN Mobility Team' },
  { id: 'damage_report', type: 'email', name: 'Vehicle Damage Report', subject: 'Vehicle Damage Report - {bike}', body: 'Dear {name},\n\nA damage report has been filed for your rented vehicle.\nEstimated Repair Cost: {repair_cost}.\n\nJAIBEN Mobility Team' },
  { id: 'otp', type: 'sms', name: 'OTP Code (SMS)', subject: 'OTP Code Pin', body: 'JAIBEN: Your OTP is {otp}. Valid for 10 mins. Do not share this code.' },
  { id: 'payment_due_sms', type: 'sms', name: 'Payment Due (SMS)', subject: 'Payment Due Alert', body: 'JAIBEN: Payment of {amount} due on {due_date} for your rental. Avoid late fees!' },
  { id: 'battery_low_sms', type: 'sms', name: 'Battery Low Warning (SMS)', subject: 'Battery Low Alert', body: 'JAIBEN: Your bike battery is low. Visit nearest swap station or charge point.' },
  { id: 'kyc_approved_sms', type: 'sms', name: 'KYC Approved (SMS)', subject: 'KYC Approved Alert', body: 'JAIBEN: Great news! Your KYC is verified. You can now rent EVs. Download app to start!' }
];

export default function AdminNotificationsPage() {
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [broadcasts, setBroadcasts] = useState<Broadcast[]>([]);
  const [selectedTemplateId, setSelectedTemplateId] = useState<string>('');

  // Tabs: 'inbox' (System Events) vs 'outbox' (Admin Messaging logs)
  const [activeTab, setActiveTab] = useState<'inbox' | 'outbox'>('inbox');

  // Filters
  const [filter, setFilter] = useState<string>('all');
  const [categoryFilter, setCategoryFilter] = useState<string>('all');
  const [searchQuery, setSearchQuery] = useState<string>('');

  // Dialog/Modals State
  const [selectedNotif, setSelectedNotif] = useState<Notification | null>(null);
  const [selectedBroadcast, setSelectedBroadcast] = useState<Broadcast | null>(null);
  const [showComposeModal, setShowComposeModal] = useState<boolean>(false);
  const [showSimulatorDrawer, setShowSimulatorDrawer] = useState<boolean>(false);

  // Broadcast Form State
  const [composeChannels, setComposeChannels] = useState<{ email: boolean; sms: boolean; push: boolean }>({ email: true, sms: false, push: true });
  const [composeTargetType, setComposeTargetType] = useState<'all' | 'group' | 'specific'>('all');
  const [composeTargetGroup, setComposeTargetGroup] = useState<string>('biker');
  const [composeTargetUsers, setComposeTargetUsers] = useState<string[]>(['USR-002']); // Pre-select Karim Hasan (BIKER)
  const [userSearchQuery, setUserSearchQuery] = useState<string>('');
  const [composeTitle, setComposeTitle] = useState<string>('');
  const [composeMessage, setComposeMessage] = useState<string>('');
  const [composeIsScheduled, setComposeIsScheduled] = useState<boolean>(false);
  const [composeScheduleDate, setComposeScheduleDate] = useState<string>('');
  const [composeScheduleTime, setComposeScheduleTime] = useState<string>('');
  const [isSending, setIsSending] = useState<boolean>(false);
  const [sendingStep, setSendingStep] = useState<string>('');

  useEffect(() => {
    // Sync System Notifications
    const savedNotifs = localStorage.getItem('jaiben_admin_notifications');
    if (savedNotifs) {
      try { setNotifications(JSON.parse(savedNotifs)); } catch (e) {
        setNotifications(initialNotifications);
        saveNotifications(initialNotifications);
      }
    } else {
      setNotifications(initialNotifications);
      saveNotifications(initialNotifications);
    }

    // Sync Outbox Broadcasts
    const savedBroadcasts = localStorage.getItem('jaiben_admin_broadcasts');
    if (savedBroadcasts) {
      try { setBroadcasts(JSON.parse(savedBroadcasts)); } catch (e) {
        setBroadcasts(initialBroadcasts);
        saveBroadcasts(initialBroadcasts);
      }
    } else {
      setBroadcasts(initialBroadcasts);
      saveBroadcasts(initialBroadcasts);
    }
  }, []);

  const saveNotifications = (newNotifs: Notification[]) => {
    localStorage.setItem('jaiben_admin_notifications', JSON.stringify(newNotifs));
    window.dispatchEvent(new Event('jaiben_notifications_update'));
  };

  const saveBroadcasts = (newBroadcasts: Broadcast[]) => {
    localStorage.setItem('jaiben_admin_broadcasts', JSON.stringify(newBroadcasts));
  };

  const markAsRead = (id: string) => {
    const updated = notifications.map(n => n.id === id ? { ...n, read: true } : n);
    setNotifications(updated);
    saveNotifications(updated);
  };

  const toggleReadStatus = (id: string) => {
    const updated = notifications.map(n => n.id === id ? { ...n, read: !n.read } : n);
    setNotifications(updated);
    saveNotifications(updated);
    toast.success(updated.find(n => n.id === id)?.read ? 'Marked as read' : 'Marked as unread');
  };

  const deleteNotification = (id: string) => {
    const updated = notifications.filter(n => n.id !== id);
    setNotifications(updated);
    saveNotifications(updated);
    toast.success('Alert deleted');
  };

  const markAllAsRead = () => {
    const updated = notifications.map(n => ({ ...n, read: true }));
    setNotifications(updated);
    saveNotifications(updated);
    toast.success('All alerts marked as read');
  };

  const clearAllNotifications = () => {
    if (confirm('Are you sure you want to delete all alert history?')) {
      setNotifications([]);
      saveNotifications([]);
      toast.success('Inbox alerts cleared');
    }
  };

  const deleteBroadcast = (id: string) => {
    if (confirm('Delete this broadcast log?')) {
      const updated = broadcasts.filter(b => b.id !== id);
      setBroadcasts(updated);
      saveBroadcasts(updated);
      toast.success('Broadcast log deleted');
    }
  };

  // Broadcast Message submission handler
  const handleSendBroadcast = (e: React.FormEvent) => {
    e.preventDefault();

    if (!composeTitle.trim()) {
      toast.error('Please enter a message title');
      return;
    }
    if (!composeMessage.trim()) {
      toast.error('Please enter the message content');
      return;
    }

    if (composeTargetType === 'specific' && composeTargetUsers.length === 0) {
      toast.error('Please select at least one target recipient user');
      return;
    }

    const selectedChannels = Object.entries(composeChannels)
      .filter(([_, enabled]) => enabled)
      .map(([channel]) => channel as 'email' | 'sms' | 'push');

    if (selectedChannels.length === 0) {
      toast.error('Please select at least one dispatch channel (SMS, Email, or Push)');
      return;
    }

    setIsSending(true);

    // Multi-step send animation steps
    const steps = ['Establishing secured connections...', 'Parsing user database targeted rules...', 'Delivering gateway payloads...', 'Verification completed!'];
    let stepIdx = 0;
    setSendingStep(steps[0]);

    const interval = setInterval(() => {
      stepIdx++;
      if (stepIdx < steps.length) {
        setSendingStep(steps[stepIdx]);
      } else {
        clearInterval(interval);
        finalizeBroadcast();
      }
    }, 600);

    const finalizeBroadcast = () => {
      // Calculate fake recipient count
      let recipients = 1;
      let targetDesc = '';
      if (composeTargetType === 'all') {
        recipients = 512;
        targetDesc = 'All Active Users';
      } else if (composeTargetType === 'group') {
        recipients = composeTargetGroup === 'biker' ? 320 : composeTargetGroup === 'investor' ? 84 : 42;
        targetDesc = composeTargetGroup.charAt(0).toUpperCase() + composeTargetGroup.slice(1) + ' Group';
      } else {
        recipients = composeTargetUsers.length;
        if (recipients === 0) {
          recipients = 1;
          targetDesc = 'Specific User';
        } else if (recipients === 1) {
          const u = mockUsersList.find(usr => usr.id === composeTargetUsers[0]);
          targetDesc = u ? `${u.name} (${u.role.toUpperCase()})` : 'Specific User';
        } else if (recipients === 2) {
          const u1 = mockUsersList.find(usr => usr.id === composeTargetUsers[0]);
          const u2 = mockUsersList.find(usr => usr.id === composeTargetUsers[1]);
          targetDesc = `${u1?.name || 'User'}, ${u2?.name || 'User'}`;
        } else {
          const u1 = mockUsersList.find(usr => usr.id === composeTargetUsers[0]);
          const u2 = mockUsersList.find(usr => usr.id === composeTargetUsers[1]);
          targetDesc = `${u1?.name || 'User'}, ${u2?.name || 'User'} + ${recipients - 2} others`;
        }
      }

      const newBroadcast: Broadcast = {
        id: `broad-${Date.now()}`,
        title: composeTitle,
        message: composeMessage,
        channels: selectedChannels,
        targetType: composeTargetType,
        targetValue: targetDesc,
        sentAt: new Date().toISOString(),
        status: composeIsScheduled ? 'scheduled' : 'sent',
        scheduleTime: composeIsScheduled ? `${composeScheduleDate} ${composeScheduleTime}` : undefined,
        recipientCount: recipients
      };

      const updated = [newBroadcast, ...broadcasts];
      setBroadcasts(updated);
      saveBroadcasts(updated);

      setIsSending(false);
      setShowComposeModal(false);

      // Reset form fields
      setComposeTitle('');
      setComposeMessage('');
      setComposeIsScheduled(false);

      if (composeIsScheduled) {
        toast.success(`Message successfully scheduled for ${newBroadcast.scheduleTime}!`);
      } else {
        toast.success(`Successfully broadcasted to ${recipients} users!`);
      }
    };
  };

  // Simulates a system event trigger in real-time
  const triggerSimulation = (type: string) => {
    let newNotif: Notification;
    const nowStr = new Date().toISOString();

    switch (type) {
      case 'kyc':
        newNotif = {
          id: `sim-${Date.now()}`,
          category: 'kyc',
          priority: 'high',
          title: 'Walk-in KYC Document Uploaded',
          message: 'Front desk officer submitted remaining documents for biker Rahim Ahmed.',
          time: nowStr,
          read: false,
          meta: {
            link: '/admin/kyc',
            actionLabel: 'Approve NID',
            details: {
              'Applicant': 'Rahim Ahmed',
              'Hub Agent': 'Banani Front Desk',
              'Documents Uploaded': 'TIN Certificate, Bank Account Info',
              'Priority': 'High Action Needed'
            }
          }
        };
        toast('New Biker KYC submitted!', { icon: '📝' });
        break;
      case 'overdue':
        newNotif = {
          id: `sim-${Date.now()}`,
          category: 'rental',
          priority: 'critical',
          title: 'CRITICAL: EV Rental Overdue Lock Triggered',
          message: 'Rider USR-005 has failed to submit payment for 7 days. Automatic immobilization initiated.',
          time: nowStr,
          read: false,
          meta: {
            link: '/admin/rentals',
            actionLabel: 'Immobilize Vehicle',
            details: {
              'Rental ID': 'RNT-004',
              'Rider': 'Farid Ahmed',
              'Vehicle Plate': 'Dhaka Metro Ha-5678',
              'Overdue Duration': '7 Days',
              'Current Status': 'Locked'
            }
          }
        };
        toast.error('CRITICAL: EV Rental Overdue Lock Triggered!', { duration: 5000 });
        break;
      case 'battery':
        newNotif = {
          id: `sim-${Date.now()}`,
          category: 'maintenance',
          priority: 'high',
          title: 'High Speed Charge Warning',
          message: 'Swap station battery BAT-DH-004 reported 90°C terminal temperatures during fast charge.',
          time: nowStr,
          read: false,
          meta: {
            link: '/admin/maintenance',
            actionLabel: 'Eject Battery',
            details: {
              'Battery ID': 'BAT-DH-004',
              'Location': 'Banani Hub Cabinet #3',
              'Charge SOC': '88%',
              'Status': 'Fast Charging Ejected'
            }
          }
        };
        toast.error('High Battery Charge Temp Warning!');
        break;
      case 'investment':
        newNotif = {
          id: `sim-${Date.now()}`,
          category: 'investor',
          priority: 'medium',
          title: 'Partial Payment Investment Received',
          message: 'Investor Karim Hasan submitted 50% deposit for 1 Bike FICO investment.',
          time: nowStr,
          read: false,
          meta: {
            link: '/admin/investors',
            actionLabel: 'Review Ledger',
            details: {
              'Investor Name': 'Karim Hasan',
              'Plan Subscribed': '1 Bike Plan',
              'Deposit Received': '৳100,000 (50% partial)',
              'Journal Status': 'Draft auto-posted'
            }
          }
        };
        toast.success('New Investment Partial Payment Received!');
        break;
      default:
        return;
    }

    const updated = [newNotif, ...notifications];
    setNotifications(updated);
    saveNotifications(updated);
  };

  const getCategoryBadge = (category: string) => {
    const config: Record<string, { label: string; bg: string; text: string; icon: any }> = {
      kyc: { label: 'KYC Request', bg: 'bg-blue-50 border-blue-200', text: 'text-blue-700', icon: Shield },
      rental: { label: 'Rentals', bg: 'bg-emerald-50 border-emerald-200', text: 'text-emerald-700', icon: FileText },
      maintenance: { label: 'Maintenance', bg: 'bg-amber-50 border-amber-200', text: 'text-amber-700', icon: Wrench },
      swap_station: { label: 'Swap Station', bg: 'bg-purple-50 border-purple-200', text: 'text-purple-700', icon: Zap },
      investor: { label: 'Investor', bg: 'bg-indigo-50 border-indigo-200', text: 'text-indigo-700', icon: Wallet },
      system: { label: 'System', bg: 'bg-slate-50 border-slate-200', text: 'text-slate-700', icon: Info },
    };
    const active = config[category] || config.system;
    return (
      <span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full border text-xs font-semibold ${active.bg} ${active.text}`}>
        <active.icon className="w-3.5 h-3.5" /> {active.label}
      </span>
    );
  };

  const getPriorityBadge = (priority: string) => {
    const config: Record<string, { label: string; bg: string; text: string }> = {
      low: { label: 'Low', bg: 'bg-slate-100', text: 'text-slate-700' },
      medium: { label: 'Medium', bg: 'bg-amber-100', text: 'text-amber-700' },
      high: { label: 'High', bg: 'bg-orange-100', text: 'text-orange-700' },
      critical: { label: 'Critical', bg: 'bg-red-100 animate-pulse border-red-200 border', text: 'text-red-700 font-extrabold' },
    };
    const active = config[priority] || config.low;
    return (
      <span className={`px-2 py-0.5 rounded border text-[10px] font-bold uppercase tracking-wider ${active.bg} ${active.text}`}>
        {active.label}
      </span>
    );
  };

  const filteredNotifs = notifications.filter(n => {
    if (filter === 'unread' && n.read) return false;
    if (categoryFilter !== 'all' && n.category !== categoryFilter) return false;
    if (searchQuery) {
      const q = searchQuery.toLowerCase();
      return n.title.toLowerCase().includes(q) || n.message.toLowerCase().includes(q);
    }
    return true;
  });

  const filteredBroadcasts = broadcasts.filter(b => {
    if (searchQuery) {
      const q = searchQuery.toLowerCase();
      return b.title.toLowerCase().includes(q) || b.message.toLowerCase().includes(q) || b.targetValue.toLowerCase().includes(q);
    }
    return true;
  });

  const unreadCount = notifications.filter(n => !n.read).length;
  const criticalCount = notifications.filter(n => n.priority === 'critical' && !n.read).length;

  return (
    <div className="p-4 lg:p-6 max-w-8xl mx-auto space-y-6">
      {/* Header section with responsive layout and clear actions */}
      <div className="flex flex-col xl:flex-row xl:items-center xl:justify-between gap-4">
        <div>
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-accent/10 flex items-center justify-center text-accent">
              <Bell className="w-5 h-5" />
            </div>
            <div>
              <h1 className="text-2xl lg:text-3xl font-extrabold text-slate-800">Notifications & Messaging</h1>
              <p className="text-sm text-slate-500 mt-0.5">Disseminate email/SMS broadcasts and inspect real-time EV triggers</p>
            </div>
          </div>
        </div>

        {/* Global Controls Container */}
        <div className="flex flex-wrap items-center gap-2 self-start xl:self-center">
          <button
            onClick={() => setShowComposeModal(true)}
            className="flex items-center justify-center gap-2 py-2.5 px-4 bg-accent hover:bg-accent-dark text-white rounded-xl text-sm font-semibold shadow-md shadow-accent/10 transition-all cursor-pointer grow sm:grow-0"
          >
            <Send className="w-4 h-4" /> Compose Broadcast
          </button>

          <button
            onClick={() => setShowSimulatorDrawer(true)}
            className="flex items-center justify-center gap-2 py-2.5 px-4 bg-slate-900 hover:bg-slate-800 text-white rounded-xl text-sm font-semibold transition-all cursor-pointer grow sm:grow-0"
          >
            <Play className="w-4 h-4 text-emerald-400" /> Event Simulator
          </button>

          {activeTab === 'inbox' && (
            <>
              <button
                onClick={markAllAsRead}
                disabled={unreadCount === 0}
                className="flex items-center justify-center gap-2 py-2.5 px-4 bg-white border border-slate-200 text-slate-600 rounded-xl text-sm font-semibold hover:bg-slate-50 transition-colors disabled:opacity-50 cursor-pointer grow sm:grow-0"
              >
                <CheckCheck className="w-4 h-4 text-emerald-500" /> Mark All Read
              </button>
              <button
                onClick={clearAllNotifications}
                disabled={notifications.length === 0}
                className="flex items-center justify-center gap-2 py-2.5 px-4 bg-white border border-red-200 text-red-600 rounded-xl text-sm font-semibold hover:bg-red-50 transition-colors disabled:opacity-50 cursor-pointer grow sm:grow-0"
              >
                <Trash2 className="w-4 h-4" /> Clear History
              </button>
            </>
          )}
        </div>
      </div>

      {/* Dynamic Tabs: Inbox vs Outbox */}
      <div className="flex border-b border-slate-200">
        <button
          onClick={() => { setActiveTab('inbox'); setFilter('all'); }}
          className={`py-3 px-6 text-sm font-bold border-b-2 transition-all flex items-center gap-2 ${activeTab === 'inbox' ? 'border-accent text-accent' : 'border-transparent text-slate-500 hover:text-slate-800'
            }`}
        >
          <Bell className="w-4 h-4" /> Alert Inbox ({notifications.length})
          {unreadCount > 0 && (
            <span className="px-2 py-0.5 rounded-full bg-red-500 text-white text-[10px] font-extrabold">{unreadCount}</span>
          )}
        </button>
        <button
          onClick={() => { setActiveTab('outbox'); setFilter('all'); }}
          className={`py-3 px-6 text-sm font-bold border-b-2 transition-all flex items-center gap-2 ${activeTab === 'outbox' ? 'border-accent text-accent' : 'border-transparent text-slate-500 hover:text-slate-800'
            }`}
        >
          <Send className="w-4 h-4" /> Broadcast History ({broadcasts.length})
        </button>
      </div>

      {/* Stats Cards Section */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <div className="bg-white p-4 rounded-xl border border-slate-100 shadow-sm flex items-center justify-between">
          <div>
            <p className="text-xs text-slate-500 font-semibold uppercase">Pending Alerts</p>
            <p className="text-2xl font-extrabold text-slate-800 mt-1">{unreadCount}</p>
          </div>
          <div className="w-10 h-10 rounded-xl bg-red-50 flex items-center justify-center text-red-500">
            <Bell className="w-5 h-5" />
          </div>
        </div>
        <div className="bg-white p-4 rounded-xl border border-slate-100 shadow-sm flex items-center justify-between">
          <div>
            <p className="text-xs text-slate-500 font-semibold uppercase">Critical Failures</p>
            <p className="text-2xl font-extrabold text-red-600 mt-1">{criticalCount}</p>
          </div>
          <div className="w-10 h-10 rounded-xl bg-red-100 flex items-center justify-center text-red-600 animate-pulse">
            <AlertTriangle className="w-5 h-5" />
          </div>
        </div>
        <div className="bg-white p-4 rounded-xl border border-slate-100 shadow-sm flex items-center justify-between">
          <div>
            <p className="text-xs text-slate-500 font-semibold uppercase">Total Messages Outbox</p>
            <p className="text-2xl font-extrabold text-slate-800 mt-1">
              {broadcasts.reduce((acc, curr) => acc + curr.recipientCount, 0)}
            </p>
          </div>
          <div className="w-10 h-10 rounded-xl bg-accent-light/35 flex items-center justify-center text-accent">
            <Send className="w-5 h-5" />
          </div>
        </div>
        <div className="bg-white p-4 rounded-xl border border-slate-100 shadow-sm flex items-center justify-between">
          <div>
            <p className="text-xs text-slate-500 font-semibold uppercase">Broadcast Events</p>
            <p className="text-2xl font-extrabold text-slate-800 mt-1">{broadcasts.length}</p>
          </div>
          <div className="w-10 h-10 rounded-xl bg-indigo-50 flex items-center justify-center text-indigo-500">
            <Sparkles className="w-5 h-5" />
          </div>
        </div>
      </div>

      {/* Main Grid Layout */}
      <div className="grid lg:grid-cols-4 gap-6 items-start">

        {/* Desktop Sidebar Filters: Kept for Desktop views */}
        <div className="hidden lg:block lg:col-span-1 space-y-4 sticky top-6">
          <div className="bg-white p-4 rounded-xl border border-slate-100 shadow-sm space-y-4">
            <h3 className="font-bold text-slate-700 flex items-center gap-2"><Filter className="w-4 h-4 text-accent" /> Filter Inbox</h3>

            {activeTab === 'inbox' && (
              <div className="space-y-1">
                {[
                  { id: 'all', label: 'All Alerts' },
                  { id: 'unread', label: 'Unread Only' },
                ].map(f => (
                  <button
                    key={f.id}
                    onClick={() => setFilter(f.id)}
                    className={`w-full flex items-center justify-between px-3 py-2 text-sm font-semibold rounded-lg text-left transition-colors cursor-pointer ${filter === f.id ? 'bg-accent text-white' : 'text-slate-600 hover:bg-slate-50'
                      }`}
                  >
                    {f.label}
                    {f.id === 'unread' && unreadCount > 0 && (
                      <span className={`px-2 py-0.5 rounded-full text-xs font-bold ${filter === f.id ? 'bg-white text-accent' : 'bg-red-500 text-white'}`}>
                        {unreadCount}
                      </span>
                    )}
                  </button>
                ))}
              </div>
            )}

            {activeTab === 'inbox' && (
              <div className="border-t border-slate-100 pt-3 space-y-2">
                <p className="text-xs font-semibold text-slate-400 uppercase tracking-wider px-2">Inbox Categories</p>
                <div className="space-y-1">
                  {[
                    { id: 'all', label: 'All Categories' },
                    { id: 'kyc', label: 'KYC Verification' },
                    { id: 'rental', label: 'Rentals & Fines' },
                    { id: 'maintenance', label: 'Vehicle Service' },
                    { id: 'swap_station', label: 'Cabinet Network' },
                    { id: 'investor', label: 'Investor Ledger' },
                    { id: 'withdraw', label: 'Withdrawal Requests' },
                  ].map(cat => {
                    const catCount = cat.id === 'all'
                      ? notifications.length
                      : notifications.filter(n => n.category === cat.id).length;
                    return (
                      <button
                        key={cat.id}
                        onClick={() => setCategoryFilter(cat.id)}
                        className={`w-full flex items-center justify-between px-3 py-2 text-sm font-semibold rounded-lg text-left transition-colors cursor-pointer ${categoryFilter === cat.id ? 'bg-slate-100 text-slate-800' : 'text-slate-600 hover:bg-slate-50'
                          }`}
                      >
                        <span>{cat.label}</span>
                        {catCount > 0 && (
                          <span className={`px-2 py-0.5 rounded-full text-xs font-bold ${categoryFilter === cat.id ? 'bg-accent text-white' : 'bg-slate-100 text-slate-600 border border-slate-200'
                            }`}>
                            {catCount}
                          </span>
                        )}
                      </button>
                    );
                  })}
                </div>
              </div>
            )}

            {activeTab === 'outbox' && (
              <div className="p-2 text-xs text-slate-500 italic bg-slate-50 rounded-lg">
                View all previous announcements, targeted SMS alerts, and newsletter dispatches sent by administrators.
              </div>
            )}
          </div>
        </div>

        {/* Dynamic Main Listing Section */}
        <div className="lg:col-span-3 space-y-4">

          {/* Responsive scrollable Category Pills on Mobile/Tablet */}
          {activeTab === 'inbox' && (
            <div className="flex gap-2 overflow-x-auto pb-1 lg:hidden -mx-4 px-4 scrollbar-none">
              {[
                { id: 'all', label: 'All Categories' },
                { id: 'kyc', label: 'KYC Verification' },
                { id: 'rental', label: 'Rentals & Fines' },
                { id: 'maintenance', label: 'Vehicle Service' },
                { id: 'swap_station', label: 'Cabinet Network' },
                { id: 'investor', label: 'Investor Ledger' },
                { id: 'withdraw', label: 'Withdrawal Requests' },
              ].map(cat => {
                const catCount = cat.id === 'all'
                  ? notifications.length
                  : notifications.filter(n => n.category === cat.id).length;
                return (
                  <button
                    key={cat.id}
                    onClick={() => setCategoryFilter(cat.id)}
                    className={`px-4 py-2 rounded-full text-xs font-bold border transition-colors shrink-0 whitespace-nowrap cursor-pointer flex items-center gap-1.5 ${categoryFilter === cat.id
                        ? 'bg-accent border-accent text-white shadow-sm'
                        : 'bg-white border-slate-200 text-slate-600 hover:bg-slate-50'
                      }`}
                  >
                    <span>{cat.label}</span>
                    {catCount > 0 && (
                      <span className={`px-1.5 py-0.5 rounded-full text-[10px] font-bold ${categoryFilter === cat.id ? 'bg-white text-accent' : 'bg-slate-100 text-slate-500'
                        }`}>
                        {catCount}
                      </span>
                    )}
                  </button>
                );
              })}
            </div>
          )}

          {/* Search bar */}
          <div className="relative">
            <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
            <input
              type="text"
              placeholder={activeTab === 'inbox' ? 'Search alert title, rider, or hardware logs...' : 'Search broadcast announcements, groups, or text content...'}
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full pl-10 pr-4 py-3 border border-slate-200 rounded-xl text-sm bg-white text-slate-700 focus:outline-none focus:ring-2 focus:ring-accent/20 focus:border-accent"
            />
          </div>

          {/* List items Container */}
          <div className="bg-white rounded-xl border border-slate-100 shadow-sm overflow-hidden divide-y divide-slate-100">

            {/* ALERT INBOX TAB VIEW */}
            {activeTab === 'inbox' && (
              filteredNotifs.length === 0 ? (
                <div className="p-12 text-center">
                  <Bell className="w-12 h-12 text-slate-300 mx-auto mb-3" />
                  <p className="text-sm font-semibold text-slate-700">No alerts found</p>
                  <p className="text-xs text-slate-400 mt-1">Try modifying your filter settings or search query.</p>
                </div>
              ) : (
                filteredNotifs.map(notif => (
                  <div
                    key={notif.id}
                    className={`p-4 flex gap-4 transition-colors relative hover:bg-slate-50/50 ${!notif.read ? 'bg-accent-light/10 border-l-4 border-accent' : ''
                      }`}
                  >
                    <div className="flex-1 space-y-1.5 min-w-0 cursor-pointer" onClick={() => setSelectedNotif(notif)}>
                      <div className="flex items-center gap-2 flex-wrap">
                        {getCategoryBadge(notif.category)}
                        {getPriorityBadge(notif.priority)}
                        <span className="text-[10px] text-slate-400 ml-auto">
                          {new Date(notif.time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })},{' '}
                          {new Date(notif.time).toLocaleDateString([], { month: 'short', day: 'numeric' })}
                        </span>
                      </div>
                      <h4 className={`text-sm font-bold text-slate-800 flex items-center gap-1.5 ${!notif.read ? 'text-slate-900 font-extrabold' : ''}`}>
                        {!notif.read && <span className="w-2 h-2 rounded-full bg-accent inline-block shrink-0 animate-ping" />}
                        {notif.title}
                      </h4>
                      <p className="text-xs text-slate-600 leading-relaxed truncate">{notif.message}</p>
                    </div>

                    <div className="flex items-center gap-0.5 sm:gap-1 self-center shrink-0">
                      <button
                        onClick={() => toggleReadStatus(notif.id)}
                        className="p-2 hover:bg-slate-100 rounded-lg text-slate-400 hover:text-accent transition-colors cursor-pointer"
                        title={notif.read ? 'Mark as unread' : 'Mark as read'}
                      >
                        {notif.read ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4 text-accent" />}
                      </button>
                      <button
                        onClick={() => deleteNotification(notif.id)}
                        className="p-2 hover:bg-red-50 rounded-lg text-slate-400 hover:text-red-600 transition-colors cursor-pointer"
                        title="Delete Alert"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </div>
                  </div>
                ))
              )
            )}

            {/* BROADCAST OUTBOX LOGS TAB VIEW */}
            {activeTab === 'outbox' && (
              filteredBroadcasts.length === 0 ? (
                <div className="p-12 text-center">
                  <Send className="w-12 h-12 text-slate-300 mx-auto mb-3" />
                  <p className="text-sm font-semibold text-slate-700">No sent broadcasts</p>
                  <p className="text-xs text-slate-400 mt-1">Announcements sent to riders/investors will appear here.</p>
                </div>
              ) : (
                filteredBroadcasts.map(broad => (
                  <div
                    key={broad.id}
                    className="p-4 flex gap-4 transition-colors relative hover:bg-slate-50/50"
                  >
                    <div className="flex-1 space-y-1.5 min-w-0 cursor-pointer" onClick={() => setSelectedBroadcast(broad)}>
                      <div className="flex items-center gap-2 flex-wrap">
                        <span className="inline-flex items-center gap-1 px-2.5 py-1 bg-accent/5 border border-accent/20 rounded-full text-xs font-bold text-accent">
                          <Send className="w-3 h-3" /> Broadcast Log
                        </span>

                        {/* Selected Channels Icons */}
                        <div className="flex items-center gap-1.5 text-slate-400">
                          {broad.channels.includes('email') && <span title="Email dispatched"><Mail className="w-3.5 h-3.5 text-blue-500" /></span>}
                          {broad.channels.includes('sms') && <span title="SMS dispatched"><MessageSquare className="w-3.5 h-3.5 text-emerald-500" /></span>}
                          {broad.channels.includes('push') && <span title="App Push dispatched"><Bell className="w-3.5 h-3.5 text-amber-500" /></span>}
                        </div>

                        {/* Status tag */}
                        <span className={`px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider ${broad.status === 'scheduled' ? 'bg-amber-100 text-amber-800' : 'bg-green-100 text-green-800'
                          }`}>
                          {broad.status}
                        </span>

                        <span className="text-[10px] text-slate-400 ml-auto">
                          {new Date(broad.sentAt).toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })}
                        </span>
                      </div>

                      <h4 className="text-sm font-bold text-slate-800">{broad.title}</h4>
                      <p className="text-xs text-slate-600 truncate">{broad.message}</p>

                      <div className="flex items-center gap-4 text-[10px] text-slate-400 font-medium">
                        <span>Target: <strong className="text-slate-600 font-bold">{broad.targetValue}</strong></span>
                        <span>Delivered: <strong className="text-slate-600 font-bold">{broad.recipientCount} accounts</strong></span>
                      </div>
                    </div>

                    <div className="flex items-center shrink-0">
                      <button
                        onClick={() => deleteBroadcast(broad.id)}
                        className="p-2 hover:bg-red-50 rounded-lg text-slate-400 hover:text-red-600 transition-colors cursor-pointer"
                        title="Delete Log"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </div>
                  </div>
                ))
              )
            )}
          </div>
        </div>
      </div>

      {/* =========================================Compose MESSAGE BROADCAST MODAL ========================================= */}
      {showComposeModal && (
        <div className="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 flex items-center justify-center p-4 overflow-y-auto">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-xl overflow-hidden border border-slate-100 flex flex-col my-8">

            {/* Modal Header */}
            <div className="p-4 bg-gradient-to-r from-accent to-accent-dark text-white flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Send className="w-5 h-5 animate-pulse" />
                <h3 className="font-extrabold text-base lg:text-lg">Compose Message & Broadcast</h3>
              </div>
              <button
                onClick={() => setShowComposeModal(false)}
                className="p-1.5 hover:bg-white/10 rounded-lg transition-colors text-white"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            {/* Modal Form */}
            <form onSubmit={handleSendBroadcast} className="p-6 space-y-5 overflow-y-auto max-h-[75vh]">

              {/* Channel Selector Checkboxes */}
              <div className="space-y-2">
                <label className="text-xs font-bold text-slate-700 uppercase tracking-wider block">1. Select Dispatch Channel(s)</label>
                <div className="grid grid-cols-3 gap-3">
                  {[
                    { id: 'email', label: 'Email Dispatch', icon: Mail, color: 'border-blue-200 text-blue-600 bg-blue-50/20' },
                    { id: 'sms', label: 'SMS Payload', icon: MessageSquare, color: 'border-emerald-200 text-emerald-600 bg-emerald-50/20' },
                    { id: 'push', label: 'Push Alert', icon: Bell, color: 'border-amber-200 text-amber-600 bg-amber-50/20' },
                  ].map(ch => {
                    const enabled = composeChannels[ch.id as 'email' | 'sms' | 'push'];
                    return (
                      <button
                        key={ch.id}
                        type="button"
                        onClick={() => setComposeChannels(prev => ({ ...prev, [ch.id]: !enabled }))}
                        className={`flex flex-col items-center justify-center p-3 rounded-xl border-2 transition-all cursor-pointer text-center ${enabled ? 'border-accent bg-accent-light/10 text-accent font-bold scale-[1.02]' : 'border-slate-200 text-slate-500 bg-white hover:border-slate-300'
                          }`}
                      >
                        <ch.icon className={`w-5 h-5 mb-1.5 ${enabled ? 'text-accent' : 'text-slate-400'}`} />
                        <span className="text-[10px] tracking-tight">{ch.label}</span>
                      </button>
                    );
                  })}
                </div>
              </div>

              {/* Recipient Target Rules */}
              <div className="space-y-3">
                <label className="text-xs font-bold text-slate-700 uppercase tracking-wider block">2. Recipient Targets</label>
                <div className="grid grid-cols-3 gap-2">
                  {[
                    { id: 'all', label: 'All Users' },
                    { id: 'group', label: 'User Group' },
                    { id: 'specific', label: 'Specific User' }
                  ].map(t => (
                    <button
                      key={t.id}
                      type="button"
                      onClick={() => setComposeTargetType(t.id as any)}
                      className={`py-2 px-3 text-xs font-semibold rounded-lg border text-center transition-all cursor-pointer ${composeTargetType === t.id ? 'bg-slate-900 border-slate-900 text-white' : 'bg-white border-slate-200 text-slate-600 hover:bg-slate-50'
                        }`}
                    >
                      {t.label}
                    </button>
                  ))}
                </div>

                {/* Suboptions based on selected target */}
                {composeTargetType === 'group' && (
                  <div className="p-3 bg-slate-50 border border-slate-200 rounded-xl space-y-1.5 animate-fadeIn">
                    <label className="text-[10px] font-bold text-slate-500 uppercase block">Select User Group Role</label>
                    <select
                      value={composeTargetGroup}
                      onChange={(e) => setComposeTargetGroup(e.target.value)}
                      className="w-full px-3 py-2 border border-slate-200 rounded-lg text-xs bg-white focus:outline-none"
                    >
                      <option value="biker">Bikers Group (320 accounts)</option>
                      <option value="investor">Investors Group (84 accounts)</option>
                      <option value="merchant">Merchants Group (15 accounts)</option>
                      <option value="swap-station">Swap Station Operators (12 accounts)</option>
                    </select>
                  </div>
                )}

                {composeTargetType === 'specific' && (
                  <div className="p-4 bg-slate-50 border border-slate-200 rounded-xl space-y-3 animate-fadeIn">
                    <div className="flex justify-between items-center">
                      <label className="text-[10px] font-bold text-slate-500 uppercase block">Search & Select Specific Users ({composeTargetUsers.length} selected)</label>
                      {composeTargetUsers.length > 0 && (
                        <button
                          type="button"
                          onClick={() => setComposeTargetUsers([])}
                          className="text-[10px] font-bold text-red-500 hover:text-red-700 cursor-pointer"
                        >
                          Clear Selection
                        </button>
                      )}
                    </div>

                    {/* Selected Users Badges / Pills */}
                    {composeTargetUsers.length > 0 && (
                      <div className="flex flex-wrap gap-1.5 p-2 bg-white border border-slate-100 rounded-lg max-h-24 overflow-y-auto">
                        {composeTargetUsers.map(userId => {
                          const u = mockUsersList.find(usr => usr.id === userId);
                          if (!u) return null;
                          return (
                            <span key={userId} className="inline-flex items-center gap-1 px-2.5 py-0.5 bg-slate-100 border border-slate-200 text-slate-700 rounded-full text-[10px] font-semibold">
                              <span>{u.name} ({u.role.toUpperCase()})</span>
                              <button
                                type="button"
                                onClick={() => setComposeTargetUsers(prev => prev.filter(id => id !== userId))}
                                className="hover:bg-slate-200 rounded-full p-0.5 text-slate-400 hover:text-slate-600 cursor-pointer"
                              >
                                <X className="w-2.5 h-2.5" />
                              </button>
                            </span>
                          );
                        })}
                      </div>
                    )}

                    {/* Search Field */}
                    <div className="relative">
                      <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-slate-400" />
                      <input
                        type="text"
                        placeholder="Search users by name, phone or group..."
                        value={userSearchQuery}
                        onChange={(e) => setUserSearchQuery(e.target.value)}
                        className="w-full pl-8 pr-3 py-1.5 border border-slate-200 rounded-lg text-xs bg-white text-slate-700 focus:outline-none focus:ring-1 focus:ring-accent"
                      />
                    </div>

                    {/* Quick helper controls */}
                    <div className="flex gap-2">
                      <button
                        type="button"
                        onClick={() => {
                          const filteredIds = mockUsersList
                            .filter(usr => {
                              const q = userSearchQuery.toLowerCase();
                              return usr.name.toLowerCase().includes(q) || usr.phone.includes(q) || usr.role.includes(q);
                            })
                            .map(u => u.id);
                          setComposeTargetUsers(prev => Array.from(new Set([...prev, ...filteredIds])));
                        }}
                        className="text-[10px] font-bold text-accent hover:text-accent-dark cursor-pointer animate-pulse"
                      >
                        Select All Filtered
                      </button>
                    </div>

                    {/* Scrollable list of users */}
                    <div className="border border-slate-200 rounded-lg max-h-40 overflow-y-auto bg-white divide-y divide-slate-100">
                      {mockUsersList
                        .filter(usr => {
                          const q = userSearchQuery.toLowerCase();
                          return usr.name.toLowerCase().includes(q) || usr.phone.includes(q) || usr.role.includes(q);
                        })
                        .map(usr => {
                          const isSelected = composeTargetUsers.includes(usr.id);
                          return (
                            <div
                              key={usr.id}
                              onClick={() => {
                                setComposeTargetUsers(prev =>
                                  isSelected ? prev.filter(id => id !== usr.id) : [...prev, usr.id]
                                );
                              }}
                              className={`flex items-center justify-between p-2 text-xs cursor-pointer hover:bg-slate-50 transition-colors ${isSelected ? 'bg-accent/5' : ''
                                }`}
                            >
                              <div className="flex items-center gap-2">
                                <div className="w-6 h-6 rounded-full bg-slate-100 flex items-center justify-center font-bold text-slate-600 text-[10px]">
                                  {usr.name.charAt(0)}
                                </div>
                                <div>
                                  <p className="font-bold text-slate-800">{usr.name}</p>
                                  <p className="text-[10px] text-slate-400">{usr.phone} • <span className="capitalize">{usr.role}</span></p>
                                </div>
                              </div>
                              <input
                                type="checkbox"
                                checked={isSelected}
                                onChange={() => { }} // toggled by parent div onClick
                                className="w-3.5 h-3.5 accent-accent"
                              />
                            </div>
                          );
                        })}
                    </div>
                  </div>
                )}
              </div>

              {/* Template Selector Dropdown */}
              <div className="space-y-1">
                <label className="text-xs font-bold text-slate-700 uppercase tracking-wider block">Message Template (Optional)</label>
                <select
                  value={selectedTemplateId}
                  onChange={(e) => {
                    const templateId = e.target.value;
                    setSelectedTemplateId(templateId);
                    if (templateId) {
                      const template = messageTemplates.find(t => t.id === templateId);
                      if (template) {
                        setComposeTitle(template.subject);
                        setComposeMessage(template.body);
                        // Automatically check channels based on template type
                        setComposeChannels(prev => ({
                          ...prev,
                          email: template.type === 'email',
                          sms: template.type === 'sms',
                          push: true // Keep push alert active by default
                        }));
                      }
                    } else {
                      setComposeTitle('');
                      setComposeMessage('');
                    }
                  }}
                  className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm bg-white focus:outline-none focus:ring-1 focus:ring-accent"
                >
                  <option value="">-- Select Template --</option>
                  <option disabled className="font-semibold text-slate-400">Email Templates</option>
                  {messageTemplates.filter(t => t.type === 'email').map(t => (
                    <option key={t.id} value={t.id}>&nbsp;&nbsp;{t.name}</option>
                  ))}
                  <option disabled className="font-semibold text-slate-400">SMS Templates</option>
                  {messageTemplates.filter(t => t.type === 'sms').map(t => (
                    <option key={t.id} value={t.id}>&nbsp;&nbsp;{t.name}</option>
                  ))}
                </select>
              </div>

              {/* Subject Title */}
              <div className="space-y-1">
                <label className="text-xs font-bold text-slate-700 uppercase tracking-wider block">3. Message Header Title</label>
                <input
                  type="text"
                  placeholder="e.g. Action Required: Weekly Rental Invoice Generated"
                  value={composeTitle}
                  onChange={(e) => setComposeTitle(e.target.value)}
                  className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm bg-white focus:outline-none focus:ring-1 focus:ring-accent"
                />
              </div>

              {/* Message Content */}
              <div className="space-y-1">
                <div className="flex justify-between items-center">
                  <label className="text-xs font-bold text-slate-700 uppercase tracking-wider block">4. Main Message Text</label>
                  <span className="text-[10px] text-slate-400">{composeMessage.length} characters</span>
                </div>
                <textarea
                  rows={4}
                  placeholder="Compose your custom text, html, or notification alert details here..."
                  value={composeMessage}
                  onChange={(e) => setComposeMessage(e.target.value)}
                  className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm bg-white focus:outline-none focus:ring-1 focus:ring-accent"
                />
              </div>

              {/* Scheduling Section */}
              <div className="border-t border-slate-100 pt-4 space-y-3">
                <label className="flex items-center gap-2 cursor-pointer select-none">
                  <input
                    type="checkbox"
                    checked={composeIsScheduled}
                    onChange={(e) => setComposeIsScheduled(e.target.checked)}
                    className="w-4 h-4 accent-accent rounded"
                  />
                  <span className="text-xs font-bold text-slate-700 uppercase tracking-wider">Schedule for later</span>
                </label>

                {composeIsScheduled && (
                  <div className="grid grid-cols-2 gap-3 p-3 bg-slate-50 border border-slate-200 rounded-xl animate-fadeIn">
                    <div>
                      <label className="text-[10px] font-bold text-slate-500 uppercase block mb-1">Select Date</label>
                      <div className="relative">
                        <Calendar className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
                        <input
                          type="date"
                          value={composeScheduleDate}
                          onChange={(e) => setComposeScheduleDate(e.target.value)}
                          className="w-full pl-9 pr-3 py-2 border border-slate-200 rounded-lg text-xs bg-white focus:outline-none"
                        />
                      </div>
                    </div>
                    <div>
                      <label className="text-[10px] font-bold text-slate-500 uppercase block mb-1">Select Time</label>
                      <div className="relative">
                        <Clock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
                        <input
                          type="time"
                          value={composeScheduleTime}
                          onChange={(e) => setComposeScheduleTime(e.target.value)}
                          className="w-full pl-9 pr-3 py-2 border border-slate-200 rounded-lg text-xs bg-white focus:outline-none"
                        />
                      </div>
                    </div>
                  </div>
                )}
              </div>

              {/* Action Buttons */}
              <div className="border-t border-slate-100 pt-4 flex gap-2 justify-end">
                <button
                  type="button"
                  onClick={() => setShowComposeModal(false)}
                  className="py-2.5 px-4 bg-white border border-slate-200 text-slate-600 rounded-lg text-xs font-semibold hover:bg-slate-50 transition-colors"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={isSending}
                  className="py-2.5 px-5 bg-accent hover:bg-accent-dark text-white rounded-lg text-xs font-semibold transition-all shadow-md shadow-accent/10 flex items-center gap-1.5"
                >
                  <Send className="w-3.5 h-3.5" /> {composeIsScheduled ? 'Schedule Broadcast' : 'Send Broadcast'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* ========================================= SENDING DISPATCHING PROCESS ANIMATION ========================================= */}
      {isSending && (
        <div className="fixed inset-0 bg-black/80 backdrop-blur-md z-[100] flex items-center justify-center p-4">
          <div className="bg-slate-900 border border-slate-800 p-8 rounded-2xl shadow-2xl max-w-sm w-full text-center space-y-4">
            <div className="w-16 h-16 border-4 border-accent border-t-transparent rounded-full animate-spin mx-auto" />
            <h3 className="text-white font-extrabold text-lg">Dispatching Broadcast</h3>
            <p className="text-slate-400 text-xs animate-pulse">{sendingStep}</p>
          </div>
        </div>
      )}

      {/* ========================================= ALERT INBOX DETAIL MODAL ========================================= */}
      {selectedNotif && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-xl shadow-2xl w-full max-w-lg overflow-hidden border border-slate-100 flex flex-col max-h-[85vh]">
            <div className="p-4 bg-slate-50 border-b border-slate-100 flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Bell className="w-5 h-5 text-accent animate-bounce" />
                <h3 className="font-extrabold text-slate-800">Alert Details</h3>
              </div>
              <button
                onClick={() => setSelectedNotif(null)}
                className="p-1 hover:bg-slate-200 rounded-lg transition-colors text-slate-400 hover:text-slate-600"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="p-6 overflow-y-auto space-y-6 flex-1">
              <div className="flex items-center gap-2">
                {getCategoryBadge(selectedNotif.category)}
                {getPriorityBadge(selectedNotif.priority)}
              </div>

              <div>
                <h4 className="text-base font-extrabold text-slate-800 leading-snug">{selectedNotif.title}</h4>
                <p className="text-[10px] text-slate-400 mt-1">
                  Time Triggered: {new Date(selectedNotif.time).toLocaleString()}
                </p>
              </div>

              <div className="p-4 bg-slate-50 border border-slate-150 rounded-xl">
                <p className="text-sm font-semibold text-slate-700">Event Message</p>
                <p className="text-xs text-slate-600 mt-1 leading-relaxed">{selectedNotif.message}</p>
              </div>

              {selectedNotif.meta?.details && (
                <div className="space-y-2">
                  <p className="text-sm font-semibold text-slate-700">Detailed Context Metadata</p>
                  <div className="border border-slate-100 rounded-xl divide-y divide-slate-50 overflow-hidden bg-white">
                    {Object.entries(selectedNotif.meta.details).map(([key, val]) => (
                      <div key={key} className="flex justify-between p-2.5 text-xs">
                        <span className="text-slate-400 font-semibold">{key}</span>
                        <span className="text-slate-700 font-bold text-right">{val}</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>

            <div className="p-4 bg-slate-50 border-t border-slate-100 flex gap-2 justify-end">
              <button
                onClick={() => {
                  if (!selectedNotif.read) markAsRead(selectedNotif.id);
                  setSelectedNotif(null);
                }}
                className="py-2 px-4 bg-white border border-slate-200 text-slate-600 rounded-lg text-xs font-semibold hover:bg-slate-100 transition-colors"
              >
                Dismiss / Close
              </button>
              {selectedNotif.meta?.link && (
                <Link
                  href={selectedNotif.meta.link}
                  onClick={() => {
                    if (!selectedNotif.read) markAsRead(selectedNotif.id);
                    setSelectedNotif(null);
                  }}
                  className="py-2 px-4 bg-accent hover:bg-accent-dark text-white rounded-lg text-xs font-semibold transition-colors flex items-center gap-1"
                >
                  {selectedNotif.meta.actionLabel || 'Go to Actions'} <ChevronRight className="w-3.5 h-3.5" />
                </Link>
              )}
            </div>
          </div>
        </div>
      )}

      {/* ========================================= SENT BROADCAST DETAIL MODAL ========================================= */}
      {selectedBroadcast && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-xl shadow-2xl w-full max-w-lg overflow-hidden border border-slate-100 flex flex-col max-h-[85vh]">
            <div className="p-4 bg-slate-50 border-b border-slate-100 flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Send className="w-5 h-5 text-accent animate-pulse" />
                <h3 className="font-extrabold text-slate-800">Broadcast Log Details</h3>
              </div>
              <button
                onClick={() => setSelectedBroadcast(null)}
                className="p-1 hover:bg-slate-200 rounded-lg transition-colors text-slate-400 hover:text-slate-600"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="p-6 overflow-y-auto space-y-6 flex-1">

              <div className="flex items-center gap-2 flex-wrap">
                <span className="inline-flex items-center gap-1 px-2.5 py-1 bg-accent/5 border border-accent/20 rounded-full text-xs font-bold text-accent">
                  <Send className="w-3 h-3" /> Dispatched Announcement
                </span>
                <span className="px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider bg-green-100 text-green-800">
                  {selectedBroadcast.status}
                </span>
              </div>

              <div>
                <h4 className="text-base font-extrabold text-slate-800 leading-snug">{selectedBroadcast.title}</h4>
                <p className="text-[10px] text-slate-400 mt-1">
                  Sent: {new Date(selectedBroadcast.sentAt).toLocaleString()}
                </p>
              </div>

              <div className="p-4 bg-slate-50 border border-slate-150 rounded-xl">
                <p className="text-sm font-semibold text-slate-700">Announced Content</p>
                <p className="text-xs text-slate-600 mt-1 leading-relaxed whitespace-pre-wrap">{selectedBroadcast.message}</p>
              </div>

              {/* Channels & Targets Details */}
              <div className="space-y-2">
                <p className="text-sm font-semibold text-slate-700">Broadcast Parameters</p>
                <div className="border border-slate-100 rounded-xl divide-y divide-slate-50 bg-white">
                  <div className="flex justify-between p-3 text-xs">
                    <span className="text-slate-400 font-semibold">Message Target Rules</span>
                    <span className="text-slate-750 font-extrabold">{selectedBroadcast.targetValue}</span>
                  </div>
                  <div className="flex justify-between p-3 text-xs">
                    <span className="text-slate-400 font-semibold">Total Targeted Recipients</span>
                    <span className="text-slate-750 font-extrabold">{selectedBroadcast.recipientCount} accounts</span>
                  </div>
                  <div className="flex justify-between p-3 text-xs">
                    <span className="text-slate-400 font-semibold">Dispatch Channels</span>
                    <span className="text-slate-750 font-extrabold capitalize">{selectedBroadcast.channels.join(', ')}</span>
                  </div>
                </div>
              </div>
            </div>

            <div className="p-4 bg-slate-50 border-t border-slate-100 flex gap-2 justify-end">
              <button
                onClick={() => setSelectedBroadcast(null)}
                className="py-2 px-4 bg-accent hover:bg-accent-dark text-white rounded-lg text-xs font-semibold hover:bg-slate-100 transition-colors"
              >
                Done / Close
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ========================================= COLLAPSIBLE SIMULATOR DRAWER (MOBILE FRIENDLY) ========================================= */}
      {showSimulatorDrawer && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-end">
          <div className="bg-slate-900 border border-slate-800 text-white w-full max-w-sm h-full shadow-2xl p-6 flex flex-col justify-between animate-slideLeft">
            <div className="space-y-6">
              <div className="flex items-center justify-between border-b border-slate-800 pb-4">
                <h3 className="font-extrabold text-sm flex items-center gap-2 text-emerald-400">
                  <Play className="w-4 h-4" /> SYSTEM EVENT SIMULATOR
                </h3>
                <button
                  onClick={() => setShowSimulatorDrawer(false)}
                  className="p-1 hover:bg-white/10 rounded-lg transition-colors text-white"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>
              <p className="text-xs text-slate-400">Simulate real-time external events to verify database pipelines, toaster notifications, and dashboard stats.</p>

              <div className="space-y-3 pt-2">
                {[
                  { id: 'kyc', label: 'Simulate Biker KYC Upload', desc: 'Adds walker-in application event', color: 'text-blue-400' },
                  { id: 'overdue', label: 'Simulate Rental 7d Overdue', desc: 'Adds critical fine immobilization log', color: 'text-red-400' },
                  { id: 'battery', label: 'Simulate Battery Alert (90°C)', desc: 'Adds battery fast charge overheat trigger', color: 'text-amber-400' },
                  { id: 'investment', label: 'Simulate Investor Deposit', desc: 'Adds investor deposit partial log', color: 'text-indigo-400' }
                ].map(sim => (
                  <button
                    key={sim.id}
                    onClick={() => { triggerSimulation(sim.id); setShowSimulatorDrawer(false); }}
                    className="w-full flex flex-col p-3 rounded-xl bg-white/5 border border-white/10 hover:bg-white/10 text-left transition-all group cursor-pointer"
                  >
                    <div className="flex items-center justify-between w-full">
                      <span className="text-xs font-bold text-white">{sim.label}</span>
                      <PlusCircle className={`w-4 h-4 ${sim.color} opacity-50 group-hover:opacity-100 transition-opacity`} />
                    </div>
                    <span className="text-[10px] text-slate-400 mt-1">{sim.desc}</span>
                  </button>
                ))}
              </div>
            </div>

            <div className="border-t border-slate-800 pt-4">
              <button
                onClick={() => setShowSimulatorDrawer(false)}
                className="w-full py-2 bg-white/5 hover:bg-white/10 text-slate-300 rounded-lg text-xs font-bold text-center border border-white/10 transition-colors"
              >
                Close Panel
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
