// ── PANEL DE ADMIN ────────────────────────────────────────────
const AdminScreen = () => {
  const[tab,setTab]=React.useState('usuarios');
  const[stats,setStats]=React.useState({});
  const[users,setUsers]=React.useState([]);
  const[invites,setInvites]=React.useState([]);
  const[events,setEvents]=React.useState([]);
  const[modal,setModal]=React.useState(false);
  const[invForm,setInvForm]=React.useState({email:'',plan:'v1',name:''});
  const[copied,setCopied]=React.useState('');
  const[sending,setSending]=React.useState(false);

  const load=()=>{
    API.get('/admin/stats').then(r=>r&&setStats(r));
    API.get('/admin/users').then(r=>r&&setUsers(r));
    API.get('/admin/invitations').then(r=>r&&setInvites(r));
    API.get('/admin/hotmart-events').then(r=>r&&setEvents(r));
  };
  React.useEffect(()=>{load();},[]);

  const sendInvite=async()=>{
    if(!invForm.email){showToast('Email requerido','error');return;}
    setSending(true);
    const res=await API.post('/admin/invite',invForm);
    setSending(false);
    if(res.error){showToast(res.error,'error');return;}
    setModal(false);
    setInvForm({email:'',plan:'v1',name:''});
    showToast(res.email_sent?'Invitación enviada por email ✓':'Invitación creada (email no configurado)');
    load();
    // Copiar link al portapapeles
    if(res.invite_url) { try{navigator.clipboard.writeText(res.invite_url);}catch{} }
  };

  const copyLink=async(url)=>{
    try{await navigator.clipboard.writeText(url); setCopied(url); setTimeout(()=>setCopied(''),2000);}catch{}
  };

  const updateUser=async(id,field,val)=>{
    const u=users.find(x=>x.id===id);
    await API.put(`/admin/users/${id}`,{...u,[field]:val});
    showToast('Actualizado ✓');
    load();
  };

  const deleteInvite=async(id)=>{
    if(!confirm('¿Cancelar esta invitación?'))return;
    await API.del(`/admin/invitations/${id}`);
    showToast('Invitación cancelada');
    load();
  };

  const statusColor={active:EJ.green,suspended:EJ.pink,pending:'#F59E0B'};
  const statusLabel={active:'Activa',suspended:'Suspendida',pending:'Pendiente'};
  const planLabel={v1:'Esencial ($3)',v2:'Pro IA ($6)'};
  const hotmartColor={'active':EJ.green,'canceled':'#F59E0B','payment_failed':EJ.pink,'suspended':EJ.pink};

  return (
    <div style={{padding:'28px 32px',background:EJ.bgApp,minHeight:'100%'}}>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',marginBottom:24}}>
        <div>
          <h2 style={{margin:0,fontFamily:'Nunito, sans-serif',fontWeight:800,fontSize:26,color:EJ.navy}}>Panel de Admin</h2>
          <p style={{margin:'4px 0 0',fontSize:13,color:EJ.secondary}}>Gestión de usuarias, invitaciones y Hotmart</p>
        </div>
        <Btn variant="primary" size="sm" onClick={()=>setModal(true)}>+ Enviar invitación</Btn>
      </div>

      {/* Stats */}
      <div style={{display:'grid',gridTemplateColumns:'repeat(5,1fr)',gap:14,marginBottom:24}}>
        {[
          {label:'Usuarias totales',value:stats.total_users||0,color:EJ.navy},
          {label:'Activas',value:stats.active_users||0,color:EJ.green},
          {label:'Suspendidas',value:stats.suspended_users||0,color:EJ.pink},
          {label:'Invitaciones pendientes',value:stats.pending_invites||0,color:EJ.violet},
          {label:'Eventos Hotmart hoy',value:stats.events_today||0,color:EJ.cyan},
        ].map((s,i)=><Card key={i} style={{padding:16,textAlign:'center'}}>
          <div style={{fontSize:10,color:EJ.muted,textTransform:'uppercase',letterSpacing:'.05em',marginBottom:6}}>{s.label}</div>
          <div style={{fontSize:28,fontWeight:700,color:s.color,fontFamily:'JetBrains Mono, monospace'}}>{s.value}</div>
        </Card>)}
      </div>

      {/* Tabs */}
      <div style={{display:'flex',background:'#fff',borderRadius:50,padding:4,marginBottom:20,border:`1px solid ${EJ.border}`,width:'fit-content',gap:4}}>
        {[{id:'usuarios',label:'👥 Usuarias'},{id:'invitaciones',label:'✉️ Invitaciones'},{id:'hotmart',label:'🔗 Hotmart'}].map(t=>(
          <button key={t.id} onClick={()=>setTab(t.id)} style={{padding:'8px 18px',borderRadius:50,border:'none',cursor:'pointer',fontFamily:'Nunito, sans-serif',fontWeight:700,fontSize:13,background:tab===t.id?EJ.navy:'transparent',color:tab===t.id?'#fff':EJ.muted,transition:'all .2s'}}>
            {t.label}
          </button>
        ))}
      </div>

      {/* USUARIOS */}
      {tab==='usuarios'&&<Card>
        <div style={{overflowX:'auto'}}>
          <table style={{width:'100%',borderCollapse:'collapse',fontSize:13}}>
            <thead><tr style={{background:EJ.bgApp}}>
              {['Email','Nombre','Plan','Estado Cuenta','Estado Hotmart','Registro','Último acceso','Acciones'].map(h=><th key={h} style={{padding:'8px 12px',textAlign:'left',fontSize:11,fontWeight:600,color:EJ.muted,textTransform:'uppercase',letterSpacing:'.05em',borderBottom:`1.5px solid ${EJ.border}`,whiteSpace:'nowrap'}}>{h}</th>)}
            </tr></thead>
            <tbody>
              {users.length===0?<tr><td colSpan="8" style={{padding:32,textAlign:'center',color:EJ.muted}}>Sin usuarias registradas</td></tr>:
              users.map(u=><tr key={u.id} style={{borderBottom:`1px solid ${EJ.border}`}}>
                <td style={{padding:'10px 12px',fontWeight:600}}>{u.email}</td>
                <td style={{padding:'10px 12px'}}>{u.name||'—'}</td>
                <td style={{padding:'10px 12px'}}>
                  <select value={u.plan} onChange={e=>updateUser(u.id,'plan',e.target.value)} style={{fontSize:12,border:`1px solid ${EJ.border}`,borderRadius:8,padding:'3px 8px',background:'#fff',cursor:'pointer'}}>
                    <option value="v1">Esencial</option>
                    <option value="v2">Pro IA</option>
                  </select>
                </td>
                <td style={{padding:'10px 12px'}}>
                  <select value={u.status} onChange={e=>updateUser(u.id,'status',e.target.value)} style={{fontSize:12,border:`1px solid ${EJ.border}`,borderRadius:8,padding:'3px 8px',background:'#fff',cursor:'pointer',color:statusColor[u.status]||EJ.muted}}>
                    <option value="active">Activa</option>
                    <option value="suspended">Suspendida</option>
                  </select>
                </td>
                <td style={{padding:'10px 12px'}}>
                  <span style={{fontSize:11,fontWeight:600,color:hotmartColor[u.hotmart_subscription_status]||EJ.muted}}>
                    {u.hotmart_subscription_status||'—'}
                  </span>
                </td>
                <td style={{padding:'10px 12px',color:EJ.muted,fontSize:12}}>{u.created_at?.slice(0,10)||'—'}</td>
                <td style={{padding:'10px 12px',color:EJ.muted,fontSize:12}}>{u.last_login?.slice(0,10)||'Nunca'}</td>
                <td style={{padding:'10px 12px'}}>
                  <button onClick={()=>updateUser(u.id,'status',u.status==='active'?'suspended':'active')} style={{background:'none',border:`1px solid ${u.status==='active'?EJ.pink:EJ.green}`,borderRadius:8,padding:'4px 10px',cursor:'pointer',fontSize:11,color:u.status==='active'?EJ.pink:EJ.green,fontWeight:600}}>
                    {u.status==='active'?'Suspender':'Reactivar'}
                  </button>
                </td>
              </tr>)}
            </tbody>
          </table>
        </div>
      </Card>}

      {/* INVITACIONES */}
      {tab==='invitaciones'&&<Card>
        <div style={{marginBottom:16,padding:'14px 16px',background:EJ.cyanLight,borderRadius:16,fontSize:13,color:EJ.body}}>
          <strong>💡 Cómo funciona:</strong> Cuando envías una invitación, la usuaria recibe un email con un link único. 
          Al hacer clic, puede registrarse y el link se marca como usado. 
          Si no tienes email configurado, copia el link manualmente y envíalo por WhatsApp.
        </div>
        <div style={{overflowX:'auto'}}>
          <table style={{width:'100%',borderCollapse:'collapse',fontSize:13}}>
            <thead><tr style={{background:EJ.bgApp}}>
              {['Email','Plan','Estado','Expira','Link de invitación','Transacción Hotmart',''].map(h=><th key={h} style={{padding:'8px 12px',textAlign:'left',fontSize:11,fontWeight:600,color:EJ.muted,textTransform:'uppercase',letterSpacing:'.05em',borderBottom:`1.5px solid ${EJ.border}`}}>{h}</th>)}
            </tr></thead>
            <tbody>
              {invites.length===0?<tr><td colSpan="7" style={{padding:32,textAlign:'center',color:EJ.muted}}>Sin invitaciones</td></tr>:
              invites.map(inv=>{
                const expired=new Date(inv.expires_at)<new Date();
                const invUrl=`${window.location.origin}/invitacion?token=${inv.token}`;
                return <tr key={inv.id} style={{borderBottom:`1px solid ${EJ.border}`,opacity:expired?0.6:1}}>
                  <td style={{padding:'10px 12px',fontWeight:600}}>{inv.email}</td>
                  <td style={{padding:'10px 12px'}}><Badge variant={inv.plan==='v2'?'violet':'cyan'}>{inv.plan==='v2'?'Pro':'Esencial'}</Badge></td>
                  <td style={{padding:'10px 12px'}}>
                    <Badge variant={inv.status==='used'?'green':expired?'soft':'cyan'}>
                      {inv.status==='used'?'✓ Usada':expired?'Expirada':'Pendiente'}
                    </Badge>
                  </td>
                  <td style={{padding:'10px 12px',fontSize:12,color:EJ.muted}}>{inv.expires_at?.slice(0,10)}</td>
                  <td style={{padding:'10px 12px'}}>
                    {inv.status==='pending'&&!expired&&<div style={{display:'flex',alignItems:'center',gap:8}}>
                      <code style={{fontSize:11,background:EJ.bgApp,padding:'4px 8px',borderRadius:8,color:EJ.navy,maxWidth:200,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap',display:'block'}}>{invUrl}</code>
                      <button onClick={()=>copyLink(invUrl)} style={{background:copied===invUrl?EJ.green:EJ.cyan,color:'#fff',border:'none',borderRadius:8,padding:'4px 10px',cursor:'pointer',fontSize:11,fontWeight:600,whiteSpace:'nowrap'}}>
                        {copied===invUrl?'✓ Copiado':'Copiar'}
                      </button>
                    </div>}
                  </td>
                  <td style={{padding:'10px 12px',fontSize:12,color:EJ.muted}}>{inv.hotmart_transaction||'Manual'}</td>
                  <td style={{padding:'10px 12px'}}>
                    {inv.status==='pending'&&<button onClick={()=>deleteInvite(inv.id)} style={{background:'none',border:'none',cursor:'pointer',color:EJ.pink,fontSize:16}}>✕</button>}
                  </td>
                </tr>;
              })}
            </tbody>
          </table>
        </div>
      </Card>}

      {/* HOTMART EVENTOS */}
      {tab==='hotmart'&&<div>
        <Card style={{marginBottom:16,padding:'16px 20px'}}>
          <div style={{fontFamily:'Nunito, sans-serif',fontWeight:800,fontSize:15,color:EJ.navy,marginBottom:10}}>🔗 URL del Webhook para Hotmart</div>
          <div style={{display:'flex',alignItems:'center',gap:12}}>
            <code style={{flex:1,background:EJ.bgApp,padding:'12px 16px',borderRadius:12,fontSize:13,color:EJ.navy,fontFamily:'JetBrains Mono, monospace',border:`1px solid ${EJ.border}`}}>
              {window.location.origin}/api/webhook/hotmart
            </code>
            <button onClick={()=>copyLink(window.location.origin+'/api/webhook/hotmart')} style={{background:EJ.navy,color:'#fff',border:'none',borderRadius:12,padding:'12px 20px',cursor:'pointer',fontFamily:'Nunito, sans-serif',fontWeight:700,fontSize:13,whiteSpace:'nowrap'}}>
              {copied===window.location.origin+'/api/webhook/hotmart'?'✓ Copiado':'Copiar URL'}
            </button>
          </div>
          <div style={{marginTop:12,fontSize:12,color:EJ.muted,lineHeight:1.6}}>
            <strong>Configura en Hotmart:</strong> Panel → Herramientas → Webhook → + Registrar → Pega esta URL.<br/>
            <strong>Eventos recomendados:</strong> PURCHASE_APPROVED · SUBSCRIPTION_CANCELLATION · PURCHASE_REFUNDED · SUBSCRIPTION_PAYMENT_FAILED<br/>
            <strong>Variable de entorno:</strong> Agrega <code style={{background:EJ.bgApp,padding:'1px 6px',borderRadius:4}}>HOTMART_HOTTOK</code> con el token de seguridad de Hotmart para mayor seguridad.
          </div>
        </Card>
        <Card>
          <div style={{fontFamily:'Nunito, sans-serif',fontWeight:800,fontSize:15,color:EJ.navy,marginBottom:16}}>📋 Log de eventos recientes</div>
          {events.length===0?<div style={{textAlign:'center',padding:32,color:EJ.muted}}><div style={{fontSize:28,marginBottom:8}}>🔗</div><p>Sin eventos. Cuando Hotmart envíe notificaciones, aparecerán aquí.</p></div>:(
            <div style={{overflowX:'auto'}}>
              <table style={{width:'100%',borderCollapse:'collapse',fontSize:13}}>
                <thead><tr style={{background:EJ.bgApp}}>
                  {['Evento','Email','Transacción','Plan','Estado','Fecha'].map(h=><th key={h} style={{padding:'8px 12px',textAlign:'left',fontSize:11,fontWeight:600,color:EJ.muted,textTransform:'uppercase',borderBottom:`1.5px solid ${EJ.border}`}}>{h}</th>)}
                </tr></thead>
                <tbody>
                  {events.map(e=><tr key={e.id} style={{borderBottom:`1px solid ${EJ.border}`}}>
                    <td style={{padding:'10px 12px'}}>
                      <Badge variant={e.event?.includes('APPROVED')||e.event?.includes('REACTIVATION')?'green':e.event?.includes('CANCEL')||e.event?.includes('REFUND')||e.event?.includes('FAILED')?'pink':'soft'}>
                        {e.event||'—'}
                      </Badge>
                    </td>
                    <td style={{padding:'10px 12px'}}>{e.email||'—'}</td>
                    <td style={{padding:'10px 12px',fontFamily:'JetBrains Mono, monospace',fontSize:11,color:EJ.muted}}>{e.transaction?.slice(0,16)||'—'}</td>
                    <td style={{padding:'10px 12px'}}><Badge variant={e.plan==='v2'?'violet':'cyan'}>{e.plan}</Badge></td>
                    <td style={{padding:'10px 12px'}}><Badge variant={e.processed?'green':'soft'}>{e.processed?'✓ Procesado':'Pendiente'}</Badge></td>
                    <td style={{padding:'10px 12px',fontSize:12,color:EJ.muted}}>{e.created_at?.slice(0,16)}</td>
                  </tr>)}
                </tbody>
              </table>
            </div>
          )}
        </Card>
      </div>}

      {/* MODAL INVITACIÓN */}
      <Modal open={modal} onClose={()=>setModal(false)} title="✉️ Enviar invitación" width={440}>
        <div style={{marginBottom:16,padding:'12px 14px',background:EJ.cyanLight,borderRadius:12,fontSize:12,color:EJ.body,lineHeight:1.6}}>
          La usuaria recibirá un email con link de activación. Si SMTP no está configurado, se generará un link que puedes copiar y enviar manualmente.
        </div>
        <div style={{display:'flex',flexDirection:'column',gap:14}}>
          <Input label="Email de la usuaria *" type="email" placeholder="maria@email.com" value={invForm.email} onChange={e=>setInvForm(f=>({...f,email:e.target.value}))}/>
          <Input label="Nombre (opcional)" placeholder="María González" value={invForm.name} onChange={e=>setInvForm(f=>({...f,name:e.target.value}))}/>
          <Select label="Plan" value={invForm.plan} onChange={e=>setInvForm(f=>({...f,plan:e.target.value}))} options={[{value:'v1',label:'V1 — Esencial ($3/mes)'},{value:'v2',label:'V2 — Pro con IA ($6/mes)'}]}/>
        </div>
        <div style={{display:'flex',justifyContent:'flex-end',gap:10,marginTop:20}}>
          <Btn variant="ghost" size="sm" onClick={()=>setModal(false)}>Cancelar</Btn>
          <Btn variant="primary" size="sm" onClick={sendInvite} disabled={sending}>{sending?'Enviando...':'Enviar invitación'}</Btn>
        </div>
      </Modal>
    </div>
  );
};
Object.assign(window, { AdminScreen });
