import React, { useState, useRef, useEffect, useCallback } from 'react';
import { createPortal } from 'react-dom';
import {
  Search, X, LayoutGrid, History, Zap, MessageCircle,
  Target, ShoppingCart, Fingerprint, PencilLine, Lock, Globe,
  Settings, Send, Crown, Route, ShieldCheck, ShieldBan, Mail,
  ChevronRight, CornerDownLeft, SearchX, Users, RefreshCw, Package, ChevronDown, FileText, Image, Folder
} from 'lucide-react';
import { cn } from "@/lib/utils";
import { ModernCardHeader, GhostButton } from '../ui/settings-ui';
import { LOCAL_INDEX } from './searchIndex';


import type { LucideIcon } from 'lucide-react';

interface GlobalSearchProps {
  rtl?: boolean;
}

interface SearchOption {
  title: string;
  description: string;
  target: string;
  link: string;
}

interface SearchResult {
  title: string;
  description: string;
  icon: string;
  section: string;
  link: string;
  source: 'plugin' | 'users' | 'orders' | 'products' | 'subscriptions' | 'coupons' | 'campaign_broadcasts' | 'notification_rules' | 'posts' | 'pages' | 'media' | 'categories';
  user_id?: number;
  options?: SearchOption[];
  thumbnail_url?: string;
}

const IconRenderer = ({ iconName, className }: { iconName: string, className?: string }) => {
  const icons: Record<string, LucideIcon> = {
    LayoutGrid, History, Zap, MessageCircle, Target, ShoppingCart,
    Fingerprint, PencilLine, Lock, Globe, Settings, Send, Crown,
    Route, ShieldCheck, ShieldBan, Mail, Search, Users, RefreshCw, Package, FileText, Image, Folder
  };
  const Icon = icons[iconName] || Search;
  return <Icon className={className} />;
};



const GlobalSearch: React.FC<GlobalSearchProps> = ({ rtl }) => {
  const [isOpen, setIsOpen] = useState(false);
  const [query, setQuery] = useState('');
  const [results, setResults] = useState<SearchResult[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [selectedIndex, setSelectedIndex] = useState(-1);
  const [isMac] = useState(() => {
    if (typeof navigator === 'undefined') return false;
    return navigator.platform.toUpperCase().indexOf('MAC') >= 0;
  });
  const [activeSources, setActiveSources] = useState<string[]>(['plugin', 'users', 'orders', 'products', 'subscriptions', 'coupons', 'campaign_broadcasts', 'notification_rules', 'posts', 'pages', 'media', 'categories']);
  const [history, setHistory] = useState<SearchResult[]>(() => {
    try {
      const saved = localStorage.getItem('wawp_search_history');
      return saved ? JSON.parse(saved) : [];
    } catch {
      return [];
    }
  });
  const inputRef = useRef<HTMLInputElement>(null);
  const searchTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);
  const [dropdownOpen, setDropdownOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setDropdownOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  useEffect(() => {
    const handleGlobalShortcut = (e: KeyboardEvent) => {
      if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'k') {
        e.preventDefault();
        setIsOpen(true);
      }
    };
    window.addEventListener('keydown', handleGlobalShortcut);
    return () => window.removeEventListener('keydown', handleGlobalShortcut);
  }, []);

  useEffect(() => {
    if (isOpen && inputRef.current) {
      inputRef.current.focus();
    }
  }, [isOpen]);

  const performSearch = useCallback(async (searchQuery: string, sources: string[]) => {
    if (searchQuery.length < 2) {
      setResults([]);
      setIsLoading(false);
      return;
    }

    // 1. Instantaneous Local Client-Side Search for plugin sections & specific settings
    const localMatches: SearchResult[] = [];
    if (sources.includes('plugin')) {
      const q = searchQuery.toLowerCase();
      LOCAL_INDEX.forEach(item => {
        let pageMatch = false;
        if (
          item.title.toLowerCase().includes(q) ||
          item.description.toLowerCase().includes(q) ||
          item.keywords.some(kw => kw.toLowerCase().includes(q))
        ) {
          pageMatch = true;
        }

        const matchedOpts: SearchOption[] = [];
        if (item.options) {
          item.options.forEach(opt => {
            if (
              opt.title.toLowerCase().includes(q) ||
              opt.description.toLowerCase().includes(q) ||
              opt.keywords.some(kw => kw.toLowerCase().includes(q))
            ) {
              matchedOpts.push({
                title: opt.title,
                description: opt.description,
                target: opt.target,
                link: `${window.location.pathname}?page=wawp&wawp_section=${item.section}&highlight_setting=${opt.target}`
              });
            }
          });
        }

        if (pageMatch || matchedOpts.length > 0) {
          localMatches.push({
            title: item.title,
            description: item.description,
            icon: item.icon,
            section: item.section,
            link: `${window.location.pathname}?page=wawp&wawp_section=${item.section}`,
            source: 'plugin',
            options: matchedOpts
          });
        }
      });

      // Update state instantly!
      setResults(localMatches);
    }

    const backendSources = sources.filter(s => s !== 'plugin');
    if (backendSources.length === 0) {
      setIsLoading(false);
      return;
    }

    try {
      const win = window as unknown as {
        wawpDashboardData?: {
          nonce?: string;
          global?: { nonce?: string; restUrl?: string; wpRestNonce?: string }
        };
        WAWPAutoCheck?: { nonce?: string };
        wpApiSettings?: { nonce?: string };
      };

      const dashboardData = win.wawpDashboardData;
      const nonce = dashboardData?.global?.wpRestNonce ||
        dashboardData?.nonce ||
        dashboardData?.global?.nonce ||
        win.WAWPAutoCheck?.nonce ||
        win.wpApiSettings?.nonce;

      let baseUrl = dashboardData?.global?.restUrl || '/wp-json/wawp/v1';
      baseUrl = baseUrl.replace(/\/$/, '');
      try {
        const urlObj = new URL(baseUrl, window.location.origin);
        if (urlObj.origin === window.location.origin) {
          baseUrl = urlObj.pathname + urlObj.search;
          baseUrl = baseUrl.replace(/\/$/, '');
        } else {
          if (baseUrl.startsWith('http:') && window.location.protocol === 'https:') {
            baseUrl = baseUrl.replace('http:', 'https:');
          } else if (baseUrl.startsWith('https:') && window.location.protocol === 'http:') {
            baseUrl = baseUrl.replace('https:', 'http:');
          }
        }
      } catch (e) {
        console.warn('[GlobalSearch] URL parsing failed, using raw baseUrl:', e);
      }

      const searchUrl = `${baseUrl}/global-search?q=${encodeURIComponent(searchQuery)}&sources=${encodeURIComponent(backendSources.join(','))}&_wpnonce=${encodeURIComponent(nonce || '')}`;

      const res = await fetch(searchUrl, {
        credentials: 'include',
        headers: {
          'X-WP-Nonce': nonce || '',
          'Content-Type': 'application/json'
        }
      });

      if (!res.ok) {
        console.error(`[GlobalSearch] Search request failed with status: ${res.status}`);
        return;
      }

      const json = await res.json() as { results?: SearchResult[] };
      const backendResults = json.results || [];
      
      // Combine local instantaneous plugin results and remote database records elegantly!
      setResults([...localMatches, ...backendResults]);
      setSelectedIndex(-1);
    } catch (err) {
      console.error('[GlobalSearch] Search exception:', err);
    } finally {
      setIsLoading(false);
    }
  }, []);

  useEffect(() => {
    if (query.length > 1) {
      if (searchTimeout.current) clearTimeout(searchTimeout.current);
      searchTimeout.current = setTimeout(() => performSearch(query, activeSources), 300);
    }
    return () => {
      if (searchTimeout.current) clearTimeout(searchTimeout.current);
    };
  }, [query, activeSources, performSearch]);

  const toggleSearch = () => {
    setIsOpen(!isOpen);
    if (isOpen) {
      setQuery('');
      setResults([]);
      setSelectedIndex(-1);
    }
  };

  const toggleSource = (source: string) => {
    setActiveSources(prev => {
      let next;
      if (prev.includes(source)) {
        if (prev.length === 1) next = prev;
        else next = prev.filter(s => s !== source);
      } else {
        next = [...prev, source];
      }
      if (query.length > 1) setIsLoading(true);
      return next;
    });
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    const activeResults = query.length < 2 ? history : results;
    if (e.key === 'ArrowDown') {
      e.preventDefault();
      setSelectedIndex(prev => (prev < activeResults.length - 1 ? prev + 1 : prev));
    } else if (e.key === 'ArrowUp') {
      e.preventDefault();
      setSelectedIndex(prev => (prev > 0 ? prev - 1 : prev));
    } else if (e.key === 'Enter' && selectedIndex >= 0) {
      handleItemClick(activeResults[selectedIndex]);
    } else if (e.key === 'Escape') {
      toggleSearch();
    }
  };

  const addToHistory = (item: SearchResult) => {
    const newHistory = [item, ...history.filter(h => h.link !== item.link)].slice(0, 5);
    setHistory(newHistory);
    localStorage.setItem('wawp_search_history', JSON.stringify(newHistory));
  };

  const handleItemClick = (item: SearchResult) => {
    addToHistory(item);
    if (item.source !== 'plugin') {
      window.open(item.link, '_blank');
      return;
    }
    window.history.pushState({ section: item.section }, "", item.link);
    window.dispatchEvent(new CustomEvent('wawp-navigate', { detail: item.section }));
    window.scrollTo({ top: 0, behavior: 'smooth' });
    toggleSearch();
  };

  const handleOptionClick = (item: SearchResult, opt: SearchOption) => {
    addToHistory({
      ...item,
      title: `${item.title} - ${opt.title}`,
      description: opt.description,
      link: opt.link
    });
    window.history.pushState({ section: item.section, highlight_setting: opt.target }, "", opt.link);
    window.dispatchEvent(new CustomEvent('wawp-navigate', { detail: item.section }));
    window.scrollTo({ top: 0, behavior: 'smooth' });
    toggleSearch();
  };

  const clearHistory = (e: React.MouseEvent) => {
    e.stopPropagation();
    setHistory([]);
    localStorage.removeItem('wawp_search_history');
  };

  return (
    <>
      <button
        onClick={toggleSearch}
        className="p-2 rounded-xl hover:bg-white/10 transition-all duration-200 text-white group relative"
        title={`Quick Search (${isMac ? '⌘K' : 'Ctrl+K'})`}
      >
        <Search className="w-5 h-5" />
      </button>

      {isOpen && createPortal(
        <div
          className="fixed inset-0 z-[9999999] bg-slate-900/40 backdrop-blur-sm flex items-start justify-center pt-24 px-4 transition-all animate-in fade-in duration-300"
          onClick={toggleSearch}
        >
          <div
            className="w-full max-w-2xl bg-white rounded-2xl shadow-2xl border border-slate-200/60 overflow-hidden animate-in slide-in-from-top-4 duration-300"
            onClick={e => e.stopPropagation()}
          >
            <ModernCardHeader
              title="Global OmniSearch"
              description="Search users, orders, and features"
              icon={Search}
              rightAction={
                <GhostButton size="icon" onClick={toggleSearch} className="text-slate-400 hover:text-slate-600">
                  <X className="w-4 h-4" />
                </GhostButton>
              }
            />
            <div className="relative border-b border-slate-100 p-4 pb-2">
              <div className="relative flex items-center bg-slate-50 border border-slate-200 rounded-xl px-4 py-1.5 focus-within:ring-2 focus-within:ring-emerald-500/10 focus-within:border-emerald-500/30 transition-all duration-200">
                <Search className={cn("w-4 h-4 mr-3 transition-colors shrink-0", isLoading ? "text-emerald-500 animate-pulse" : "text-slate-400")} />
                <input
                  ref={inputRef}
                  type="text"
                  placeholder="Search users, orders, products, features..."
                  className={cn(
                    "flex-1 bg-transparent border-none outline-none ring-0 focus:ring-0 focus:outline-none text-slate-700 placeholder:text-slate-400 text-sm font-medium h-8 shadow-none shadow-transparent border-transparent focus:border-transparent",
                    rtl && "text-right"
                  )}
                  value={query}
                  onChange={(e) => {
                    const val = e.target.value;
                    setQuery(val);
                    if (val.length > 1) {
                      setIsLoading(true);
                    } else {
                      setResults([]);
                      setIsLoading(false);
                      setSelectedIndex(-1);
                    }
                  }}
                  onKeyDown={handleKeyDown}
                  style={{ border: 'none', outline: 'none', boxShadow: 'none' }}
                />
                {query && (
                  <button
                    onClick={() => {
                      setQuery('');
                      setResults([]);
                      setIsLoading(false);
                      setSelectedIndex(-1);
                    }}
                    className="ml-2 p-1 rounded-lg hover:bg-slate-200 text-slate-400 transition-colors shrink-0"
                  >
                    <X className="w-3.5 h-3.5" />
                  </button>
                )}
              </div>

              <div className="relative mt-4 flex items-center gap-3 px-1" ref={dropdownRef}>
                <button
                  onClick={() => setDropdownOpen(!dropdownOpen)}
                  className="flex items-center gap-2 px-3.5 py-2 bg-slate-50 hover:bg-slate-100 border border-slate-200 hover:border-slate-300 text-slate-700 hover:text-slate-900 rounded-full text-[11px] font-bold shadow-sm transition-all duration-200 active:scale-95 shrink-0"
                >
                  <span>Filter Sources</span>
                  <ChevronDown className={cn("w-3.5 h-3.5 text-slate-400 transition-transform duration-200", dropdownOpen && "rotate-180")} />
                </button>

                <div className="flex items-center gap-1.5 overflow-x-auto py-0.5 max-w-[calc(100%-140px)]">
                  {activeSources.slice(0, 2).map((val) => {
                    const config = {
                      plugin: { label: 'Wawp Plugin', color: 'bg-emerald-50 text-emerald-700 border-emerald-100' },
                      users: { label: 'Users', color: 'bg-blue-50 text-blue-700 border-blue-100' },
                      orders: { label: 'Orders', color: 'bg-indigo-50 text-indigo-700 border-indigo-100' },
                      products: { label: 'Products', color: 'bg-amber-50 text-amber-700 border-amber-100' },
                      subscriptions: { label: 'Subscriptions', color: 'bg-teal-50 text-teal-700 border-teal-100' },
                      coupons: { label: 'Coupons', color: 'bg-pink-50 text-pink-700 border-pink-100' },
                      campaign_broadcasts: { label: 'Campaigns', color: 'bg-rose-50 text-rose-700 border-rose-100' },
                      notification_rules: { label: 'Rules', color: 'bg-violet-50 text-violet-700 border-violet-100' },
                      posts: { label: 'Posts', color: 'bg-orange-50 text-orange-700 border-orange-100' },
                      pages: { label: 'Pages', color: 'bg-sky-50 text-sky-700 border-sky-100' },
                      media: { label: 'Media', color: 'bg-yellow-50 text-yellow-700 border-yellow-100' },
                      categories: { label: 'Categories', color: 'bg-cyan-50 text-cyan-700 border-cyan-100' },
                    }[val] || { label: val, color: 'bg-slate-50 text-slate-600 border-slate-100' };

                    return (
                      <span
                        key={val}
                        className={cn(
                          "flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[10px] font-bold border shadow-sm shrink-0",
                          config.color
                        )}
                      >
                        {config.label}
                      </span>
                    );
                  })}
                  {activeSources.length > 2 && (
                    <span className="text-[10px] font-bold text-slate-400 bg-slate-50 px-2.5 py-1 rounded-full border border-slate-100 shrink-0">
                      +{activeSources.length - 2} more
                    </span>
                  )}
                </div>

                {dropdownOpen && (
                  <div className="absolute top-full left-0 mt-1.5 w-60 bg-white border border-slate-100 rounded-2xl shadow-xl p-2.5 z-50 animate-in fade-in slide-in-from-top-2 duration-150 space-y-1">
                    <div className="px-2 py-1.5 border-b border-slate-100 flex items-center justify-between">
                      <span className="text-[10px] font-black uppercase tracking-widest text-slate-400">Filter Sources</span>
                      <div className="flex gap-2">
                        <button
                          onClick={() => setActiveSources(['plugin', 'users', 'orders', 'products', 'subscriptions', 'coupons', 'campaign_broadcasts', 'notification_rules', 'posts', 'pages', 'media', 'categories'])}
                          className="text-[9px] font-bold text-emerald-500 hover:text-emerald-600"
                        >
                          All
                        </button>
                        <button
                          onClick={() => setActiveSources(['plugin'])}
                          className="text-[9px] font-bold text-rose-400 hover:text-rose-500"
                        >
                          Clear
                        </button>
                      </div>
                    </div>
                    <div className="max-h-64 overflow-y-auto py-1 space-y-0.5">
                      {[
                        { value: 'plugin', label: 'Wawp Plugin', icon: 'Zap', colorClass: 'text-emerald-500' },
                        { value: 'users', label: 'Users', icon: 'Users', colorClass: 'text-blue-500' },
                        { value: 'orders', label: 'Orders', icon: 'ShoppingCart', colorClass: 'text-indigo-500' },
                        { value: 'products', label: 'Products', icon: 'Package', colorClass: 'text-amber-500' },
                        { value: 'subscriptions', label: 'Subscriptions', icon: 'RefreshCw', colorClass: 'text-teal-500' },
                        { value: 'coupons', label: 'Coupons', icon: 'Crown', colorClass: 'text-pink-500' },
                        { value: 'campaign_broadcasts', label: 'Campaigns', icon: 'Target', colorClass: 'text-rose-500' },
                        { value: 'notification_rules', label: 'Rules', icon: 'Zap', colorClass: 'text-violet-500' },
                        { value: 'posts', label: 'Posts', icon: 'FileText', colorClass: 'text-orange-500' },
                        { value: 'pages', label: 'Pages', icon: 'FileText', colorClass: 'text-sky-500' },
                        { value: 'media', label: 'Media', icon: 'Image', colorClass: 'text-yellow-500' },
                        { value: 'categories', label: 'Categories', icon: 'Folder', colorClass: 'text-cyan-500' },
                      ].map((opt) => {
                        const isSelected = activeSources.includes(opt.value);
                        return (
                          <button
                            key={opt.value}
                            onClick={() => toggleSource(opt.value)}
                            className="w-full flex items-center justify-between p-2 rounded-xl text-left transition-colors hover:bg-slate-50 group active:scale-[0.98]"
                          >
                            <div className="flex items-center gap-2.5">
                              <div className={cn("transition-colors", opt.colorClass)}>
                                <IconRenderer iconName={opt.icon} className="w-4 h-4" />
                              </div>
                              <span className="text-xs font-semibold text-slate-700 group-hover:text-slate-900">{opt.label}</span>
                            </div>
                            <div className={cn(
                              "w-4 h-4 rounded-md border flex items-center justify-center transition-all duration-200",
                              isSelected ? "bg-emerald-500 border-emerald-500 text-white" : "border-slate-200 bg-white"
                            )}>
                              {isSelected && <X className="w-2.5 h-2.5 stroke-[3]" />}
                            </div>
                          </button>
                        );
                      })}
                    </div>
                  </div>
                )}
              </div>
            </div>

            <div className="max-h-[450px] overflow-y-auto custom-scrollbar p-2">
              {query.length < 2 ? (
                <>
                  {history.length > 0 ? (
                    <div className="space-y-1">
                      <div className="px-3 py-2 flex items-center justify-between">
                        <h4 className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Recent Searches</h4>
                        <button onClick={clearHistory} className="text-[10px] font-bold text-rose-500/60 hover:text-rose-500 transition-colors">CLEAR</button>
                      </div>
                      {history.map((item, index) => (
                        <button
                          key={`history-${index}`}
                          onClick={() => handleItemClick(item)}
                          className={cn(
                            "w-full group flex items-start gap-4 p-3 rounded-xl transition-all duration-200 text-left outline-none",
                            index === selectedIndex ? "bg-emerald-50/80 ring-1 ring-emerald-100" : "hover:bg-slate-50"
                          )}
                        >
                          <div className={cn(
                            "p-2.5 rounded-xl transition-all duration-200 shadow-sm shrink-0",
                            index === selectedIndex ? "bg-emerald-500 text-white" : "bg-slate-50 text-slate-400"
                          )}>
                            <IconRenderer iconName={item.icon} className="w-4 h-4" />
                          </div>
                          <div className="flex-1 min-w-0 pt-0.5">
                            <div className="text-base font-bold text-slate-700 flex items-center gap-2">
                              {item.title}
                              <History className="w-3 h-3 text-slate-300" />
                            </div>
                            <div className="text-[11px] text-slate-400 line-clamp-1">{item.description}</div>
                          </div>
                        </button>
                      ))}
                    </div>
                  ) : (
                    <div className="py-20 flex flex-col items-center justify-center text-center">
                      <div className="w-16 h-16 bg-emerald-50 rounded-full flex items-center justify-center mb-6 animate-pulse">
                        <Zap className="w-8 h-8 text-emerald-500" />
                      </div>
                      <h3 className="text-base font-bold text-slate-800 mb-2">OmniSearch Discovery</h3>
                      <p className="text-sm text-slate-400 max-w-[320px] leading-relaxed">
                        Search across your entire platform, commerce, and users in real-time.
                      </p>
                    </div>
                  )}
                </>
              ) : (
                <>
                  <div className="px-3 py-2 flex items-center justify-between">
                    <h4 className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Search Results</h4>
                    {results.length > 0 && <span className="text-[10px] font-bold text-emerald-500/50">{results.length} Matches</span>}
                  </div>

                  {results.length > 0 ? (
                    <div className="space-y-4 max-h-[450px] overflow-y-auto pr-1">
                      {results.map((item, index) => {
                        const showHeader = index === 0 || item.source !== results[index - 1]?.source;
                        const srcConfig = {
                          plugin: { label: 'Wawp Pages & Settings', color: 'emerald' },
                          users: { label: 'Registered Users', color: 'blue' },
                          orders: { label: 'WooCommerce Orders', color: 'amber' },
                          products: { label: 'WooCommerce Products', color: 'indigo' },
                          subscriptions: { label: 'WooCommerce Subscriptions', color: 'teal' },
                          coupons: { label: 'WooCommerce Coupons', color: 'pink' },
                          campaign_broadcasts: { label: 'Broadcast Campaigns', color: 'rose' },
                          notification_rules: { label: 'Notification Rules', color: 'violet' },
                          posts: { label: 'WordPress Posts', color: 'orange' },
                          pages: { label: 'WordPress Pages', color: 'sky' },
                          media: { label: 'Media Library', color: 'yellow' },
                          categories: { label: 'Categories & Tags', color: 'cyan' },
                        }[item.source] || { label: item.source, color: 'slate' };

                        return (
                          <div key={`${item.source}-${item.section}-${item.user_id || index}`} className="space-y-2">
                            {showHeader && (
                              <div className="flex items-center gap-2 px-3 pt-3 pb-1 first:pt-1">
                                <div className={cn(
                                  "w-1 h-3.5 rounded-full",
                                  item.source === 'plugin' && "bg-emerald-500",
                                  item.source === 'users' && "bg-blue-500",
                                  item.source === 'orders' && "bg-amber-500",
                                  item.source === 'products' && "bg-indigo-500",
                                  item.source === 'subscriptions' && "bg-teal-500",
                                  item.source === 'coupons' && "bg-pink-500",
                                  item.source === 'campaign_broadcasts' && "bg-rose-500",
                                  item.source === 'notification_rules' && "bg-violet-500"
                                )} />
                                <span className="text-[11px] font-black uppercase tracking-widest text-slate-400">
                                  {srcConfig.label}
                                </span>
                                <span className="text-[9px] font-bold px-1.5 py-0.5 bg-slate-50 text-slate-400 rounded-full border border-slate-100">
                                  {results.filter(r => r.source === item.source).length}
                                </span>
                              </div>
                            )}

                            <button
                              onClick={() => handleItemClick(item)}
                              className={cn(
                                "w-full group flex items-start gap-4 p-3 rounded-xl transition-all duration-200 text-left outline-none",
                                index === selectedIndex ? "bg-emerald-50/80 ring-1 ring-emerald-100" : "hover:bg-slate-50"
                              )}
                            >
                              {item.thumbnail_url ? (
                                <div className="w-11 h-11 rounded-xl overflow-hidden shadow-sm shrink-0 border border-slate-100 bg-white flex items-center justify-center">
                                  <img src={item.thumbnail_url} alt="" className="w-full h-full object-contain p-1" />
                                </div>
                              ) : (
                                <div className={cn(
                                  "p-2.5 rounded-xl transition-all duration-200 shadow-sm shrink-0",
                                  index === selectedIndex 
                                    ? (item.source === 'plugin' ? "bg-emerald-500 text-white" : item.source === 'users' ? "bg-blue-500 text-white" : item.source === 'orders' ? "bg-amber-500 text-white" : item.source === 'subscriptions' ? "bg-teal-500 text-white" : item.source === 'coupons' ? "bg-pink-500 text-white" : item.source === 'campaign_broadcasts' ? "bg-rose-500 text-white" : item.source === 'notification_rules' ? "bg-violet-500 text-white" : "bg-indigo-500 text-white")
                                    : "bg-slate-50 text-slate-500 group-hover:bg-slate-100"
                                )}>
                                  <IconRenderer iconName={item.icon} className="w-5 h-5" />
                                </div>
                              )}

                              <div className="flex-1 min-w-0 pt-0.5">
                                <div className="text-lg font-bold flex items-center gap-2 text-slate-800 group-hover:text-emerald-700 transition-colors">
                                  {item.title}
                                  <ChevronRight className={cn(
                                    "w-4 h-4 transition-all duration-300",
                                    index === selectedIndex ? "text-emerald-500 opacity-100 translate-x-0" : "text-slate-300 opacity-0 -translate-x-2 group-hover:opacity-100 group-hover:translate-x-0"
                                  )} />
                                </div>
                                <div className="text-xs font-medium text-slate-500 mt-1">
                                  <span className={cn("uppercase tracking-wider line-clamp-1", item.source !== 'plugin' && "normal-case tracking-normal")}>
                                    {item.description}
                                  </span>
                                </div>
                                {item.options && item.options.length > 0 && (
                                  <div className="mt-3 pl-3 border-l-2 border-emerald-500/20 space-y-2">
                                    <div className="text-[9px] font-black text-slate-400 uppercase tracking-widest mb-1">Direct Settings Links</div>
                                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
                                      {item.options.map((opt: SearchOption, optIdx: number) => (
                                        <div
                                          key={`${opt.target}-${optIdx}`}
                                          onClick={(e) => {
                                            e.stopPropagation();
                                            handleOptionClick(item, opt);
                                          }}
                                          className="flex flex-col p-2 bg-slate-50/60 hover:bg-emerald-50/40 rounded-lg border border-slate-100/50 hover:border-emerald-100/40 transition-all text-left cursor-pointer group/opt"
                                        >
                                          <span className="text-[11px] font-bold text-slate-700 group-hover/opt:text-emerald-600 transition-colors flex items-center gap-1.5">
                                            <div className="w-1.5 h-1.5 rounded-full bg-slate-300 group-hover/opt:bg-emerald-500 transition-all" />
                                            {opt.title}
                                          </span>
                                          <span className="text-[10px] text-slate-400 line-clamp-1 mt-0.5">{opt.description}</span>
                                        </div>
                                      ))}
                                    </div>
                                  </div>
                                )}
                              </div>
                            </button>
                          </div>
                        );
                      })}
                    </div>
                  ) : (
                    <div className="py-20 flex flex-col items-center justify-center text-center">
                      <div className="w-16 h-16 bg-slate-50 rounded-full flex items-center justify-center mb-4">
                        <SearchX className="w-8 h-8 text-slate-300" />
                      </div>
                      <p className="text-sm font-medium text-slate-500">No results found for <span className="text-emerald-600 font-bold">"{query}"</span></p>
                      <p className="text-xs text-slate-400 mt-1">Try toggling filters or checking your keywords.</p>
                    </div>
                  )}
                </>
              )}
            </div>

            <div className="bg-slate-50/50 border-t border-slate-100 p-3 px-4 flex items-center justify-between">
              <div className="flex items-center gap-4">
                <div className="flex items-center gap-1.5">
                  <div className="px-1.5 py-0.5 bg-white border border-slate-200 rounded text-[10px] font-bold text-slate-500 shadow-sm flex items-center gap-0.5">
                    <CornerDownLeft className="w-2.5 h-2.5" />
                  </div>
                  <span className="text-[10px] text-slate-400 font-medium">to select</span>
                </div>
                <div className="flex items-center gap-1.5">
                  <div className="flex gap-1">
                    <div className="px-1.5 py-0.5 bg-white border border-slate-200 rounded text-[10px] font-bold text-slate-500 shadow-sm">↑</div>
                    <div className="px-1.5 py-0.5 bg-white border border-slate-200 rounded text-[10px] font-bold text-slate-500 shadow-sm">↓</div>
                  </div>
                  <span className="text-[10px] text-slate-400 font-medium">to navigate</span>
                </div>
              </div>
              <div className="flex items-center gap-1 text-[10px] font-bold text-emerald-500/40 tracking-tighter uppercase">
                <ShieldCheck className="w-3 h-3" />
                Wawp
              </div>
            </div>
          </div>
        </div>,
        document.body
      )}
    </>
  );
};

export default GlobalSearch;
