import React, { useState, useRef, useEffect } from 'react';
import { base44 } from '@/api/base44Client';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Send, Bot, User, Loader2, Ticket, Plus, ChevronRight, Clock, CheckCircle2, AlertCircle, Circle, MessageSquare, Tag } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import NexusNav from '@/components/dashboard/NexusNav';
import BottomTabBar from '@/components/layout/BottomTabBar';

const CATEGORIES = ['depósito', 'retiro', 'operaciones', 'verificación', 'seguridad', 'técnico', 'otro'];

const STATUS_CONFIG = {
  abierto:      { label: 'Abierto',      color: 'text-sky-400/80',     border: 'border-sky-500/25',     bg: 'rgba(14,165,233,0.07)',  Icon: Circle },
  en_progreso:  { label: 'En progreso',  color: 'text-yellow-400/80',  border: 'border-yellow-500/25',  bg: 'rgba(234,179,8,0.07)',   Icon: Clock },
  resuelto:     { label: 'Resuelto',     color: 'text-emerald-400/80', border: 'border-emerald-500/25', bg: 'rgba(16,185,129,0.07)',  Icon: CheckCircle2 },
  cerrado:      { label: 'Cerrado',      color: 'text-white/30',       border: 'border-white/10',        bg: 'rgba(255,255,255,0.02)', Icon: AlertCircle },
};

function generateTicketNumber() {
  return 'TKT-' + String(Math.floor(100000 + Math.random() * 900000));
}

function timeAgo(dateStr) {
  if (!dateStr) return '';
  const diff = (Date.now() - new Date(dateStr).getTime()) / 1000;
  if (diff < 60) return 'ahora mismo';
  if (diff < 3600) return `hace ${Math.floor(diff / 60)}m`;
  if (diff < 86400) return `hace ${Math.floor(diff / 3600)}h`;
  return `hace ${Math.floor(diff / 86400)}d`;
}

// ─── CHAT IA ──────────────────────────────────────────────────────────────────
function ChatAI() {
  const [messages, setMessages] = useState([
    { id: 1, role: 'assistant', content: '¡Hola! Soy el asistente virtual de NEXUS. Puedo ayudarte con preguntas sobre depósitos, retiros, operaciones de compra/venta, comisiones y uso de la plataforma. ¿En qué puedo ayudarte?' }
  ]);
  const [input, setInput] = useState('');
  const [loading, setLoading] = useState(false);
  const endRef = useRef(null);

  useEffect(() => { endRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [messages, loading]);

  const SYSTEM_PROMPT = `Eres el asistente de soporte técnico de NEXUS, una plataforma de trading de criptomonedas simulado.

POLÍTICA DE VERACIDAD ABSOLUTA — OBLIGATORIA:
1. SOLO puedes responder con información incluida en este prompt o en el historial del chat.
2. Si el usuario pregunta por sus saldos, portafolio, transacciones u otros datos de cuenta que no conoces, responde EXACTAMENTE: "No puedo verificar esa información con los datos disponibles."
3. ESTÁ TERMINANTEMENTE PROHIBIDO inventar: estadísticas, saldos, usuarios, transacciones, integraciones, funcionalidades, incidencias o configuraciones.
4. Si no sabes la respuesta, di: "No dispongo de esa información."
5. Prioridad máxima: VERACIDAD > COMPLETITUD. Es preferible decir "No lo sé" que dar información incorrecta.

HECHOS VERIFICADOS DE LA PLATAFORMA (única información que puedes afirmar):
- Entorno 100% simulado. Ningún dinero real está involucrado.
- Saldo inicial de prueba: $100 USD (simulado).
- Comisión por compra/venta de crypto: 0% (sin comisiones).
- Comisión de swap (crypto→crypto): 0.5%.
- Datos de precios: en tiempo real desde la API pública de CoinGecko.
- Monedas disponibles: top 20 del mercado por capitalización (BTC, ETH, SOL, BNB, etc.).
- Retiros simulados: disponibles en cualquier momento, sin mínimo.
- No se requiere verificación KYC.

SECCIONES REALES DE LA APP (solo estas existen):
- "Inicio" (Dashboard): Muestra estadísticas, portafolio y una tabla de mercados. Al hacer clic en una criptomoneda en la tabla se abre un panel de Comprar/Vender.
- "Billetera" (Wallet): Permite depositar USD, retirar, enviar crypto, realizar Intercambio (Swap, comisión 0.5%) y Conversión Inteligente.
- "Historial": Lista todas las transacciones realizadas.
- "Perfil": Configuración de cuenta y seguridad.
- "Soporte": Esta sección con chat y tickets.

NO EXISTEN en NEXUS: trading de futuros, apalancamiento, margen, staking, lending, NFTs, tarjetas de débito, ni ninguna otra función no mencionada arriba.

Responde de forma concisa y profesional. Si algo no está en este prompt, di que no puedes verificarlo.`;

  const send = async (e) => {
    e.preventDefault();
    if (!input.trim() || loading) return;
    const userMsg = { id: Date.now(), role: 'user', content: input };
    setMessages(prev => [...prev, userMsg]);
    setInput('');
    setLoading(true);
    try {
      const history = messages.slice(-8).map(m => `${m.role === 'user' ? 'Usuario' : 'Asistente'}: ${m.content}`).join('\n');
      const res = await base44.integrations.Core.InvokeLLM({
        prompt: `${SYSTEM_PROMPT}\n\nHistorial:\n${history}\n\nUsuario: ${userMsg.content}`,
      });
      setMessages(prev => [...prev, { id: Date.now() + 1, role: 'assistant', content: res }]);
    } catch {
      setMessages(prev => [...prev, { id: Date.now() + 1, role: 'assistant', content: 'Error al conectar. Intenta de nuevo.' }]);
    } finally {
      setLoading(false);
    }
  };

  const quickQ = [
    '¿Cómo deposito dinero?',
    '¿Cómo vendo mis criptomonedas?',
    '¿Cuáles son las comisiones?',
    '¿Cómo funciona el swap?',
    '¿El saldo es real?',
  ];

  return (
    <div className="border border-white/8 overflow-hidden" style={{ background: 'rgba(255,255,255,0.02)' }}>
      {/* Header */}
      <div className="border-b border-white/8 p-4 flex items-center gap-3">
        <div className="w-8 h-8 border border-white/10 flex items-center justify-center" style={{ background: 'rgba(239,68,68,0.08)' }}>
          <Bot className="w-4 h-4 text-red-400/60" />
        </div>
        <div>
          <p className="text-white/70 text-sm tracking-wide">Asistente Virtual NEXUS</p>
          <p className="text-white/20 text-[9px] tracking-widest uppercase flex items-center gap-1.5">
            <span className="w-1.5 h-1.5 bg-emerald-400 rounded-full animate-pulse inline-block" />
            En línea · Respuesta inmediata
          </p>
        </div>
      </div>

      {/* Messages */}
      <div className="h-[400px] overflow-y-auto p-5 space-y-4">
        {messages.map(m => (
          <motion.div key={m.id} initial={{ opacity: 0, y: 6 }} animate={{ opacity: 1, y: 0 }}
            className={`flex gap-3 ${m.role === 'user' ? 'flex-row-reverse' : ''}`}>
            <div className={`w-7 h-7 border flex items-center justify-center shrink-0 ${m.role === 'user' ? 'border-white/10' : 'border-red-500/20'}`}>
              {m.role === 'user' ? <User className="w-3.5 h-3.5 text-white/40" /> : <Bot className="w-3.5 h-3.5 text-red-400/50" />}
            </div>
            <div className={`max-w-[78%] border p-3.5 ${m.role === 'user' ? 'border-white/8' : 'border-red-500/10'}`}
              style={{ background: m.role === 'user' ? 'rgba(255,255,255,0.03)' : 'rgba(239,68,68,0.03)' }}>
              <p className="text-white/65 text-sm leading-relaxed whitespace-pre-wrap font-light">{m.content}</p>
            </div>
          </motion.div>
        ))}
        {loading && (
          <div className="flex gap-3">
            <div className="w-7 h-7 border border-red-500/20 flex items-center justify-center">
              <Bot className="w-3.5 h-3.5 text-red-400/50" />
            </div>
            <div className="border border-white/8 p-4 flex gap-1.5 items-center">
              {[0, 0.15, 0.3].map((d, i) => (
                <div key={i} className="w-1.5 h-1.5 bg-white/25 rounded-full animate-bounce" style={{ animationDelay: `${d}s` }} />
              ))}
            </div>
          </div>
        )}
        <div ref={endRef} />
      </div>

      {/* Quick questions */}
      {messages.length === 1 && (
        <div className="px-5 pb-3">
          <p className="text-white/15 text-[9px] tracking-widest uppercase mb-2">Preguntas frecuentes</p>
          <div className="flex flex-wrap gap-2">
            {quickQ.map((q, i) => (
              <button key={i} onClick={() => setInput(q)}
                className="px-3 py-1.5 border border-white/8 text-white/30 text-xs hover:border-red-500/25 hover:text-red-400/60 transition-all">
                {q}
              </button>
            ))}
          </div>
        </div>
      )}

      {/* Input */}
      <form onSubmit={send} className="border-t border-white/8 p-4 flex gap-3">
        <input value={input} onChange={e => setInput(e.target.value)} disabled={loading}
          placeholder="Escribe tu pregunta..."
          className="flex-1 bg-transparent border border-white/8 text-white/80 h-11 px-4 text-sm focus:outline-none focus:border-red-500/25 transition-all placeholder:text-white/12"
        />
        <button type="submit" disabled={!input.trim() || loading}
          className="h-11 px-4 border border-red-500/35 text-red-400/70 hover:bg-red-500/8 transition-all disabled:opacity-25">
          {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Send className="w-4 h-4" />}
        </button>
      </form>
    </div>
  );
}

// ─── NUEVO TICKET ──────────────────────────────────────────────────────────────
function NewTicketForm({ onClose, onCreated, userEmail }) {
  const [subject, setSubject] = useState('');
  const [category, setCategory] = useState('operaciones');
  const [message, setMessage] = useState('');
  const [loading, setLoading] = useState(false);

  const submit = async (e) => {
    e.preventDefault();
    if (!subject.trim() || !message.trim()) return;
    setLoading(true);
    const ticket = await base44.entities.SupportTicket.create({
      ticket_number: generateTicketNumber(),
      subject: subject.trim(),
      category,
      status: 'abierto',
      user_email: userEmail || '',
      messages: [
        { role: 'user', content: message.trim(), timestamp: new Date().toISOString() },
        { role: 'agent', content: 'Gracias por contactarnos. Hemos recibido tu ticket y un agente lo revisará pronto. Tiempo estimado de respuesta: 24h.', timestamp: new Date(Date.now() + 2000).toISOString() }
      ]
    });
    setLoading(false);
    onCreated(ticket);
  };

  return (
    <motion.div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center p-4"
      initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}>
      <div className="absolute inset-0 bg-black/85 backdrop-blur-sm" onClick={onClose} />
      <motion.div className="relative w-full max-w-lg border border-white/8 z-10 overflow-hidden"
        style={{ background: 'rgba(8,8,8,0.99)' }}
        initial={{ y: 40, opacity: 0 }} animate={{ y: 0, opacity: 1 }}>
        <div className="border-b border-white/5 p-5 flex items-center gap-3">
          <div className="w-8 h-8 border border-white/10 flex items-center justify-center">
            <Plus className="w-4 h-4 text-white/40" />
          </div>
          <p className="text-white/70 text-sm tracking-widest uppercase">Nuevo Ticket</p>
          <button onClick={onClose} className="ml-auto text-white/20 hover:text-white/60 text-xl leading-none">×</button>
        </div>
        <form onSubmit={submit} className="p-5 space-y-4">
          <div>
            <label className="text-[9px] tracking-widest uppercase text-white/25 block mb-2">Categoría</label>
            <select value={category} onChange={e => setCategory(e.target.value)}
              className="w-full bg-transparent border border-white/8 text-white/60 h-10 px-3 text-sm focus:outline-none focus:border-white/20 transition-all capitalize"
              style={{ background: 'rgba(255,255,255,0.03)' }}>
              {CATEGORIES.map(c => <option key={c} value={c} className="bg-black capitalize">{c}</option>)}
            </select>
          </div>
          <div>
            <label className="text-[9px] tracking-widest uppercase text-white/25 block mb-2">Asunto</label>
            <input value={subject} onChange={e => setSubject(e.target.value)} required
              placeholder="Describe brevemente el problema"
              className="w-full bg-transparent border border-white/8 text-white/70 h-10 px-3 text-sm focus:outline-none focus:border-white/20 transition-all placeholder:text-white/15"
            />
          </div>
          <div>
            <label className="text-[9px] tracking-widest uppercase text-white/25 block mb-2">Descripción</label>
            <textarea value={message} onChange={e => setMessage(e.target.value)} required rows={4}
              placeholder="Explica el problema con detalle..."
              className="w-full bg-transparent border border-white/8 text-white/70 px-3 py-2.5 text-sm focus:outline-none focus:border-white/20 transition-all resize-none placeholder:text-white/15"
            />
          </div>
          <div className="flex gap-3 pt-1">
            <button type="button" onClick={onClose}
              className="flex-1 py-3 border border-white/8 text-white/25 text-xs tracking-widest uppercase hover:bg-white/5 transition-all">
              Cancelar
            </button>
            <button type="submit" disabled={loading || !subject.trim() || !message.trim()}
              className="flex-1 py-3 border border-white/20 text-white/60 text-xs tracking-widest uppercase hover:bg-white/5 transition-all disabled:opacity-25 flex items-center justify-center gap-2">
              {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : 'Crear Ticket'}
            </button>
          </div>
        </form>
      </motion.div>
    </motion.div>
  );
}

// ─── TICKET DETAIL ─────────────────────────────────────────────────────────────
function TicketDetail({ ticket, onClose }) {
  const qc = useQueryClient();
  const [reply, setReply] = useState('');
  const [loading, setLoading] = useState(false);
  const endRef = useRef(null);
  const cfg = STATUS_CONFIG[ticket.status] || STATUS_CONFIG.abierto;
  const Icon = cfg.Icon;

  useEffect(() => { endRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [ticket.messages]);

  const sendReply = async (e) => {
    e.preventDefault();
    if (!reply.trim() || loading) return;
    setLoading(true);
    const userMsg = { role: 'user', content: reply.trim(), timestamp: new Date().toISOString() };

    // Get AI response based on ticket context
    let agentResponse = 'Gracias por la información adicional. Nuestro equipo la revisará y te responderá pronto.';
    try {
      agentResponse = await base44.integrations.Core.InvokeLLM({
        prompt: `Eres un agente de soporte de NEXUS (plataforma de trading crypto 100% simulado, sin dinero real).
POLÍTICA DE VERACIDAD: NUNCA inventes saldos, transacciones, estadísticas ni funciones que no existen. Si no puedes verificar un dato, di exactamente: "No puedo verificar esa información con los datos disponibles."
Funciones REALES de NEXUS: Compra/Venta de crypto (0% comisión), Swap crypto→crypto (0.5% comisión), Depósito/Retiro simulado, historial de transacciones.
NO EXISTEN en NEXUS: futuros, apalancamiento, staking, NFTs, ni ninguna otra función no mencionada.
El ticket es sobre: "${ticket.subject}" (categoría: ${ticket.category}).
El usuario dice: "${reply.trim()}"
Responde de forma breve, profesional y SOLO con información verificable.`,
      });
    } catch {}

    const agentMsg = { role: 'agent', content: agentResponse, timestamp: new Date(Date.now() + 500).toISOString() };
    const updatedMessages = [...(ticket.messages || []), userMsg, agentMsg];

    await base44.entities.SupportTicket.update(ticket.id, {
      messages: updatedMessages,
      status: ticket.status === 'abierto' ? 'en_progreso' : ticket.status,
    });
    qc.invalidateQueries({ queryKey: ['support_tickets'] });
    setReply('');
    setLoading(false);
  };

  return (
    <motion.div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center p-4"
      initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}>
      <div className="absolute inset-0 bg-black/85 backdrop-blur-sm" onClick={onClose} />
      <motion.div className="relative w-full max-w-lg border border-white/8 z-10 overflow-hidden flex flex-col max-h-[90vh]"
        style={{ background: 'rgba(8,8,8,0.99)' }}
        initial={{ y: 40, opacity: 0 }} animate={{ y: 0, opacity: 1 }}>

        {/* Header */}
        <div className="border-b border-white/5 p-5 shrink-0">
          <div className="flex items-start justify-between gap-3">
            <div className="flex-1 min-w-0">
              <p className="text-white/20 text-[9px] tracking-widest uppercase mb-1">{ticket.ticket_number}</p>
              <p className="text-white/70 text-sm truncate">{ticket.subject}</p>
            </div>
            <div className={`px-2.5 py-1 border ${cfg.border} flex items-center gap-1.5 shrink-0`} style={{ background: cfg.bg }}>
              <Icon className={`w-3 h-3 ${cfg.color}`} />
              <span className={`text-[9px] tracking-widest uppercase ${cfg.color}`}>{cfg.label}</span>
            </div>
          </div>
          <div className="flex items-center gap-3 mt-2">
            <span className="text-white/20 text-[9px] capitalize">{ticket.category}</span>
            <span className="text-white/10">·</span>
            <span className="text-white/15 text-[9px]">{timeAgo(ticket.created_date)}</span>
          </div>
          <button onClick={onClose} className="absolute top-4 right-4 text-white/20 hover:text-white/60 text-xl leading-none">×</button>
        </div>

        {/* Messages */}
        <div className="flex-1 overflow-y-auto p-5 space-y-4">
          {(ticket.messages || []).map((m, i) => (
            <div key={i} className={`flex gap-3 ${m.role === 'user' ? 'flex-row-reverse' : ''}`}>
              <div className={`w-7 h-7 border flex items-center justify-center shrink-0 ${m.role === 'user' ? 'border-white/10' : 'border-white/8'}`}>
                {m.role === 'user'
                  ? <User className="w-3.5 h-3.5 text-white/35" />
                  : <Bot className="w-3.5 h-3.5 text-white/25" />}
              </div>
              <div className="flex-1 min-w-0">
                <div className={`border p-3.5 ${m.role === 'user' ? 'border-white/8' : 'border-white/5'}`}
                  style={{ background: m.role === 'user' ? 'rgba(255,255,255,0.03)' : 'rgba(255,255,255,0.015)' }}>
                  <p className="text-white/60 text-sm leading-relaxed whitespace-pre-wrap font-light">{m.content}</p>
                </div>
                <p className="text-white/15 text-[9px] mt-1 px-1">{m.role === 'user' ? 'Tú' : 'Agente NEXUS'} · {timeAgo(m.timestamp)}</p>
              </div>
            </div>
          ))}
          {loading && (
            <div className="flex gap-3">
              <div className="w-7 h-7 border border-white/8 flex items-center justify-center">
                <Bot className="w-3.5 h-3.5 text-white/20" />
              </div>
              <div className="border border-white/5 p-4 flex gap-1.5 items-center">
                {[0, 0.15, 0.3].map((d, i) => (
                  <div key={i} className="w-1.5 h-1.5 bg-white/20 rounded-full animate-bounce" style={{ animationDelay: `${d}s` }} />
                ))}
              </div>
            </div>
          )}
          <div ref={endRef} />
        </div>

        {/* Reply */}
        {ticket.status !== 'cerrado' && ticket.status !== 'resuelto' && (
          <form onSubmit={sendReply} className="border-t border-white/5 p-4 flex gap-3 shrink-0">
            <input value={reply} onChange={e => setReply(e.target.value)} disabled={loading}
              placeholder="Escribe una respuesta..."
              className="flex-1 bg-transparent border border-white/8 text-white/70 h-10 px-3 text-sm focus:outline-none focus:border-white/15 transition-all placeholder:text-white/12"
            />
            <button type="submit" disabled={!reply.trim() || loading}
              className="h-10 px-4 border border-white/15 text-white/40 hover:bg-white/5 transition-all disabled:opacity-20">
              {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Send className="w-4 h-4" />}
            </button>
          </form>
        )}
      </motion.div>
    </motion.div>
  );
}

// ─── TICKETS LIST ──────────────────────────────────────────────────────────────
function TicketsList({ userEmail }) {
  const qc = useQueryClient();
  const [showNew, setShowNew] = useState(false);
  const [selected, setSelected] = useState(null);

  const { data: tickets = [], isLoading } = useQuery({
    queryKey: ['support_tickets'],
    queryFn: () => base44.entities.SupportTicket.list('-created_date', 50),
    refetchInterval: 15000,
  });

  const handleCreated = (ticket) => {
    qc.invalidateQueries({ queryKey: ['support_tickets'] });
    setShowNew(false);
    setSelected(ticket);
  };

  const selectedTicket = selected ? (tickets.find(t => t.id === selected.id) || selected) : null;

  return (
    <div>
      <div className="flex items-center justify-between mb-5">
        <p className="text-white/20 text-[9px] tracking-widest uppercase">{tickets.length} ticket{tickets.length !== 1 ? 's' : ''}</p>
        <button onClick={() => setShowNew(true)}
          className="flex items-center gap-2 border border-white/10 px-4 py-2 text-white/40 text-xs tracking-widest uppercase hover:border-white/20 hover:text-white/60 transition-all">
          <Plus className="w-3.5 h-3.5" />
          Nuevo ticket
        </button>
      </div>

      {isLoading ? (
        <div className="flex justify-center py-12">
          <Loader2 className="w-5 h-5 animate-spin text-white/20" />
        </div>
      ) : tickets.length === 0 ? (
        <div className="border border-white/5 p-10 text-center" style={{ background: 'rgba(255,255,255,0.01)' }}>
          <Ticket className="w-8 h-8 text-white/10 mx-auto mb-3" />
          <p className="text-white/25 text-sm">Sin tickets de soporte</p>
          <p className="text-white/12 text-xs mt-1">Crea uno si tienes algún problema con la plataforma</p>
        </div>
      ) : (
        <div className="space-y-2">
          {tickets.map(t => {
            const cfg = STATUS_CONFIG[t.status] || STATUS_CONFIG.abierto;
            const Icon = cfg.Icon;
            const lastMsg = (t.messages || []).slice(-1)[0];
            return (
              <button key={t.id} onClick={() => setSelected(t)}
                className="w-full border border-white/5 p-4 flex items-start gap-4 hover:border-white/10 hover:bg-white/2 transition-all text-left"
                style={{ background: 'rgba(255,255,255,0.015)' }}>
                <div className={`mt-0.5 px-2 py-0.5 border ${cfg.border} flex items-center gap-1 shrink-0`} style={{ background: cfg.bg }}>
                  <Icon className={`w-3 h-3 ${cfg.color}`} />
                </div>
                <div className="flex-1 min-w-0">
                  <div className="flex items-start justify-between gap-3 mb-1">
                    <p className="text-white/65 text-sm truncate">{t.subject}</p>
                    <span className="text-white/15 text-[9px] shrink-0">{timeAgo(t.created_date)}</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <span className="text-white/15 text-[9px]">{t.ticket_number}</span>
                    <span className="text-white/10">·</span>
                    <span className="text-white/15 text-[9px] capitalize">{t.category}</span>
                    {lastMsg && (
                      <>
                        <span className="text-white/10">·</span>
                        <span className="text-white/12 text-[9px] truncate max-w-[160px]">{lastMsg.content.slice(0, 50)}…</span>
                      </>
                    )}
                  </div>
                </div>
                <ChevronRight className="w-4 h-4 text-white/15 shrink-0 mt-0.5" />
              </button>
            );
          })}
        </div>
      )}

      <AnimatePresence>
        {showNew && <NewTicketForm onClose={() => setShowNew(false)} onCreated={handleCreated} userEmail={userEmail} />}
        {selectedTicket && <TicketDetail ticket={selectedTicket} onClose={() => setSelected(null)} />}
      </AnimatePresence>
    </div>
  );
}

// ─── MAIN ──────────────────────────────────────────────────────────────────────
export default function Support() {
  const [tab, setTab] = useState('chat');
  const [user, setUser] = useState(null);

  useEffect(() => {
    base44.auth.me().then(setUser).catch(() => {});
  }, []);

  const tabs = [
    { id: 'chat',    label: 'Chat',    Icon: MessageSquare },
    { id: 'tickets', label: 'Tickets', Icon: Tag },
  ];

  return (
    <div className="min-h-screen bg-black text-white">
      <NexusNav />
      <div className="pt-8 md:pt-28 max-w-3xl mx-auto px-4 sm:px-6 lg:px-8 pb-28">

        {/* Header */}
        <div className="flex items-center gap-4 mb-8">
          <div className="w-px h-6 bg-red-500/50" />
          <h2 className="text-white/40 text-[10px] tracking-[0.4em] uppercase">Soporte</h2>
          <div className="flex-1 h-px bg-white/5" />
        </div>

        {/* Tabs */}
        <div className="flex border-b border-white/5 mb-6">
          {tabs.map(({ id, label, Icon }) => (
            <button key={id} onClick={() => setTab(id)}
              className={`flex items-center gap-2 px-5 py-3 text-xs tracking-widest uppercase transition-all ${
                tab === id ? 'text-white/70 border-b border-white/30 -mb-px' : 'text-white/20 hover:text-white/40'
              }`}>
              <Icon className="w-3.5 h-3.5" />
              {label}
            </button>
          ))}
        </div>

        <AnimatePresence mode="wait">
          {tab === 'chat' ? (
            <motion.div key="chat" initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0 }}>
              <ChatAI />
            </motion.div>
          ) : (
            <motion.div key="tickets" initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0 }}>
              <TicketsList userEmail={user?.email} />
            </motion.div>
          )}
        </AnimatePresence>
      </div>
      <BottomTabBar />
    </div>
  );
}