// ===== Orders list with stage tabs + table =====
function Orders({ orders, query, setQuery, onOpen, onNav }){
  const [stage, setStage] = React.useState("entrada");
  const [prio, setPrio] = React.useState("todas");
  const [sort, setSort] = React.useState({ key:"num", dir:"desc" });

  const counts = {
    entrada: orders.filter(o=>STATUSES[o.status].stage==="entrada").length,
    reparacion: orders.filter(o=>STATUSES[o.status].stage==="reparacion").length,
    salida: orders.filter(o=>STATUSES[o.status].stage==="salida").length,
  };
  const tabs = [
    { id:"entrada", label:"Entrada", count:counts.entrada },
    { id:"reparacion", label:"Reparación", count:counts.reparacion },
    { id:"salida", label:"Salida", count:counts.salida },
  ];

  let rows = orders.filter(o => STATUSES[o.status].stage === stage);
  if(prio !== "todas") rows = rows.filter(o => o.priority === prio);
  if(query.trim()){
    const q = query.toLowerCase();
    rows = rows.filter(o => {
      const c = getClient(o.clientId);
      return [o.num, o.brand, o.model, o.serial, c.name].join(" ").toLowerCase().includes(q);
    });
  }
  rows = [...rows].sort((a,b)=>{
    let av, bv;
    if(sort.key==="num"){ av=+a.num; bv=+b.num; }
    else if(sort.key==="cliente"){ av=getClient(a.clientId).name; bv=getClient(b.clientId).name; }
    else if(sort.key==="precio"){ av=a.estimate; bv=b.estimate; }
    else { av=a[sort.key]; bv=b[sort.key]; }
    if(av<bv) return sort.dir==="asc"?-1:1;
    if(av>bv) return sort.dir==="asc"?1:-1;
    return 0;
  });

  function toggleSort(key){
    setSort(s => s.key===key ? { key, dir: s.dir==="asc"?"desc":"asc" } : { key, dir:"asc" });
  }

  const Th = ({ label, k, align="left", w }) => (
    <th style={{ textAlign:align, padding:"0 14px", width:w }}>
      <button onClick={()=>k&&toggleSort(k)} style={{ display:"inline-flex", alignItems:"center", gap:5, border:"none", background:"transparent",
        fontSize:11.5, fontWeight:700, letterSpacing:"0.04em", textTransform:"uppercase", color: sort.key===k?"var(--ink-2)":"var(--faint)", cursor:k?"pointer":"default" }}>
        {label}
        {k && <Icon name="chevronDown" size={13} style={{ opacity: sort.key===k?1:0.35, transform: sort.key===k&&sort.dir==="asc"?"rotate(180deg)":"none", transition:"transform .15s" }} />}
      </button>
    </th>
  );

  return (
    <div style={{ display:"flex", flexDirection:"column", gap:16, animation:"fadeUp .35s ease" }}>
      {/* mini status row */}
      <div style={{ display:"grid", gridTemplateColumns:"repeat(3,1fr)", gap:14 }}>
        {[
          { icon:"check", t:"Estado del taller", s:"¡Todo en orden!", hue:155 },
          { icon:"orders", t:"Órdenes abiertas", s:`${counts.entrada+counts.reparacion} abiertas`, hue:256 },
          { icon:"sms", t:"Notificaciones SMS", s:"0 créditos · Recargar", hue:70 },
        ].map(c=>(
          <Card key={c.t} pad={15} style={{ display:"flex", alignItems:"center", gap:13 }}>
            <div style={{ width:40, height:40, borderRadius:11, display:"flex", alignItems:"center", justifyContent:"center", background:`oklch(0.95 0.04 ${c.hue})`, color:`oklch(0.5 0.13 ${c.hue})` }}><Icon name={c.icon} size={20} /></div>
            <div>
              <div style={{ fontSize:14, fontWeight:700 }}>{c.t}</div>
              <div style={{ fontSize:13, color:"var(--muted)", marginTop:1 }}>{c.s}</div>
            </div>
          </Card>
        ))}
      </div>

      <Card pad={0}>
        {/* tabs */}
        <div style={{ display:"flex", alignItems:"center", gap:4, padding:"6px 8px", borderBottom:"1px solid var(--line)" }}>
          {tabs.map(t=>{
            const active = stage===t.id;
            return (
              <button key={t.id} onClick={()=>setStage(t.id)}
                style={{ display:"flex", alignItems:"center", gap:8, padding:"10px 16px", border:"none", background:"transparent",
                  borderRadius:9, fontSize:14, fontWeight: active?700:600, color: active?"var(--accent-ink)":"var(--muted)",
                  position:"relative", transition:"color .14s" }}>
                {t.label}
                <span style={{ minWidth:20, height:20, padding:"0 6px", borderRadius:99, fontSize:11.5, fontWeight:700,
                  display:"flex", alignItems:"center", justifyContent:"center",
                  background: active?"var(--accent-soft)":"var(--surface-2)", color: active?"var(--accent-ink)":"var(--muted)" }}>{t.count}</span>
                {active && <span style={{ position:"absolute", left:12, right:12, bottom:-7, height:3, borderRadius:99, background:"var(--accent)" }} />}
              </button>
            );
          })}
          <div style={{ marginLeft:"auto", display:"flex", alignItems:"center", gap:8, paddingRight:8 }}>
            <div style={{ position:"relative" }}>
              <select value={prio} onChange={e=>setPrio(e.target.value)}
                style={{ appearance:"none", padding:"8px 30px 8px 12px", fontSize:13, fontWeight:600, color:"var(--ink-2)", border:"1px solid var(--line)", borderRadius:9, background:"var(--surface)", cursor:"pointer" }}>
                <option value="todas">Toda prioridad</option>
                {Object.values(PRIORITIES).map(p=><option key={p.id} value={p.id}>{p.label}</option>)}
              </select>
              <Icon name="chevronDown" size={14} style={{ position:"absolute", right:10, top:"50%", transform:"translateY(-50%)", color:"var(--faint)", pointerEvents:"none" }} />
            </div>
            <IconBtn icon="refresh" title="Actualizar" />
          </div>
        </div>

        {/* count line */}
        <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", padding:"11px 20px", fontSize:13, color:"var(--muted)", borderBottom:"1px solid var(--line-2)" }}>
          <span>Cantidad: <strong style={{ color:"var(--ink)" }}>{rows.length}</strong> {rows.length===1?"orden":"órdenes"}{query&&<span> · filtrando "{query}"</span>}</span>
          <span style={{ display:"flex", alignItems:"center", gap:6 }}><Icon name="clock" size={15} /> Tiempo tareas: 0 min restantes</span>
        </div>

        {/* table */}
        <div style={{ overflowX:"auto" }}>
          <table style={{ width:"100%", borderCollapse:"collapse", minWidth:780 }}>
            <thead>
              <tr style={{ height:40, background:"var(--surface-2)" }}>
                <Th label="N°" k="num" w={92} />
                <Th label="Prioridad" k="priority" w={120} />
                <Th label="Estado" k="status" w={150} />
                <Th label="Equipo" k="model" />
                <Th label="Cliente" k="cliente" />
                <Th label="Responsable" w={150} />
                <Th label="Precio" k="precio" align="right" w={100} />
                <th style={{ width:110 }}></th>
              </tr>
            </thead>
            <tbody>
              {rows.length===0 && (
                <tr><td colSpan={8}>
                  <div style={{ padding:"54px 20px", textAlign:"center", color:"var(--faint)" }}>
                    <Icon name="orders" size={34} style={{ opacity:0.4 }} />
                    <div style={{ fontSize:14.5, fontWeight:600, color:"var(--muted)", marginTop:10 }}>Sin órdenes en esta etapa</div>
                    <div style={{ fontSize:13, marginTop:3 }}>Crea una nueva orden de ingreso para empezar.</div>
                  </div>
                </td></tr>
              )}
              {rows.map(o=>{
                const c = getClient(o.clientId); const t = getTech(o.techId);
                return (
                  <tr key={o.id} onClick={()=>onOpen(o.id)}
                    style={{ height:62, borderBottom:"1px solid var(--line-2)", cursor:"pointer", transition:"background .12s" }}
                    onMouseEnter={e=>e.currentTarget.style.background="var(--surface-2)"}
                    onMouseLeave={e=>e.currentTarget.style.background="transparent"}>
                    <td style={{ padding:"0 14px" }}>
                      <span style={{ display:"inline-flex", alignItems:"center", gap:7 }}>
                        <Icon name="tools" size={15} style={{ color:"var(--faint)" }} />
                        <span className="mono" style={{ fontSize:13.5, fontWeight:600, color:"var(--accent-ink)" }}>{o.num}</span>
                      </span>
                    </td>
                    <td style={{ padding:"0 14px" }}><PriorityTag priority={o.priority} /></td>
                    <td style={{ padding:"0 14px" }}><StatusBadge status={o.status} size="sm" /></td>
                    <td style={{ padding:"0 14px" }}>
                      <div style={{ display:"flex", alignItems:"center", gap:11 }}>
                        <DeviceGlyph type={o.device} size={36} />
                        <div style={{ minWidth:0 }}>
                          <div style={{ fontSize:14, fontWeight:700, whiteSpace:"nowrap" }}>{o.model}</div>
                          <div style={{ fontSize:12, color:"var(--muted)" }}>{o.brand} · {getDevice(o.device).label}</div>
                        </div>
                      </div>
                    </td>
                    <td style={{ padding:"0 14px" }}>
                      <div style={{ fontSize:13.5, fontWeight:600 }}>{c.name}</div>
                      <div style={{ fontSize:12, color:"var(--muted)" }} className="mono">{c.phone}</div>
                    </td>
                    <td style={{ padding:"0 14px" }}>
                      <div style={{ display:"flex", alignItems:"center", gap:8 }}>
                        <Avatar name={t?.name || o.responsible || "—"} initials={t?.initials} hue={t?.hue||256} size={28} />
                        <span style={{ fontSize:13, fontWeight:600, color:"var(--ink-2)" }}>{t ? t.name.split(" ")[0] : (o.responsible ? o.responsible.split(" ")[0] : "—")}</span>
                      </div>
                    </td>
                    <td style={{ padding:"0 14px", textAlign:"right" }}>
                      <span className="mono" style={{ fontSize:13.5, fontWeight:600, color: o.estimate>0?"var(--ink)":"var(--faint)" }}>{fmtMoney(o.estimate)}</span>
                    </td>
                    <td style={{ padding:"0 12px" }} onClick={e=>e.stopPropagation()}>
                      <div style={{ display:"flex", alignItems:"center", gap:2, justifyContent:"flex-end" }}>
                        <IconBtn icon="eye" size={16} title="Ver detalle" onClick={()=>onOpen(o.id)} />
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </Card>
    </div>
  );
}

Object.assign(window, { Orders });
