// ===== Dashboard =====
function Dashboard({ orders, user, onOpen, onNav }){
  const open = orders.filter(o => STATUSES[o.status].stage !== "salida");
  const entrada = orders.filter(o => STATUSES[o.status].stage === "entrada");
  const reparacion = orders.filter(o => STATUSES[o.status].stage === "reparacion" && o.status !== "listo");
  const listo = orders.filter(o => o.status === "listo");
  const entregadoMes = orders.filter(o => o.status === "entregado");
  const ingresos = orders.reduce((s,o)=> s + orderPaid(o), 0);
  const tech = getTech(user.techId);

  const stats = [
    { label:"Órdenes abiertas", value:open.length, icon:"orders", hue:256, sub:`${entrada.length} en entrada`, route:"orders" },
    { label:"En reparación", value:reparacion.length, icon:"tools", hue:256, sub:"en banco de trabajo" },
    { label:"Listas para entrega", value:listo.length, icon:"box", hue:155, sub:"esperan al cliente", emph:true },
    { label:"Ingresos cobrados", value:fmtMoney(ingresos), icon:"chart", hue:70, sub:"acumulado", money:true },
  ];

  const recent = [...orders].sort((a,b)=> new Date(b.createdAt)-new Date(a.createdAt)).slice(0,5);
  const week = [6,9,5,11,8,13,open.length];

  return (
    <div style={{ display:"flex", flexDirection:"column", gap:20, animation:"fadeUp .35s ease" }}>
      {/* greeting */}
      <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", flexWrap:"wrap", gap:14 }}>
        <div>
          <h2 style={{ fontSize:23, fontWeight:800, margin:0, letterSpacing:"-0.02em" }}>
            Hola, {user.name.split(" ")[0]} 👋
          </h2>
          <p style={{ fontSize:14.5, color:"var(--muted)", margin:"4px 0 0" }}>
            Tienes <strong style={{ color:"var(--ink)" }}>{entrada.length} equipos</strong> esperando diagnóstico y <strong style={{ color:"var(--st-listo)" }}>{listo.length} listos</strong> para entregar.
          </p>
        </div>
        <Btn icon="plus" size="md" onClick={()=>onNav("new")}>Nueva orden</Btn>
      </div>

      {/* stat cards */}
      <div style={{ display:"grid", gridTemplateColumns:"repeat(4, 1fr)", gap:16 }}>
        {stats.map(s=>(
          <Card key={s.label} pad={18} style={{ cursor:s.route?"pointer":"default", position:"relative", overflow:"hidden",
              borderColor: s.emph ? "oklch(0.85 0.07 155)" : "var(--line)" }}
            onClick={()=> s.route && onNav(s.route)}>
            <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between" }}>
              <div style={{ width:38, height:38, borderRadius:10, display:"flex", alignItems:"center", justifyContent:"center",
                background:`oklch(0.95 0.04 ${s.hue})`, color:`oklch(0.5 0.13 ${s.hue})` }}>
                <Icon name={s.icon} size={20} />
              </div>
              {s.route && <Icon name="arrowRight" size={16} style={{ color:"var(--faint)" }} />}
            </div>
            <div style={{ fontSize:30, fontWeight:800, marginTop:14, letterSpacing:"-0.02em" }} className={s.money?"mono":""}>{s.value}</div>
            <div style={{ fontSize:13.5, fontWeight:600, color:"var(--ink-2)", marginTop:2 }}>{s.label}</div>
            <div style={{ fontSize:12.5, color:"var(--faint)", marginTop:3 }}>{s.sub}</div>
          </Card>
        ))}
      </div>

      <div style={{ display:"grid", gridTemplateColumns:"1.5fr 1fr", gap:16 }}>
        {/* Recent orders */}
        <Card pad={0}>
          <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", padding:"16px 20px", borderBottom:"1px solid var(--line)" }}>
            <h3 style={{ fontSize:15.5, fontWeight:700, margin:0 }}>Órdenes recientes</h3>
            <button onClick={()=>onNav("orders")} style={{ border:"none", background:"transparent", color:"var(--accent-ink)", fontSize:13, fontWeight:600 }}>Ver todas →</button>
          </div>
          <div>
            {recent.map((o,i)=>{
              const c = getClient(o.clientId);
              return (
                <button key={o.id} onClick={()=>onOpen(o.id)}
                  style={{ display:"flex", alignItems:"center", gap:13, width:"100%", padding:"13px 20px", border:"none",
                    borderBottom: i<recent.length-1?"1px solid var(--line-2)":"none", background:"transparent", textAlign:"left", transition:"background .12s" }}
                  onMouseEnter={e=>e.currentTarget.style.background="var(--surface-2)"}
                  onMouseLeave={e=>e.currentTarget.style.background="transparent"}>
                  <DeviceGlyph type={o.device} size={40} />
                  <div style={{ minWidth:0, flex:1 }}>
                    <div style={{ display:"flex", alignItems:"center", gap:8 }}>
                      <span className="mono" style={{ fontSize:13, fontWeight:600, color:"var(--accent-ink)" }}>#{o.num}</span>
                      <span style={{ fontSize:14, fontWeight:700, whiteSpace:"nowrap", overflow:"hidden", textOverflow:"ellipsis" }}>{o.brand} {o.model}</span>
                    </div>
                    <div style={{ fontSize:12.5, color:"var(--muted)", marginTop:2 }}>{c.name} · {relTime(o.createdAt)}</div>
                  </div>
                  <StatusBadge status={o.status} size="sm" />
                </button>
              );
            })}
          </div>
        </Card>

        {/* side column */}
        <div style={{ display:"flex", flexDirection:"column", gap:16 }}>
          <Card pad={18}>
            <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", marginBottom:14 }}>
              <h3 style={{ fontSize:15, fontWeight:700, margin:0 }}>Ingresos esta semana</h3>
              <Icon name="chart" size={17} style={{ color:"var(--faint)" }} />
            </div>
            <Sparkbars values={week} h={56} />
            <div style={{ display:"flex", justifyContent:"space-between", marginTop:8, fontSize:11, color:"var(--faint)" }}>
              {["L","M","M","J","V","S","D"].map((d,i)=><span key={i}>{d}</span>)}
            </div>
          </Card>

          <Card pad={18}>
            <h3 style={{ fontSize:15, fontWeight:700, margin:"0 0 14px" }}>Carga por técnico</h3>
            <div style={{ display:"flex", flexDirection:"column", gap:12 }}>
              {TECHS.slice(0,3).map(t=>{
                const count = open.filter(o=>o.techId===t.id).length;
                const pct = Math.min(100, count*22);
                return (
                  <div key={t.id} style={{ display:"flex", alignItems:"center", gap:10 }}>
                    <Avatar name={t.name} initials={t.initials} hue={t.hue} size={30} />
                    <div style={{ flex:1, minWidth:0 }}>
                      <div style={{ display:"flex", justifyContent:"space-between", fontSize:13 }}>
                        <span style={{ fontWeight:600 }}>{t.name.split(" ")[0]} {t.name.split(" ")[1]?.[0]}.</span>
                        <span style={{ color:"var(--muted)", fontWeight:600 }}>{count}</span>
                      </div>
                      <div style={{ height:6, borderRadius:99, background:"var(--line-2)", marginTop:5, overflow:"hidden" }}>
                        <div style={{ width:`${pct}%`, height:"100%", borderRadius:99, background:`oklch(0.6 0.12 ${t.hue})`, transition:"width .4s" }} />
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Dashboard });
