import { useState, useMemo, useRef, useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import Fuse from 'fuse.js';
import {
  Search,
  ChevronRight,
  LogIn,
  LayoutDashboard,
  Radio,
  Users,
  Car,
  Calendar,
  Plane,
  MapPin,
  FileText,
  UserCog,
  Settings,
  Bot,
  HelpCircle,
  BookOpen,
  X,
  Menu,
  Shield,
  Clock,
  AlertTriangle,
  CheckCircle,
} from 'lucide-react';

// ─── Help Content Data ───────────────────────────────────────────────────────

interface HelpSection {
  id: string;
  title: string;
  icon: any;
  category: string;
  keywords: string[];
  content: HelpArticle[];
}

interface HelpArticle {
  id: string;
  title: string;
  body: string;
  steps?: string[];
  tip?: string;
  warning?: string;
  image?: string;
}

const helpSections: HelpSection[] = [
  {
    id: 'getting-started',
    title: 'Getting Started',
    icon: LogIn,
    category: 'Basics',
    keywords: ['login', 'sign in', 'account', 'password', 'auth0', 'register', 'new user', 'first time', 'getting started', 'setup'],
    content: [
      {
        id: 'logging-in',
        title: 'Logging In',
        body: 'Navigate to the VIP Coordinator URL and click "Sign in with Auth0." Enter your email and password on the Auth0 login screen. After authentication, you\'ll be directed to the Dashboard (or My Schedule for drivers).',
        steps: [
          'Open your browser and go to the VIP Coordinator URL.',
          'Click the "Sign in with Auth0" button.',
          'Enter your email address and password.',
          'Click "Continue" to authenticate.',
          'You\'ll be redirected to the application.',
        ],
        tip: 'Your login session persists across browser refreshes. You won\'t need to log in again unless you sign out or your session expires.',
        image: '/help-assets/screenshots/01-login-page.png',
      },
      {
        id: 'first-time-users',
        title: 'First-Time Users & Approval',
        body: 'When you first sign up, your account requires administrator approval. You\'ll see a "Pending Approval" page until an admin activates your account. The very first user to register is automatically approved as an Administrator.',
        tip: 'Contact your team lead if your account hasn\'t been approved yet. They can approve it from the User Management page.',
      },
      {
        id: 'user-roles',
        title: 'Understanding Your Role',
        body: 'VIP Coordinator has three roles with different access levels:\n\n**Administrator** \u2014 Full system access including user management, admin tools, and all features.\n\n**Coordinator** \u2014 Can manage VIPs, drivers, events, flights, and view reports. Cannot manage users or admin settings.\n\n**Driver** \u2014 Limited view focused on their own schedule. Can see assigned events and update their status (In Progress, Completed).',
      },
    ],
  },
  {
    id: 'navigation',
    title: 'Navigation',
    icon: BookOpen,
    category: 'Basics',
    keywords: ['menu', 'navigation', 'sidebar', 'top bar', 'admin menu', 'mobile', 'find page'],
    content: [
      {
        id: 'nav-overview',
        title: 'Navigation Overview',
        body: 'The top navigation bar provides quick access to all sections:\n\n- **Dashboard** \u2014 Overview of today\'s activities and stats\n- **War Room** \u2014 Real-time command center for active operations\n- **VIPs** \u2014 Manage VIP profiles and travel details\n- **Fleet** \u2014 Manage drivers and vehicles\n- **Activities** \u2014 Schedule and track events\n- **Flights** \u2014 Track flight arrivals and departures\n- **Admin** (dropdown) \u2014 Users, Reports, GPS Tracking, Admin Tools, Help\n\nYour profile avatar appears in the top-right. Click it to switch themes, change appearance, or sign out.',
        image: '/help-assets/screenshots/03-dashboard.png',
      },
      {
        id: 'mobile-nav',
        title: 'Mobile Navigation',
        body: 'On tablets and phones, the navigation collapses into a hamburger menu. Tap the menu icon (\u2630) in the top-left to open the navigation drawer. The drawer includes all the same links plus your user info and a sign-out button.',
        tip: 'The app is fully responsive \u2014 all features work on mobile browsers.',
      },
    ],
  },
  {
    id: 'dashboard',
    title: 'Dashboard',
    icon: LayoutDashboard,
    category: 'Core Features',
    keywords: ['dashboard', 'home', 'overview', 'summary', 'today', 'stats', 'quick actions'],
    content: [
      {
        id: 'dashboard-overview',
        title: 'Using the Dashboard',
        body: 'The Dashboard is your home base with a quick snapshot of the current situation. You\'ll see summary cards showing the count of VIPs, drivers, vehicles, and today\'s events. Below are today\'s schedule timeline, recent activity, and quick-action shortcuts.',
        tip: 'The Dashboard auto-refreshes. It\'s a great page to keep open as your primary monitoring screen.',
        image: '/help-assets/screenshots/03-dashboard.png',
      },
    ],
  },
  {
    id: 'war-room',
    title: 'War Room',
    icon: Radio,
    category: 'Core Features',
    keywords: ['war room', 'command center', 'real-time', 'active events', 'urgent', 'in progress', 'operations', 'live'],
    content: [
      {
        id: 'war-room-overview',
        title: 'Using the War Room',
        body: 'The War Room is your real-time operations center for active event coordination. It shows live status of all events happening now, upcoming events sorted by urgency, and which drivers are currently assigned.',
        image: '/help-assets/screenshots/04-war-room.png',
      },
      {
        id: 'war-room-colors',
        title: 'Event Status Colors',
        body: 'Events in the War Room are color-coded:\n\n- **Red / Urgent** \u2014 Events starting in the next 5-15 minutes\n- **Blue / In Progress** \u2014 Currently active events\n- **Green / Completed** \u2014 Recently finished events\n- **Gray / Scheduled** \u2014 Upcoming events\n\nClick any event card to view details or update its status.',
        tip: 'Keep the War Room open on a large screen or dedicated monitor during active operations for best situational awareness.',
      },
    ],
  },
  {
    id: 'vips',
    title: 'VIP Management',
    icon: Users,
    category: 'Core Features',
    keywords: ['vip', 'guest', 'visitor', 'add vip', 'create vip', 'edit vip', 'delete vip', 'organization', 'department', 'arrival', 'party size', 'emergency contact', 'phone', 'email', 'roster'],
    content: [
      {
        id: 'vip-list',
        title: 'Viewing VIPs',
        body: 'Navigate to **VIPs** from the top menu to see all VIP profiles. Use the search bar to filter by name or organization, and the department filter to narrow results. Each row shows the VIP\'s name, organization, department, arrival mode, and party size.',
        image: '/help-assets/screenshots/05-vip-list.png',
      },
      {
        id: 'add-vip',
        title: 'Adding a New VIP',
        body: 'Click **"+ Add VIP"** on the VIP List page to create a new VIP profile.',
        steps: [
          'Click "+ Add VIP" button in the top-right.',
          'Enter the VIP\'s name (required).',
          'Select their department (Office of Development, Admin, or Other).',
          'Choose arrival mode: Flight or Self-Driving.',
          'Optionally set: organization, airport pickup, venue transport, party size, and notes.',
          'Click "Save" to create the profile.',
        ],
        image: '/help-assets/screenshots/06-vip-edit-form.png',
      },
      {
        id: 'vip-contact-info',
        title: 'VIP Contact & Emergency Info',
        body: 'Each VIP can have contact and emergency information stored. Scroll down in the VIP edit form to find these fields:\n\n- **Phone** \u2014 VIP\'s phone number\n- **Email** \u2014 VIP\'s email address\n- **Emergency Contact Name** \u2014 Name of emergency contact\n- **Emergency Contact Phone** \u2014 Emergency contact number\n\nThis information appears on the Accountability Roster report.',
        tip: 'Fill in emergency contacts for all VIPs attending large events. This information is critical for safety and accountability.',
        image: '/help-assets/screenshots/07-vip-edit-contact-info.png',
      },
      {
        id: 'vip-roster-only',
        title: 'Roster-Only VIPs',
        body: 'Check the **"Roster Only"** option for VIPs you\'re tracking for accountability purposes only (not actively coordinating transport for). Roster-only VIPs appear in reports but don\'t clutter the active coordination views.',
      },
    ],
  },
  {
    id: 'fleet',
    title: 'Fleet Management',
    icon: Car,
    category: 'Core Features',
    keywords: ['fleet', 'driver', 'vehicle', 'van', 'suv', 'sedan', 'bus', 'add driver', 'add vehicle', 'enroll', 'phone', 'license plate', 'seat capacity', 'availability'],
    content: [
      {
        id: 'drivers-tab',
        title: 'Managing Drivers',
        body: 'Navigate to **Fleet** to see the Drivers tab. This shows all drivers including their name, phone, department, availability status, and whether they have a linked user account.',
        image: '/help-assets/screenshots/08-fleet-drivers.png',
      },
      {
        id: 'add-driver',
        title: 'Adding a Driver',
        body: 'Add a new driver to the system so they can be assigned to events.',
        steps: [
          'Go to Fleet and ensure the Drivers tab is selected.',
          'Click "+ Add Driver".',
          'Enter the driver\'s full name (required).',
          'Enter their phone number (required).',
          'Optionally select a department.',
          'Optionally link to a user account (for app login access).',
          'Click "Create Driver".',
        ],
        tip: 'To give a driver login access: have them sign up first, then link their user account here. They\'ll see a "My Schedule" page with their assignments.',
      },
      {
        id: 'vehicles-tab',
        title: 'Managing Vehicles',
        body: 'Click the **Vehicles** tab in Fleet to see your entire fleet. Each vehicle shows its name, type, license plate, seat capacity, status, and currently assigned driver.',
        image: '/help-assets/screenshots/09-fleet-vehicles.png',
      },
      {
        id: 'add-vehicle',
        title: 'Adding a Vehicle',
        body: 'Add vehicles to your fleet so they can be assigned to events.',
        steps: [
          'Go to Fleet and click the Vehicles tab.',
          'Click "+ Add Vehicle".',
          'Enter a recognizable name (e.g., "Blue Van", "Suburban #3").',
          'Select the vehicle type (Van, SUV, Sedan, Bus, Golf Cart, Truck).',
          'Enter the seat capacity.',
          'Optionally add license plate and notes.',
          'Click "Create Vehicle".',
        ],
        tip: 'Keep vehicle names simple and distinctive. Names like "White Suburban" or "Van #2" help coordinators quickly identify vehicles during operations.',
      },
    ],
  },
  {
    id: 'activities',
    title: 'Activities & Scheduling',
    icon: Calendar,
    category: 'Core Features',
    keywords: ['activity', 'event', 'schedule', 'transport', 'meeting', 'meal', 'accommodation', 'create event', 'conflict', 'assign driver', 'assign vehicle', 'pickup', 'dropoff', 'status'],
    content: [
      {
        id: 'viewing-activities',
        title: 'Viewing Activities',
        body: 'Navigate to **Activities** to see all scheduled events. Filter by status (Scheduled, In Progress, Completed, Cancelled), date, or type. Use the search bar to find events by title, VIP name, or location.',
        image: '/help-assets/screenshots/10-activities.png',
      },
      {
        id: 'create-activity',
        title: 'Creating an Activity',
        body: 'Schedule a new transport, meeting, meal, or other event.',
        steps: [
          'Click "+ New Activity" on the Activities page.',
          'Enter a descriptive title.',
          'Select the event type (Transport, Meeting, Event, Meal, Accommodation).',
          'Choose one or more VIPs for this event.',
          'Set the start and end times.',
          'Optionally assign a driver and vehicle.',
          'For transport: enter pickup and dropoff locations.',
          'For other types: enter the event location.',
          'Add description and notes as needed.',
          'Click "Create" to save.',
        ],
        tip: 'The system automatically checks for scheduling conflicts with drivers, vehicles, and VIPs. You\'ll see a warning if there\'s an overlap.',
      },
      {
        id: 'activity-types',
        title: 'Activity Types',
        body: '| Type | Use For |\n|------|------|\n| **Transport** | Airport pickups, venue-to-venue rides, departure drops |\n| **Meeting** | Scheduled meetings between VIPs and hosts |\n| **Event** | Conferences, ceremonies, tours |\n| **Meal** | Breakfast, lunch, dinner, receptions |\n| **Accommodation** | Hotel check-in / check-out |',
      },
      {
        id: 'conflict-detection',
        title: 'Conflict Detection',
        body: 'When creating or editing an activity, the system automatically checks for:\n\n- **Driver conflicts** \u2014 A driver can\'t be assigned to two events simultaneously\n- **Vehicle conflicts** \u2014 A vehicle can\'t be double-booked\n- **VIP conflicts** \u2014 A VIP can\'t be in two places at once\n\nIf a conflict is detected, you\'ll see a warning with details about the overlapping event. You can adjust the timing or proceed anyway.',
        warning: 'Proceeding past a conflict warning means you\'re accepting the scheduling overlap. Make sure you have a plan for handling it.',
      },
    ],
  },
  {
    id: 'flights',
    title: 'Flight Tracking',
    icon: Plane,
    category: 'Core Features',
    keywords: ['flight', 'airline', 'airport', 'iata', 'arrival', 'departure', 'delayed', 'landed', 'tracking', 'flight number'],
    content: [
      {
        id: 'viewing-flights',
        title: 'Viewing Flights',
        body: 'Navigate to **Flights** to see all tracked flights. The page shows flight number, route (departure/arrival airports), date, scheduled and actual times, status, and which VIP is on each flight.',
        image: '/help-assets/screenshots/11-flights.png',
      },
      {
        id: 'adding-flight',
        title: 'Adding a Flight',
        body: 'Flights are typically added through the VIP edit form.',
        steps: [
          'Edit a VIP\'s profile.',
          'In the Flights section, click "+ Add Flight".',
          'Enter the flight number (e.g., "AA1234").',
          'Set the flight date.',
          'Enter departure airport (IATA code, e.g., "JFK").',
          'Enter arrival airport (IATA code, e.g., "LAX").',
          'For multi-leg itineraries, set the segment number.',
          'Save the VIP profile.',
        ],
        tip: 'Use standard 3-letter IATA airport codes (JFK, LAX, ORD, ATL). The system uses these to auto-track flight status when an API key is configured.',
      },
    ],
  },
  {
    id: 'gps-tracking',
    title: 'GPS Tracking',
    icon: MapPin,
    category: 'Advanced Features',
    keywords: ['gps', 'tracking', 'location', 'map', 'traccar', 'enroll', 'device', 'driver location', 'real-time', 'live map', 'privacy', 'shift hours', 'battery'],
    content: [
      {
        id: 'gps-overview',
        title: 'GPS Tracking Overview',
        body: 'The GPS Tracking page provides real-time location monitoring for your driver fleet. The dashboard shows total enrolled devices, active drivers, update interval, and shift hours. Navigate between Live Map, Devices, Stats, and Settings tabs.',
        image: '/help-assets/screenshots/15-gps-tracking.png',
      },
      {
        id: 'enroll-driver-gps',
        title: 'Enrolling a Driver for GPS',
        body: 'Set up a driver for real-time location tracking.',
        steps: [
          'Go to GPS Tracking and click the "Devices" tab.',
          'Click "Enroll Driver".',
          'Select the driver from the dropdown.',
          'The system creates a unique device identifier.',
          'Have the driver install "Traccar Client" on their phone (iOS App Store or Google Play).',
          'In the Traccar Client app, enter the device identifier and server URL.',
          'Set the reporting frequency to match your GPS settings (e.g., 30 seconds).',
          'Enable tracking in the app.',
          'The driver\'s location will appear on the Live Map.',
        ],
        tip: 'GPS tracking respects driver privacy \u2014 tracking only occurs during configured shift hours. Drivers must give consent.',
        image: '/help-assets/screenshots/16-gps-devices.png',
      },
      {
        id: 'gps-settings',
        title: 'GPS Settings',
        body: 'Configure GPS tracking behavior from the Settings tab:\n\n- **Update Interval** (30-300 seconds) \u2014 How often drivers report location. Lower = more precise but higher battery drain.\n- **Data Retention** (7-90 days) \u2014 How long location history is stored before cleanup.\n- **Tracking Hours** \u2014 Start and end times for when tracking is active. Drivers are NOT tracked outside these hours.',
        tip: 'For most events, 30-60 second intervals balance tracking precision with battery life. Lower to 15-30 seconds only during critical operations.',
        image: '/help-assets/screenshots/17-gps-settings.png',
      },
    ],
  },
  {
    id: 'reports',
    title: 'Reports',
    icon: FileText,
    category: 'Advanced Features',
    keywords: ['report', 'roster', 'accountability', 'pdf', 'download', 'print', 'emergency contact', 'export'],
    content: [
      {
        id: 'accountability-roster',
        title: 'VIP Accountability Roster',
        body: 'The Accountability Roster is a comprehensive report for event-day use. It includes each VIP\'s name, organization, contact info, emergency contacts, arrival mode, assigned driver/vehicle, flight details, party size, and special notes.',
        steps: [
          'Navigate to Admin > Reports.',
          'The roster displays on screen with all active VIPs.',
          'Click "Download PDF" to generate a formatted PDF document.',
          'The PDF uses your configured branding from Admin Tools.',
        ],
        tip: 'Print the Accountability Roster before each event as a backup reference. It\'s invaluable during emergencies when you need quick access to VIP contact and emergency information.',
        image: '/help-assets/screenshots/12-reports.png',
      },
    ],
  },
  {
    id: 'user-management',
    title: 'User Management',
    icon: UserCog,
    category: 'Administration',
    keywords: ['user', 'approve', 'role', 'administrator', 'coordinator', 'driver', 'pending', 'account', 'permission'],
    content: [
      {
        id: 'approving-users',
        title: 'Approving New Users',
        body: 'When a new person signs up, their account is "Pending" until approved.',
        steps: [
          'Navigate to Admin > Users.',
          'Look for users with a "Pending" status badge.',
          'Click "Approve" to grant them access.',
          'The user can log in on their next attempt.',
        ],
        tip: 'The Admin menu shows a red badge with the count of pending approvals so you never miss a new user request.',
        image: '/help-assets/screenshots/13-users.png',
      },
      {
        id: 'changing-roles',
        title: 'Changing User Roles',
        body: 'Change a user\'s role to adjust their access level.',
        steps: [
          'On the Users page, find the target user.',
          'Use the Role dropdown to select: Administrator, Coordinator, or Driver.',
          'The change takes effect immediately.',
        ],
        warning: 'Be careful when removing Administrator roles \u2014 that user cannot restore their own access. Another admin must do it.',
      },
    ],
  },
  {
    id: 'admin-tools',
    title: 'Admin Tools',
    icon: Settings,
    category: 'Administration',
    keywords: ['admin', 'tools', 'database', 'statistics', 'pdf', 'branding', 'logo', 'signal', 'messaging', 'test data', 'seed', 'generate', 'clear'],
    content: [
      {
        id: 'admin-tools-overview',
        title: 'Admin Tools Overview',
        body: 'The Admin Tools page (Admin > Admin Tools) provides system management for administrators. It includes database statistics, PDF customization, Signal messaging management, and test data controls.',
        image: '/help-assets/screenshots/14-admin-tools.png',
      },
      {
        id: 'pdf-customization',
        title: 'PDF Customization',
        body: 'Customize the appearance of generated PDF reports:\n\n- **Branding** \u2014 Organization name, logo, accent color, and tagline\n- **Contact Information** \u2014 Primary and secondary contact details shown in PDFs\n- **Document Options** \u2014 Watermarks (Draft/Confidential), timestamps, page size\n- **Content Display** \u2014 Toggle visibility of flight info, driver/vehicle names, VIP notes\n- **Custom Messages** \u2014 Header and footer text\n\nClick "Preview Sample PDF" to see how your settings look, then "Save PDF Settings" to apply.',
      },
      {
        id: 'signal-messaging',
        title: 'Signal Messaging',
        body: 'Communicate with drivers via encrypted Signal messages:\n\n- **Connection Status** \u2014 Shows if Signal is connected and which phone number is linked\n- **Send Test Message** \u2014 Verify the connection works\n- **Chat History** \u2014 View message statistics and manage chat records',
      },
      {
        id: 'test-data',
        title: 'Test Data Management',
        body: 'For development and demos:\n\n- **Generate Complete Test Data** \u2014 Creates 20 VIPs, 8 drivers, 10 vehicles, flights, and 100+ events with realistic times\n- **Refresh Event Times** \u2014 Regenerates events with fresh timestamps relative to now\n- **Clear All Data** \u2014 Removes everything for a fresh start',
        warning: '"Clear All Data" is irreversible. Only use it when you want to start completely fresh.',
      },
    ],
  },
  {
    id: 'ai-assistant',
    title: 'AI Assistant',
    icon: Bot,
    category: 'Advanced Features',
    keywords: ['ai', 'assistant', 'copilot', 'chat', 'ask', 'question', 'help', 'bot', 'upload', 'image', 'screenshot', 'email'],
    content: [
      {
        id: 'using-ai',
        title: 'Using the AI Assistant',
        body: 'The AI Assistant is a built-in copilot accessible from any page. It can query your live data and help with coordination tasks.',
        steps: [
          'Click the blue "AI Assistant" button in the bottom-right corner.',
          'Type your question in the chat input.',
          'Press Enter or click Send.',
          'The AI will respond with information from your live data.',
        ],
        image: '/help-assets/screenshots/18-ai-assistant.png',
      },
      {
        id: 'ai-examples',
        title: 'What to Ask the AI',
        body: 'The AI Assistant can answer questions about your data:\n\n- "What\'s happening today?"\n- "Who are the VIPs arriving by flight?"\n- "Which drivers are available right now?"\n- "Show me the schedule for Roger Mosby"\n- "What events are in progress?"\n- "How many vehicles do we have available?"\n\nYou can also **upload screenshots** of emails with travel itineraries \u2014 the AI will extract and organize the information.',
        tip: 'The AI has access to live data. Use it as a quick way to get answers without navigating through multiple pages.',
      },
    ],
  },
  {
    id: 'driver-view',
    title: 'Driver View',
    icon: Shield,
    category: 'Role-Specific',
    keywords: ['driver', 'my schedule', 'status update', 'in progress', 'completed', 'pickup', 'assignment'],
    content: [
      {
        id: 'driver-schedule',
        title: 'My Schedule (Driver View)',
        body: 'Drivers with a linked user account see a simplified interface focused on their assignments. The "My Schedule" page shows only events assigned to them, sorted by time.',
      },
      {
        id: 'driver-status-updates',
        title: 'Updating Event Status',
        body: 'Drivers can update the status of their assigned events to keep the coordination team informed.',
        steps: [
          'Open "My Schedule" from the navigation.',
          'Find the current event.',
          'Tap "Start" when you begin the pickup/transport.',
          'The event moves to "In Progress" (visible to coordinators in the War Room).',
          'Tap "Complete" when the VIP is delivered.',
          'The event moves to "Completed".',
        ],
        tip: 'Keep your event statuses updated in real-time! This helps coordinators know exactly where VIPs are at all times.',
      },
    ],
  },
  {
    id: 'faq',
    title: 'FAQ',
    icon: HelpCircle,
    category: 'Help',
    keywords: ['faq', 'question', 'problem', 'issue', 'help', 'troubleshoot', 'fix', 'password', 'approval', 'mobile', 'phone'],
    content: [
      {
        id: 'faq-pending',
        title: 'I signed up but can\'t access anything',
        body: 'Your account needs administrator approval. Contact your team lead and ask them to approve your account in the User Management section (Admin > Users).',
      },
      {
        id: 'faq-driver-schedule',
        title: 'I\'m a driver but can\'t see my schedule',
        body: 'Your user account needs to be linked to a driver profile. An administrator must go to Fleet > Drivers, find your driver record, and enter your User Account ID.',
      },
      {
        id: 'faq-mobile',
        title: 'Can I use this on my phone?',
        body: 'Yes! The web application is fully responsive and works on mobile browsers. Navigate to the same URL on your phone. For GPS tracking, you\'ll also need the Traccar Client app.',
      },
      {
        id: 'faq-password',
        title: 'How do I change my password?',
        body: 'Passwords are managed through Auth0. Click your profile avatar in the top-right corner, or use the "Forgot Password" option on the login screen to reset your password.',
      },
      {
        id: 'faq-conflict',
        title: 'What happens if two events conflict?',
        body: 'The system warns you about scheduling conflicts when creating or editing events. You\'ll see which driver, vehicle, or VIP has an overlapping booking. You can adjust the timing or choose to proceed with the overlap.',
      },
      {
        id: 'faq-gps-always-on',
        title: 'Is GPS tracking always on?',
        body: 'No. GPS tracking only operates during configured Shift Hours (set by administrators in GPS Settings). Outside those hours, driver locations are not tracked or recorded.',
      },
      {
        id: 'faq-data-retention',
        title: 'How long is location data kept?',
        body: 'Location data is automatically deleted after the configured retention period (default: 30 days). Administrators can adjust this in GPS Settings from 7 to 90 days.',
      },
    ],
  },
];

// ─── Categories ──────────────────────────────────────────────────────────────

const categories = [
  { name: 'Basics', icon: BookOpen },
  { name: 'Core Features', icon: LayoutDashboard },
  { name: 'Advanced Features', icon: Settings },
  { name: 'Administration', icon: Shield },
  { name: 'Role-Specific', icon: Users },
  { name: 'Help', icon: HelpCircle },
];

// ─── Fuse.js Search Setup ────────────────────────────────────────────────────

interface SearchableItem {
  sectionId: string;
  sectionTitle: string;
  articleId: string;
  articleTitle: string;
  body: string;
  keywords: string[];
  steps: string;
}

function buildSearchIndex(): SearchableItem[] {
  const items: SearchableItem[] = [];
  for (const section of helpSections) {
    for (const article of section.content) {
      items.push({
        sectionId: section.id,
        sectionTitle: section.title,
        articleId: article.id,
        articleTitle: article.title,
        body: article.body,
        keywords: section.keywords,
        steps: article.steps?.join(' ') || '',
      });
    }
  }
  return items;
}

// ─── Main Component ──────────────────────────────────────────────────────────

export function Help() {
  const location = useLocation();
  const [searchQuery, setSearchQuery] = useState('');
  const [activeSection, setActiveSection] = useState<string | null>(null);
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const contentRef = useRef<HTMLDivElement>(null);
  const sectionRefs = useRef<Record<string, HTMLDivElement | null>>({});
  const articleRefs = useRef<Record<string, HTMLDivElement | null>>({});

  // Build search index
  const searchIndex = useMemo(() => buildSearchIndex(), []);
  const fuse = useMemo(
    () =>
      new Fuse(searchIndex, {
        keys: [
          { name: 'articleTitle', weight: 0.35 },
          { name: 'keywords', weight: 0.30 },
          { name: 'body', weight: 0.20 },
          { name: 'steps', weight: 0.10 },
          { name: 'sectionTitle', weight: 0.05 },
        ],
        threshold: 0.4,
        includeMatches: true,
        includeScore: true,
      }),
    [searchIndex]
  );

  // Search results
  const searchResults = useMemo(() => {
    if (!searchQuery.trim()) return null;
    return fuse.search(searchQuery.trim());
  }, [fuse, searchQuery]);

  // Scroll to section from hash or click
  useEffect(() => {
    const hash = location.hash.replace('#', '');
    if (hash) {
      const el = sectionRefs.current[hash] || articleRefs.current[hash];
      if (el) {
        setTimeout(() => el.scrollIntoView({ behavior: 'smooth', block: 'start' }), 100);
        setActiveSection(hash);
      }
    }
  }, [location.hash]);

  const scrollToSection = (id: string) => {
    const el = sectionRefs.current[id];
    if (el) {
      el.scrollIntoView({ behavior: 'smooth', block: 'start' });
      setActiveSection(id);
      setSidebarOpen(false);
    }
  };

  const scrollToArticle = (sectionId: string, articleId: string) => {
    setActiveSection(sectionId);
    setSidebarOpen(false);
    const el = articleRefs.current[articleId];
    if (el) {
      setTimeout(() => el.scrollIntoView({ behavior: 'smooth', block: 'start' }), 50);
    }
  };

  // Track active section on scroll
  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        for (const entry of entries) {
          if (entry.isIntersecting) {
            setActiveSection(entry.target.id);
          }
        }
      },
      { rootMargin: '-20% 0px -70% 0px' }
    );

    Object.values(sectionRefs.current).forEach((ref) => {
      if (ref) observer.observe(ref);
    });

    return () => observer.disconnect();
  }, []);

  // Render markdown-lite (bold, newlines, tables)
  const renderBody = (text: string) => {
    const lines = text.split('\n');
    const elements: JSX.Element[] = [];
    let tableRows: string[][] = [];
    let inTable = false;

    const processLine = (line: string, key: number) => {
      // Bold
      const parts = line.split(/(\*\*[^*]+\*\*)/g);
      return (
        <span key={key}>
          {parts.map((part, i) => {
            if (part.startsWith('**') && part.endsWith('**')) {
              return <strong key={i} className="font-semibold text-foreground">{part.slice(2, -2)}</strong>;
            }
            // Em dash
            return <span key={i}>{part}</span>;
          })}
        </span>
      );
    };

    for (let i = 0; i < lines.length; i++) {
      const line = lines[i].trim();

      // Table detection
      if (line.startsWith('|') && line.endsWith('|')) {
        const cells = line.split('|').filter(Boolean).map(c => c.trim());
        if (cells.every(c => /^[-:]+$/.test(c))) {
          // Separator row, skip
          continue;
        }
        tableRows.push(cells);
        inTable = true;
        continue;
      }

      // Flush table
      if (inTable && tableRows.length > 0) {
        elements.push(
          <div key={`table-${i}`} className="overflow-x-auto my-3">
            <table className="min-w-full text-sm border border-border rounded-lg overflow-hidden">
              <thead>
                <tr className="bg-muted">
                  {tableRows[0].map((cell, ci) => (
                    <th key={ci} className="px-3 py-2 text-left font-semibold text-foreground border-b border-border">
                      {processLine(cell, ci)}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {tableRows.slice(1).map((row, ri) => (
                  <tr key={ri} className={ri % 2 === 0 ? 'bg-card' : 'bg-muted/50'}>
                    {row.map((cell, ci) => (
                      <td key={ci} className="px-3 py-2 text-muted-foreground border-b border-border">
                        {processLine(cell, ci)}
                      </td>
                    ))}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        );
        tableRows = [];
        inTable = false;
      }

      if (!line) {
        elements.push(<br key={`br-${i}`} />);
      } else if (line.startsWith('- ')) {
        elements.push(
          <div key={i} className="flex items-start gap-2 ml-2">
            <span className="text-primary mt-1.5 flex-shrink-0">&#8226;</span>
            <span className="text-muted-foreground">{processLine(line.slice(2), i)}</span>
          </div>
        );
      } else {
        elements.push(
          <p key={i} className="text-muted-foreground leading-relaxed">
            {processLine(line, i)}
          </p>
        );
      }
    }

    // Flush remaining table
    if (tableRows.length > 0) {
      elements.push(
        <div key="table-end" className="overflow-x-auto my-3">
          <table className="min-w-full text-sm border border-border rounded-lg overflow-hidden">
            <thead>
              <tr className="bg-muted">
                {tableRows[0].map((cell, ci) => (
                  <th key={ci} className="px-3 py-2 text-left font-semibold text-foreground border-b border-border">
                    {processLine(cell, ci)}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {tableRows.slice(1).map((row, ri) => (
                <tr key={ri} className={ri % 2 === 0 ? 'bg-card' : 'bg-muted/50'}>
                  {row.map((cell, ci) => (
                    <td key={ci} className="px-3 py-2 text-muted-foreground border-b border-border">
                      {processLine(cell, ci)}
                    </td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      );
    }

    return <div className="space-y-1">{elements}</div>;
  };

  // ─── Render Search Results ─────────────────────────────────────────────────

  const renderSearchResults = () => {
    if (!searchResults) return null;

    if (searchResults.length === 0) {
      return (
        <div className="flex flex-col items-center justify-center py-16 text-center">
          <Search className="h-12 w-12 text-muted-foreground/50 mb-4" />
          <h3 className="text-lg font-medium text-foreground mb-2">No results found</h3>
          <p className="text-muted-foreground max-w-md">
            Try different keywords or browse the topics in the sidebar.
          </p>
        </div>
      );
    }

    return (
      <div className="space-y-4">
        <div className="flex items-center gap-2 text-sm text-muted-foreground mb-6">
          <Search className="h-4 w-4" />
          <span>{searchResults.length} result{searchResults.length !== 1 ? 's' : ''} for "{searchQuery}"</span>
          <button
            onClick={() => setSearchQuery('')}
            className="ml-auto text-primary hover:text-primary/80 text-sm font-medium"
          >
            Clear search
          </button>
        </div>
        {searchResults.map((result) => {
          const section = helpSections.find(s => s.id === result.item.sectionId);
          const article = section?.content.find(a => a.id === result.item.articleId);
          if (!section || !article) return null;
          const Icon = section.icon;

          return (
            <button
              key={result.item.articleId}
              onClick={() => {
                setSearchQuery('');
                scrollToArticle(section.id, article.id);
              }}
              className="w-full text-left bg-card border border-border rounded-lg p-4 hover:border-primary/50 hover:shadow-soft transition-all"
            >
              <div className="flex items-center gap-2 text-xs text-muted-foreground mb-1.5">
                <Icon className="h-3.5 w-3.5" />
                <span>{section.title}</span>
                <ChevronRight className="h-3 w-3" />
                <span className="font-medium text-foreground">{article.title}</span>
              </div>
              <p className="text-sm text-muted-foreground line-clamp-2">
                {article.body.slice(0, 200)}...
              </p>
            </button>
          );
        })}
      </div>
    );
  };

  // ─── Render Article ────────────────────────────────────────────────────────

  const renderArticle = (article: HelpArticle, sectionIcon: any) => {
    return (
      <div
        key={article.id}
        id={article.id}
        ref={(el) => { articleRefs.current[article.id] = el; }}
        className="bg-card border border-border rounded-lg p-5 md:p-6"
      >
        <h3 className="text-lg font-semibold text-foreground mb-3">{article.title}</h3>

        {renderBody(article.body)}

        {/* Steps */}
        {article.steps && article.steps.length > 0 && (
          <div className="mt-4 bg-muted/50 rounded-lg p-4 border border-border">
            <h4 className="text-sm font-semibold text-foreground mb-3 flex items-center gap-2">
              <CheckCircle className="h-4 w-4 text-primary" />
              Steps
            </h4>
            <ol className="space-y-2">
              {article.steps.map((step, i) => (
                <li key={i} className="flex items-start gap-3 text-sm text-muted-foreground">
                  <span className="flex-shrink-0 w-6 h-6 rounded-full bg-primary/10 text-primary text-xs font-bold flex items-center justify-center mt-0.5">
                    {i + 1}
                  </span>
                  <span className="leading-relaxed">{step}</span>
                </li>
              ))}
            </ol>
          </div>
        )}

        {/* Tip */}
        {article.tip && (
          <div className="mt-4 flex items-start gap-3 bg-blue-50 dark:bg-blue-950/30 border border-blue-200 dark:border-blue-800 rounded-lg p-3">
            <Clock className="h-4 w-4 text-blue-600 dark:text-blue-400 mt-0.5 flex-shrink-0" />
            <p className="text-sm text-blue-800 dark:text-blue-200">{article.tip}</p>
          </div>
        )}

        {/* Warning */}
        {article.warning && (
          <div className="mt-4 flex items-start gap-3 bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-800 rounded-lg p-3">
            <AlertTriangle className="h-4 w-4 text-amber-600 dark:text-amber-400 mt-0.5 flex-shrink-0" />
            <p className="text-sm text-amber-800 dark:text-amber-200">{article.warning}</p>
          </div>
        )}

        {/* Image */}
        {article.image && (
          <div className="mt-4">
            <img
              src={article.image}
              alt={article.title}
              className="rounded-lg border border-border shadow-soft w-full"
              loading="lazy"
              onError={(e) => { (e.target as HTMLImageElement).style.display = 'none'; }}
            />
          </div>
        )}
      </div>
    );
  };

  // ─── Main Render ───────────────────────────────────────────────────────────

  return (
    <div className="min-h-[80vh]">
      {/* Header */}
      <div className="mb-6">
        <div className="flex items-center justify-between mb-2">
          <div>
            <h1 className="text-2xl md:text-3xl font-bold text-foreground flex items-center gap-3">
              <BookOpen className="h-7 w-7 md:h-8 md:w-8 text-primary" />
              Help Guide
            </h1>
            <p className="text-muted-foreground mt-1">
              Everything you need to know about using VIP Coordinator
            </p>
          </div>
          {/* Mobile sidebar toggle */}
          <button
            onClick={() => setSidebarOpen(!sidebarOpen)}
            className="lg:hidden flex items-center gap-2 px-3 py-2 border border-border rounded-lg text-sm text-muted-foreground hover:bg-accent"
          >
            <Menu className="h-4 w-4" />
            Topics
          </button>
        </div>

        {/* Search Bar */}
        <div className="relative mt-4">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground" />
          <input
            type="text"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder="Search help topics... (e.g., 'add VIP', 'GPS tracking', 'driver enrollment')"
            className="w-full pl-10 pr-10 py-3 bg-card border border-border rounded-lg text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent text-sm md:text-base"
          />
          {searchQuery && (
            <button
              onClick={() => setSearchQuery('')}
              className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
            >
              <X className="h-4 w-4" />
            </button>
          )}
        </div>
      </div>

      <div className="flex gap-6 relative">
        {/* Sidebar - Desktop */}
        <aside className="hidden lg:block w-64 flex-shrink-0">
          <div className="sticky top-24 max-h-[calc(100vh-8rem)] overflow-y-auto scrollbar-thin">
            <nav className="space-y-1">
              {categories.map((cat) => {
                const catSections = helpSections.filter(s => s.category === cat.name);
                const CatIcon = cat.icon;
                return (
                  <div key={cat.name} className="mb-3">
                    <div className="flex items-center gap-2 px-3 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider">
                      <CatIcon className="h-3.5 w-3.5" />
                      {cat.name}
                    </div>
                    {catSections.map((section) => {
                      const Icon = section.icon;
                      const isActiveSec = activeSection === section.id;
                      return (
                        <button
                          key={section.id}
                          onClick={() => scrollToSection(section.id)}
                          className={`w-full flex items-center gap-2 px-3 py-2 text-sm rounded-lg transition-colors ${
                            isActiveSec
                              ? 'bg-primary/10 text-primary font-medium'
                              : 'text-muted-foreground hover:bg-accent hover:text-foreground'
                          }`}
                        >
                          <Icon className="h-4 w-4 flex-shrink-0" />
                          {section.title}
                        </button>
                      );
                    })}
                  </div>
                );
              })}
            </nav>
          </div>
        </aside>

        {/* Mobile Sidebar Overlay */}
        {sidebarOpen && (
          <div className="fixed inset-0 z-50 lg:hidden">
            <div
              className="fixed inset-0 bg-black/50 backdrop-blur-sm"
              onClick={() => setSidebarOpen(false)}
            />
            <div className="fixed inset-y-0 left-0 w-72 bg-card shadow-elevated p-4 overflow-y-auto animate-in slide-in-from-left duration-200">
              <div className="flex items-center justify-between mb-4">
                <h3 className="font-semibold text-foreground">Topics</h3>
                <button onClick={() => setSidebarOpen(false)} className="text-muted-foreground hover:text-foreground">
                  <X className="h-5 w-5" />
                </button>
              </div>
              <nav className="space-y-1">
                {categories.map((cat) => {
                  const catSections = helpSections.filter(s => s.category === cat.name);
                  const CatIcon = cat.icon;
                  return (
                    <div key={cat.name} className="mb-3">
                      <div className="flex items-center gap-2 px-3 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider">
                        <CatIcon className="h-3.5 w-3.5" />
                        {cat.name}
                      </div>
                      {catSections.map((section) => {
                        const Icon = section.icon;
                        return (
                          <button
                            key={section.id}
                            onClick={() => scrollToSection(section.id)}
                            className="w-full flex items-center gap-2 px-3 py-2.5 text-sm rounded-lg text-muted-foreground hover:bg-accent hover:text-foreground"
                          >
                            <Icon className="h-4 w-4 flex-shrink-0" />
                            {section.title}
                          </button>
                        );
                      })}
                    </div>
                  );
                })}
              </nav>
            </div>
          </div>
        )}

        {/* Main Content */}
        <div className="flex-1 min-w-0" ref={contentRef}>
          {searchQuery ? (
            renderSearchResults()
          ) : (
            <div className="space-y-10">
              {helpSections.map((section) => {
                const Icon = section.icon;
                return (
                  <div
                    key={section.id}
                    id={section.id}
                    ref={(el) => { sectionRefs.current[section.id] = el; }}
                  >
                    <div className="flex items-center gap-3 mb-4">
                      <div className="h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center">
                        <Icon className="h-5 w-5 text-primary" />
                      </div>
                      <div>
                        <h2 className="text-xl font-bold text-foreground">{section.title}</h2>
                        <span className="text-xs text-muted-foreground">{section.category}</span>
                      </div>
                    </div>

                    <div className="space-y-4">
                      {section.content.map((article) => renderArticle(article, section.icon))}
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
