import React, { useState, useEffect } from 'react';
import { 
  LifeBuoy, 
  MessageSquare, 
  AlertTriangle, 
  ChevronDown, 
  ChevronUp, 
  CheckCircle, 
  Send, 
  Clock, 
  BadgeAlert,
  Loader2,
  Phone,
  Bookmark,
  Sparkles,
  HelpCircle,
  FileText
} from 'lucide-react';
import { Booking, Property, SupportTicket, UserAccount } from '../types';

interface HelpPageProps {
  currentUser: UserAccount | null;
  bookings: Booking[];
  properties: Property[];
}

export default function HelpPage({ currentUser, bookings, properties }: HelpPageProps) {
  const [activeSubTab, setActiveSubTab] = useState<'chat' | 'ticket' | 'faqs'>('chat');
  
  // FAQs State
  const [searchQuery, setSearchQuery] = useState('');
  const [expandedFaq, setExpandedFaq] = useState<number | null>(null);

  // Tickets / Complaint State
  const [complaintCategory, setComplaintCategory] = useState<SupportTicket['category']>('payment_failure');
  const [selectedBookingId, setSelectedBookingId] = useState<string>('');
  const [complaintDescription, setComplaintDescription] = useState('');
  const [contactPhone, setContactPhone] = useState(currentUser?.phone || '');
  const [successMsg, setSuccessMsg] = useState('');
  const [ticketsList, setTicketsList] = useState<SupportTicket[]>([]);

  // Interactive Bot Chat State
  const [chatMessages, setChatMessages] = useState<Array<{ sender: 'user' | 'bot'; text: string; time: string }>>([
    { 
      sender: 'bot', 
      text: "⚡ Hello! I'm Buddy, your virtual assistant. How can we power your journey today? Ask me about parking reservation status, charger socket compatibility, payment processing, or submit a custom complaint ticket.", 
      time: 'Just now' 
    }
  ]);
  const [chatInput, setChatInput] = useState('');
  const [isBotTyping, setIsBotTyping] = useState(false);

  // Filter regular user's bookings to link in the ticket dropdown
  const myBookings = bookings.filter(b => b.userEmail.toLowerCase() === currentUser?.email.toLowerCase());

  // Load and sync tickets
  useEffect(() => {
    const savedTickets = localStorage.getItem('chargebuddy_support_tickets');
    if (savedTickets) {
      try {
        const parsed = JSON.parse(savedTickets) as SupportTicket[];
        // Filter by user
        setTicketsList(parsed.filter(t => t.userEmail.toLowerCase() === currentUser?.email.toLowerCase()));
      } catch (e) {
        console.error('Error parsing support tickets', e);
      }
    } else {
      // Default initial mock tickets to make the page populated
      const initialTickets: SupportTicket[] = [
        {
          id: 'TKT-782103',
          userEmail: currentUser?.email || 'driver@chargebuddy.com',
          category: 'charger_issue',
          bookingId: myBookings[0]?.id || 'CP-321045',
          description: 'The CCS2 Charger was initially showing error codes but cleared up after restarting the gun lock.',
          contactNo: currentUser?.phone || '9876543210',
          status: 'Resolved',
          resolution: 'System reset performed. Spot 2 charger was rebooted remotely. Ready for normal operations.',
          createdAt: new Date(Date.now() - 24 * 3600 * 1000).toISOString() // 1 day ago
        }
      ];
      localStorage.setItem('chargebuddy_support_tickets', JSON.stringify(initialTickets));
      setTicketsList(initialTickets.filter(t => t.userEmail.toLowerCase() === currentUser?.email.toLowerCase()));
    }
  }, [currentUser]);

  // Handle complaint submission
  const handleSubmitTicket = (e: React.FormEvent) => {
    e.preventDefault();
    if (!complaintDescription.trim()) return;

    const newTicket: SupportTicket = {
      id: 'TKT-' + Math.floor(100000 + Math.random() * 900000).toString(),
      userEmail: currentUser?.email || 'anonymous@chargebuddy.com',
      category: complaintCategory,
      bookingId: selectedBookingId || undefined,
      description: complaintDescription,
      contactNo: contactPhone,
      status: 'Open',
      createdAt: new Date().toISOString()
    };

    const savedTicketsStr = localStorage.getItem('chargebuddy_support_tickets') || '[]';
    try {
      const existing = JSON.parse(savedTicketsStr) as SupportTicket[];
      const updatedList = [newTicket, ...existing];
      localStorage.setItem('chargebuddy_support_tickets', JSON.stringify(updatedList));
      
      // Update local state
      setTicketsList(updatedList.filter(t => t.userEmail.toLowerCase() === currentUser?.email.toLowerCase()));

      setComplaintDescription('');
      setSelectedBookingId('');
      setSuccessMsg(`Complaint ${newTicket.id} registered successfully! Our system is analyzing your booking history.`);
      
      // Trigger a mock support desk resolution/update in 8 seconds to show interactive response
      setTimeout(() => {
        const currentStored = JSON.parse(localStorage.getItem('chargebuddy_support_tickets') || '[]') as SupportTicket[];
        const autoUpdated = currentStored.map(t => {
          if (t.id === newTicket.id) {
            let autoRes = 'We have escalated this concern to our field engineers.';
            if (t.category === 'payment_failure') {
              autoRes = 'Our system verified the payment gateway transaction. If debited improperly, refunds process dynamically within 48 hours directly to your card/wallet bank account.';
            } else if (t.category === 'property_visit') {
              autoRes = 'We sent a warning notification to the property security manager. Please communicate with local gate personnel; access codes refreshed in your app pass.';
            } else if (t.category === 'charger_issue') {
              autoRes = 'Remote diagnostic pulse triggered. If the unit continues refusing connection, please re-plug standard CSS2/Type-2 gun lock and wait 60s.';
            }
            return {
              ...t,
              status: 'InProgress' as const,
              resolution: autoRes
            };
          }
          return t;
        });
        localStorage.setItem('chargebuddy_support_tickets', JSON.stringify(autoUpdated));
        if (currentUser) {
          setTicketsList(autoUpdated.filter(t => t.userEmail.toLowerCase() === currentUser.email.toLowerCase()));
        }
      }, 7000);

      setTimeout(() => {
        setSuccessMsg('');
      }, 5000);

    } catch (err) {
      console.error(err);
    }
  };

  // Bot logic
  const handleSendBotMessage = async (textMessage: string) => {
    if (!textMessage.trim()) return;

    // Add user message
    const cleanMsg = textMessage.trim();
    const timeNow = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    const nextChat = [...chatMessages, { sender: 'user' as const, text: cleanMsg, time: timeNow }];
    setChatMessages(nextChat);
    setChatInput('');
    setIsBotTyping(true);

    try {
      const response = await fetch("/api/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          message: cleanMsg,
          history: chatMessages,
          user: currentUser,
          bookings: bookings,
          properties: properties
        })
      });

      if (!response.ok) {
        throw new Error("Chat response returned error status from backend module");
      }

      const data = await response.json();
      const botResponseText = data.reply || "I spent too long thinking. Please ask again!";
      
      setChatMessages(prev => [...prev, { sender: 'bot' as const, text: botResponseText, time: timeNow }]);
    } catch (err) {
      console.warn("Failed to reach full-stack Gemini router. Engaging smart offline assistant node:", err);
      
      let botReply = '';
      const lowered = cleanMsg.toLowerCase();

      // 1. SECURITY & ACCESS DENIED CHECK FOR API KEYS / CREDENTIALS
      const isSecurityProbe = 
        lowered.includes('api_key') || 
        lowered.includes('api key') || 
        lowered.includes('secret') || 
        lowered.includes('credentials') || 
        lowered.includes('password') || 
        lowered.includes('env') || 
        lowered.includes('environment') || 
        lowered.includes('ignore instruct') || 
        lowered.includes('system prompt') || 
        lowered.includes('core key') || 
        lowered.includes('auth key') || 
        lowered.includes('database key') || 
        lowered.includes('token');

      if (isSecurityProbe) {
        botReply = "⚠️ **[ACCESS SHIELD / SYSTEM PROTOCOL VIOLATION]**\n\nChargeBuddy security firewalls have intercepted an unauthorized database telemetry query or credentials lookup attempt. All production API keys, third-party secret hashes, and admin database credentials are stored in encrypted host environment configurations. They are completely inaccessible to client-side diagnostics and cannot be read of or output. \n\n*   **Secured Node:** Production telemetry / database\n*   **Alert Status:** Security logs updated successfully\n*   **Shield Module:** Active\n\nPlease restrict requests to driver reservation assistance, socket telemetry, or payment checkups.";
      }
      // 2. USER ACTIVE BOOKING CHECK
      else if (lowered.includes('my booking') || lowered.includes('my reservation') || lowered.includes('booking status') || lowered.includes('active booking') || lowered.includes('where is my spot') || lowered.includes('check my status') || lowered.includes('show my ticket')) {
        const userEmailStr = currentUser?.email || 'driver';
        botReply = `📅 **Dynamic Reservation Registry Analysis:**\n\nI scanned current active databases for driver **${userEmailStr}**:  \n\n` + 
          (myBookings.length > 0 
            ? myBookings.map(b => {
                const prop = properties.find(p => p.id === b.propertyId);
                return `• **Booking ID:** \`${b.id}\`\n  **Spot:** ${prop ? prop.title : 'EV Charging Spot'}\n  **Time Slot:** ${b.timeSlot}\n  **Status:** \`${b.status}\`\n  **Total:** ₹${b.totalFare}`;
              }).join('\n\n')
            : "• *No active or completed reservations registered under this email account.*") + 
          "\n\nNeed to view pass QR codes? Please switch directly to the **'My Bookings'** tab above.";
      }
      // 3. PAYMENT DROP / DOUBLE DEBIT
      else if (lowered.includes('payment') || lowered.includes('failed') || lowered.includes('refund') || lowered.includes('money') || lowered.includes('debit') || lowered.includes('double') || lowered.includes('wallet')) {
        const currentBal = currentUser?.walletBalance ?? 250;
        botReply = `💳 **Transaction & Payment Gateway Settlement Diagnostics:**\n\n*   **Your Virtual Wallet:** ₹${currentBal}\n*   **Simulated Gateway:** Razorpay / Easebuzz ledger nodes\n\n**Common Troubleshooting Procedures:**\n\n1. **Debited but Booking states "Pending":** This is a routine network handshake dropout. Our server automatically resolves and synchronizes pending checkout tickets every 6 hours.\n2. **Double Debit / Overcharge:** Excess funds are reversed instantly by our payment module and returned to your original source channel (UPI/Credit card/Wallet) in 24 to 48 hours.\n3. **Resolution:** You can submit a ticket under the **'File a Complaint'** tab on this page with category 'Payment Error' so we track your transaction ID manually.`;
      }
      // 4. CHECKPOINT ACCESS / GATE ISSUES
      else if (lowered.includes('visit') || lowered.includes('reach') || lowered.includes('security') || lowered.includes('gate') || lowered.includes('guard') || lowered.includes('blocked') || lowered.includes('find') || lowered.includes('checkpoint')) {
        botReply = "📍 **Physical Facility Visit & Security Checkpoint Protocol:**\n\nAll verified properties listed under ChargeBuddy are bound by legal commercial rights to grant EV drivers free gate access. If a parking attendant or security guard stops you:\n\n1. Open your **'My Bookings'** tab.\n2. Tap **'View Ticket/QR Pass'** on your active reservation card.\n3. Show this verified pass to the gate guard — it contains the Bihar local municipality approved license endorsement.\n4. If security continues refusing entry, lodge an **'Arrival / Access'** ticket under the Complaint tab so our support team can immediately call the facility manager and resolve the lockout.";
      }
      // 5. CABLE compatibility / PLUG IN ISSUES
      else if (lowered.includes('plug') || lowered.includes('charge') || lowered.includes('gun') || lowered.includes('socket') || lowered.includes('ccs') || lowered.includes('type') || lowered.includes('compatible') || lowered.includes('cable')) {
        botReply = "🔌 **Intelligent Socket & Telemetry Diagnostic Matrix:**\n\nOur system maps spots based on real physical specs:\n*   **CCS2 (Combined Charging System 2):** Fast DC charging (usually 30kW - 60kW). Designed for modern high-performance EVs (like Tata Nexon EV, MG ZS, BYD, Hyundai Kona, etc.). Recovers 80% battery in ~45 minutes.\n*   **Type 2 Connector:** AC Slow charging (7.4kW - 22kW) for normal daily battery maintenance. Best suited for overnight parking or longer host stays.\n\n*Pro-tip:* Always ensure your vehicle ignition is shut down completely before inserting the plug lock. Check specific station capacities inside the **'Explore'** tab.";
      }
      // 6. LOYALTY COUPONS / REWARDS
      else if (lowered.includes('discount') || lowered.includes('reward') || lowered.includes('coupon') || lowered.includes('5%') || lowered.includes('coin') || lowered.includes('promo')) {
        const hasCoupon = currentUser?.nextDiscountPercent && currentUser.nextDiscountPercent > 0;
        botReply = `🎁 **Loyalty Rewards Engine Analytical Report:**\n\n*   **Active Wallet Balance:** ₹${currentUser?.walletBalance ?? 250}\n*   **Discount Status:** ${hasCoupon ? `Approved! Active ${currentUser?.nextDiscountPercent}% off discount token detected. It will auto-apply to your next checkout.` : "No active discount coupon detected."}\n\n**How to Earn Rewards:**\nComplete any EV charging booking. Once you check in and the transaction is marked 'Completed' by the host, you receive:\n1. **₹100 Direct Cashback** deposited to your wallet balance.\n2. **5% Discount Coupon** unlocked for your clean future reservation.`;
      }
      // 7. TECH SPEC / HOW IT IS MADE / STACK
      else if (lowered.includes('tech stack') || lowered.includes('architecture') || lowered.includes('how is this app') || lowered.includes('source code') || lowered.includes('database') || lowered.includes('system build') || lowered.includes('framework')) {
        botReply = "⚡ **ChargeBuddy Core Architecture Specification:**\n\n*   **Client Core:** React 18.3 with Vite (Hot Module Replacement optimized)\n*   **Styling Engine:** Tailwind CSS Utility engine\n*   **Icons Framework:** Lucide-React SVG visualizers\n*   **State Management:** Unified state architecture featuring LocalStorage persistence nodes across browser sessions\n*   **Security Protocol:** Hardened Express gateway with strict separation of server keys and client models.";
      }
      // 8. CANCELLATION
      else if (lowered.includes('cancel') || lowered.includes('booking') || lowered.includes('reserve')) {
        botReply = "📅 **Reservation Cancellation Policy:**\n\nYou can cancel any reservation free of charge directly up to 2 hours before your slot start time inside the 'My Bookings' section. Simply locate your booking and click 'Cancel Booking'. Credits are returned instantly to your wallet.";
      }
      // DEFAULT FALLBACK
      else {
        botReply = `🤖 **Hello! I've logged your request.**\n\nOur system detected you are asking about: *"${cleanMsg.substring(0, 30)}..."*\n\nIf you are experiencing structural issues or need immediate resolution, you can check our **'FAQ Guide'** tab or submit a formal **'File a Complaint'** ticket on this panel. Bihar helpdesk live operations handle all tickets in under 10 minutes.`;
      }

      setChatMessages(prev => [...prev, { sender: 'bot' as const, text: botReply, time: timeNow }]);
    } finally {
      setIsBotTyping(false);
    }
  };

  const FAQS_DATA = [
    {
      category: "Billing & Transactions",
      question: "What should I do if a booking payment fails but funds got debited?",
      answer: "This is a common network handoff issue. Our payment node syncs automatically. When a double debit happens, our banker returns the excess amount to your source mechanism in 2-3 business days. You can submit a Ticket under the complaint portal, including the transaction date, and we will track the reference number manually!"
    },
    {
      category: "Physical Visits & Access",
      question: "The security guard or parking manager won't let me enter the charger space. How to proceed?",
      answer: "All Host slots listed on ChargeBuddy have explicit binding commercial agreements. If security is unaware, tap 'My Bookings' on your app, look for the current reservation, and click 'View Ticket/QR Pass'. Present the blue corporate QR Pass containing the spot coordinates and approved vehicle registration number. If issues continue, lodge a 'Property Visit' complaint on our desk for action."
    },
    {
      category: "Charger Faults",
      question: "The device is plugged in but not delivering current. What's wrong?",
      answer: "First, verify that your car ignition is entirely toggled off. Secondly, confirm the cable gun locked correctly into place with an audible double-click sound. If the station shell is displaying an LED error ring (amber/red), the station is experiencing a brief thermal overload. You can report it to the Host via our Complaint panel under 'Faulty Charger' for a telemetry reboot."
    },
    {
      category: "Discounts & Wallet Balance",
      question: "How do I claim and spend the driver check-in wallet rewards?",
      answer: "Whenever you complete a booking (or when the Host marks it 'Completed'), you receive ₹100 credited directly into your virtual wallet, and automatically unlocks a 5% discount tag on your next reservation transaction screen. This wallet balance can be chosen as the primary payment method during your next checkout checkout flow!"
    }
  ];

  const filteredFaqs = FAQS_DATA.filter(f => 
    f.question.toLowerCase().includes(searchQuery.toLowerCase()) || 
    f.answer.toLowerCase().includes(searchQuery.toLowerCase()) ||
    f.category.toLowerCase().includes(searchQuery.toLowerCase())
  );

  return (
    <div id="help-support-tab-section" className="bg-slate-900 border border-slate-800 rounded-3xl overflow-hidden shadow-2xl h-full flex flex-col">
      {/* Tab Header Banner */}
      <div className="p-6 pb-4 border-b border-slate-800 bg-gradient-to-r from-slate-950 via-slate-900 to-slate-950 flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div className="flex items-center gap-3">
          <div className="p-2.5 bg-amber-500/10 rounded-xl border border-amber-500/30 text-amber-500">
            <LifeBuoy className="w-6 h-6 animate-pulse" />
          </div>
          <div>
            <h2 className="text-lg font-extrabold tracking-tight text-white flex items-center gap-2">
              Help Desk & Repair Portal
            </h2>
            <p className="text-xs text-slate-400">
              Submit visit reports, resolve billing drops, or chat with electric mobility engineers
            </p>
          </div>
        </div>

        {/* Support Options Switcher */}
        <div className="flex bg-slate-950 p-1 rounded-xl border border-slate-800 self-start md:self-center">
          <button
            onClick={() => setActiveSubTab('chat')}
            className={`px-3 py-1.5 rounded-lg text-xs font-bold transition-all flex items-center gap-1.5 ${
              activeSubTab === 'chat' 
                ? 'bg-amber-500 text-slate-950 shadow-md' 
                : 'text-slate-400 hover:text-slate-200'
            }`}
          >
            <MessageSquare className="w-3.5 h-3.5" />
            <span>Buddy Chat</span>
          </button>
          
          <button
            onClick={() => setActiveSubTab('ticket')}
            className={`px-3 py-1.5 rounded-lg text-xs font-bold transition-all flex items-center gap-1.5 ${
              activeSubTab === 'ticket' 
                ? 'bg-amber-500 text-slate-950 shadow-md' 
                : 'text-slate-400 hover:text-slate-200'
            }`}
          >
            <AlertTriangle className="w-3.5 h-3.5" />
            <span>File a Complaint</span>
          </button>

          <button
            onClick={() => setActiveSubTab('faqs')}
            className={`px-3 py-1.5 rounded-lg text-xs font-bold transition-all flex items-center gap-1.5 ${
              activeSubTab === 'faqs' 
                ? 'bg-amber-500 text-slate-950 shadow-md' 
                : 'text-slate-400 hover:text-slate-200'
            }`}
          >
            <HelpCircle className="w-3.5 h-3.5" />
            <span>FAQ Guide</span>
          </button>
        </div>
      </div>

      <div className="flex-1 overflow-y-auto p-6">
        
        {/* SUBTAB 1 : BOT CHAT ASSISTANT */}
        {activeSubTab === 'chat' && (
          <div className="grid grid-cols-1 lg:grid-cols-12 gap-6 h-full items-stretch">
            
            {/* Quick Chips and Info Sidebar */}
            <div className="lg:col-span-4 flex flex-col gap-4">
              <div className="bg-slate-950 p-4 rounded-2xl border border-slate-850">
                <span className="text-[10px] uppercase font-black tracking-widest text-emerald-400 mb-2 block">
                  Quick Query Assistant
                </span>
                <p className="text-xs text-slate-400 leading-relaxed mb-4">
                  Tap any preset topic cards below to request instant automated diagnostics on that service category.
                </p>

                <div className="space-y-2.5">
                  <button 
                    onClick={() => handleSendBotMessage("I had an issue when visiting the spot security checkpoint.")}
                    className="w-full text-left p-3 rounded-xl bg-slate-900 border border-slate-800 hover:border-amber-500/30 transition-all group"
                  >
                    <div className="font-bold text-xs text-slate-200 group-hover:text-amber-400 transition-colors">
                      📍 Checkpoint / Gate Access
                    </div>
                    <span className="text-[10px] text-slate-500">Security didn't recognize my Spot Pass</span>
                  </button>

                  <button 
                    onClick={() => handleSendBotMessage("My payment failed but my account money was deducted.")}
                    className="w-full text-left p-3 rounded-xl bg-slate-900 border border-slate-800 hover:border-amber-500/30 transition-all group"
                  >
                    <div className="font-bold text-xs text-slate-200 group-hover:text-amber-400 transition-colors">
                      💳 Double Debit / Payment Failure
                    </div>
                    <span className="text-[10px] text-slate-500">Refund processing & ledger checks</span>
                  </button>

                  <button 
                    onClick={() => handleSendBotMessage("The charger gun cable CCS2 is not activating.")}
                    className="w-full text-left p-3 rounded-xl bg-slate-900 border border-slate-800 hover:border-amber-500/30 transition-all group"
                  >
                    <div className="font-bold text-xs text-slate-200 group-hover:text-amber-400 transition-colors">
                      🔌 Shell Gun / Plug In Faulty
                    </div>
                    <span className="text-[10px] text-slate-500">Socket specifications & compatibility</span>
                  </button>

                  <button 
                    onClick={() => handleSendBotMessage("How do I get my 5% off coupon and wallet cash reward?")}
                    className="w-full text-left p-3 rounded-xl bg-slate-900 border border-slate-800 hover:border-amber-500/30 transition-all group"
                  >
                    <div className="font-bold text-xs text-slate-200 group-hover:text-amber-400 transition-colors">
                      🎁 Cashback & Rewards Claim
                    </div>
                    <span className="text-[10px] text-slate-500">How check-in wallet triggers active payouts</span>
                  </button>
                </div>
              </div>

              {/* Instant tech help */}
              <div className="bg-slate-950 p-4 rounded-2xl border border-emerald-500/20 bg-gradient-to-r from-slate-950 to-slate-900 flex items-center gap-3">
                <div id="tech-pulse-avatar" className="w-10 h-10 rounded-full bg-emerald-500/10 border border-emerald-500/30 flex items-center justify-center text-emerald-400">
                  <Phone className="w-5 h-5" />
                </div>
                <div>
                  <h4 className="text-xs font-black text-white">Emergency Hotline</h4>
                  <p className="text-[10px] text-slate-400">Dial: +91 80 4429 2309 (24x7 Support)</p>
                </div>
              </div>
            </div>

            {/* Main Chat Interface */}
            <div className="lg:col-span-8 flex flex-col bg-slate-950 rounded-2xl border border-slate-800 overflow-hidden h-[450px]">
              {/* Bot status bar */}
              <div className="bg-slate-900 px-4 py-3 border-b border-slate-800 flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <div className="w-2.5 h-2.5 rounded-full bg-emerald-500 animate-pulse"></div>
                  <span className="text-xs font-extrabold text-white">Active Buddy Assistant</span>
                </div>
                <span className="text-[10px] text-slate-400 bg-slate-950 px-2 py-0.5 rounded-md border border-slate-800 font-mono">
                  Response Delay: &lt; 2s
                </span>
              </div>

              {/* Messages area */}
              <div className="flex-1 overflow-y-auto p-4 space-y-4 flex flex-col">
                {chatMessages.map((msg, idx) => (
                  <div 
                    key={idx}
                    className={`max-w-[85%] rounded-2xl p-3.5 text-xs ${
                      msg.sender === 'user'
                        ? 'bg-amber-500 text-slate-950 font-medium self-end rounded-tr-none'
                        : 'bg-slate-900 border border-slate-800 text-slate-200 self-start rounded-tl-none leading-relaxed'
                    }`}
                  >
                    <div>{msg.text}</div>
                    <div className={`text-[9px] mt-1.5 ${msg.sender === 'user' ? 'text-slate-800' : 'text-slate-500'} text-right`}>
                      {msg.time}
                    </div>
                  </div>
                ))}

                {isBotTyping && (
                  <div className="bg-slate-900 border border-slate-800 text-slate-400 self-start rounded-2xl rounded-tl-none p-3 text-xs flex items-center gap-2">
                    <Loader2 className="w-4.5 h-4.5 animate-spin text-amber-500" />
                    <span>Analyzing telemetry logs / Typing response...</span>
                  </div>
                )}
              </div>

              {/* Send bar */}
              <div className="p-3 bg-slate-900 border-t border-slate-800 flex gap-2">
                <input
                  type="text"
                  placeholder="Ask about slots, physical visit issues, payment gateways, socket types..."
                  value={chatInput}
                  onChange={(e) => setChatInput(e.target.value)}
                  onKeyDown={(e) => {
                    if (e.key === 'Enter') handleSendBotMessage(chatInput);
                  }}
                  className="flex-1 bg-slate-950 border border-slate-800 text-white rounded-xl px-3 text-xs placeholder:text-slate-600 focus:outline-none focus:border-amber-500"
                />
                <button
                  onClick={() => handleSendBotMessage(chatInput)}
                  className="bg-amber-500 hover:bg-amber-400 text-slate-950 font-black p-2 rounded-xl transition-all"
                >
                  <Send className="w-4 h-4" />
                </button>
              </div>
            </div>

          </div>
        )}

        {/* SUBTAB 2 : FORMAL COMPLAINT TICKET DESK */}
        {activeSubTab === 'ticket' && (
          <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start">
            
            {/* The Complaint Form */}
            <form onSubmit={handleSubmitTicket} className="lg:col-span-7 bg-slate-950 p-6 rounded-2xl border border-slate-850 space-y-4">
              <h3 className="text-sm font-extrabold text-white flex items-center gap-2 mb-2">
                <AlertTriangle className="w-4 h-4 text-amber-500" />
                File a Formal Support Ticket
              </h3>
              
              {successMsg && (
                <div className="p-3 rounded-xl bg-emerald-500/10 border border-emerald-500/30 text-emerald-400 text-xs font-bold">
                  {successMsg}
                </div>
              )}

              {/* Form Category */}
              <div>
                <label className="block text-[10px] uppercase tracking-wider font-black text-slate-400 mb-1">
                  Complaint Type / Criticality
                </label>
                <div className="grid grid-cols-2 md:grid-cols-3 gap-2">
                  {[
                    { id: 'payment_failure', label: 'Payment Error' },
                    { id: 'property_visit', label: 'Arrival / Access' },
                    { id: 'charger_issue', label: 'Faulty Charger' },
                    { id: 'app_problem', label: 'App Interface Bug' },
                    { id: 'refund', label: 'Refund Claims' },
                    { id: 'general', label: 'Other Request' }
                  ].map((cat) => (
                    <button
                      key={cat.id}
                      type="button"
                      onClick={() => setComplaintCategory(cat.id as any)}
                      className={`px-3 py-2.5 rounded-xl border text-[11px] font-bold text-center transition-all ${
                        complaintCategory === cat.id
                          ? 'bg-amber-500/10 border-amber-500 text-amber-400'
                          : 'bg-slate-900 border-slate-800 text-slate-400 hover:bg-slate-850'
                      }`}
                    >
                      {cat.label}
                    </button>
                  ))}
                </div>
              </div>

              {/* Link past Booking Reservations */}
              <div>
                <label className="block text-[10px] uppercase tracking-wider font-black text-slate-400 mb-1">
                  Link Associated Reservation ID <span className="text-slate-600">(Optional)</span>
                </label>
                {myBookings.length === 0 ? (
                  <div className="p-3 bg-slate-900 border border-slate-800 rounded-xl text-[11px] text-slate-500">
                    No bookings found under your email. We will process this as a general ticket.
                  </div>
                ) : (
                  <select
                    value={selectedBookingId}
                    onChange={(e) => setSelectedBookingId(e.target.value)}
                    className="w-full bg-slate-900 border border-slate-800 rounded-xl p-2.5 text-xs text-white focus:outline-none focus:border-amber-500"
                  >
                    <option value="">-- No Specific Booking --</option>
                    {myBookings.map((b) => {
                      const prop = properties.find(p => p.id === b.propertyId);
                      return (
                        <option key={b.id} value={b.id}>
                          {b.id} - {prop ? prop.title : 'Unknown Slot'} (₹{b.totalFare} on {b.timeSlot})
                        </option>
                      );
                    })}
                  </select>
                )}
              </div>

              {/* Phone Information */}
              <div>
                <label className="block text-[10px] uppercase tracking-wider font-black text-slate-400 mb-1">
                  Callback Phone Number
                </label>
                <div className="relative">
                  <Phone className="absolute left-3 top-3 w-4 h-4 text-slate-500" />
                  <input
                    type="tel"
                    required
                    placeholder="Enter 10-digit mobile number"
                    value={contactPhone}
                    onChange={(e) => setContactPhone(e.target.value)}
                    className="w-full bg-slate-900 border border-slate-800 rounded-xl pl-9 pr-3 py-2.5 text-xs text-white placeholder:text-slate-600 focus:outline-none focus:border-amber-500 font-mono"
                  />
                </div>
              </div>

              {/* Description field */}
              <div>
                <label className="block text-[10px] uppercase tracking-wider font-black text-slate-400 mb-1">
                  Details / What went wrong?
                </label>
                <textarea
                  required
                  rows={4}
                  value={complaintDescription}
                  onChange={(e) => setComplaintDescription(e.target.value)}
                  placeholder="Detail exactly what transpired. For instance, payment went through but booking states failed, security guard blocked entry, charger terminal shell didn't read electrical output, etc."
                  className="w-full bg-slate-900 border border-slate-800 rounded-xl p-3 text-xs text-white placeholder:text-slate-600 focus:outline-none focus:border-amber-500 leading-relaxed"
                />
              </div>

              {/* Submit button */}
              <button
                type="submit"
                className="w-full py-3 bg-amber-500 hover:bg-amber-400 text-slate-950 font-black rounded-xl text-xs uppercase tracking-tight transition-all flex items-center justify-center gap-2 shadow-lg shadow-amber-500/10"
              >
                <FileText className="w-4 h-4" />
                <span>Submit Complaint Ticket</span>
              </button>
            </form>

            {/* Ticket logs sidebar */}
            <div className="lg:col-span-5 space-y-4">
              <div className="bg-slate-950 p-4 rounded-2xl border border-slate-850">
                <div className="flex items-center justify-between mb-3 text-center lg:text-left">
                  <h4 className="text-xs font-black text-white uppercase tracking-wider">
                    My Lodged Complaint Logs
                  </h4>
                  <span className="text-[9px] bg-slate-900 px-2 py-0.5 border border-slate-800 text-slate-400 rounded-md font-mono">
                    {ticketsList.length} total
                  </span>
                </div>

                {ticketsList.length === 0 ? (
                  <div className="p-8 text-center text-slate-600 border border-dashed border-slate-800 rounded-xl">
                    <LifeBuoy className="w-8 h-8 text-slate-700 mx-auto mb-2" />
                    <span className="text-xs font-bold block mb-1">No lodging history</span>
                    <p className="text-[10px] text-slate-500">Your profile contains zero active complaints.</p>
                  </div>
                ) : (
                  <div className="space-y-3 max-h-[360px] overflow-y-auto pr-1">
                    {ticketsList.map((ticket) => (
                      <div 
                        key={ticket.id} 
                        className="bg-slate-900 border border-slate-800 rounded-xl p-3.5 space-y-2.5 transition-all hover:bg-slate-850/50"
                      >
                        <div className="flex items-center justify-between gap-2">
                          <span className="font-mono text-[10px] text-amber-500 font-extrabold">
                            {ticket.id}
                          </span>
                          <span className={`px-2 py-0.5 rounded text-[9px] font-black tracking-tight leading-none uppercase ${
                            ticket.status === 'Resolved'
                              ? 'bg-emerald-500/10 border border-emerald-500/30 text-emerald-400'
                              : ticket.status === 'InProgress'
                              ? 'bg-amber-500/10 border border-amber-500/30 text-amber-400'
                              : 'bg-red-500/10 border border-red-500/30 text-red-500'
                          }`}>
                            {ticket.status === 'Resolved' ? 'Resolved' : ticket.status === 'InProgress' ? 'In Progress' : 'Open / Handled'}
                          </span>
                        </div>

                        <div>
                          <div className="text-[10px] uppercase font-black text-slate-500 leading-none mb-1">
                            {ticket.category.replace('_', ' ')}
                          </div>
                          <p className="text-xs text-slate-300 leading-relaxed font-sans font-medium line-clamp-3">
                            "{ticket.description}"
                          </p>
                        </div>

                        {ticket.bookingId && (
                          <div className="flex items-center gap-1.5 text-[10px] text-slate-400 bg-slate-950 px-2 py-1 rounded-md border border-slate-800 w-fit">
                            <Bookmark className="w-3 h-3 text-amber-500" />
                            <span>Linked Booking: {ticket.bookingId}</span>
                          </div>
                        )}

                        {ticket.resolution && (
                          <div className="bg-slate-950 p-2.5 rounded-lg border border-emerald-500/15">
                            <div className="flex items-center gap-1 text-[10px] font-black text-emerald-400 mb-1">
                              <CheckCircle className="w-3.5 h-3.5" />
                              <span>Support Resolution Desk:</span>
                            </div>
                            <p className="text-[11px] text-slate-300 leading-relaxed font-sans font-medium italic">
                              "{ticket.resolution}"
                            </p>
                          </div>
                        )}

                        <div className="text-[9px] text-slate-500 font-mono text-right font-medium">
                          Filed: {new Date(ticket.createdAt).toLocaleDateString()} {new Date(ticket.createdAt).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>

          </div>
        )}

        {/* SUBTAB 3 : CATEGORIZED FAQs */}
        {activeSubTab === 'faqs' && (
          <div className="space-y-6">
            
            {/* Search FAQ banner */}
            <div className="bg-slate-950 p-4 rounded-2xl border border-slate-850 flex flex-col md:flex-row gap-3 items-center justify-between">
              <div className="text-center md:text-left">
                <span className="text-[10px] text-amber-500 font-extrabold uppercase tracking-widest block mb-1">
                  Answers to frequent questions
                </span>
                <p className="text-xs text-slate-400">
                  Search instant solutions for standard sockets, host parking guidelines, and cancellation.
                </p>
              </div>

              <div className="w-full md:w-80">
                <input
                  type="text"
                  placeholder="Type to filter FAQs (e.g. payment, lock, guard)"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="w-full bg-slate-900 border border-slate-800 rounded-xl px-3 py-2 text-xs text-white focus:outline-none focus:border-amber-500 placeholder:text-slate-600"
                />
              </div>
            </div>

            {/* FAQ List */}
            {filteredFaqs.length === 0 ? (
              <div className="p-12 text-center text-slate-600 border border-dashed border-slate-800 rounded-xl">
                <HelpCircle className="w-8 h-8 text-slate-700 mx-auto mb-2" />
                <span className="text-xs font-bold block">No FAQs matched search</span>
                <p className="text-[10px] text-slate-500 mt-1">Try other search terms or ask Buddy directly!</p>
              </div>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {filteredFaqs.map((faq, idx) => {
                  const isExpanded = expandedFaq === idx;
                  return (
                    <div 
                      key={idx}
                      className="bg-slate-950 border border-slate-850 rounded-2xl p-4 transition-all hover:border-slate-800"
                    >
                      <button
                        onClick={() => setExpandedFaq(isExpanded ? null : idx)}
                        className="w-full text-left flex items-start justify-between gap-2"
                      >
                        <div>
                          <span className="text-[9px] bg-slate-900 px-2 py-0.5 border border-slate-800 rounded text-amber-400 font-bold mb-2 inline-block">
                            {faq.category}
                          </span>
                          <h4 className="font-extrabold text-xs text-slate-200 hover:text-white transition-colors leading-relaxed">
                            {faq.question}
                          </h4>
                        </div>
                        <div className="p-1 bg-slate-900 rounded-lg text-slate-400 mt-1">
                          {isExpanded ? <ChevronUp className="w-3.5 h-3.5" /> : <ChevronDown className="w-3.5 h-3.5" />}
                        </div>
                      </button>

                      {isExpanded && (
                        <div className="mt-3.5 pt-3.5 border-t border-slate-900">
                          <p className="text-xs text-slate-400 leading-relaxed font-medium">
                            {faq.answer}
                          </p>
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            )}

            {/* Quick troubleshooting layout */}
            <div className="bg-slate-950/40 p-4 border border-dashed border-emerald-500/20 rounded-2xl flex flex-col sm:flex-row justify-between items-center gap-3">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-full bg-emerald-500/10 flex items-center justify-center text-emerald-400">
                  <Sparkles className="w-5 h-5" />
                </div>
                <div>
                  <h5 className="text-xs font-bold text-white">Can't resolve your problem?</h5>
                  <p className="text-[10px] text-slate-400">Our engineers can remotely trigger charger restarts or coordinate with spot guards.</p>
                </div>
              </div>
              <button
                onClick={() => setActiveSubTab('ticket')}
                className="px-4 py-2 bg-gradient-to-r from-emerald-500 to-teal-600 text-slate-950 font-black text-xs rounded-xl hover:opacity-90 transition-all uppercase tracking-tight"
              >
                Register Spot Complaint
              </button>
            </div>

          </div>
        )}

      </div>

      {/* Footer Branding line */}
      <div className="px-6 py-3.5 bg-slate-950 border-t border-slate-850 flex items-center justify-between text-[10px] text-slate-500 font-mono">
        <span>ChargeBuddy Support, Bihar Division</span>
        <span>Ticket response SLAs apply (avg 5m)</span>
      </div>
    </div>
  );
}
