// ===== Order detail =====
function OrderDetail({ order, user, onBack, onUpdate, inventory, onConsumePart, onReturnPart, templates, onNotify }){
  const [diag, setDiag] = React.useState(order.diagnosis || "");
  const [editDiag, setEditDiag] = React.useState(false);
  const [showNotify, setShowNotify] = React.useState(false);
  const [doc, setDoc] = React.useState(null); // null | "ingreso" | "retiro"
  const [editEst, setEditEst] = React.useState(false);
  const [estVal, setEstVal] = React.useState(order.estimate || 0);
  const [showPay, setShowPay] = React.useState(false);
  const [showPart, setShowPart] = React.useState(false);
  const [showClose, setShowClose] = React.useState(false);
  const c = getClient(order.clientId);
  const t = getTech(order.techId);
  const dev = getDevice(order.device);
  const curIndex = FLOW.indexOf(order.status === "espera" ? "reparacion" : (order.status==="presupuesto"?"diagnostico":order.status));

  const payments = orderPayments(order);
  const paid = orderPaid(order);
  const balance = orderBalance(order);
  const parts = orderParts(order);
  const partsCost = orderPartsCost(order);
  const partsCharge = parts.reduce((s,p)=>s+(+p.price||0)*(+p.qty||1),0);
  const outcome = getOutcome(order.outcome);
  const canEdit = ROLES[user.roleId]?.perms.includes("advance") || ROLES[user.roleId]?.perms.includes("diagnosis");

  function log(o, text){ return { ...o, log:[...o.log, { t:new Date().toISOString(), who:user.name, text }] }; }

  function advance(){
    const idx = FLOW.indexOf(order.status==="espera"?"reparacion":(order.status==="presupuesto"?"diagnostico":order.status));
    const next = FLOW[Math.min(idx+1, FLOW.length-1)];
    if(next === order.status) return;
    onUpdate(log({ ...order, status:next }, `Estado cambiado a "${STATUSES[next].label}".`));
  }
  function setStatus(s){
    if(s===order.status) return;
    onUpdate(log({ ...order, status:s }, `Estado cambiado a "${STATUSES[s].label}".`));
  }
  function saveDiag(){
    onUpdate(log({ ...order, diagnosis:diag }, "Diagnóstico actualizado.")); setEditDiag(false);
  }
  function saveEst(){
    const v = +estVal || 0;
    onUpdate(log({ ...order, estimate:v }, `Presupuesto actualizado a ${fmtMoney(v)}.`)); setEditEst(false);
  }
  function addPayment(p){
    const next = [...payments, p];
    onUpdate(log({ ...order, payments:next, paid:undefined }, `Abono registrado: ${fmtMoney(p.amount)} (${p.method}).`));
    setShowPay(false);
  }
  function addPart(item, qty){
    const next = [...parts, { invId:item.id, name:item.name, sku:item.sku, qty, cost:item.cost, price:item.price }];
    onConsumePart(item.id, qty);
    onUpdate(log({ ...order, parts:next }, `Repuesto usado: ${qty}× ${item.name}.`));
    setShowPart(false);
  }
  function removePart(idx){
    const p = parts[idx];
    onReturnPart(p.invId, p.qty);
    const next = parts.filter((_,i)=>i!==idx);
    onUpdate(log({ ...order, parts:next }, `Repuesto devuelto al inventario: ${p.qty}× ${p.name}.`));
  }
  function setOutcome(oc){
    let o2 = log({ ...order, outcome:oc.id }, `Resultado registrado: "${oc.label}".`);
    // outcomes that close the order move to delivered-ready flow
    if(["reparado","sin_falla"].includes(oc.id) && order.status!=="entregado") o2 = { ...o2, status: o2.status==="entregado"?"entregado":"listo" };
    onUpdate(o2);
    setShowClose(false);
  }

  const isDone = order.status==="entregado";
  const nextLabel = isDone ? "Orden entregada" : `Avanzar a "${STATUSES[FLOW[Math.min(curIndex+1,FLOW.length-1)]].label}"`;
  const ocVars = outcome ? STATUS_VARS[outcome.color] : null;

  return (
    <div style={{ animation:"fadeUp .35s ease", maxWidth:1100 }}>
      <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", marginBottom:16, flexWrap:"wrap", gap:12 }}>
        <button onClick={onBack} style={{ display:"inline-flex", alignItems:"center", gap:6, border:"none", background:"transparent", color:"var(--muted)", fontSize:13.5, fontWeight:600, padding:0 }}>
          <Icon name="arrowLeft" size={16} /> Volver a órdenes
        </button>
        <div style={{ display:"flex", gap:8 }}>
          <Btn variant="secondary" size="sm" icon="print" onClick={()=>setDoc(isDone?"retiro":"ingreso")}>{isDone?"Comprobante de retiro":"Imprimir comprobante"}</Btn>
          <Btn variant="secondary" size="sm" icon="whatsapp" onClick={()=>setShowNotify(true)}>Avisar al cliente</Btn>
          {!isDone && <Btn size="sm" icon="arrowRight" onClick={advance}>{nextLabel}</Btn>}
        </div>
      </div>

      {/* header card */}
      <Card style={{ marginBottom:16 }}>
        <div style={{ display:"flex", alignItems:"center", gap:18, flexWrap:"wrap" }}>
          <div style={{ width:60, height:60, borderRadius:14, display:"flex", alignItems:"center", justifyContent:"center", background:"var(--surface-2)", border:"1px solid var(--line)", color:"var(--accent-ink)" }}>
            <Icon name={dev.icon} size={32} />
          </div>
          <div style={{ flex:1, minWidth:0 }}>
            <div style={{ display:"flex", alignItems:"center", gap:10, flexWrap:"wrap" }}>
              <span className="mono" style={{ fontSize:14, fontWeight:600, color:"var(--accent-ink)" }}>Orden #{order.num}</span>
              <StatusBadge status={order.status} />
              <PriorityTag priority={order.priority} />
              {outcome && (
                <span style={{ display:"inline-flex", alignItems:"center", gap:6, padding:"5px 11px", borderRadius:99, fontSize:12.5, fontWeight:600, color:ocVars.fg, background:ocVars.bg }}>
                  <Icon name={outcome.icon} size={14} /> {outcome.label}
                </span>
              )}
            </div>
            <h2 style={{ fontSize:22, fontWeight:800, margin:"6px 0 2px", letterSpacing:"-0.02em" }}>{order.brand} {order.model}</h2>
            <div style={{ fontSize:13, color:"var(--muted)" }}>{dev.label} · Ingresó {fmtDateTime(order.createdAt)}</div>
          </div>
          <div style={{ textAlign:"right" }}>
            <div style={{ fontSize:12.5, color:"var(--muted)" }}>Presupuesto</div>
            <div className="mono" style={{ fontSize:26, fontWeight:800, letterSpacing:"-0.02em" }}>{fmtMoney(order.estimate)}</div>
            {balance>0
              ? <div style={{ fontSize:12.5, color:"var(--st-entrada)", fontWeight:600 }}>Saldo {fmtMoney(balance)}</div>
              : (order.estimate>0 && <div style={{ fontSize:12.5, color:"var(--st-listo)", fontWeight:600 }}>Pagado completo</div>)}
          </div>
        </div>

        {/* stepper */}
        <div style={{ marginTop:22, paddingTop:20, borderTop:"1px solid var(--line)" }}>
          <div style={{ display:"flex", alignItems:"center" }}>
            {FLOW.map((s,i)=>{
              const done = i < curIndex, active = i === curIndex;
              return (
                <React.Fragment key={s}>
                  <button onClick={()=>setStatus(s)} style={{ display:"flex", flexDirection:"column", alignItems:"center", gap:7, border:"none", background:"transparent", cursor:"pointer", flexShrink:0 }}>
                    <div style={{ width:34, height:34, borderRadius:"50%", display:"flex", alignItems:"center", justifyContent:"center", fontSize:13, fontWeight:700,
                      background: done?"var(--accent)":active?"var(--accent-soft)":"var(--surface-2)",
                      color: done?"#fff":active?"var(--accent-ink)":"var(--faint)",
                      border:`2px solid ${done||active?"var(--accent)":"var(--line)"}`, transition:"all .2s" }}>
                      {done ? <Icon name="check" size={17} /> : i+1}
                    </div>
                    <span style={{ fontSize:12, fontWeight: active?700:600, color: active?"var(--ink)":done?"var(--ink-2)":"var(--faint)", whiteSpace:"nowrap" }}>{STATUSES[s].label}</span>
                  </button>
                  {i<FLOW.length-1 && (
                    <div style={{ flex:1, height:2, margin:"0 6px", marginBottom:22, borderRadius:99, background: i<curIndex?"var(--accent)":"var(--line)", transition:"background .3s" }} />
                  )}
                </React.Fragment>
              );
            })}
          </div>
          {order.status==="espera" && (
            <div style={{ display:"inline-flex", alignItems:"center", gap:7, marginTop:14, padding:"7px 12px", borderRadius:8, background:"var(--st-entrada-soft)", color:"var(--st-entrada)", fontSize:12.5, fontWeight:600 }}>
              <Icon name="clock" size={15} /> En espera de repuesto
            </div>
          )}
        </div>
      </Card>

      <div style={{ display:"grid", gridTemplateColumns:"1.6fr 1fr", gap:16, alignItems:"start" }}>
        {/* left */}
        <div style={{ display:"flex", flexDirection:"column", gap:16 }}>
          <Card>
            <h3 style={{ fontSize:15, fontWeight:700, margin:"0 0 12px" }}>Falla reportada</h3>
            <p style={{ fontSize:14, lineHeight:1.6, color:"var(--ink-2)", margin:0 }}>{order.issue}</p>
          </Card>

          <Card>
            <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", marginBottom:12 }}>
              <h3 style={{ fontSize:15, fontWeight:700, margin:0 }}>Diagnóstico técnico</h3>
              {!editDiag && <button onClick={()=>setEditDiag(true)} style={{ display:"inline-flex", alignItems:"center", gap:5, border:"none", background:"transparent", color:"var(--accent-ink)", fontSize:13, fontWeight:600 }}><Icon name="edit" size={15} /> Editar</button>}
            </div>
            {editDiag ? (
              <div>
                <textarea value={diag} onChange={e=>setDiag(e.target.value)} rows={4} autoFocus
                  style={{ ...inputStyle, resize:"vertical", lineHeight:1.5 }} placeholder="Describe el diagnóstico y la reparación a realizar…" />
                <div style={{ display:"flex", gap:8, marginTop:10, justifyContent:"flex-end" }}>
                  <Btn variant="ghost" size="sm" onClick={()=>{setDiag(order.diagnosis||"");setEditDiag(false);}}>Cancelar</Btn>
                  <Btn size="sm" icon="check" onClick={saveDiag}>Guardar</Btn>
                </div>
              </div>
            ) : (
              <p style={{ fontSize:14, lineHeight:1.6, color: order.diagnosis?"var(--ink-2)":"var(--faint)", margin:0, fontStyle: order.diagnosis?"normal":"italic" }}>
                {order.diagnosis || "Aún sin diagnóstico. Haz clic en Editar para agregarlo."}
              </p>
            )}
          </Card>

          {/* parts / repuestos */}
          <Card>
            <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", marginBottom:14 }}>
              <h3 style={{ fontSize:15, fontWeight:700, margin:0 }}>Repuestos usados</h3>
              <button onClick={()=>setShowPart(true)} style={{ display:"inline-flex", alignItems:"center", gap:5, border:"none", background:"transparent", color:"var(--accent-ink)", fontSize:13, fontWeight:600 }}><Icon name="plus" size={15} /> Agregar repuesto</button>
            </div>
            {parts.length===0 ? (
              <p style={{ fontSize:13.5, color:"var(--faint)", margin:0, fontStyle:"italic" }}>Aún no se han descontado repuestos del inventario para esta orden.</p>
            ) : (
              <div>
                {parts.map((p,i)=>(
                  <div key={i} style={{ display:"flex", alignItems:"center", gap:12, padding:"10px 0", borderBottom: i<parts.length-1?"1px solid var(--line-2)":"none" }}>
                    <span style={{ width:32, height:32, borderRadius:8, background:"var(--surface-2)", border:"1px solid var(--line)", display:"flex", alignItems:"center", justifyContent:"center", color:"var(--muted)", flexShrink:0 }}><Icon name="chip" size={16} /></span>
                    <div style={{ flex:1, minWidth:0 }}>
                      <div style={{ fontSize:13.5, fontWeight:600 }}>{p.name}</div>
                      <div style={{ fontSize:12, color:"var(--muted)" }}><span className="mono">{p.sku}</span> · {p.qty} und · costo {fmtMoney(p.cost)}</div>
                    </div>
                    <span className="mono" style={{ fontSize:13.5, fontWeight:700 }}>{fmtMoney((p.price||0)*p.qty)}</span>
                    {!isDone && <IconBtn icon="trash" size={15} title="Devolver al inventario" onClick={()=>removePart(i)} />}
                  </div>
                ))}
                <div style={{ display:"flex", justifyContent:"space-between", marginTop:12, paddingTop:12, borderTop:"1px solid var(--line)", fontSize:13 }}>
                  <span style={{ color:"var(--muted)" }}>Costo de repuestos (interno): <strong className="mono" style={{ color:"var(--ink-2)" }}>{fmtMoney(partsCost)}</strong></span>
                  <span style={{ color:"var(--muted)" }}>Cobrado en repuestos: <strong className="mono" style={{ color:"var(--ink)" }}>{fmtMoney(partsCharge)}</strong></span>
                </div>
              </div>
            )}
          </Card>

          {/* activity log */}
          <Card>
            <h3 style={{ fontSize:15, fontWeight:700, margin:"0 0 16px" }}>Bitácora de la orden</h3>
            <div style={{ position:"relative", paddingLeft:8 }}>
              {[...order.log].reverse().map((l,i,arr)=>(
                <div key={i} style={{ display:"flex", gap:13, position:"relative", paddingBottom: i<arr.length-1?18:0 }}>
                  <div style={{ display:"flex", flexDirection:"column", alignItems:"center", flexShrink:0 }}>
                    <div style={{ width:11, height:11, borderRadius:"50%", background: i===0?"var(--accent)":"var(--surface)", border:`2px solid ${i===0?"var(--accent)":"var(--line)"}`, marginTop:3, zIndex:1 }} />
                    {i<arr.length-1 && <div style={{ width:2, flex:1, background:"var(--line)", marginTop:2 }} />}
                  </div>
                  <div style={{ paddingBottom:2 }}>
                    <div style={{ fontSize:13.5, color:"var(--ink-2)", lineHeight:1.45 }}>{l.text}</div>
                    <div style={{ fontSize:12, color:"var(--faint)", marginTop:2 }}>{l.who} · {fmtDateTime(l.t)}</div>
                  </div>
                </div>
              ))}
            </div>
          </Card>
        </div>

        {/* right */}
        <div style={{ display:"flex", flexDirection:"column", gap:16 }}>
          {/* COBRO */}
          <Card style={{ borderColor:"oklch(0.9 0.04 256)" }}>
            <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", marginBottom:14 }}>
              <h3 style={{ fontSize:15, fontWeight:700, margin:0 }}>Cobro y presupuesto</h3>
              {!editEst && !isDone && <button onClick={()=>{setEstVal(order.estimate||0);setEditEst(true);}} style={{ display:"inline-flex", alignItems:"center", gap:5, border:"none", background:"transparent", color:"var(--accent-ink)", fontSize:13, fontWeight:600 }}><Icon name="edit" size={15} /> Editar</button>}
            </div>

            {editEst ? (
              <div style={{ marginBottom:14 }}>
                <Field label="Presupuesto estimado (US$)">
                  <TextInput type="number" min="0" value={estVal} autoFocus onChange={e=>setEstVal(e.target.value)} style={{ fontFamily:"var(--mono)" }} />
                </Field>
                <div style={{ display:"flex", gap:8, marginTop:10, justifyContent:"flex-end" }}>
                  <Btn variant="ghost" size="sm" onClick={()=>setEditEst(false)}>Cancelar</Btn>
                  <Btn size="sm" icon="check" onClick={saveEst}>Guardar</Btn>
                </div>
              </div>
            ) : (
              <div style={{ display:"flex", flexDirection:"column", gap:9, marginBottom:14 }}>
                <CobroRow label="Presupuesto" value={fmtMoney(order.estimate)} />
                <CobroRow label="Abonado" value={fmtMoney(paid)} tone="listo" />
                <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", paddingTop:9, borderTop:"1px solid var(--line)" }}>
                  <span style={{ fontSize:13.5, fontWeight:700 }}>Saldo pendiente</span>
                  <span className="mono" style={{ fontSize:18, fontWeight:800, color: balance>0?"var(--st-entrada)":"var(--st-listo)" }}>{fmtMoney(balance)}</span>
                </div>
              </div>
            )}

            {/* payments list */}
            {payments.length>0 && (
              <div style={{ marginBottom:12 }}>
                {payments.map((p,i)=>(
                  <div key={i} style={{ display:"flex", alignItems:"center", gap:8, padding:"6px 0", fontSize:12.5 }}>
                    <Icon name="check" size={14} style={{ color:"var(--st-listo)" }} />
                    <span style={{ flex:1, color:"var(--ink-2)" }}>{p.method} · {fmtDate(p.t)}</span>
                    <span className="mono" style={{ fontWeight:600 }}>{fmtMoney(p.amount)}</span>
                  </div>
                ))}
              </div>
            )}

            {!isDone && <Btn variant="soft" size="sm" icon="plus" style={{ width:"100%" }} onClick={()=>setShowPay(true)}>Registrar abono / pago</Btn>}
          </Card>

          {/* RESULTADO */}
          <Card>
            <h3 style={{ fontSize:15, fontWeight:700, margin:"0 0 6px" }}>Resultado de la reparación</h3>
            <p style={{ fontSize:12.5, color:"var(--muted)", margin:"0 0 12px" }}>Define el desenlace del equipo.</p>
            {outcome ? (
              <div style={{ display:"flex", alignItems:"center", gap:11, padding:"12px", borderRadius:10, background:ocVars.bg }}>
                <span style={{ width:34, height:34, borderRadius:9, background:"var(--surface)", display:"flex", alignItems:"center", justifyContent:"center", color:ocVars.fg, flexShrink:0 }}><Icon name={outcome.icon} size={18} /></span>
                <div style={{ flex:1 }}>
                  <div style={{ fontSize:14, fontWeight:700, color:ocVars.fg }}>{outcome.label}</div>
                  <div style={{ fontSize:12, color:"var(--ink-2)" }}>{outcome.desc}</div>
                </div>
                {!isDone && <button onClick={()=>setShowClose(true)} style={{ border:"none", background:"transparent", color:"var(--accent-ink)", fontSize:12.5, fontWeight:600 }}>Cambiar</button>}
              </div>
            ) : (
              <Btn variant="secondary" size="sm" icon="check" style={{ width:"100%" }} onClick={()=>setShowClose(true)}>Registrar resultado</Btn>
            )}
          </Card>

          <Card>
            <h3 style={{ fontSize:15, fontWeight:700, margin:"0 0 14px" }}>Cliente</h3>
            <div style={{ display:"flex", alignItems:"center", gap:12, marginBottom:14 }}>
              <Avatar name={c.name} hue={256} size={44} />
              <div style={{ minWidth:0 }}>
                <div style={{ fontSize:15, fontWeight:700 }}>{c.name}</div>
                <div style={{ fontSize:12.5, color:"var(--muted)" }}>{c.orders} órdenes en total</div>
              </div>
            </div>
            <InfoRow icon="phone" label="Teléfono" value={c.phone} mono />
            <InfoRow icon="sms" label="Correo" value={c.email} />
          </Card>

          <Card>
            <h3 style={{ fontSize:15, fontWeight:700, margin:"0 0 14px" }}>Equipo</h3>
            <InfoRow icon="device" label="Tipo" value={dev.label} />
            <InfoRow icon="box" label="Marca / Modelo" value={`${order.brand} ${order.model}`} />
            <InfoRow icon="chip" label="Serie / IMEI" value={order.serial||"—"} mono />
            <div style={{ display:"flex", alignItems:"flex-start", gap:11, padding:"7px 0" }}>
              <span style={{ color:"var(--faint)", marginTop:2 }}><Icon name="settings" size={17} /></span>
              <span style={{ fontSize:13, color:"var(--muted)", width:96, flexShrink:0, marginTop:3 }}>Bloqueo</span>
              <div style={{ marginLeft:"auto" }}><UnlockSummary unlock={order.unlock} /></div>
            </div>
            {order.accessories?.length>0 && (
              <div style={{ marginTop:12, paddingTop:12, borderTop:"1px solid var(--line-2)" }}>
                <div style={{ fontSize:12.5, fontWeight:600, color:"var(--muted)", marginBottom:8 }}>Accesorios entregados</div>
                <div style={{ display:"flex", flexWrap:"wrap", gap:6 }}>
                  {order.accessories.map(a=><span key={a} style={{ padding:"4px 10px", borderRadius:99, background:"var(--surface-2)", border:"1px solid var(--line)", fontSize:12, fontWeight:600, color:"var(--ink-2)" }}>{a}</span>)}
                </div>
              </div>
            )}
          </Card>

          {order.photos && Object.keys(order.photos).length>0 && (
            <Card>
              <h3 style={{ fontSize:15, fontWeight:700, margin:"0 0 14px" }}>Fotos del equipo</h3>
              <div style={{ display:"grid", gridTemplateColumns:"repeat(2,1fr)", gap:10 }}>
                {Object.entries(order.photos).map(([label,src])=>(
                  <a key={label} href={src} target="_blank" rel="noopener" style={{ position:"relative", height:96, borderRadius:10, overflow:"hidden", border:"1px solid var(--line)", display:"block" }}>
                    <img src={src} alt={label} style={{ width:"100%", height:"100%", objectFit:"cover", display:"block" }} />
                    <div style={{ position:"absolute", left:0, right:0, bottom:0, padding:"3px 8px", fontSize:11, fontWeight:600, color:"#fff", background:"linear-gradient(transparent, oklch(0.2 0.03 262 / 0.7))" }}>{label}</div>
                  </a>
                ))}
              </div>
            </Card>
          )}

          <Card>
            <h3 style={{ fontSize:15, fontWeight:700, margin:"0 0 14px" }}>Responsable</h3>
            <div style={{ display:"flex", alignItems:"center", gap:12 }}>
              <Avatar name={t?.name || order.responsible || "—"} initials={t?.initials} hue={t?.hue||256} size={42} />
              <div>
                <div style={{ fontSize:14.5, fontWeight:700 }}>{t?.name || order.responsible || "Sin asignar"}</div>
                <div style={{ fontSize:12.5, color:"var(--muted)" }}>{t?.role || (order.responsible ? "Responsable (Gestioo)" : "")}</div>
              </div>
            </div>
          </Card>

          <Card>
            <h3 style={{ fontSize:15, fontWeight:700, margin:"0 0 4px" }}>Acceso rápido (QR)</h3>
            <p style={{ fontSize:12.5, color:"var(--muted)", margin:"0 0 14px", lineHeight:1.5 }}>Escanea con la app Casepoint para abrir esta orden en el celular.</p>
            <div style={{ display:"flex", alignItems:"center", gap:14 }}>
              <div style={{ padding:8, borderRadius:10, border:"1px solid var(--line)", background:"#fff", flexShrink:0 }}>
                <QRCode text={orderUrl(order)} size={104} cell={4} />
              </div>
              <div style={{ minWidth:0 }}>
                <div style={{ fontSize:12, color:"var(--muted)", marginBottom:3 }}>Enlace de la orden</div>
                <div className="mono" style={{ fontSize:11.5, color:"var(--accent-ink)", wordBreak:"break-all", lineHeight:1.4 }}>{orderUrl(order)}</div>
              </div>
            </div>
          </Card>
        </div>
      </div>

      {showPay && <PaymentModal balance={balance} user={user} onSave={addPayment} onClose={()=>setShowPay(false)} />}
      {showPart && <PartPicker inventory={inventory} onPick={addPart} onClose={()=>setShowPart(false)} />}
      {showClose && <OutcomeModal current={order.outcome} onPick={setOutcome} onClose={()=>setShowClose(false)} />}
      {showNotify && <NotifyModal order={order} templates={templates} onSend={(n)=>{ onNotify(n); setShowNotify(false); }} onClose={()=>setShowNotify(false)} />}
      {doc && <DocModal order={order} kind={doc} onClose={()=>setDoc(null)} />}
    </div>
  );
}

function CobroRow({ label, value, tone }){
  return (
    <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center" }}>
      <span style={{ fontSize:13.5, color:"var(--muted)" }}>{label}</span>
      <span className="mono" style={{ fontSize:14, fontWeight:600, color: tone==="listo"?"var(--st-listo)":"var(--ink)" }}>{value}</span>
    </div>
  );
}

function InfoRow({ icon, label, value, mono }){
  return (
    <div style={{ display:"flex", alignItems:"center", gap:11, padding:"7px 0" }}>
      <span style={{ color:"var(--faint)" }}><Icon name={icon} size={17} /></span>
      <span style={{ fontSize:13, color:"var(--muted)", width:96, flexShrink:0 }}>{label}</span>
      <span className={mono?"mono":""} style={{ fontSize:13.5, fontWeight:600, color:"var(--ink)", textAlign:"right", marginLeft:"auto", wordBreak:"break-word" }}>{value}</span>
    </div>
  );
}

// ===== Modals =====
function ModalShell({ title, onClose, children, maxWidth=440 }){
  return (
    <div onClick={onClose} style={{ position:"fixed", inset:0, zIndex:90, background:"oklch(0.2 0.03 262 / 0.42)", display:"flex", alignItems:"center", justifyContent:"center", padding:24, animation:"fadeIn .15s ease" }}>
      <div onClick={e=>e.stopPropagation()} style={{ width:"100%", maxWidth, background:"var(--surface)", borderRadius:16, boxShadow:"var(--shadow-lg)", animation:"popIn .18s ease", overflow:"hidden" }}>
        <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", padding:"18px 22px", borderBottom:"1px solid var(--line)" }}>
          <h3 style={{ fontSize:17, fontWeight:800, margin:0 }}>{title}</h3>
          <IconBtn icon="x" size={18} onClick={onClose} />
        </div>
        {children}
      </div>
    </div>
  );
}

function PaymentModal({ balance, user, onSave, onClose }){
  const [amount, setAmount] = React.useState(balance>0 ? String(balance) : "");
  const [method, setMethod] = React.useState("efectivo");
  const METHODS = [["efectivo","Efectivo"],["tarjeta","Tarjeta"],["transferencia","Transferencia"]];
  const valid = +amount > 0;
  return (
    <ModalShell title="Registrar abono / pago" onClose={onClose}>
      <div style={{ padding:"20px 22px", display:"flex", flexDirection:"column", gap:15 }}>
        {balance>0 && <div style={{ fontSize:13, color:"var(--muted)" }}>Saldo pendiente: <strong className="mono" style={{ color:"var(--st-entrada)" }}>{fmtMoney(balance)}</strong></div>}
        <Field label="Monto recibido (US$)" required>
          <TextInput type="number" min="0" value={amount} autoFocus onChange={e=>setAmount(e.target.value)} style={{ fontFamily:"var(--mono)", fontSize:18 }} />
        </Field>
        <Field label="Método de pago">
          <div style={{ display:"flex", gap:8 }}>
            {METHODS.map(([id,l])=>(
              <button key={id} onClick={()=>setMethod(id)} style={{ flex:1, padding:"9px", borderRadius:9, fontSize:13, fontWeight:600, cursor:"pointer",
                border:`1px solid ${method===id?"var(--accent)":"var(--line)"}`, background: method===id?"var(--accent-soft)":"var(--surface)", color: method===id?"var(--accent-ink)":"var(--ink-2)" }}>{l}</button>
            ))}
          </div>
        </Field>
      </div>
      <div style={{ display:"flex", justifyContent:"flex-end", gap:10, padding:"16px 22px", borderTop:"1px solid var(--line)" }}>
        <Btn variant="secondary" onClick={onClose}>Cancelar</Btn>
        <Btn icon="check" disabled={!valid} onClick={()=>onSave({ t:new Date().toISOString(), amount:+amount, method, who:user.name })}>Registrar pago</Btn>
      </div>
    </ModalShell>
  );
}

function PartPicker({ inventory, onPick, onClose }){
  const [q, setQ] = React.useState("");
  const [sel, setSel] = React.useState(null);
  const [qty, setQty] = React.useState(1);
  const list = inventory.filter(it => !q || (it.name+it.sku).toLowerCase().includes(q.toLowerCase()));
  return (
    <ModalShell title="Usar repuesto del inventario" onClose={onClose} maxWidth={500}>
      <div style={{ padding:"18px 22px" }}>
        <div style={{ position:"relative", marginBottom:12 }}>
          <span style={{ position:"absolute", left:12, top:"50%", transform:"translateY(-50%)", color:"var(--faint)" }}><Icon name="search" size={17} /></span>
          <TextInput value={q} autoFocus onChange={e=>setQ(e.target.value)} placeholder="Buscar repuesto o SKU…" style={{ paddingLeft:37 }} />
        </div>
        <div style={{ display:"flex", flexDirection:"column", gap:7, maxHeight:300, overflowY:"auto" }}>
          {list.map(it=>{
            const out = it.stock<=0; const active = sel?.id===it.id;
            return (
              <button key={it.id} disabled={out} onClick={()=>{setSel(it);setQty(1);}}
                style={{ display:"flex", alignItems:"center", gap:11, padding:"10px 12px", borderRadius:10, textAlign:"left", cursor:out?"not-allowed":"pointer", opacity:out?0.5:1,
                  border:`1px solid ${active?"var(--accent)":"var(--line)"}`, background: active?"var(--accent-soft)":"var(--surface)" }}>
                <span style={{ width:34, height:34, borderRadius:8, background:"var(--surface-2)", border:"1px solid var(--line)", display:"flex", alignItems:"center", justifyContent:"center", color:"var(--muted)", flexShrink:0 }}><Icon name={getInvCat(it.cat).icon} size={17} /></span>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontSize:13.5, fontWeight:600 }}>{it.name}</div>
                  <div style={{ fontSize:12, color:"var(--muted)" }}><span className="mono">{it.sku}</span> · {out?"Sin stock":`${it.stock} en stock`}</div>
                </div>
                <span className="mono" style={{ fontSize:13, fontWeight:600 }}>{fmtMoney(it.price)}</span>
              </button>
            );
          })}
        </div>
        {sel && (
          <div style={{ display:"flex", alignItems:"flex-end", gap:12, marginTop:14, paddingTop:14, borderTop:"1px solid var(--line)" }}>
            <Field label="Cantidad" style={{ width:110 }}>
              <div style={{ display:"flex", alignItems:"center", gap:0, border:"1px solid var(--line)", borderRadius:9, overflow:"hidden" }}>
                <button onClick={()=>setQty(q=>Math.max(1,q-1))} style={{ width:34, height:38, border:"none", background:"var(--surface-2)", fontSize:18, color:"var(--ink-2)" }}>−</button>
                <span className="mono" style={{ flex:1, textAlign:"center", fontWeight:700 }}>{qty}</span>
                <button onClick={()=>setQty(q=>Math.min(sel.stock,q+1))} style={{ width:34, height:38, border:"none", background:"var(--surface-2)", fontSize:18, color:"var(--ink-2)" }}>+</button>
              </div>
            </Field>
            <Btn icon="check" style={{ flex:1 }} onClick={()=>onPick(sel, qty)}>Descontar del inventario</Btn>
          </div>
        )}
      </div>
    </ModalShell>
  );
}

function OutcomeModal({ current, onPick, onClose }){
  return (
    <ModalShell title="Resultado de la reparación" onClose={onClose} maxWidth={480}>
      <div style={{ padding:"18px 22px", display:"flex", flexDirection:"column", gap:9 }}>
        {Object.values(OUTCOMES).map(oc=>{
          const v = STATUS_VARS[oc.color]; const active = current===oc.id;
          return (
            <button key={oc.id} onClick={()=>onPick(oc)}
              style={{ display:"flex", alignItems:"center", gap:12, padding:"12px 14px", borderRadius:11, textAlign:"left", cursor:"pointer",
                border:`1.5px solid ${active?v.fg:"var(--line)"}`, background: active?v.bg:"var(--surface)" }}>
              <span style={{ width:36, height:36, borderRadius:9, background:v.bg, color:v.fg, display:"flex", alignItems:"center", justifyContent:"center", flexShrink:0 }}><Icon name={oc.icon} size={19} /></span>
              <div style={{ flex:1 }}>
                <div style={{ fontSize:14, fontWeight:700 }}>{oc.label}</div>
                <div style={{ fontSize:12.5, color:"var(--muted)" }}>{oc.desc}</div>
              </div>
              {active && <Icon name="check" size={18} style={{ color:v.fg }} />}
            </button>
          );
        })}
      </div>
    </ModalShell>
  );
}

Object.assign(window, { OrderDetail, InfoRow, CobroRow, ModalShell, PaymentModal, PartPicker, OutcomeModal });
