/* Portal del CLIENTE — vista limpia, levanta tickets, ve sus equipos. */

function ClientPortal({ user, onLogout }) {
  const [empresa, setEmpresa] = React.useState(null);
  const [tab, setTab] = React.useState('tickets');
  const [tickets, setTickets] = React.useState([]);
  const [equipos, setEquipos] = React.useState({ users:[], devices:[] });
  const [showNew, setShowNew] = React.useState(false);
  const [toast, setToastMsg] = React.useState(null);

  React.useEffect(() => {
    window.API.clienteMe().then(r => setEmpresa(r.empresa));
    reload();
    const stop = window.useWS(m => {
      if (m.type === 'state_changed' || m.type === 'notificacion') reload();
    });
    return stop;
  }, []);

  function reload() {
    window.API.clienteTickets().then(setTickets);
    window.API.clienteEquipos().then(setEquipos);
  }
  function showToast(msg, type='success') { setToastMsg({msg, type, key: Date.now()}); }

  async function crearTicket(form) {
    try {
      await window.API.clienteCrearTicket(form);
      setShowNew(false);
      showToast('Ticket enviado a soporte');
      reload();
    } catch(e) { showToast(e.body?.error || 'Error', 'error'); }
  }

  const abiertos = tickets.filter(t => t.status !== 'resolved');
  const cerrados = tickets.filter(t => t.status === 'resolved');

  return (
    <div style={{minHeight:'100vh',background:'linear-gradient(180deg,#f5f5f7 0%,#eef0f3 100%)',fontFamily:"'Plus Jakarta Sans',sans-serif"}}>
      <header style={{background:'#fff',borderBottom:'1px solid #e2e8f0',padding:'14px 24px',display:'flex',alignItems:'center',gap:14,position:'sticky',top:0,zIndex:10}}>
        <div style={{width:36,height:36,borderRadius:9,background:'#2563eb',display:'flex',alignItems:'center',justifyContent:'center',color:'#fff',fontSize:13,fontWeight:900}}>IT</div>
        <div style={{flex:1}}>
          <div style={{fontSize:14,fontWeight:800,color:'#0f172a'}}>{empresa?.name || 'Portal Cliente'}</div>
          <div style={{fontSize:11,color:'#94a3b8'}}>{user.nombre} · Cliente</div>
        </div>
        <button onClick={onLogout} style={{padding:'7px 14px',background:'#fef2f2',color:'#dc2626',border:'none',borderRadius:8,fontSize:12,fontWeight:600,cursor:'pointer'}}>Salir</button>
      </header>

      <div style={{maxWidth:900,margin:'0 auto',padding:'28px 20px'}}>
        <div style={{display:'flex',gap:6,marginBottom:24,borderBottom:'1.5px solid #e2e8f0'}}>
          {[
            {id:'tickets',label:`Tickets (${abiertos.length} abiertos)`},
            {id:'equipos',label:`Mis equipos (${equipos.users.length})`},
            {id:'empresa',label:'Mi empresa'},
          ].map(t=>(
            <button key={t.id} onClick={()=>setTab(t.id)}
              style={{padding:'10px 18px',background:'transparent',border:'none',borderBottom:tab===t.id?'2px solid #2563eb':'2px solid transparent',marginBottom:-1.5,cursor:'pointer',fontFamily:'inherit',fontSize:13,fontWeight:600,color:tab===t.id?'#2563eb':'#64748b'}}>
              {t.label}
            </button>
          ))}
        </div>

        {tab==='tickets' && (
          <div>
            <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:16}}>
              <h2 style={{margin:0,fontSize:18,fontWeight:800,color:'#0f172a'}}>Mis solicitudes de soporte</h2>
              <Btn onClick={()=>setShowNew(true)}>+ Nuevo ticket</Btn>
            </div>
            {abiertos.length > 0 && <>
              <div style={{fontSize:11,fontWeight:700,color:'#64748b',textTransform:'uppercase',marginBottom:8}}>Abiertos · {abiertos.length}</div>
              {abiertos.map(t => <ClienteTicketCard key={t.id} ticket={t} onComment={async(msg)=>{await window.API.comentarTicket(t.id,msg);showToast('Comentario enviado');}}/>)}
            </>}
            {cerrados.length > 0 && <>
              <div style={{fontSize:11,fontWeight:700,color:'#64748b',textTransform:'uppercase',marginTop:24,marginBottom:8}}>Resueltos</div>
              {cerrados.slice(0,5).map(t => <ClienteTicketCard key={t.id} ticket={t} />)}
            </>}
            {tickets.length===0 && (
              <Card style={{padding:'40px 24px',textAlign:'center',color:'#94a3b8'}}>
                <div style={{fontSize:14,marginBottom:14}}>Aún no tienes solicitudes</div>
                <Btn size="sm" onClick={()=>setShowNew(true)}>Crear el primero</Btn>
              </Card>
            )}
          </div>
        )}

        {tab==='equipos' && (
          <div>
            <h2 style={{margin:'0 0 16px',fontSize:18,fontWeight:800,color:'#0f172a'}}>Equipos registrados</h2>
            <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fill,minmax(280px,1fr))',gap:12}}>
              {equipos.users.map(u => (
                <Card key={u.id} style={{padding:'14px 16px'}}>
                  <div style={{fontWeight:700,fontSize:14,color:'#0f172a'}}>{u.name}</div>
                  <div style={{fontSize:11,color:'#64748b',marginBottom:8}}>{u.position}</div>
                  <div style={{fontSize:12,color:'#475569',lineHeight:1.5}}>
                    <div>📦 {u.equipment?.brand} {u.equipment?.model}</div>
                    <div>💻 {u.equipment?.os}</div>
                    <div>🔢 {u.equipment?.hostname} · {u.equipment?.ip}</div>
                    <div>🔗 AnyDesk: <code>{u.anydesk}</code></div>
                  </div>
                </Card>
              ))}
              {equipos.devices.map(d => (
                <Card key={d.id} style={{padding:'14px 16px',background:'#f8fafc'}}>
                  <div style={{fontWeight:700,fontSize:14,color:'#0f172a'}}>{d.brand} {d.model}</div>
                  <div style={{fontSize:11,color:'#64748b'}}>{d.type} · {d.location}</div>
                  <div style={{fontSize:12,color:'#475569',marginTop:6}}>IP: {d.ip || '—'}</div>
                </Card>
              ))}
              {equipos.users.length===0 && equipos.devices.length===0 && (
                <Card style={{padding:'24px',textAlign:'center',color:'#94a3b8',gridColumn:'1/-1'}}>Sin equipos registrados</Card>
              )}
            </div>
          </div>
        )}

        {tab==='empresa' && empresa && (
          <Card style={{padding:'20px 24px'}}>
            <h2 style={{margin:'0 0 16px',fontSize:18,fontWeight:800,color:'#0f172a'}}>{empresa.name}</h2>
            <Row label="RFC" value={empresa.rif} />
            <Row label="Contacto" value={empresa.contact} />
            <Row label="Teléfono" value={empresa.phone} />
            <Row label="Email" value={empresa.email} />
            <Row label="Dirección" value={empresa.address} />
            <Row label="Plan" value={empresa.plan} />
            {empresa.network && <>
              <h3 style={{fontSize:13,fontWeight:700,color:'#0f172a',marginTop:18,marginBottom:8}}>Red</h3>
              <Row label="ISP" value={empresa.network.isp} />
              <Row label="IP pública" value={empresa.network.publicIp} />
              <Row label="Router" value={empresa.network.routerModel} />
            </>}
          </Card>
        )}
      </div>

      {showNew && (
        <Modal title="Nueva solicitud de soporte" onClose={()=>setShowNew(false)}>
          <NuevoTicketForm equipos={equipos.users} onSave={crearTicket} onCancel={()=>setShowNew(false)} />
        </Modal>
      )}

      {toast && <Toast key={toast.key} message={toast.msg} type={toast.type} onDone={()=>setToastMsg(null)} />}
    </div>
  );
}

function ClienteTicketCard({ ticket, onComment }) {
  const [expanded, setExpanded] = React.useState(false);
  const [coms, setComs] = React.useState([]);
  const [msg, setMsg] = React.useState('');

  React.useEffect(() => {
    if (expanded) window.API.listComentarios(ticket.id).then(setComs);
  }, [expanded, ticket.id]);

  const statusColor = { open:'orange', in_progress:'blue', resolved:'green' }[ticket.status];
  const statusLabel = { open:'Abierto', in_progress:'En atención', resolved:'Resuelto' }[ticket.status];
  const priorityColor = { urgent:'red', high:'orange', medium:'yellow', low:'slate' }[ticket.priority];

  return (
    <Card style={{padding:'14px 18px',marginBottom:10}}>
      <div style={{display:'flex',alignItems:'flex-start',gap:12}}>
        <div style={{flex:1}}>
          <div style={{display:'flex',alignItems:'center',gap:8,marginBottom:4}}>
            <Badge label={statusLabel} color={statusColor} />
            <Badge label={ticket.priority} color={priorityColor} />
            <span style={{fontSize:11,color:'#94a3b8'}}>{DB.timeAgo(ticket.createdAt)}</span>
          </div>
          <div style={{fontWeight:700,fontSize:14,color:'#0f172a'}}>{ticket.title}</div>
          <div style={{fontSize:13,color:'#475569',marginTop:4}}>{ticket.description}</div>
        </div>
        <button onClick={()=>setExpanded(!expanded)} style={{background:'none',border:'none',color:'#64748b',cursor:'pointer',fontSize:11}}>
          {expanded?'▲':'▼'}
        </button>
      </div>
      {expanded && (
        <div style={{marginTop:14,paddingTop:14,borderTop:'1px solid #f1f5f9'}}>
          <div style={{fontSize:11,fontWeight:700,color:'#64748b',textTransform:'uppercase',marginBottom:8}}>Conversación</div>
          {coms.map(c => (
            <div key={c.id} style={{padding:'8px 12px',marginBottom:6,background:c.autor_rol==='cliente'?'#eff6ff':'#f8fafc',borderRadius:8,fontSize:12}}>
              <div style={{fontWeight:600,color:'#0f172a',fontSize:11}}>{c.autor_nombre} · {DB.timeAgo(c.creado)}</div>
              <div style={{color:'#475569',marginTop:2}}>{c.mensaje}</div>
            </div>
          ))}
          {coms.length===0 && <div style={{fontSize:12,color:'#94a3b8',marginBottom:10}}>Aún sin comentarios</div>}
          {ticket.history?.length > 0 && (
            <div style={{fontSize:11,color:'#94a3b8',marginTop:10}}>
              <div style={{fontWeight:700,textTransform:'uppercase',marginBottom:6}}>Historial</div>
              {ticket.history.map((h,i)=>(<div key={i}>· {DB.formatDateTime(h.date)}: {h.note}</div>))}
            </div>
          )}
          {onComment && ticket.status !== 'resolved' && (
            <div style={{display:'flex',gap:8,marginTop:12}}>
              <input value={msg} onChange={e=>setMsg(e.target.value)} placeholder="Agregar comentario..."
                style={{flex:1,padding:'8px 12px',border:'1.5px solid #e2e8f0',borderRadius:8,fontSize:13,fontFamily:'inherit',outline:'none'}} />
              <Btn size="sm" disabled={!msg.trim()} onClick={async()=>{await onComment(msg);setMsg('');window.API.listComentarios(ticket.id).then(setComs);}}>Enviar</Btn>
            </div>
          )}
        </div>
      )}
    </Card>
  );
}

function NuevoTicketForm({ equipos = [], onSave, onCancel }) {
  const [f, setF] = React.useState({ title:'', description:'', priority:'medium', userId:'' });
  return (
    <div style={{display:'flex',flexDirection:'column',gap:12}}>
      <Field label="Título" value={f.title} onChange={v=>setF({...f,title:v})} placeholder="Ej: Mi PC no enciende" />
      <div>
        <label style={{fontSize:11,fontWeight:700,color:'#64748b',textTransform:'uppercase',display:'block',marginBottom:6}}>Descripción</label>
        <textarea value={f.description} onChange={e=>setF({...f,description:e.target.value})} rows={4}
          placeholder="Describe el problema con detalle..."
          style={{width:'100%',padding:'10px 12px',border:'1.5px solid #e2e8f0',borderRadius:8,fontSize:13,fontFamily:'inherit',resize:'vertical',outline:'none'}} />
      </div>
      <Selector label="Prioridad" value={f.priority} onChange={v=>setF({...f,priority:v})} options={[
        {value:'low',label:'Baja — sin prisa'},
        {value:'medium',label:'Media — esta semana'},
        {value:'high',label:'Alta — hoy'},
        {value:'urgent',label:'Urgente — bloqueante'},
      ]} />
      {equipos.length > 0 && <Selector label="Equipo afectado (opcional)" value={f.userId} onChange={v=>setF({...f,userId:v})} options={[
        {value:'',label:'— No especificado —'},
        ...equipos.map(u=>({value:u.id,label:`${u.name} (${u.equipment?.hostname || u.position})`})),
      ]} />}
      <div style={{display:'flex',gap:8,justifyContent:'flex-end',marginTop:6}}>
        <Btn size="sm" variant="secondary" onClick={onCancel}>Cancelar</Btn>
        <Btn size="sm" disabled={!f.title || !f.description} onClick={()=>onSave(f)}>Enviar a soporte</Btn>
      </div>
    </div>
  );
}
