/* Santos OS — Inicio (Dashboard): branch selector + clickable KPI bubbles */
const LABEL_TO_METRIC = {
  'Ventas hoy':'ventas', 'Ticket promedio':'ticket', 'Captura cliente':'captura',
  'Miembros activos':'miembros', 'Uptime POS':'uptime', 'Stockouts críticos':'stockouts',
  'Despachos hoy':'despachos', 'Órdenes procesadas':'ordenes', 'SKUs en tránsito':'transito',
  'Cadena de frío':'frio', 'Uptime WMS':'uptime', 'Lotes por vencer':'lotes',
};

function KpiCard({ label, value, sub, trend, trendLabel, accent, warning, onClick }) {
  const T = window.T;
  const tc = trend==='up'?T.success:trend==='down'?T.danger:T.fg3;
  const ta = trend==='up'?'▲':trend==='down'?'▼':'—';
  const [hover, setHover] = React.useState(false);
  return (
    <div onClick={onClick} onMouseEnter={()=>setHover(true)} onMouseLeave={()=>setHover(false)}
      style={{flex:1, minWidth:'45%', background:T.surface, borderRadius:16, padding:16, cursor:onClick?'pointer':'default', position:'relative',
        boxShadow:hover&&onClick?'0 6px 18px rgba(8,54,47,0.14)':'0 2px 8px rgba(8,54,47,0.07)',
        border:warning?`1.5px solid ${T.warning}`:'1px solid transparent', transform:hover&&onClick?'translateY(-1px)':'none', transition:'all .14s'}}>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start'}}>
        <div style={{fontSize:11, fontWeight:600, color:T.fg2, textTransform:'uppercase', letterSpacing:0.5, marginBottom:6}}>{label}</div>
        {onClick && <span style={{fontSize:13, opacity:hover?1:0.4, transition:'opacity .14s'}}>▦</span>}
      </div>
      <div style={{fontSize:26, fontWeight:700, color:accent||T.fg1, marginBottom:2, fontFamily:T.font}}>{value}</div>
      {sub && <div style={{fontSize:12, color:T.fg2, marginBottom:4}}>{sub}</div>}
      {trendLabel && <div style={{display:'flex', alignItems:'center', gap:3, marginTop:4}}><span style={{fontSize:11, fontWeight:700, color:tc}}>{ta}</span><span style={{fontSize:11, fontWeight:600, color:tc}}>{trendLabel}</span></div>}
    </div>
  );
}

function Dashboard({ user, perms, onNav, onToast }) {
  const T = window.T;
  const { Card, SectionLabel, Btn } = window;
  const [branch, setBranch] = React.useState('grupo');
  const data = window.BRANCH_DATA[branch];
  const isCedi = branch==='cedi';

  return (
    <div style={{flex:1, display:'flex', flexDirection:'column', overflow:'hidden'}}>
      <window.AppHeader user={user} onLogout={()=>onNav('logout')} />
      <div style={{flex:1, overflowY:'auto', background:T.bg, borderRadius:'24px 24px 0 0', marginTop:-12, padding:'20px 16px 24px'}}>

        {/* Branch selector — separates CEDI / pharmacies, with Grupo aggregate */}
        {perms.kpis && (
          <div style={{display:'flex', gap:8, overflowX:'auto', marginBottom:16, paddingBottom:2}}>
            {window.BRANCHES.map(b=>{
              const on = branch===b.key;
              return <button key={b.key} onClick={()=>setBranch(b.key)} style={{flexShrink:0, padding:'8px 15px', borderRadius:20, border:`1px solid ${on?T.primary:T.border}`, background:on?T.primary:T.surface, color:on?'#fff':T.fg2, fontSize:12.5, fontWeight:700, cursor:'pointer', fontFamily:T.font, display:'flex', alignItems:'center', gap:6}}>{b.key==='grupo'&&<span style={{fontSize:13}}>◆</span>}{b.short}</button>;
            })}
          </div>
        )}

        {/* Branch banner */}
        {perms.kpis && data.banner && (
          <div onClick={()=>onNav(data.banner.go)} style={{display:'flex', alignItems:'center', gap:12, background:data.banner.kind==='warn'?T.warningLight:T.infoLight, borderRadius:14, padding:14, marginBottom:10, border:`1px solid ${data.banner.kind==='warn'?T.warning:T.info}`, cursor:'pointer'}}>
            <span style={{fontSize:22}}>{data.banner.icon}</span>
            <div style={{flex:1}}><div style={{fontSize:13, fontWeight:700, color:data.banner.kind==='warn'?'#92400E':T.primaryDark}}>{data.banner.title}</div><div style={{fontSize:11, color:data.banner.kind==='warn'?'#B45309':T.primaryMid, marginTop:1}}>{data.banner.sub}</div></div>
            <span style={{fontSize:24, color:data.banner.kind==='warn'?T.warning:T.info, fontWeight:300}}>›</span>
          </div>
        )}

        {/* AI approvals (retail only) */}
        {perms.approveOrders && !isCedi && (
          <div onClick={()=>onNav('alertas')} style={{display:'flex', alignItems:'center', gap:12, background:T.infoLight, borderRadius:14, padding:14, marginBottom:16, border:`1px solid ${T.info}`, cursor:'pointer'}}>
            <span style={{fontSize:22}}>AI</span>
            <div style={{flex:1}}><div style={{fontSize:13, fontWeight:700, color:T.primaryDark}}>2 pedidos esperan tu aprobación</div><div style={{fontSize:11, color:T.primaryMid, marginTop:1}}>Generados esta mañana · Confianza 87%</div></div>
            <span style={{fontSize:24, color:T.info, fontWeight:300}}>›</span>
          </div>
        )}

        {!perms.kpis && <div style={{background:T.primaryLight, borderRadius:14, padding:14, marginBottom:16}}><div style={{fontSize:13, color:T.primaryDark, lineHeight:1.5}}>Usa las pestañas para consultar inventario, registrar canjes y buscar clientes.</div></div>}

        {/* Data-driven KPI sections — each bubble deep-links to its chart */}
        {perms.kpis && data.sections.map(sec=>(
          <React.Fragment key={sec.label}>
            <SectionLabel>{sec.label}</SectionLabel>
            <div style={{display:'flex', gap:12, marginBottom:20}}>
              {sec.cards.map(c=>{
                const metric = LABEL_TO_METRIC[c.label];
                return <KpiCard key={c.label} {...c} onClick={metric?()=>onNav('analitica', metric):undefined} />;
              })}
            </div>
          </React.Fragment>
        ))}

        <SectionLabel>Acciones rápidas</SectionLabel>
        <div style={{display:'flex', gap:10, marginBottom:20}}>
          {[
            ...(perms.approveOrders?[{icon:'◉', label:'Aprobar pedidos', go:'alertas', color:T.info}]:[]),
            {icon:'★', label:'Buscar cliente', go:'clientes', color:T.secondary},
            {icon:'▢', label:'Ver inventario', go:'almacen', color:T.primary},
            {icon:'↗', label:'Analítica', go:'analitica', color:T.success},
          ].map(a=>(
            <button key={a.label} onClick={()=>onNav(a.go)} style={{flex:1, background:T.surface, borderRadius:14, padding:14, display:'flex', flexDirection:'column', alignItems:'center', gap:6, border:`1.5px solid ${a.color}40`, cursor:'pointer', boxShadow:'0 1px 4px rgba(0,0,0,0.04)'}}>
              <span style={{fontSize:22}}>{a.icon}</span>
              <span style={{fontSize:10, fontWeight:700, color:a.color, textAlign:'center'}}>{a.label}</span>
            </button>
          ))}
        </div>

        {perms.kpis && !isCedi && <Card style={{marginBottom:16}}>
          <div style={{fontSize:11, fontWeight:700, color:T.fg2, letterSpacing:1, marginBottom:12}}>RESUMEN DEL TURNO</div>
          <div style={{display:'flex', flexWrap:'wrap', gap:10, marginBottom:14}}>
            {[['L. 47,850','Ventas'],['12','Miembros nuevos'],['7','Canjes entregados'],['2','Aprob. pendientes']].map(([v,l])=>(
              <div key={l} style={{flex:1, minWidth:'45%', background:T.bg, borderRadius:10, padding:10}}><div style={{fontSize:18, fontWeight:800, color:T.fg1, marginBottom:2}}>{v}</div><div style={{fontSize:10, color:T.fg3}}>{l}</div></div>
            ))}
          </div>
          <div style={{display:'flex', gap:8}}>
            <Btn variant="success" style={{flex:1, padding:'11px'}} onClick={()=>onToast('✆ Resumen enviado por WhatsApp')}>✆  WhatsApp</Btn>
            <Btn variant="primary" style={{flex:1, padding:'11px'}} onClick={()=>onToast('L Corte de caja registrado · cuadrado')}>L  Corte de caja</Btn>
          </div>
        </Card>}

        <div style={{display:'flex', alignItems:'center', gap:10, background:T.primaryLight, borderRadius:12, padding:12}}>
          <div style={{display:'flex', alignItems:'center', gap:5, background:T.primary, borderRadius:8, padding:'3px 8px'}}><span style={{width:6, height:6, borderRadius:3, background:T.success, display:'inline-block'}}></span><span style={{fontSize:11, fontWeight:700, color:'#fff'}}>Claude AI</span></div>
          <span style={{flex:1, fontSize:11, color:T.primaryDark}}>{data.ai}</span>
        </div>
      </div>
    </div>
  );
}
window.Dashboard = Dashboard;
