const Admin = () => {
  const t = window.t || (k => k);
  const {toast, confirm} = useApp();
  const [tab, setTab] = useState('overview');
  const [tickets, setTickets] = useState([]);
  const [replyText, setReplyText] = useState({});
  const [supportFilter, setSupportFilter] = useState('open');
  const [expandedTk, setExpandedTk] = useState({});
  const [users, setUsers] = useState([]);
  const [metrics, setMetrics] = useState(null);
  const [logs, setLogs] = useState([]);
  const [logLevel, setLogLevel] = useState('');
  const [search, setSearch] = useState('');
  const [selectedUser, setSelectedUser] = useState(null);
  const [userDetail, setUserDetail] = useState(null);
  const [detailTab, setDetailTab] = useState('activity');
  const [loadingDetail, setLoadingDetail] = useState(false);
  const [expandedSub, setExpandedSub] = useState(null);
  const [subViewMode, setSubViewMode] = useState({});  // {subId: 'summary'|'post'}
  const [giftMonths, setGiftMonths] = useState(1);
  const [showGiftFor, setShowGiftFor] = useState(null);
  const [showCreateUser, setShowCreateUser] = useState(false);
  const [newUser, setNewUser] = useState({email:'',password:'',name:'',license:'PPL',plan:'free'});
  const [showChangePass, setShowChangePass] = useState(null);
  const [newPass, setNewPass] = useState('');
  const [ifrRoutes, setIfrRoutes] = useState(() => JSON.parse(document.getElementById('ifr-data')?.textContent || '[]'));
  const [editingRoute, setEditingRoute] = useState(null);
  const [routeForm, setRouteForm] = useState({from:'',to:'',rules:'Z',fl:'',route:'',dur:'',notes:''});
  const [userFilter, setUserFilter] = useState('all'); // all|premium|gifted|free|blocked|instructor

  // Load data from API
  useEffect(() => {
    api.adminMetrics().then(d => setMetrics(d)).catch(() => {});
    api.adminUsers('').then(d => setUsers(d.users || [])).catch(() => {});
  }, []);

  const logsLoaded = useRef('');
  const supportLoaded = useRef(false);

  useEffect(() => {
    if (tab === 'logs' && logsLoaded.current !== logLevel) {
      logsLoaded.current = logLevel;
      api.adminLogs(logLevel).then(d => setLogs(d.logs || [])).catch(() => {});
    }
  }, [tab, logLevel]);

  useEffect(() => {
    if (tab === 'support' && !supportLoaded.current) {
      supportLoaded.current = true;
      api.adminSupport().then(d => setTickets(d.tickets || [])).catch(() => {});
    }
  }, [tab]);

  const searchUsers = (q) => {
    setSearch(q);
    api.adminUsers(q).then(d => setUsers(d.users || [])).catch(() => {});
  };

  const openUserDetail = async (u) => {
    setSelectedUser(u);
    setDetailTab('activity');
    setLoadingDetail(true);
    try {
      const d = await api.adminUserDetail(u.id);
      setUserDetail(d);
    } catch (e) {
      toast('Error cargando detalle');
      setUserDetail(null);
    }
    setLoadingDetail(false);
  };

  const closeDetail = () => { setSelectedUser(null); setUserDetail(null); };

  const toggleBlock = async (id, currentStatus) => {
    const block = currentStatus !== 'blocked';
    try {
      await api.adminBlock(id, block);
      setUsers(u => u.map(x => x.id === id ? {...x, status: block ? 'blocked' : 'active'} : x));
      if (userDetail && userDetail.user.id === id) {
        setUserDetail(d => ({...d, user: {...d.user, status: block ? 'blocked' : 'active'}}));
      }
      toast(block ? 'Usuario bloqueado' : 'Usuario desbloqueado');
    } catch (e) { toast('Error: ' + (e.error || 'desconocido')); }
  };

  const giftPremium = async (id, months) => {
    try {
      await api.adminGift(id, months);
      setUsers(u => u.map(x => x.id === id ? {...x, plan: 'gifted'} : x));
      if (userDetail && userDetail.user.id === id) {
        setUserDetail(d => ({...d, user: {...d.user, plan: 'gifted', stripe_subscription_id: null}}));
      }
      toast(months === 0 ? 'Premium vitalicio regalado' : `Premium regalado (${months} ${months===1?'mes':'meses'})`);
      setShowGiftFor(null);
      setGiftMonths(1);
    } catch (e) { toast('Error: ' + (e.error || 'desconocido')); }
  };

  const doCreateUser = async () => {
    if (!newUser.email || !newUser.password || !newUser.name) { toast('Rellena email, contraseña y nombre'); return; }
    try {
      await api.adminCreateUser(newUser);
      toast('Usuario creado');
      setShowCreateUser(false);
      setNewUser({email:'',password:'',name:'',license:'PPL',plan:'free'});
      api.adminUsers(search).then(d => setUsers(d.users || [])).catch(() => {});
    } catch (e) { toast('Error: ' + (e.error || 'desconocido')); }
  };

  const doChangePass = async () => {
    if (!newPass || newPass.length < 8) { toast('Mínimo 8 caracteres'); return; }
    try {
      await api.adminChangePassword(showChangePass, newPass);
      toast('Contraseña cambiada');
      setShowChangePass(null);
      setNewPass('');
    } catch (e) { toast('Error: ' + (e.error || 'desconocido')); }
  };

  const saveIfrRoutes = (routes) => {
    setIfrRoutes(routes);
    // Persist to DOM script block + localStorage
    const el = document.getElementById('ifr-data');
    if (el) el.textContent = JSON.stringify(routes);
    try { localStorage.setItem('aeroplan_ifr_routes', JSON.stringify(routes)); } catch(e){}
  };

  const addOrUpdateRoute = () => {
    if (!routeForm.from || !routeForm.to || !routeForm.route) { toast('From, To y Ruta son obligatorios'); return; }
    let updated;
    if (editingRoute !== null) {
      updated = ifrRoutes.map((r, i) => i === editingRoute ? {...routeForm} : r);
    } else {
      updated = [...ifrRoutes, {...routeForm}];
    }
    saveIfrRoutes(updated);
    setEditingRoute(null);
    setRouteForm({from:'',to:'',rules:'Z',fl:'',route:'',dur:'',notes:''});
    toast(editingRoute !== null ? 'Ruta actualizada' : 'Ruta añadida');
  };

  const deleteRoute = (idx) => {
    saveIfrRoutes(ifrRoutes.filter((_, i) => i !== idx));
    toast('Ruta eliminada');
  };

  const editRoute = (idx) => {
    setEditingRoute(idx);
    setRouteForm({...ifrRoutes[idx]});
  };

  const revokePremium = async (id) => {
    try {
      await api.adminRevoke(id);
      setUsers(u => u.map(x => x.id === id ? {...x, plan: 'free', plan_until: null} : x));
      if (userDetail && userDetail.user.id === id) {
        setUserDetail(d => ({...d, user: {...d.user, plan: 'free', plan_until: null}}));
      }
      toast('Premium revocado');
    } catch (e) { toast('Error: ' + (e.error || 'desconocido')); }
  };

  const planBadge = (p) => {
    const labels = {admin: 'Admin', premium: 'Premium', gifted: 'Gifted', free: 'Free'};
    const accent = p === 'premium' || p === 'gifted' || p === 'admin';
    return <span className={`chip ${accent ? 'chip-accent' : ''}`}>{labels[p] || p}</span>;
  };

  const fmtDate = (ts) => {
    if (!ts) return '—';
    const d = new Date(ts * 1000);
    return d.toLocaleDateString('es', {day: '2-digit', month: 'short', year: 'numeric'}) + ' ' + d.toLocaleTimeString('es', {hour: '2-digit', minute: '2-digit'});
  };

  const fmtAgo = (ts) => {
    if (!ts) return 'nunca';
    const diff = Math.floor(Date.now() / 1000) - ts;
    if (diff < 60) return 'ahora';
    if (diff < 3600) return `hace ${Math.floor(diff / 60)} min`;
    if (diff < 86400) return `hace ${Math.floor(diff / 3600)}h`;
    return `hace ${Math.floor(diff / 86400)}d`;
  };

  const levelColor = (l) => l === 'error' ? 'var(--err)' : l === 'warn' ? 'var(--warn)' : 'var(--ok)';

  const TABS = [{id:'overview',l:t('admin.overview')},{id:'users',l:t('admin.users')},{id:'ifr',l:t('admin.ifr')},{id:'logs',l:t('admin.logs')},{id:'support',l:t('admin.support')}];

  return <div className="page fade-in">
    <section className="page-hero">
      <div className="page-hero-grid"/>
      <div className="page-hero-glow"/>
      <div className="page-hero-inner">
        <div className="chip chip-accent eyebrow"><Icon name="shield" size={12}/> {t('admin.panel')}</div>
        <h1 className="display">
          <span className="word-rise" style={{animationDelay:'0s'}}>{t('admin.title')}</span>{' '}
          <span className="word-rise underline-swash" style={{animationDelay:'.08s'}}>{t('admin.title2')}</span>{' '}
          <span className="word-rise" style={{animationDelay:'.16s'}}>{t('admin.title3')}</span>
        </h1>
        <p className="sub" style={{marginTop:14}}>{t('admin.subtitle')}</p>
      </div>
    </section>
    <div className="seg" style={{marginBottom:22}}>{TABS.map(t=><button key={t.id} className={tab===t.id?'active':''} onClick={()=>setTab(t.id)}>{t.l}</button>)}</div>

    {/* ===== INSTRUCTOR REQUESTS BANNER (all tabs) ===== */}
    {metrics && metrics.instructor_requests > 0 && <div className="card slide-up" style={{padding:'14px 20px',marginBottom:16,background:'var(--warn)',color:'#fff',borderRadius:12,display:'flex',alignItems:'center',gap:12,cursor:'pointer'}} onClick={()=>{setTab('users');setUserFilter('instructor');searchUsers('');}}>
      <Icon name="shield" size={18}/>
      <div style={{flex:1}}>
        <div style={{fontWeight:700,fontSize:14}}>{metrics.instructor_requests} solicitud{metrics.instructor_requests>1?'es':''} de instructor pendiente{metrics.instructor_requests>1?'s':''}</div>
        <div style={{fontSize:12,opacity:.85}}>Haz clic para revisar y asignar licencia</div>
      </div>
      <Icon name="chev_right" size={16}/>
    </div>}

    {/* ===== OVERVIEW ===== */}
    {tab==='overview' && metrics && <>
      <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit,minmax(180px,1fr))',gap:12,marginBottom:20}}>
        {[
          {k:'MRR',v:`${metrics.mrr_eur}€`,sub:metrics.paying_users?`${metrics.paying_users} suscriptores`:null},
          {k:'Usuarios',v:metrics.users_total},
          {k:'Premium',v:metrics.users_premium,sub:metrics.gifted_total?`${metrics.gifted_total} gifted (${metrics.gifted_lifetime} vitalicio${metrics.gifted_temp?`, ${metrics.gifted_temp} temporal`:''})`:null},
          {k:'Envíos OK',v:metrics.submissions_ok},
          {k:'Envíos Error',v:metrics.submissions_error},
          {k:'Bloqueados',v:metrics.users_blocked},
        ].map((m,i)=>(
          <div key={i} className="card slide-up" style={{padding:18,animationDelay:`${i*.04}s`}}>
            <div className="caption" style={{fontSize:11,textTransform:'uppercase',letterSpacing:'.1em',marginBottom:8}}>{m.k}</div>
            <div className="display" style={{fontSize:30,marginBottom:4}}>{m.v}</div>
            {m.sub && <div className="caption" style={{fontSize:10,marginTop:2}}>{m.sub}</div>}
          </div>
        ))}
      </div>
      {metrics.series && <div className="card" style={{padding:22}}>
        <h3 className="h3" style={{marginBottom:16}}>Envíos (14 días)</h3>
        <div style={{display:'flex',alignItems:'flex-end',gap:6,height:130}}>
          {metrics.series.map((s,i)=>{const max=Math.max(...metrics.series.map(x=>x.count),1);const h=(s.count/max)*100;return <div key={i} style={{flex:1,display:'flex',flexDirection:'column',alignItems:'center',gap:6}}>
            <div className="bar" style={{width:'70%',height:`${Math.max(h,2)}%`,transition:'height .5s'}}/>
            <div className="caption mono" style={{fontSize:9}}>{s.date.slice(5)}</div>
          </div>})}
        </div>
      </div>}
    </>}

    {/* User detail overlay — rendered at component level so it works from any tab */}
    {selectedUser && <div style={{position:'fixed',inset:0,background:'rgba(0,0,0,.4)',zIndex:100,display:'flex',justifyContent:'center',alignItems:'flex-start',paddingTop:60,overflowY:'auto'}} onClick={e=>{if(e.target===e.currentTarget) closeDetail();}}>
        <div className="card" style={{width:'100%',maxWidth:900,margin:'0 16px 40px',padding:0,overflow:'hidden',animation:'fadeSlideUp .2s ease'}}>
          {/* Header */}
          <div style={{padding:'20px 24px',borderBottom:'1px solid var(--stroke)',display:'flex',alignItems:'center',gap:14}}>
            <div style={{width:44,height:44,borderRadius:12,background:'var(--accent-soft)',color:'var(--accent)',display:'flex',alignItems:'center',justifyContent:'center',fontFamily:'var(--serif)',fontWeight:600,fontSize:18,border:'1px solid var(--stroke)'}}>
              {(userDetail?.user?.name || selectedUser.name || '?')[0]}
            </div>
            <div style={{flex:1}}>
              <div style={{fontSize:16,fontWeight:600,display:'flex',alignItems:'center',gap:8}}>
                {userDetail?.user?.name || selectedUser.name}
                {planBadge(userDetail?.user?.plan || selectedUser.plan)}
                {(userDetail?.user?.status || selectedUser.status) === 'blocked' && <span className="chip" style={{background:'var(--err)',color:'#fff',fontSize:10}}>Bloqueado</span>}
              </div>
              <div className="caption">{userDetail?.user?.email || selectedUser.email}{(userDetail?.user?.phone || selectedUser.phone) ? ` · ${userDetail?.user?.phone || selectedUser.phone}` : ''} · {userDetail?.user?.license || ''} · Registro {fmtDate(userDetail?.user?.created_at || selectedUser.created_at)}</div>
              {userDetail?.user && <div className="caption" style={{fontSize:10,marginTop:2}}>
                {userDetail.user.plan === 'premium' && userDetail.user.stripe_subscription_id && <span style={{color:'var(--ok)'}}>Stripe activo</span>}
                {userDetail.user.plan === 'premium' && !userDetail.user.stripe_subscription_id && <span style={{color:'var(--warn)'}}>Premium (sin Stripe)</span>}
                {userDetail.user.plan === 'gifted' && userDetail.user.plan_until && <span style={{color:'var(--accent)'}}>Gift hasta {fmtDate(userDetail.user.plan_until)}</span>}
                {userDetail.user.plan === 'gifted' && !userDetail.user.plan_until && <span style={{color:'var(--accent)'}}>Gift vitalicio ♾</span>}
                {userDetail.user.plan_until && userDetail.user.plan === 'premium' && <span> · Renueva {fmtDate(userDetail.user.plan_until)}</span>}
              </div>}
            </div>
            <button className="btn btn-ghost btn-icon" onClick={closeDetail}><Icon name="close" size={16}/></button>
          </div>

          {/* Actions bar */}
          {userDetail && <div style={{padding:'12px 24px',borderBottom:'1px solid var(--stroke)',display:'flex',gap:8,flexWrap:'wrap'}}>
            <button className="btn btn-sm" style={{color: userDetail.user.status === 'blocked' ? 'var(--ok)' : 'var(--err)', border: '1px solid var(--stroke)', borderRadius: 8, padding: '6px 14px'}} onClick={() => toggleBlock(userDetail.user.id, userDetail.user.status)}>
              <Icon name={userDetail.user.status === 'blocked' ? 'check' : 'ban'} size={13}/>
              {userDetail.user.status === 'blocked' ? ' Desbloquear' : ' Bloquear'}
            </button>
            {(userDetail.user.plan === 'free' || userDetail.user.plan === 'premium') && <button className="btn btn-sm" style={{color:'var(--accent)',border:'1px solid var(--stroke)',borderRadius:8,padding:'6px 14px'}} onClick={()=>{setShowGiftFor(userDetail.user.id);setGiftMonths(1);}}>
              <Icon name="gift" size={13}/> Regalar Premium
            </button>}
            {(userDetail.user.plan === 'premium' || userDetail.user.plan === 'gifted') && <button className="btn btn-sm" style={{color:'var(--warn)',border:'1px solid var(--stroke)',borderRadius:8,padding:'6px 14px'}} onClick={()=>revokePremium(userDetail.user.id)}>
              <Icon name="ban" size={13}/> Quitar Premium
            </button>}
            {userDetail.user.stripe_subscription_id && <button className="btn btn-sm" style={{color:'var(--err)',border:'1px solid var(--stroke)',borderRadius:8,padding:'6px 14px'}} onClick={async()=>{
              const ok = await confirm('¿Cancelar la suscripción Stripe de este usuario? Mantendrá acceso hasta el fin del periodo actual.', {title:'Cancelar suscripción',yes:'Cancelar sub',no:'Volver'});
              if (!ok) return;
              try {
                await api.adminCancelSub(userDetail.user.id);
                toast('Suscripción cancelada');
                openUserDetail({id:userDetail.user.id});
              } catch(err) { toast('Error: '+(err.error||'desconocido')); }
            }}>
              <Icon name="close" size={13}/> Cancelar Stripe
            </button>}
            <button className="btn btn-sm" style={{color:'var(--ink)',border:'1px solid var(--stroke)',borderRadius:8,padding:'6px 14px'}} onClick={()=>{setShowChangePass(userDetail.user.id);setNewPass('');}}>
              <Icon name="lock" size={13}/> Cambiar contraseña
            </button>
            {userDetail.user.role !== 'admin' && <button className="btn btn-sm" style={{color:'var(--err)',border:'1px solid var(--err)',borderRadius:8,padding:'6px 14px',marginLeft:'auto'}} onClick={async()=>{
              const ok = await confirm(`¿Eliminar a ${userDetail.user.name} (${userDetail.user.email})? Se borrarán todos sus datos: planes, envíos, aeronaves y tickets.`, {title:'Eliminar usuario',yes:'Eliminar',no:'Cancelar'});
              if (!ok) return;
              try {
                await api.adminDeleteUser(userDetail.user.id);
                toast('Usuario eliminado');
                closeDetail();
                api.adminUsers(search).then(d=>setUsers(d.users||[])).catch(()=>{});
                api.adminMetrics().then(d=>setMetrics(d)).catch(()=>{});
              } catch(err) { toast('Error: ' + (err.error || 'desconocido')); }
            }}>
              <Icon name="close" size={13}/> Eliminar
            </button>}
          </div>}

          {/* License selector — dedicated row */}
          {userDetail && <div style={{padding:'10px 24px',borderBottom:'1px solid var(--stroke)',display:'flex',alignItems:'center',gap:12,background: userDetail.user.license==='INSTRUCTOR_PENDING' ? 'color-mix(in srgb, var(--warn) 10%, transparent)' : 'transparent'}}>
            <Icon name="shield" size={14} style={{color: userDetail.user.license==='INSTRUCTOR_PENDING' ? 'var(--warn)' : 'var(--ink-dim)'}}/>
            <span style={{fontWeight:600,fontSize:13}}>Licencia:</span>
            {userDetail.user.license==='INSTRUCTOR_PENDING' && <span className="chip" style={{background:'var(--warn)',color:'#fff',fontSize:10}}>Solicitud pendiente</span>}
            <select className="field" value={userDetail.user.license||''} onChange={async e=>{
              const lic = e.target.value;
              try {
                await api.adminUpdateLicense(userDetail.user.id, lic);
                setUserDetail(d=>({...d,user:{...d.user,license:lic}}));
                setUsers(u=>u.map(x=>x.id===userDetail.user.id?{...x,license:lic}:x));
                api.adminMetrics().then(d=>setMetrics(d)).catch(()=>{});
                toast('Licencia actualizada: ' + (lic||'Estudiante'));
              } catch(err) { toast('Error: ' + (err.error || err.detail || 'desconocido')); }
            }} style={{padding:'6px 14px',fontSize:13,height:36,minWidth:140,borderRadius:8,fontWeight:600,border: userDetail.user.license==='INSTRUCTOR_PENDING' ? '2px solid var(--warn)' : '1px solid var(--stroke)'}}>
              <option value="">Estudiante</option>
              <option value="PPL">PPL</option>
              <option value="CPL">CPL</option>
              <option value="ATPL">ATPL</option>
              <option value="LAPL">LAPL</option>
              <option value="INSTRUCTOR">Instructor</option>
              {userDetail.user.license==='INSTRUCTOR_PENDING' && <option value="INSTRUCTOR_PENDING">⏳ Pendiente instructor</option>}
            </select>
          </div>}

          {/* Stats row */}
          {userDetail && <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit,minmax(100px,1fr))',gap:0,borderBottom:'1px solid var(--stroke)'}}>
            {[
              {k:'Planes',v:userDetail.stats.total_plans},
              {k:'Envíos OK',v:userDetail.stats.ok_submissions},
              {k:'Errores',v:userDetail.stats.error_submissions},
              {k:'Aeronaves',v:userDetail.stats.total_aircraft},
              {k:'Último login',v:fmtAgo(userDetail.user.last_login_at)},
            ].map((s,i)=><div key={i} style={{padding:'12px 16px',borderRight:i<4?'1px solid var(--stroke)':'none',textAlign:'center'}}>
              <div className="caption" style={{fontSize:10,marginBottom:4}}>{s.k}</div>
              <div style={{fontWeight:600,fontSize:15}}>{s.v}</div>
            </div>)}
          </div>}

          {/* Detail tabs */}
          {userDetail && <>
            <div className="seg" style={{margin:'12px 24px 0'}}>
              {[{id:'activity',l:'Envíos'},{id:'plans',l:'Planes'},{id:'logs',l:'Logs'},{id:'aircraft',l:'Aeronaves'},{id:'tickets',l:'Soporte'}].map(tb=>
                <button key={tb.id} className={detailTab===tb.id?'active':''} onClick={()=>setDetailTab(tb.id)}>{tb.l}</button>
              )}
            </div>
            <div style={{maxHeight:500,overflowY:'auto',padding:'0'}}>
              {/* Submissions */}
              {detailTab==='activity' && <div style={{fontFamily:'var(--mono)',fontSize:12}}>
                {userDetail.submissions.length === 0 && <div style={{padding:20,textAlign:'center',color:'var(--ink-dim)'}}>Sin envíos</div>}
                {userDetail.submissions.map((s,i)=>{
                  const isOpen = expandedSub === s.id;
                  let reqFields = null;
                  try { reqFields = JSON.parse(s.request_json || '{}'); } catch(e){}
                  return <div key={s.id} style={{borderBottom:i<userDetail.submissions.length-1?'1px solid var(--stroke)':'none'}}>
                    <div style={{padding:'10px 24px',display:'grid',gridTemplateColumns:'1fr 90px 60px 20px',gap:10,alignItems:'center',cursor:'pointer'}} onClick={()=>setExpandedSub(isOpen?null:s.id)}>
                      <div>
                        <span style={{fontWeight:600}}>{s.plan_name || s.op}</span>
                        {s.adep && s.ades && <span style={{color:'var(--ink-dim)',marginLeft:8}}>{s.adep} → {s.ades}</span>}
                        {s.icaro_ref && <span style={{color:'var(--accent)',marginLeft:8}}>{s.icaro_ref}</span>}
                        {s.error_message && <span style={{color:'var(--err)',marginLeft:8}}>{s.error_message}</span>}
                      </div>
                      <span style={{color:'var(--ink-low)',fontSize:11}}>{fmtDate(s.created_at)}</span>
                      <span className="chip" style={{fontSize:9,justifySelf:'end',color:s.status==='ok'?'var(--ok)':'var(--err)'}}>{s.status.toUpperCase()}</span>
                      <Icon name="chev_right" size={12} style={{color:'var(--ink-low)',transition:'transform .2s',transform:isOpen?'rotate(90deg)':'none'}}/>
                    </div>
                    {isOpen && (() => {
                      const vm = subViewMode[s.id] || 'summary';
                      const setVm = (m) => setSubViewMode(prev => ({...prev, [s.id]: m}));
                      // Extract friendly fields from request_json
                      const r = reqFields || {};
                      const adep = r['data.departureAerodrome'] || s.adep || '';
                      const ades = r['data.destinationAerodrome'] || s.ades || '';
                      const arcid = r['data.flightId'] || '';
                      const rules = r['data.flightRules'] || '';
                      const ftype = r['data.flightType'] || '';
                      const dia = r['dateOfFlight.dia']||''; const mes = r['dateOfFlight.mes']||''; const anio = r['dateOfFlight.anio']||'';
                      const flightDate = dia && mes ? (dia.toString().padStart(2,'0')+'/'+mes.toString().padStart(2,'0')+(anio?'/'+anio:'')) : '';
                      const eobtH = r['eobtTime.hora']||''; const eobtM = r['eobtTime.minutos']||'';
                      const eobt = eobtH ? (eobtH+':'+(eobtM||'00')) : '';
                      const acType = r['data.aircraftName'] || '';
                      const wake = r['data.wakeTurbulenceCategory'] || '';
                      const reg = r['data.aircraftRegistrationMarkings'] || '';
                      const comEq = r['data.aidEquipment'] || '';
                      const ssr = r['ssrData'] || '';
                      const speed = r['data.crusingSpeed'] || '';
                      const fl = r['data.crusingLevel'] || '';
                      const route = r['data.route'] || '';
                      const eetH = r['estimatedElapsedTime.hora']||''; const eetM = r['estimatedElapsedTime.minutos']||'';
                      const eet = eetH ? (eetH+':'+(eetM||'00')) : '';
                      const altn = r['data.alternateAerodrome1'] || '';
                      const altn2 = r['data.alternateAerodrome2'] || '';
                      const endH = r['fp19.endurance.hora']||''; const endM = r['fp19.endurance.minutos']||'';
                      const endurance = endH ? (endH+':'+(endM||'00')) : '';
                      const pob = r['fp19.personsOnBoard'] || '';
                      const pic = r['fp19.pilot'] || '';
                      const colors = r['fp19.aircraftColourAndMarkings'] || '';
                      const eRadio = r['fp19.radio'] || '';
                      const survival = r['fp19.survivalEquipment'] || '';
                      const jackets = r['fp19.lifeJackets'] || '';
                      const rmk = r['data.remarks'] || '';
                      const opr = r['data.operator'] || '';
                      const RULES_MAP = {I:'IFR',V:'VFR',Y:'VFR→IFR',Z:'IFR→VFR'};
                      const FTYPE_MAP = {S:'Regular',N:'No regular',G:'Aviacion general',M:'Militar',X:'Otros'};
                      const kv = (k,v) => v ? <div style={{display:'flex',justifyContent:'space-between',gap:8,padding:'3px 0'}}><span style={{color:'var(--ink-dim)',fontSize:11,flexShrink:0}}>{k}</span><span style={{fontWeight:500,fontSize:12,textAlign:'right',wordBreak:'break-word'}}>{v}</span></div> : null;
                      const secHead = (t) => <div style={{fontSize:10,fontWeight:700,letterSpacing:'.08em',textTransform:'uppercase',color:'var(--ink-dim)',marginBottom:4,marginTop:10}}>{t}</div>;

                      return <div style={{padding:'0 24px 16px'}}>
                        <div style={{display:'flex',gap:8,marginBottom:10,flexWrap:'wrap',fontSize:11,alignItems:'center'}}>
                          <span style={{color:'var(--ink-dim)'}}>ID: {s.id}</span>
                          <span style={{color:'var(--ink-dim)'}}>Duracion: {s.duration_ms}ms</span>
                          <span style={{color:'var(--ink-dim)'}}>Op: {s.op}</span>
                          <span style={{flex:1}}/>
                          <div className="seg" style={{margin:0,fontSize:10}}>
                            <button className={vm==='summary'?'active':''} onClick={()=>setVm('summary')}>Resumen</button>
                            <button className={vm==='post'?'active':''} onClick={()=>setVm('post')}>POST ENAIRE</button>
                          </div>
                        </div>

                        {vm === 'summary' && reqFields && <>
                          {/* Route header */}
                          <div style={{display:'flex',alignItems:'center',justifyContent:'center',gap:14,marginBottom:8,padding:'10px 0'}}>
                            <span style={{fontSize:20,fontWeight:700,letterSpacing:'.04em'}}>{adep}</span>
                            <span style={{color:'var(--ink-low)',fontSize:16}}>→</span>
                            <span style={{fontSize:20,fontWeight:700,letterSpacing:'.04em'}}>{ades}</span>
                          </div>
                          <div style={{display:'flex',gap:6,justifyContent:'center',marginBottom:12,flexWrap:'wrap'}}>
                            {rules && <span className="chip chip-accent">{RULES_MAP[rules]||rules}</span>}
                            {fl && <span className="chip">{fl}</span>}
                            {acType && <span className="chip mono">{acType}</span>}
                            {eet && <span className="chip">{eet}</span>}
                            {flightDate && <span className="chip mono">{flightDate}</span>}
                          </div>

                          <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit,minmax(200px,1fr))',gap:10}}>
                            {/* Identificacion */}
                            <div style={{background:'var(--bg-inset)',borderRadius:8,padding:12,border:'1px solid var(--stroke)'}}>
                              {secHead('Identificacion')}
                              {kv('ARCID', arcid)}
                              {kv('Reglas', RULES_MAP[rules]||rules)}
                              {kv('Tipo vuelo', FTYPE_MAP[ftype]||ftype)}
                              {kv('Fecha', flightDate)}
                            </div>
                            {/* Aeronave */}
                            <div style={{background:'var(--bg-inset)',borderRadius:8,padding:12,border:'1px solid var(--stroke)'}}>
                              {secHead('Aeronave')}
                              {kv('Tipo', acType)}
                              {kv('Estela', wake)}
                              {kv('REG', reg)}
                              {kv('Equipo COM', comEq)}
                              {kv('SSR', ssr)}
                            </div>
                            {/* Ruta */}
                            <div style={{background:'var(--bg-inset)',borderRadius:8,padding:12,border:'1px solid var(--stroke)'}}>
                              {secHead('Ruta')}
                              {kv('EOBT', eobt ? eobt+'Z' : '')}
                              {kv('Velocidad', speed)}
                              {kv('Nivel', fl)}
                              {kv('Ruta', route)}
                              {kv('EET', eet)}
                              {kv('ALTN', altn)}
                              {kv('ALTN2', altn2)}
                            </div>
                            {/* Suplementario */}
                            {(endurance || pob || pic || colors || eRadio || survival) && <div style={{background:'var(--bg-inset)',borderRadius:8,padding:12,border:'1px solid var(--stroke)'}}>
                              {secHead('Suplementario')}
                              {kv('Autonomia', endurance)}
                              {kv('POB', pob)}
                              {kv('PIC', pic)}
                              {kv('Color/Marcas', colors)}
                              {kv('Radio emergencia', eRadio)}
                              {kv('Supervivencia', survival)}
                              {kv('Chalecos', jackets)}
                            </div>}
                            {/* Observaciones */}
                            {(rmk || opr) && <div style={{background:'var(--bg-inset)',borderRadius:8,padding:12,border:'1px solid var(--stroke)'}}>
                              {secHead('Observaciones')}
                              {kv('RMK', rmk)}
                              {kv('OPR', opr)}
                            </div>}
                          </div>
                        </>}
                        {vm === 'summary' && !reqFields && <div style={{color:'var(--ink-low)',fontSize:11,padding:12}}>Sin datos de peticion</div>}

                        {vm === 'post' && <>
                          <div style={{marginBottom:10}}>
                            <div style={{fontSize:11,fontWeight:600,color:'var(--accent)',marginBottom:6,textTransform:'uppercase',letterSpacing:'.08em'}}>Peticion POST enviada a ENAIRE</div>
                            {reqFields && <div style={{background:'var(--bg-inset)',borderRadius:8,padding:12,maxHeight:300,overflowY:'auto',border:'1px solid var(--stroke)'}}>
                              {Object.entries(reqFields).filter(([k,v])=>v).sort(([a],[b])=>a.localeCompare(b)).map(([k,v])=>
                                <div key={k} style={{display:'flex',justifyContent:'space-between',gap:10,padding:'3px 0',borderBottom:'1px solid color-mix(in srgb, var(--stroke) 50%, transparent)'}}>
                                  <span style={{color:'var(--ink-dim)',flexShrink:0}}>{k}</span>
                                  <span style={{fontWeight:500,textAlign:'right',wordBreak:'break-word'}}>{v}</span>
                                </div>
                              )}
                            </div>}
                            {!reqFields && <div style={{color:'var(--ink-low)',fontSize:11}}>Sin datos de peticion</div>}
                          </div>
                        </>}

                        {/* Respuesta ENAIRE */}
                        {s.response_json && <details style={{marginTop:10,marginBottom:6}}>
                          <summary style={{fontSize:11,fontWeight:600,color:'var(--ink-dim)',cursor:'pointer',marginBottom:6}}>Respuesta ENAIRE (HTML)</summary>
                          <pre style={{background:'var(--bg-inset)',borderRadius:8,padding:10,maxHeight:200,overflowY:'auto',fontSize:10,whiteSpace:'pre-wrap',wordBreak:'break-word',border:'1px solid var(--stroke)'}}>{(() => {
                            try { const r2 = JSON.parse(s.response_json); return r2.raw || JSON.stringify(r2, null, 2); } catch(e) { return s.response_json; }
                          })()}</pre>
                        </details>}
                      </div>;
                    })()}
                  </div>;
                })}
              </div>}

              {/* Plans */}
              {detailTab==='plans' && <div style={{fontFamily:'var(--mono)',fontSize:12}}>
                {userDetail.plans.length === 0 && <div style={{padding:20,textAlign:'center',color:'var(--ink-dim)'}}>Sin planes</div>}
                {userDetail.plans.map((p,i)=><div key={p.id} style={{padding:'10px 24px',borderBottom:i<userDetail.plans.length-1?'1px solid var(--stroke)':'none',display:'flex',alignItems:'center',gap:12}}>
                  {p.favorite ? <Icon name="star" size={13} style={{color:'var(--accent)',fill:'var(--accent)'}}/> : <span style={{width:13}}/>}
                  <div style={{flex:1}}>
                    <span style={{fontWeight:600}}>{p.name}</span>
                    <span style={{color:'var(--ink-dim)',marginLeft:10}}>{p.adep} → {p.ades}</span>
                    <span style={{color:'var(--ink-low)',marginLeft:10}}>{p.flight_rules} · {p.aircraft_type}</span>
                  </div>
                  <span style={{color:'var(--ink-low)',fontSize:11}}>{fmtDate(p.updated_at)}</span>
                </div>)}
              </div>}

              {/* Logs */}
              {detailTab==='logs' && <div style={{fontFamily:'var(--mono)',fontSize:12}}>
                {userDetail.logs.length === 0 && <div style={{padding:20,textAlign:'center',color:'var(--ink-dim)'}}>Sin logs</div>}
                {userDetail.logs.map((l,i)=><div key={l.id} style={{padding:'10px 24px',borderBottom:i<userDetail.logs.length-1?'1px solid var(--stroke)':'none',display:'grid',gridTemplateColumns:'1fr 90px 50px',gap:10,alignItems:'center'}}>
                  <div>
                    <span style={{fontWeight:600,color:levelColor(l.level)}}>{l.event}</span>
                    {l.message && <span style={{color:'var(--ink-dim)',marginLeft:8}}>{l.message}</span>}
                    {l.ip && <span style={{color:'var(--ink-low)',marginLeft:8}}>{l.ip}</span>}
                  </div>
                  <span style={{color:'var(--ink-low)',fontSize:11}}>{fmtDate(l.created_at)}</span>
                  <span className="chip" style={{fontSize:9,justifySelf:'end',color:levelColor(l.level)}}>{l.level.toUpperCase()}</span>
                </div>)}
              </div>}

              {/* Aircraft */}
              {detailTab==='aircraft' && <div style={{fontFamily:'var(--mono)',fontSize:12}}>
                {userDetail.aircraft.length === 0 && <div style={{padding:20,textAlign:'center',color:'var(--ink-dim)'}}>Sin aeronaves</div>}
                {userDetail.aircraft.map((a,i)=><div key={a.id} style={{padding:'10px 24px',borderBottom:i<userDetail.aircraft.length-1?'1px solid var(--stroke)':'none',display:'flex',alignItems:'center',gap:12}}>
                  <Icon name="plane" size={14} style={{color:'var(--accent)'}}/>
                  <span style={{fontWeight:600}}>{a.registration}</span>
                  <span style={{color:'var(--ink-dim)'}}>{a.type}</span>
                  <span style={{color:'var(--ink-low)'}}>Estela {a.wake}</span>
                  {a.is_default ? <span className="chip chip-accent" style={{fontSize:9}}>Default</span> : null}
                </div>)}
              </div>}

              {/* User tickets */}
              {detailTab==='tickets' && <div style={{fontSize:13}}>
                {(!userDetail.tickets || userDetail.tickets.length === 0) && <div style={{padding:20,textAlign:'center',color:'var(--ink-dim)'}}>Sin tickets de soporte</div>}
                {(userDetail.tickets || []).map((tk,i)=><div key={tk.id} style={{padding:'14px 24px',borderBottom:i<(userDetail.tickets||[]).length-1?'1px solid var(--stroke)':'none'}}>
                  <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:6}}>
                    <span className={`chip ${tk.status==='open'?'chip-accent':tk.status==='replied'?'':'chip'}`} style={{fontSize:10}}>
                      {tk.status === 'open' ? 'Abierto' : tk.status === 'replied' ? 'Respondido' : 'Cerrado'}
                    </span>
                    <span className="caption" style={{fontSize:11}}>{fmtDate(tk.created_at)}</span>
                  </div>
                  <div style={{padding:10,background:'var(--bg-inset)',borderRadius:8,marginBottom:6,lineHeight:1.5,whiteSpace:'pre-wrap',wordBreak:'break-word'}}>{tk.message}</div>
                  {tk.admin_reply && <div style={{padding:10,background:'var(--accent-soft)',borderRadius:8,lineHeight:1.5,whiteSpace:'pre-wrap',wordBreak:'break-word',fontSize:12}}>
                    <span style={{fontWeight:600,color:'var(--accent)',marginRight:6}}>Admin:</span>{tk.admin_reply}
                  </div>}
                </div>)}
              </div>}
            </div>
          </>}

          {loadingDetail && <div style={{padding:40,textAlign:'center',color:'var(--ink-dim)'}}>Cargando...</div>}
        </div>
      </div>}

    {/* ===== USERS ===== */}
    {tab==='users' && (() => {
      const filtered = users.filter(u => {
        if (userFilter === 'all') return true;
        if (userFilter === 'premium') return u.plan === 'premium';
        if (userFilter === 'gifted') return u.plan === 'gifted';
        if (userFilter === 'free') return u.plan === 'free';
        if (userFilter === 'blocked') return u.status === 'blocked';
        if (userFilter === 'instructor') return u.license === 'INSTRUCTOR_PENDING';
        return true;
      });
      return <>
      {/* User list */}
      <div className="card" style={{padding:0,overflow:'hidden'}}>
        <div style={{padding:'16px 20px',display:'flex',justifyContent:'space-between',alignItems:'center',borderBottom:'1px solid var(--stroke)',gap:12,flexWrap:'wrap'}}>
          <div>
            <h3 className="h3">Usuarios ({filtered.length}{userFilter!=='all'?` / ${users.length}`:''})</h3>
            <div className="caption">{users.filter(u=>u.status==='active').length} activos · {users.filter(u=>u.plan==='premium'||u.plan==='gifted').length} premium · {users.filter(u=>u.status==='blocked').length} bloqueados</div>
          </div>
          <div style={{display:'flex',gap:10,alignItems:'center',flexWrap:'wrap'}}>
            <div style={{position:'relative',minWidth:200}}>
              <Icon name="search" size={14} style={{position:'absolute',left:10,top:'50%',transform:'translateY(-50%)',color:'var(--ink-low)'}}/>
              <input className="field" value={search} onChange={e=>searchUsers(e.target.value)} placeholder="Buscar…" style={{paddingLeft:32,height:36,fontSize:13}}/>
            </div>
            <button className="btn btn-primary btn-sm" style={{borderRadius:8,padding:'6px 14px'}} onClick={()=>setShowCreateUser(true)}>
              <Icon name="plus" size={13}/> Crear usuario
            </button>
          </div>
        </div>
        {/* Filter bar */}
        <div style={{padding:'10px 20px',borderBottom:'1px solid var(--stroke)',display:'flex',gap:6,flexWrap:'wrap'}}>
          {[
            {id:'all',l:'Todos',count:users.length},
            {id:'free',l:'Free',count:users.filter(u=>u.plan==='free').length},
            {id:'premium',l:'Premium',count:users.filter(u=>u.plan==='premium').length},
            {id:'gifted',l:'Gifted',count:users.filter(u=>u.plan==='gifted').length},
            {id:'blocked',l:'Bloqueados',count:users.filter(u=>u.status==='blocked').length},
            {id:'instructor',l:'📋 Pendientes',count:users.filter(u=>u.license==='INSTRUCTOR_PENDING').length},
          ].filter(f=>f.id==='all'||f.count>0).map(f=><button key={f.id} className={`btn btn-sm ${userFilter===f.id?'btn-primary':''}`} style={{borderRadius:8,padding:'4px 12px',fontSize:11,border:'1px solid var(--stroke)'}} onClick={()=>setUserFilter(f.id)}>{f.l} ({f.count})</button>)}
        </div>
        <div>
          {filtered.map((u,i)=><div key={u.id} style={{padding:'14px 20px',borderBottom:i<filtered.length-1?'1px solid var(--stroke)':'none',display:'flex',alignItems:'center',gap:12,opacity:u.status==='blocked'?.5:1,flexWrap:'wrap',cursor:'pointer',transition:'background .15s'}}
            onClick={()=>openUserDetail(u)}
            onMouseEnter={e=>e.currentTarget.style.background='var(--bg-inset)'}
            onMouseLeave={e=>e.currentTarget.style.background=''}
          >
            <div style={{width:34,height:34,borderRadius:10,background:'var(--accent-soft)',color:'var(--accent)',display:'flex',alignItems:'center',justifyContent:'center',fontFamily:'var(--serif)',fontWeight:500,flexShrink:0,border:'1px solid var(--stroke)'}}>{u.name[0]}</div>
            <div style={{flex:'1 1 180px',minWidth:0}}>
              <div style={{fontSize:14,fontWeight:600,display:'flex',alignItems:'center',gap:6}}>{u.name}</div>
              <div className="caption" style={{fontSize:11,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{u.email}{u.phone ? ` · ${u.phone}` : ''} · {u.license || '—'} · {fmtAgo(u.last_login_at)}</div>
            </div>
            {planBadge(u.plan)}
            {u.license === 'INSTRUCTOR_PENDING' && <span className="chip" style={{background:'var(--warn)',color:'#fff',fontSize:9}}>Instructor pendiente</span>}
            {u.status === 'blocked' && <span className="chip" style={{background:'var(--err)',color:'#fff',fontSize:9}}>Bloqueado</span>}
            <div style={{display:'flex',gap:4}} onClick={e=>e.stopPropagation()}>
              {u.plan === 'free' && <button className="btn btn-subtle btn-icon" title="Regalar Premium" onClick={()=>{setShowGiftFor(u.id);setGiftMonths(1);}}><Icon name="gift" size={13}/></button>}
              {(u.plan === 'premium' || u.plan === 'gifted') && <button className="btn btn-subtle btn-icon" title="Quitar Premium" style={{color:'var(--warn)'}} onClick={()=>revokePremium(u.id)}><Icon name="ban" size={13}/></button>}
              {u.role !== 'admin' && <button className="btn btn-subtle btn-icon" style={{color:u.status==='blocked'?'var(--ok)':'var(--err)'}} title={u.status==='blocked'?'Desbloquear':'Bloquear'} onClick={()=>toggleBlock(u.id, u.status)}>
                <Icon name={u.status==='blocked'?'check':'ban'} size={13}/>
              </button>}
            </div>
          </div>)}
        </div>
      </div>
    </>;
    })()}

    {/* ===== IFR ROUTES ===== */}
    {tab==='ifr' && <>
      <div className="card" style={{padding:24,marginBottom:16}}>
        <h3 className="h3" style={{marginBottom:16}}>{editingRoute !== null ? 'Editar ruta' : 'Añadir ruta IFR'}</h3>
        <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit,minmax(140px,1fr))',gap:10,marginBottom:14}}>
          <div><label className="label">Origen (ICAO)</label><input className="field" value={routeForm.from} onChange={e=>setRouteForm(f=>({...f,from:e.target.value.toUpperCase()}))} placeholder="LELL" maxLength={4}/></div>
          <div><label className="label">Destino (ICAO)</label><input className="field" value={routeForm.to} onChange={e=>setRouteForm(f=>({...f,to:e.target.value.toUpperCase()}))} placeholder="LEIB" maxLength={4}/></div>
          <div><label className="label">Reglas</label>
            <select className="field" value={routeForm.rules} onChange={e=>setRouteForm(f=>({...f,rules:e.target.value}))}>
              <option value="I">I - IFR</option><option value="Z">Z - IFR/VFR</option><option value="Y">Y - VFR/IFR</option>
            </select>
          </div>
          <div><label className="label">FL</label><input className="field" value={routeForm.fl} onChange={e=>setRouteForm(f=>({...f,fl:e.target.value.toUpperCase()}))} placeholder="F090"/></div>
          <div><label className="label">Duracion</label><input className="field" value={routeForm.dur} onChange={e=>setRouteForm(f=>({...f,dur:e.target.value}))} placeholder="01:30"/></div>
        </div>
        <div style={{marginBottom:14}}>
          <label className="label">Ruta</label>
          <input className="field" value={routeForm.route} onChange={e=>setRouteForm(f=>({...f,route:e.target.value.toUpperCase()}))} placeholder="OKABI T10 BCN"/>
        </div>
        <div style={{marginBottom:14}}>
          <label className="label">Notas</label>
          <input className="field" value={routeForm.notes} onChange={e=>setRouteForm(f=>({...f,notes:e.target.value}))} placeholder="Opcional"/>
        </div>
        <div style={{display:'flex',gap:8}}>
          <button className="btn btn-primary" onClick={addOrUpdateRoute}>{editingRoute !== null ? 'Guardar cambios' : 'Añadir ruta'}</button>
          {editingRoute !== null && <button className="btn btn-ghost" onClick={()=>{setEditingRoute(null);setRouteForm({from:'',to:'',rules:'Z',fl:'',route:'',dur:'',notes:''});}}>Cancelar</button>}
        </div>
      </div>
      <div className="card" style={{padding:0,overflow:'hidden'}}>
        <div style={{padding:'16px 20px',borderBottom:'1px solid var(--stroke)'}}>
          <h3 className="h3">Rutas IFR ({ifrRoutes.length})</h3>
        </div>
        <div style={{fontFamily:'var(--mono)',fontSize:12}}>
          {ifrRoutes.length === 0 && <div style={{padding:20,textAlign:'center',color:'var(--ink-dim)'}}>Sin rutas</div>}
          {ifrRoutes.map((r,i)=><div key={i} style={{padding:'12px 20px',borderBottom:i<ifrRoutes.length-1?'1px solid var(--stroke)':'none',display:'flex',alignItems:'center',gap:12,flexWrap:'wrap'}}>
            <span style={{fontWeight:700,minWidth:100}}>{r.from} - {r.to}</span>
            <span className="chip">{r.rules}</span>
            <span className="chip">{r.fl}</span>
            <span style={{flex:1,color:'var(--ink-dim)',fontSize:11,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{r.route}</span>
            <span style={{color:'var(--ink-low)',fontSize:11}}>{r.dur}</span>
            <div style={{display:'flex',gap:4}}>
              <button className="btn btn-subtle btn-icon" title="Editar" onClick={()=>editRoute(i)}><Icon name="edit" size={13}/></button>
              <button className="btn btn-subtle btn-icon" title="Eliminar" style={{color:'var(--err)'}} onClick={()=>deleteRoute(i)}><Icon name="close" size={13}/></button>
            </div>
          </div>)}
        </div>
      </div>
    </>}

    {/* ===== LOGS ===== */}
    {tab==='logs' && <div className="card" style={{padding:0,overflow:'hidden'}}>
      <div style={{padding:'16px 20px',borderBottom:'1px solid var(--stroke)',display:'flex',justifyContent:'space-between',alignItems:'center',flexWrap:'wrap',gap:10}}>
        <div><h3 className="h3">Actividad</h3><div className="caption">{logs.length} registros</div></div>
        <div className="seg" style={{margin:0}}>
          {['','info','warn','error'].map(l=><button key={l} className={logLevel===l?'active':''} onClick={()=>setLogLevel(l)}>{l?l.toUpperCase():'TODO'}</button>)}
        </div>
      </div>
      <div style={{fontFamily:'var(--mono)',fontSize:12,maxHeight:600,overflowY:'auto'}}>
        {logs.map((l,i)=><div key={l.id} style={{padding:'10px 20px',borderBottom:i<logs.length-1?'1px solid var(--stroke)':'none',display:'grid',gridTemplateColumns:'90px 1fr 50px',gap:10,alignItems:'center'}}>
          <span style={{color:'var(--ink-low)',fontSize:11}}>{fmtDate(l.created_at)}</span>
          <span>
            <span style={{fontWeight:600,color:levelColor(l.level)}}>{l.event}</span>
            {l.message && <span style={{color:'var(--ink-dim)',marginLeft:8}}>{l.message}</span>}
            {l.ip && <span style={{color:'var(--ink-low)',marginLeft:8}}>{l.ip}</span>}
          </span>
          <span className="chip" style={{fontSize:9,justifySelf:'end',color:levelColor(l.level)}}>{l.level.toUpperCase()}</span>
        </div>)}
        {logs.length === 0 && <div style={{padding:20,textAlign:'center',color:'var(--ink-dim)'}}>Sin logs</div>}
      </div>
    </div>}

    {/* ===== SUPPORT ===== */}
    {tab==='support' && (() => {
      const openTk = tickets.filter(x => x.status !== 'closed');
      const closedTk = tickets.filter(x => x.status === 'closed');
      return <>
        <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:14,flexWrap:'wrap',gap:10}}>
          <h3 className="h3">{t('admin.support')}</h3>
          <div className="seg" style={{margin:0}}>
            <button className={supportFilter==='open'?'active':''} onClick={()=>setSupportFilter('open')}>Abiertos ({openTk.length})</button>
            <button className={supportFilter==='closed'?'active':''} onClick={()=>setSupportFilter('closed')}>Cerrados ({closedTk.length})</button>
          </div>
        </div>

        {supportFilter==='open' && <>
          {openTk.length === 0 && <div className="card" style={{padding:30,textAlign:'center',color:'var(--ink-dim)'}}>Sin tickets abiertos</div>}
          <div style={{display:'grid',gap:10}}>
            {openTk.map(tk => {
              const isOpen = expandedTk[tk.id] !== false; // open by default for open tickets
              const lastMsg = (tk.messages||[]).slice(-1)[0];
              return <div key={tk.id} className="card" style={{padding:0,overflow:'hidden'}}>
                {/* Collapsible header */}
                <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',padding:'14px 18px',cursor:'pointer',gap:10,background:isOpen?'transparent':'var(--bg-inset)',transition:'background .15s'}} onClick={()=>setExpandedTk(s=>({...s,[tk.id]:!isOpen}))}>
                  <div style={{display:'flex',alignItems:'center',gap:10,minWidth:0,flex:1}}>
                    <div style={{width:30,height:30,borderRadius:8,background:'var(--accent-soft)',color:'var(--accent)',display:'flex',alignItems:'center',justifyContent:'center',fontFamily:'var(--serif)',fontWeight:600,fontSize:13,border:'1px solid var(--stroke)',flexShrink:0}}>{(tk.user_name||'?')[0]}</div>
                    <div style={{minWidth:0}}>
                      <div style={{fontWeight:600,fontSize:13,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{tk.user_name || 'Usuario'}</div>
                      {!isOpen && lastMsg && <div className="caption" style={{fontSize:11,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis',maxWidth:300}}>{lastMsg.sender==='admin'?'Tú: ':''}{lastMsg.body}</div>}
                    </div>
                  </div>
                  <div style={{display:'flex',alignItems:'center',gap:8,flexShrink:0}}>
                    <span className="chip chip-accent" style={{fontSize:10}}>{tk.status === 'replied' ? 'Respondido' : 'Abierto'}</span>
                    <span className="caption" style={{fontSize:10}}>{(tk.messages||[]).length} msg</span>
                    <Icon name={isOpen?'chevron-up':'chevron-down'} size={14} style={{color:'var(--ink-dim)'}}/>
                  </div>
                </div>

                {/* Expanded content */}
                {isOpen && <div style={{padding:'0 18px 18px'}}>
                  {/* User info bar */}
                  <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:10,fontSize:11}} className="caption">
                    <span style={{cursor:'pointer',textDecoration:'underline'}} onClick={e=>{e.stopPropagation();openUserDetail({id:tk.user_id,name:tk.user_name,email:tk.user_email,plan:tk.user_plan,license:tk.user_license,status:tk.user_status});}}>{tk.user_email} · {tk.user_license || '—'} · {planBadge(tk.user_plan)}</span>
                    <span>{fmtDate(tk.created_at)}</span>
                  </div>

                  {/* Conversation messages */}
                  <div style={{display:'flex',flexDirection:'column',gap:6,marginBottom:12,maxHeight:350,overflowY:'auto',padding:'4px 0'}}>
                    {(tk.messages || []).map((m, i) => <div key={m.id || i} style={{
                      alignSelf: m.sender === 'admin' ? 'flex-end' : 'flex-start',
                      maxWidth: '85%', padding: '10px 14px',
                      borderRadius: m.sender === 'admin' ? '14px 14px 4px 14px' : '14px 14px 14px 4px',
                      background: m.sender === 'admin' ? 'var(--accent-soft)' : 'var(--bg-inset)',
                      border: '1px solid var(--stroke)',
                      fontSize: 13, lineHeight: 1.5, whiteSpace: 'pre-wrap', wordBreak: 'break-word'
                    }}>
                      {m.sender === 'admin' && <div style={{fontWeight:600,fontSize:11,color:'var(--accent)',marginBottom:3}}>AeroPlan</div>}
                      {m.body}
                      <div className="caption" style={{fontSize:10,marginTop:4,textAlign:'right'}}>{new Date(m.created_at * 1000).toLocaleString()}</div>
                    </div>)}
                  </div>

                  {/* Reply + actions */}
                  <div style={{display:'flex',gap:10,alignItems:'flex-end'}}>
                    <textarea className="field" rows={2} placeholder="Responder..." value={replyText[tk.id]||''} onChange={e=>setReplyText(r=>({...r,[tk.id]:e.target.value}))} style={{flex:1,fontSize:12,resize:'vertical',minHeight:44}}/>
                    <div style={{display:'flex',gap:6}}>
                      <button className="btn btn-primary btn-sm" style={{padding:'8px 16px'}} onClick={async()=>{
                        const txt = (replyText[tk.id]||'').trim();
                        if (!txt) return;
                        try { await api.adminSupportReply(tk.id, txt); setReplyText(r=>({...r,[tk.id]:''})); api.adminSupport().then(d=>setTickets(d.tickets||[])).catch(()=>{}); toast('Respuesta enviada'); } catch(e) { toast('Error'); }
                      }}><Icon name="send" size={12}/></button>
                      <button className="btn btn-ghost btn-sm" style={{padding:'8px 12px',color:'var(--ink-dim)'}} title="Cerrar ticket" onClick={async()=>{
                        try { await api.adminSupportClose(tk.id); api.adminSupport().then(d=>setTickets(d.tickets||[])).catch(()=>{}); toast('Ticket cerrado'); } catch(e) { toast('Error'); }
                      }}><Icon name="check" size={12}/></button>
                    </div>
                  </div>
                </div>}
              </div>;
            })}
          </div>
        </>}

        {supportFilter==='closed' && <>
          {closedTk.length === 0 && <div className="card" style={{padding:30,textAlign:'center',color:'var(--ink-dim)'}}>Sin tickets cerrados</div>}
          <div style={{display:'grid',gap:10}}>
            {closedTk.map(tk => {
              const isOpen = !!expandedTk[tk.id];
              const firstMsg = (tk.messages||[])[0];
              return <div key={tk.id} className="card" style={{padding:0,overflow:'hidden',opacity:.85}}>
                {/* Collapsible header */}
                <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',padding:'14px 18px',cursor:'pointer',gap:10}} onClick={()=>setExpandedTk(s=>({...s,[tk.id]:!isOpen}))}>
                  <div style={{display:'flex',alignItems:'center',gap:10,minWidth:0,flex:1}}>
                    <div style={{width:28,height:28,borderRadius:7,background:'var(--bg-inset)',color:'var(--ink-dim)',display:'flex',alignItems:'center',justifyContent:'center',fontFamily:'var(--serif)',fontWeight:600,fontSize:12,border:'1px solid var(--stroke)',flexShrink:0}}>{(tk.user_name||'?')[0]}</div>
                    <div style={{minWidth:0}}>
                      <div style={{fontWeight:600,fontSize:12}}>{tk.user_name || 'Usuario'}</div>
                      {!isOpen && firstMsg && <div className="caption" style={{fontSize:11,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis',maxWidth:280}}>{firstMsg.body}</div>}
                    </div>
                  </div>
                  <div style={{display:'flex',alignItems:'center',gap:8,flexShrink:0}}>
                    <span className="caption" style={{fontSize:10}}>{(tk.messages||[]).length} msg · {fmtDate(tk.created_at)}</span>
                    <Icon name={isOpen?'chevron-up':'chevron-down'} size={14} style={{color:'var(--ink-dim)'}}/>
                  </div>
                </div>
                {/* Expanded content */}
                {isOpen && <div style={{padding:'0 18px 16px'}}>
                  {/* User info bar */}
                  <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:10,fontSize:11}} className="caption">
                    <span style={{cursor:'pointer',textDecoration:'underline'}} onClick={e=>{e.stopPropagation();openUserDetail({id:tk.user_id,name:tk.user_name,email:tk.user_email,plan:tk.user_plan,license:tk.user_license,status:tk.user_status});}}>{tk.user_email} · {tk.user_license || '—'} · {planBadge(tk.user_plan)}</span>
                    <span>{fmtDate(tk.created_at)}</span>
                  </div>
                  {/* Chat bubbles */}
                  <div style={{display:'flex',flexDirection:'column',gap:6,maxHeight:300,overflowY:'auto',padding:'4px 0'}}>
                    {(tk.messages || []).map((m, i) => <div key={m.id || i} style={{
                      alignSelf: m.sender === 'admin' ? 'flex-end' : 'flex-start',
                      maxWidth: '85%', padding: '10px 14px',
                      borderRadius: m.sender === 'admin' ? '14px 14px 4px 14px' : '14px 14px 14px 4px',
                      background: m.sender === 'admin' ? 'var(--accent-soft)' : 'var(--bg-inset)',
                      border: '1px solid var(--stroke)',
                      fontSize: 12, lineHeight: 1.5, whiteSpace: 'pre-wrap', wordBreak: 'break-word'
                    }}>
                      {m.sender === 'admin' && <div style={{fontWeight:600,fontSize:10,color:'var(--accent)',marginBottom:2}}>AeroPlan</div>}
                      {m.body}
                      <div className="caption" style={{fontSize:9,marginTop:3,textAlign:'right'}}>{new Date(m.created_at * 1000).toLocaleString()}</div>
                    </div>)}
                  </div>
                </div>}
              </div>;
            })}
          </div>
        </>}
      </>;
    })()}

    {/* ===== GIFT PREMIUM MODAL ===== */}
    {showGiftFor && <div style={{position:'fixed',inset:0,background:'rgba(0,0,0,.4)',zIndex:200,display:'flex',justifyContent:'center',alignItems:'center',padding:20}} onClick={e=>{if(e.target===e.currentTarget) setShowGiftFor(null);}}>
      <div className="card" style={{width:'100%',maxWidth:380,padding:28}}>
        <h3 className="h3" style={{marginBottom:16}}>Regalar Premium</h3>
        <label className="label">Duración</label>
        <div style={{display:'flex',gap:8,marginBottom:12,flexWrap:'wrap'}}>
          {[1,3,6,12].map(m=><button key={m} className={`btn btn-sm ${giftMonths===m?'btn-primary':''}`} style={{borderRadius:8,padding:'6px 16px',border:'1px solid var(--stroke)'}} onClick={()=>setGiftMonths(m)}>{m} {m===1?'mes':'meses'}</button>)}
        </div>
        <div style={{display:'flex',gap:8,marginBottom:16,flexWrap:'wrap',alignItems:'center'}}>
          <input className="field" type="number" min={1} max={120} value={giftMonths > 0 ? giftMonths : ''} onChange={e=>setGiftMonths(Math.max(1,parseInt(e.target.value)||1))} style={{width:80,textAlign:'center'}} placeholder="N"/>
          <span className="caption">meses</span>
          <span className="caption" style={{margin:'0 4px'}}>o</span>
          <button className={`btn btn-sm ${giftMonths===0?'btn-primary':''}`} style={{borderRadius:8,padding:'6px 16px',border:'1px solid var(--stroke)',fontWeight:700}} onClick={()=>setGiftMonths(0)}>♾ Vitalicio</button>
        </div>
        <div style={{display:'flex',gap:8}}>
          <button className="btn btn-primary" onClick={()=>giftPremium(showGiftFor, giftMonths)}>
            {giftMonths === 0 ? 'Regalar Vitalicio' : `Regalar ${giftMonths} ${giftMonths===1?'mes':'meses'}`}
          </button>
          <button className="btn btn-ghost" onClick={()=>setShowGiftFor(null)}>Cancelar</button>
        </div>
        {giftMonths === 0 && <div className="caption" style={{marginTop:10,color:'var(--warn)'}}>Sin fecha de expiración. Cancela la suscripción Stripe si existe.</div>}
      </div>
    </div>}

    {/* ===== CREATE USER MODAL ===== */}
    {showCreateUser && <div style={{position:'fixed',inset:0,background:'rgba(0,0,0,.4)',zIndex:200,display:'flex',justifyContent:'center',alignItems:'center',padding:20}} onClick={e=>{if(e.target===e.currentTarget) setShowCreateUser(false);}}>
      <div className="card" style={{width:'100%',maxWidth:420,padding:28}}>
        <h3 className="h3" style={{marginBottom:16}}>Crear usuario</h3>
        <div style={{display:'flex',flexDirection:'column',gap:12}}>
          <div><label className="label">Email</label><input className="field" value={newUser.email} onChange={e=>setNewUser(u=>({...u,email:e.target.value}))} placeholder="piloto@ejemplo.com"/></div>
          <div><label className="label">Nombre</label><input className="field" value={newUser.name} onChange={e=>setNewUser(u=>({...u,name:e.target.value}))} placeholder="Nombre completo"/></div>
          <div><label className="label">Contraseña</label><input className="field" type="password" value={newUser.password} onChange={e=>setNewUser(u=>({...u,password:e.target.value}))} placeholder="Mínimo 8 caracteres"/></div>
          <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:10}}>
            <div><label className="label">Licencia</label>
              <select className="field" value={newUser.license} onChange={e=>setNewUser(u=>({...u,license:e.target.value}))}>
                <option value="PPL">PPL</option><option value="CPL">CPL</option><option value="ATPL">ATPL</option><option value="LAPL">LAPL</option>
              </select>
            </div>
            <div><label className="label">Plan</label>
              <select className="field" value={newUser.plan} onChange={e=>setNewUser(u=>({...u,plan:e.target.value}))}>
                <option value="free">Free</option><option value="premium">Premium</option>
              </select>
            </div>
          </div>
        </div>
        <div style={{display:'flex',gap:8,marginTop:18}}>
          <button className="btn btn-primary" onClick={doCreateUser}>Crear</button>
          <button className="btn btn-ghost" onClick={()=>setShowCreateUser(false)}>Cancelar</button>
        </div>
      </div>
    </div>}

    {/* ===== CHANGE PASSWORD MODAL ===== */}
    {showChangePass && <div style={{position:'fixed',inset:0,background:'rgba(0,0,0,.4)',zIndex:200,display:'flex',justifyContent:'center',alignItems:'center',padding:20}} onClick={e=>{if(e.target===e.currentTarget) setShowChangePass(null);}}>
      <div className="card" style={{width:'100%',maxWidth:360,padding:28}}>
        <h3 className="h3" style={{marginBottom:16}}>Cambiar contraseña</h3>
        <div><label className="label">Nueva contraseña</label><input className="field" type="password" value={newPass} onChange={e=>setNewPass(e.target.value)} placeholder="Mínimo 8 caracteres"/></div>
        <div style={{display:'flex',gap:8,marginTop:18}}>
          <button className="btn btn-primary" onClick={doChangePass}>Cambiar</button>
          <button className="btn btn-ghost" onClick={()=>setShowChangePass(null)}>Cancelar</button>
        </div>
      </div>
    </div>}
  </div>;
};
window.Admin = Admin;
