/* Santos OS — Clientes (Club Santos loyalty: list, search, detail, canjes) */
function CustomerRow({ c, onSelect }) {
  const T = window.T;
  const initials = c.nombre.split(' ').map(w=>w[0]).slice(0,2).join('');
  return (
    <div onClick={onSelect} style={{background:T.surface, borderRadius:16, padding:15, boxShadow:'0 2px 8px rgba(8,54,47,0.07)', marginBottom:12, cursor:'pointer'}}>
      <div style={{display:'flex', gap:12, alignItems:'flex-start'}}>
        <div style={{width:46, height:46, borderRadius:23, background:T.primarySurface, display:'flex', alignItems:'center', justifyContent:'center', fontWeight:800, fontSize:15, color:T.primary, flexShrink:0}}>{initials}</div>
        <div style={{flex:1}}>
          <div style={{fontSize:15, fontWeight:700, color:T.fg1}}>{c.nombre}</div>
          <div style={{fontSize:12, color:T.fg3, marginTop:1}}>{c.whatsapp}</div>
          <div style={{fontSize:11, color:T.primaryMid, marginTop:1}}>{c.sucursal}</div>
        </div>
        <div style={{display:'flex', flexDirection:'column', gap:6, alignItems:'flex-end'}}>
          <window.TierBadge tier={c.tier} size="sm" />
          {c.refill && <span style={{background:c.refill==='overdue'?T.dangerLight:T.warningLight, color:c.refill==='overdue'?T.danger:T.warning, fontSize:10, fontWeight:700, padding:'3px 7px', borderRadius:6}}>{c.refill==='overdue'?'! Refill venc.':'◷ Refill próx.'}</span>}
        </div>
      </div>
      <div style={{display:'flex', marginTop:13, paddingTop:12, borderTop:`1px solid ${T.border}`}}>
        {[[`L. ${c.gasto.toLocaleString()}`,'Gasto anual'],[c.puntos.toLocaleString(),'Puntos'],[c.tx,'Compras']].map(([v,l],i)=>(
          <React.Fragment key={l}>
            {i>0 && <div style={{width:1, background:T.border}}></div>}
            <div style={{flex:1, textAlign:'center'}}><div style={{fontSize:15, fontWeight:700, color:T.fg1}}>{v}</div><div style={{fontSize:10, color:T.fg3, marginTop:3}}>{l}</div></div>
          </React.Fragment>
        ))}
      </div>
    </div>
  );
}

function CustomerDetail({ c, onClose, onToast }) {
  const T = window.T;
  const tc = T.tiers[c.tier];
  const goal = {BRONCE:5000, PLATA:15000, ORO:40000, JADE:999999}[c.tier];
  const remaining = Math.max(goal - c.gasto, 0);
  const pct = Math.min((c.gasto/goal)*100, 100);
  const initials = c.nombre.split(' ').map(w=>w[0]).slice(0,2).join('');
  const Section = ({title, children, action}) => (
    <div style={{marginBottom:18}}>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:10}}>
        <div style={{fontSize:13, fontWeight:700, color:T.fg1, letterSpacing:0.2}}>{title}</div>{action}
      </div>
      {children}
    </div>
  );
  return (
    <div style={{position:'absolute', inset:0, background:T.bg, display:'flex', flexDirection:'column', zIndex:30}}>
      <div style={{background:T.primary, paddingTop:52, paddingBottom:14, display:'flex', alignItems:'center', padding:'52px 16px 14px'}}>
        <button onClick={onClose} style={{background:'none', border:'none', color:'#fff', fontSize:14, fontWeight:600, cursor:'pointer', fontFamily:T.font}}>← Volver</button>
        <div style={{flex:1, textAlign:'center', fontSize:15, fontWeight:700, color:'#fff', marginRight:60}}>Perfil del Cliente</div>
      </div>
      <div style={{flex:1, overflowY:'auto', padding:16}}>
        <div style={{background:T.surface, borderRadius:16, padding:20, display:'flex', flexDirection:'column', alignItems:'center', gap:8, boxShadow:'0 2px 8px rgba(8,54,47,0.07)', marginBottom:14}}>
          <div style={{width:64, height:64, borderRadius:32, background:tc.border+'30', display:'flex', alignItems:'center', justifyContent:'center', fontSize:22, fontWeight:800, color:tc.border}}>{initials}</div>
          <div style={{fontSize:18, fontWeight:800, color:T.fg1}}>{c.nombre}</div>
          <window.TierBadge tier={c.tier} size="lg" />
          <div style={{fontSize:12, color:T.fg3}}>Miembro · {c.sucursal}</div>
        </div>

        <div style={{background:T.surface, borderRadius:16, padding:16, boxShadow:'0 2px 8px rgba(8,54,47,0.07)', marginBottom:14}}>
          <div style={{display:'flex', justifyContent:'space-between', alignItems:'center'}}>
            <div><div style={{fontSize:28, fontWeight:800, color:T.fg1}}>{c.puntos.toLocaleString()}</div><div style={{fontSize:12, color:T.fg3}}>puntos disponibles</div></div>
            <window.Btn variant="secondary" onClick={()=>onToast(`✦ ${c.nombre.split(' ')[0]} puede canjear L. ${Math.floor(c.puntos*0.1)}`)} style={{padding:'10px 18px'}}>Canjear</window.Btn>
          </div>
          <div style={{marginTop:12, background:T.bg, borderRadius:10, padding:'8px 12px'}}><span style={{fontSize:12, color:T.fg2}}>≈ L. {(c.puntos*0.1).toFixed(0)} en descuentos</span></div>
        </div>

        <Section title="Progreso de Tier">
          <div style={{background:T.surface, borderRadius:14, padding:14, boxShadow:'0 2px 8px rgba(8,54,47,0.07)'}}>
            <div style={{display:'flex', justifyContent:'space-between', marginBottom:8}}><span style={{fontSize:12, color:T.fg2}}>Gasto anual acumulado</span><span style={{fontSize:13, fontWeight:700, color:T.fg1}}>L. {c.gasto.toLocaleString()}</span></div>
            <div style={{height:6, background:T.border, borderRadius:3, overflow:'hidden'}}><div style={{width:`${pct}%`, height:'100%', background:tc.border, borderRadius:3}}></div></div>
            <div style={{fontSize:11, color:remaining>0?T.fg3:T.success, marginTop:8}}>{remaining>0?`Faltan L. ${remaining.toLocaleString()} para el siguiente tier`:'✓ Tier máximo alcanzado'}</div>
          </div>
        </Section>

        {(c.condiciones.length || c.alergias.length || c.doctor) ? (
          <Section title="Historial Clínico">
            <div style={{background:T.surface, borderRadius:14, padding:14, boxShadow:'0 2px 8px rgba(8,54,47,0.07)', display:'flex', flexDirection:'column', gap:10}}>
              {c.condiciones.length>0 && <div><div style={{fontSize:11, fontWeight:700, color:T.fg3, marginBottom:6}}>Condiciones</div><div style={{display:'flex', gap:6, flexWrap:'wrap'}}>{c.condiciones.map(x=><span key={x} style={{background:T.bg, border:`1px solid ${T.border}`, borderRadius:8, padding:'4px 10px', fontSize:12, color:T.fg1}}>{x}</span>)}</div></div>}
              {c.alergias.length>0 && <div><div style={{fontSize:11, fontWeight:700, color:T.fg3, marginBottom:6}}>! Alergias</div><div style={{display:'flex', gap:6, flexWrap:'wrap'}}>{c.alergias.map(x=><span key={x} style={{background:T.dangerLight, borderRadius:8, padding:'4px 10px', fontSize:12, color:T.danger, fontWeight:600}}>{x}</span>)}</div></div>}
              {c.doctor && <div style={{display:'flex', justifyContent:'space-between'}}><span style={{fontSize:11, fontWeight:700, color:T.fg3}}>Médico tratante</span><span style={{fontSize:13, color:T.fg1}}>{c.doctor}</span></div>}
              {c.seguro && <div style={{display:'flex', justifyContent:'space-between'}}><span style={{fontSize:11, fontWeight:700, color:T.fg3}}>Seguro médico</span><span style={{fontSize:13, color:T.fg1}}>{c.seguro}</span></div>}
            </div>
          </Section>
        ) : null}

        <Section title="Acciones">
          <div style={{display:'flex', gap:10}}>
            <window.Btn variant="success" style={{flex:1}} onClick={()=>onToast('✆ Abriendo WhatsApp…')}>✆ WhatsApp</window.Btn>
            <window.Btn variant="outline" style={{flex:1}} onClick={()=>onToast('✎ Disponible en versión completa')}>✎ Ajustar puntos</window.Btn>
          </div>
        </Section>
      </div>
    </div>
  );
}

function Clientes({ onToast }) {
  const T = window.T;
  const [tab, setTab] = React.useState('club');
  const [query, setQuery] = React.useState('');
  const [selected, setSelected] = React.useState(null);
  const counts = {BRONCE:892, PLATA:285, ORO:56, JADE:14};
  const filtered = query ? window.CUSTOMERS.filter(c=>c.nombre.toLowerCase().includes(query.toLowerCase())||c.whatsapp.includes(query)||c.dni.includes(query)||c.tier.toLowerCase().includes(query.toLowerCase())) : window.CUSTOMERS;

  if (selected) return <CustomerDetail c={selected} onClose={()=>setSelected(null)} onToast={onToast} />;

  return (
    <div style={{flex:1, display:'flex', flexDirection:'column', overflow:'hidden', background:T.bg}}>
      <div style={{background:T.primary, paddingTop:52, paddingBottom:14, padding:'52px 16px 14px'}}>
        <window.Wordmark size={20} sub="CLUB SANTOS" />
      </div>
      <div style={{background:T.bg, borderRadius:'24px 24px 0 0', marginTop:-12, flex:1, display:'flex', flexDirection:'column', overflow:'hidden'}}>
        {/* tabs */}
        <div style={{display:'flex', gap:8, padding:'16px 16px 0'}}>
          {[['club','Club Santos'],['canjes',`Canjes (${window.CANJES.length})`]].map(([k,l])=>(
            <button key={k} onClick={()=>setTab(k)} style={{flex:1, padding:'9px', borderRadius:10, border:'none', background:tab===k?T.primary:T.surface, color:tab===k?'#fff':T.fg2, fontSize:13, fontWeight:700, cursor:'pointer', fontFamily:T.font, boxShadow:tab===k?'none':`inset 0 0 0 1px ${T.border}`}}>{l}</button>
          ))}
        </div>

        {tab==='club' && <>
          <div style={{display:'flex', background:T.surface, margin:'14px 16px 0', borderRadius:14, padding:'10px 4px', boxShadow:'0 2px 8px rgba(8,54,47,0.07)'}}>
            {['BRONCE','PLATA','ORO','JADE'].map(t=>(
              <div key={t} style={{flex:1, display:'flex', flexDirection:'column', alignItems:'center', gap:3}}>
                <window.TierBadge tier={t} size="sm" showLabel={false} />
                <span style={{fontSize:9, fontWeight:700, color:T.fg3}}>{t}</span>
                <span style={{fontSize:13, fontWeight:800, color:T.fg1}}>{counts[t]}</span>
              </div>
            ))}
          </div>
          <div style={{display:'flex', alignItems:'center', gap:9, background:T.surface, border:`1px solid ${T.border}`, borderRadius:12, padding:'11px 13px', margin:'14px 16px'}}>
            <span style={{fontSize:15}}>⌕</span>
            <input value={query} onChange={e=>setQuery(e.target.value)} placeholder="Nombre, WhatsApp, DNI o tier…" style={{flex:1, border:'none', outline:'none', background:'transparent', fontSize:14, color:T.fg1, fontFamily:T.font}} />
            {query && <span onClick={()=>setQuery('')} style={{cursor:'pointer', color:T.fg3}}>✕</span>}
          </div>
          <div style={{flex:1, overflowY:'auto', padding:'0 16px 80px'}}>
            {filtered.map(c=><CustomerRow key={c.id} c={c} onSelect={()=>setSelected(c)} />)}
            {filtered.length===0 && <div style={{textAlign:'center', padding:40, color:T.fg3}}><div style={{fontSize:32}}>⌕</div><div style={{fontSize:13, marginTop:8}}>Sin resultados para "{query}"</div></div>}
          </div>
          <button onClick={()=>onToast('✓ Cliente enrollado en Club Santos · BRONCE')} style={{position:'absolute', bottom:90, right:24, background:T.primary, color:'#fff', border:'none', borderRadius:999, padding:'13px 22px', fontSize:14, fontWeight:700, boxShadow:'0 3px 8px rgba(8,54,47,0.25)', cursor:'pointer', fontFamily:T.font, zIndex:20}}>＋ Enrollar</button>
        </>}

        {tab==='canjes' && (
          <div style={{flex:1, overflowY:'auto', padding:16}}>
            {window.CANJES.map(k=>(
              <div key={k.id} style={{background:T.surface, borderRadius:16, padding:15, boxShadow:'0 2px 8px rgba(8,54,47,0.07)', marginBottom:12}}>
                <div style={{display:'flex', gap:12, alignItems:'flex-start'}}>
                  <div style={{width:44, height:44, borderRadius:12, background:T.primaryLight, display:'flex', alignItems:'center', justifyContent:'center', fontSize:20}}>Rx</div>
                  <div style={{flex:1}}><div style={{fontSize:14, fontWeight:700, color:T.fg1}}>{k.customer}</div><div style={{fontSize:12, color:T.fg2, marginTop:1}}>{k.product}</div><div style={{fontSize:11, color:T.fg3, marginTop:1}}>{k.lab} · {k.sucursal}</div></div>
                  <div style={{background:T.primary, borderRadius:10, padding:'6px 10px', textAlign:'center'}}><div style={{fontSize:16, fontWeight:800, color:'#fff'}}>{k.qty}</div><div style={{fontSize:9, color:'rgba(255,255,255,0.85)'}}>gratis</div></div>
                </div>
                <div style={{fontSize:11, color:T.fg3, margin:'10px 0 10px'}}>Listo desde {k.ready}</div>
                <div style={{display:'flex', gap:8}}>
                  <window.Btn variant="success" onClick={()=>onToast('✆ Avisando al cliente…')} style={{padding:'10px 14px'}}>✆</window.Btn>
                  <window.Btn variant="ghost" style={{flex:1, padding:'10px'}} onClick={()=>onToast(' Verificando portal del laboratorio…')}> Verificar</window.Btn>
                  <window.Btn variant="primary" style={{flex:1, padding:'10px'}} onClick={()=>onToast('✓ Canje entregado y registrado')}>✓ Entregar</window.Btn>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
window.Clientes = Clientes;
