// ===== Punto de Venta (POS) =====
function POS({ inventory, sales, onCheckout, onSaveClient, clientsTick, currentUser, onVoidSale, onDeleteSale, onUpdateSaleClient, onViewInvoice }){
  const [view, setView] = React.useState("registrar"); // registrar | historial
  const [cart, setCart] = React.useState([]); // [{id, sku, name, price, cost, qty, stock}]
  const [scan, setScan] = React.useState("");
  const [flash, setFlash] = React.useState(null); // {type, msg}
  const [cat, setCat] = React.useState("todos");
  const [method, setMethod] = React.useState("efectivo");
  const [client, setClient] = React.useState(null); // {id?, name, cedula, phone, email}
  const [showClient, setShowClient] = React.useState(false);
  const scanRef = React.useRef(null);

  // sellable = has a price
  const sellable = inventory.filter(i => i.price > 0);
  const cats = [{ id:"todos", label:"Todos" }, ...INV_CATEGORIES.filter(c => sellable.some(i=>i.cat===c.id))];
  let grid = cat==="todos" ? sellable : sellable.filter(i=>i.cat===cat);

  React.useEffect(()=>{ scanRef.current && scanRef.current.focus(); }, []);

  function flashMsg(type, msg){ setFlash({ type, msg }); setTimeout(()=>setFlash(null), 1800); }

  function addItem(item){
    if(item.price<=0) return;
    setCart(prev=>{
      const ex = prev.find(c=>c.id===item.id);
      const inCart = ex ? ex.qty : 0;
      if(inCart+1 > item.stock){ flashMsg("warn", `Sin stock suficiente de ${item.name}`); return prev; }
      if(ex) return prev.map(c=>c.id===item.id?{...c, qty:c.qty+1}:c);
      return [...prev, { id:item.id, sku:item.sku, name:item.name, price:item.price, cost:item.cost, qty:1, stock:item.stock }];
    });
  }
  function onScan(e){
    e.preventDefault();
    const code = scan.trim();
    if(!code) return;
    const item = inventory.find(i => (i.barcode && i.barcode===code) || i.sku.toLowerCase()===code.toLowerCase());
    if(!item){ flashMsg("warn", `Código "${code}" no encontrado`); setScan(""); return; }
    if(item.price<=0){ flashMsg("warn", `${item.name} no está a la venta`); setScan(""); return; }
    addItem(item); flashMsg("ok", `Agregado: ${item.name}`); setScan("");
  }
  function setQty(id, q){
    setCart(prev=>prev.map(c=>{
      if(c.id!==id) return c;
      const nq = Math.max(1, Math.min(c.stock, q));
      return { ...c, qty:nq };
    }));
  }
  function removeItem(id){ setCart(prev=>prev.filter(c=>c.id!==id)); }

  const subtotal = cart.reduce((s,c)=>s+c.price*c.qty,0);
  const itemCount = cart.reduce((s,c)=>s+c.qty,0);

  function checkout(){
    if(cart.length===0) return;
    const num = String(1004 + sales.length + 1);
    // persist client to the database (new or existing-updated)
    let cl = client;
    if(cl && !cl.id && (cl.name || cl.cedula || cl.phone || cl.email)){
      cl = onSaveClient(cl);
    }
    const sale = {
      id:"v"+num, num, date:new Date().toISOString(), method,
      clientId: cl?.id || null,
      clientName: cl?.name || "Cliente de mostrador",
      clientCedula: cl?.cedula || "", clientPhone: cl?.phone || "", clientEmail: cl?.email || "",
      items: cart.map(c=>({ sku:c.sku, name:c.name, qty:c.qty, price:c.price, cost:c.cost })),
      total: subtotal, cashier: currentUser.name,
    };
    onCheckout(sale);
    setCart([]); setClient(null); setMethod("efectivo");
    scanRef.current && scanRef.current.focus();
  }

  return (
    <div style={{ animation:"fadeUp .35s ease" }}>
      {/* view switch */}
      <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", marginBottom:16, flexWrap:"wrap", gap:12 }}>
        <div style={{ display:"flex", gap:4, background:"var(--surface-2)", padding:4, borderRadius:11, border:"1px solid var(--line)" }}>
          {[["registrar","Registrar venta","wallet"],["historial","Historial de ventas","orders"]].map(([id,l,ic])=>(
            <button key={id} onClick={()=>setView(id)}
              style={{ display:"inline-flex", alignItems:"center", gap:7, padding:"8px 16px", borderRadius:8, border:"none", fontSize:13.5, fontWeight:600, cursor:"pointer",
                background: view===id?"var(--surface)":"transparent", color: view===id?"var(--ink)":"var(--muted)", boxShadow: view===id?"var(--shadow-sm)":"none" }}>
              <Icon name={ic} size={16} /> {l}
            </button>
          ))}
        </div>
        {view==="historial" && <span style={{ fontSize:13, color:"var(--muted)" }}>{sales.filter(s=>!s.voided).length} ventas activas</span>}
      </div>

      {view==="historial" ? (
        <SalesHistory sales={sales} currentUser={currentUser} onVoidSale={onVoidSale} onDeleteSale={onDeleteSale} onUpdateSaleClient={onUpdateSaleClient} onViewInvoice={onViewInvoice} />
      ) : (
      <div style={{ display:"grid", gridTemplateColumns:"1fr 380px", gap:16, alignItems:"start" }}>
      {/* left: scan + catalog */}
      <div style={{ display:"flex", flexDirection:"column", gap:16 }}>
        <Card pad={16}>
          <form onSubmit={onScan} style={{ display:"flex", gap:10, alignItems:"center" }}>
            <div style={{ position:"relative", flex:1 }}>
              <span style={{ position:"absolute", left:13, top:"50%", transform:"translateY(-50%)", color:"var(--accent)" }}><Icon name="chip" size={20} /></span>
              <input ref={scanRef} value={scan} onChange={e=>setScan(e.target.value)}
                placeholder="Escanea el código de barras o escribe el SKU y pulsa Enter…"
                style={{ width:"100%", padding:"13px 14px 13px 42px", fontSize:15, fontFamily:"var(--mono)", borderRadius:11, border:"2px solid var(--accent)", background:"var(--accent-soft)", outline:"none", color:"var(--ink)" }} />
            </div>
            <Btn type="submit" size="lg" icon="plus">Agregar</Btn>
          </form>
          {flash && (
            <div style={{ display:"flex", alignItems:"center", gap:8, marginTop:11, padding:"8px 12px", borderRadius:9, fontSize:13, fontWeight:600,
              background: flash.type==="ok"?"var(--st-listo-soft)":"var(--st-entrada-soft)", color: flash.type==="ok"?"var(--st-listo)":"var(--st-entrada)" }}>
              <Icon name={flash.type==="ok"?"check":"warning"} size={15} /> {flash.msg}
            </div>
          )}
          <div style={{ fontSize:12, color:"var(--faint)", marginTop:10, display:"flex", alignItems:"center", gap:6 }}>
            <Icon name="warning" size={13} /> Funciona con lector USB (actúa como teclado) o haz clic en un producto abajo.
          </div>
        </Card>

        <Card pad={0}>
          <div style={{ display:"flex", gap:7, padding:"14px 16px", flexWrap:"wrap", borderBottom:"1px solid var(--line)" }}>
            {cats.map(c=>{
              const active = cat===c.id;
              return (
                <button key={c.id} onClick={()=>setCat(c.id)} style={{ padding:"6px 13px", borderRadius:99, fontSize:12.5, fontWeight:600, cursor:"pointer",
                  border:`1px solid ${active?"var(--accent)":"var(--line)"}`, background: active?"var(--accent-soft)":"var(--surface)", color: active?"var(--accent-ink)":"var(--ink-2)" }}>{c.label}</button>
              );
            })}
          </div>
          <div style={{ display:"grid", gridTemplateColumns:"repeat(auto-fill, minmax(150px, 1fr))", gap:12, padding:16 }}>
            {grid.map(it=>{
              const out = it.stock<=0;
              return (
                <button key={it.id} onClick={()=>!out&&addItem(it)} disabled={out}
                  style={{ display:"flex", flexDirection:"column", gap:8, padding:14, borderRadius:12, textAlign:"left", cursor:out?"not-allowed":"pointer", opacity:out?0.5:1,
                    border:"1px solid var(--line)", background:"var(--surface)", transition:"border-color .14s, transform .08s" }}
                  onMouseEnter={e=>!out&&(e.currentTarget.style.borderColor="var(--accent)")}
                  onMouseLeave={e=>e.currentTarget.style.borderColor="var(--line)"}
                  onMouseDown={e=>!out&&(e.currentTarget.style.transform="scale(0.98)")}
                  onMouseUp={e=>e.currentTarget.style.transform="none"}>
                  <span style={{ width:38, height:38, borderRadius:10, background:"var(--surface-2)", border:"1px solid var(--line)", display:"flex", alignItems:"center", justifyContent:"center", color:"var(--muted)" }}><Icon name={getInvCat(it.cat).icon} size={19} /></span>
                  <span style={{ fontSize:13, fontWeight:700, lineHeight:1.25, minHeight:32 }}>{it.name}</span>
                  <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between" }}>
                    <span className="mono" style={{ fontSize:15, fontWeight:800, color:"var(--accent-ink)" }}>{fmtMoney(it.price)}</span>
                    <span style={{ fontSize:11, color: out?"var(--danger)":"var(--faint)", fontWeight:600 }}>{out?"Agotado":`${it.stock} disp.`}</span>
                  </div>
                </button>
              );
            })}
          </div>
        </Card>
      </div>

      {/* right: cart / ticket */}
      <Card pad={0} style={{ position:"sticky", top:0, display:"flex", flexDirection:"column", maxHeight:"calc(100vh - 110px)" }}>
        <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", padding:"16px 18px", borderBottom:"1px solid var(--line)" }}>
          <h3 style={{ fontSize:16, fontWeight:800, margin:0, display:"flex", alignItems:"center", gap:9 }}><Icon name="orders" size={19} /> Venta actual</h3>
          {cart.length>0 && <button onClick={()=>setCart([])} style={{ border:"none", background:"transparent", color:"var(--danger)", fontSize:12.5, fontWeight:600 }}>Vaciar</button>}
        </div>

        <div style={{ flex:1, overflowY:"auto", padding: cart.length?"8px 8px":"0" }}>
          {cart.length===0 ? (
            <div style={{ padding:"48px 20px", textAlign:"center", color:"var(--faint)" }}>
              <Icon name="chip" size={34} style={{ opacity:0.4 }} />
              <div style={{ fontSize:14, fontWeight:600, color:"var(--muted)", marginTop:10 }}>Escanea o toca un producto</div>
              <div style={{ fontSize:13, marginTop:3 }}>Los artículos aparecerán aquí.</div>
            </div>
          ) : cart.map(c=>(
            <div key={c.id} style={{ display:"flex", alignItems:"center", gap:10, padding:"10px 10px", borderRadius:10 }}>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontSize:13.5, fontWeight:700, lineHeight:1.3 }}>{c.name}</div>
                <div style={{ fontSize:12, color:"var(--muted)" }} className="mono">{fmtMoney(c.price)} c/u</div>
              </div>
              <div style={{ display:"flex", alignItems:"center", border:"1px solid var(--line)", borderRadius:8, overflow:"hidden" }}>
                <button onClick={()=>setQty(c.id, c.qty-1)} style={{ width:28, height:32, border:"none", background:"var(--surface-2)", fontSize:16, color:"var(--ink-2)" }}>−</button>
                <span className="mono" style={{ width:26, textAlign:"center", fontWeight:700, fontSize:13.5 }}>{c.qty}</span>
                <button onClick={()=>setQty(c.id, c.qty+1)} style={{ width:28, height:32, border:"none", background:"var(--surface-2)", fontSize:16, color:"var(--ink-2)" }}>+</button>
              </div>
              <span className="mono" style={{ fontSize:13.5, fontWeight:700, width:64, textAlign:"right" }}>{fmtMoney(c.price*c.qty)}</span>
              <IconBtn icon="trash" size={14} title="Quitar" onClick={()=>removeItem(c.id)} />
            </div>
          ))}
        </div>

        {cart.length>0 && (
          <div style={{ borderTop:"1px solid var(--line)", padding:"16px 18px", display:"flex", flexDirection:"column", gap:13 }}>
            <div style={{ display:"flex", justifyContent:"space-between", alignItems:"baseline" }}>
              <span style={{ fontSize:14, fontWeight:600, color:"var(--muted)" }}>Total ({itemCount} {itemCount===1?"art.":"arts."})</span>
              <span className="mono" style={{ fontSize:26, fontWeight:800, letterSpacing:"-0.02em" }}>{fmtMoney(subtotal)}</span>
            </div>

            <button onClick={()=>setShowClient(true)} style={{ display:"flex", alignItems:"center", gap:11, width:"100%", padding:"11px 12px", borderRadius:10, cursor:"pointer", textAlign:"left",
              border:`1px solid ${client?"var(--accent)":"var(--line)"}`, background: client?"var(--accent-soft)":"var(--surface)" }}>
              <span style={{ width:34, height:34, borderRadius:9, flexShrink:0, display:"flex", alignItems:"center", justifyContent:"center", background: client?"var(--surface)":"var(--surface-2)", color: client?"var(--accent-ink)":"var(--faint)" }}><Icon name={client?"user":"clients"} size={18} /></span>
              <div style={{ flex:1, minWidth:0 }}>
                {client ? (
                  <>
                    <div style={{ fontSize:13.5, fontWeight:700, color:"var(--ink)", whiteSpace:"nowrap", overflow:"hidden", textOverflow:"ellipsis" }}>{client.name||"Cliente sin nombre"}</div>
                    <div style={{ fontSize:12, color:"var(--muted)" }} className="mono">{client.cedula || client.phone || "datos guardados"}</div>
                  </>
                ) : (
                  <>
                    <div style={{ fontSize:13.5, fontWeight:700, color:"var(--ink-2)" }}>Identificar cliente</div>
                    <div style={{ fontSize:12, color:"var(--faint)" }}>Registra o busca al cliente</div>
                  </>
                )}
              </div>
              {client
                ? <span onClick={e=>{e.stopPropagation();setClient(null);}} title="Quitar" style={{ color:"var(--faint)", padding:4 }}><Icon name="x" size={16} /></span>
                : <Icon name="chevronRight" size={16} style={{ color:"var(--faint)" }} />}
            </button>

            <div style={{ display:"flex", gap:6 }}>
              {[["efectivo","Efectivo"],["tarjeta","Tarjeta"],["transferencia","Transf."]].map(([id,l])=>{
                const sel = method===id;
                return (
                  <button key={id} onClick={()=>setMethod(id)} style={{ flex:1, padding:"9px 4px", borderRadius:8, fontSize:12.5, fontWeight:600, cursor:"pointer",
                    border:`1px solid ${sel?"var(--accent)":"var(--line)"}`, background: sel?"var(--accent-soft)":"var(--surface)", color: sel?"var(--accent-ink)":"var(--ink-2)" }}>{l}</button>
                );
              })}
            </div>

            <Btn size="lg" icon="check" style={{ width:"100%" }} onClick={checkout}>Cobrar e imprimir factura</Btn>
          </div>
        )}
      </Card>

      {showClient && <POSClientModal initial={client} clients={inventory && CLIENTS} onPick={(c)=>{ setClient(c); setShowClient(false); }} onClose={()=>setShowClient(false)} />}
      </div>
      )}
    </div>
  );
}

// ===== Historial de ventas con gestión de admin =====
function SalesHistory({ sales, currentUser, onVoidSale, onDeleteSale, onUpdateSaleClient, onViewInvoice }){
  const [q, setQ] = React.useState("");
  const [editClientFor, setEditClientFor] = React.useState(null); // sale
  const [confirm, setConfirm] = React.useState(null); // { type:"void"|"delete", sale }
  const isAdmin = currentUser.roleId === "admin";

  let rows = [...sales].sort((a,b)=> new Date(b.date)-new Date(a.date));
  if(q.trim()){
    const s = q.toLowerCase();
    rows = rows.filter(v => (v.num+" "+v.clientName+" "+(v.clientCedula||"")+" "+v.items.map(i=>i.name).join(" ")).toLowerCase().includes(s));
  }

  function doConfirm(){
    if(!confirm) return;
    if(confirm.type==="void") onVoidSale(confirm.sale.id);
    else onDeleteSale(confirm.sale.id);
    setConfirm(null);
  }

  return (
    <Card pad={0}>
      <div style={{ display:"flex", alignItems:"center", gap:12, padding:"14px 18px", borderBottom:"1px solid var(--line)", flexWrap:"wrap" }}>
        <div style={{ position:"relative", flex:1, minWidth:200 }}>
          <span style={{ position:"absolute", left:12, top:"50%", transform:"translateY(-50%)", color:"var(--faint)" }}><Icon name="search" size={17} /></span>
          <input value={q} onChange={e=>setQ(e.target.value)} placeholder="Buscar venta, cliente o producto…"
            style={{ width:"100%", padding:"9px 12px 9px 37px", fontSize:13.5, borderRadius:10, border:"1px solid var(--line)", background:"var(--surface-2)", outline:"none", color:"var(--ink)" }} />
        </div>
        {!isAdmin && <span style={{ display:"inline-flex", alignItems:"center", gap:6, fontSize:12, color:"var(--st-entrada)", fontWeight:600 }}><Icon name="warning" size={14} /> Solo un administrador puede anular o editar ventas</span>}
      </div>

      <div style={{ overflowX:"auto" }}>
        <table style={{ width:"100%", borderCollapse:"collapse", minWidth:720 }}>
          <thead>
            <tr style={{ height:38, background:"var(--surface-2)" }}>
              {["Venta","Fecha","Cliente","Artículos","Total",""].map((h,i)=>(
                <th key={i} style={{ textAlign: i===4?"right":"left", padding:"0 16px", fontSize:11.5, fontWeight:700, letterSpacing:"0.04em", textTransform:"uppercase", color:"var(--faint)" }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rows.map((v,idx)=>(
              <tr key={v.id} style={{ height:60, borderBottom: idx<rows.length-1?"1px solid var(--line-2)":"none", opacity: v.voided?0.55:1 }}>
                <td style={{ padding:"0 16px" }}>
                  <div style={{ display:"flex", alignItems:"center", gap:8 }}>
                    <span className="mono" style={{ fontSize:13.5, fontWeight:700, color:"var(--accent-ink)" }}>#{v.num}</span>
                    {v.voided && <span style={{ fontSize:10.5, fontWeight:700, color:"var(--danger)", background:"var(--danger-soft)", padding:"2px 7px", borderRadius:99 }}>ANULADA</span>}
                  </div>
                  <div style={{ fontSize:11.5, color:"var(--faint)", textTransform:"capitalize" }}>{v.method}</div>
                </td>
                <td style={{ padding:"0 16px", fontSize:12.5, color:"var(--muted)", whiteSpace:"nowrap" }}>{fmtDate(v.date)}<div style={{ fontSize:11, color:"var(--faint)" }}>{fmtClock(v.date)}</div></td>
                <td style={{ padding:"0 16px" }}>
                  <div style={{ fontSize:13.5, fontWeight:600 }}>{v.clientName}</div>
                  {v.clientCedula ? <div style={{ fontSize:11.5, color:"var(--muted)" }} className="mono">{v.clientCedula}</div> : <div style={{ fontSize:11.5, color:"var(--faint)", fontStyle:"italic" }}>sin datos</div>}
                </td>
                <td style={{ padding:"0 16px", fontSize:12.5, color:"var(--ink-2)" }}>{v.items.reduce((s,i)=>s+i.qty,0)} und · {v.items.length} líneas</td>
                <td style={{ padding:"0 16px", textAlign:"right" }}><span className="mono" style={{ fontSize:14, fontWeight:700, textDecoration: v.voided?"line-through":"none" }}>{fmtMoney(v.total)}</span></td>
                <td style={{ padding:"0 12px" }}>
                  <div style={{ display:"flex", gap:2, justifyContent:"flex-end" }}>
                    <IconBtn icon="eye" size={15} title="Ver factura" onClick={()=>onViewInvoice(v)} />
                    {isAdmin && !v.voided && <IconBtn icon="edit" size={15} title="Editar cliente" onClick={()=>setEditClientFor(v)} />}
                    {isAdmin && !v.voided && <IconBtn icon="refresh" size={15} title="Anular venta (devuelve stock)" onClick={()=>setConfirm({ type:"void", sale:v })} />}
                    {isAdmin && <IconBtn icon="trash" size={15} title="Eliminar venta" onClick={()=>setConfirm({ type:"delete", sale:v })} />}
                  </div>
                </td>
              </tr>
            ))}
            {rows.length===0 && (
              <tr><td colSpan={6}><div style={{ padding:"48px", textAlign:"center", color:"var(--faint)" }}><Icon name="wallet" size={32} style={{ opacity:0.4 }} /><div style={{ fontSize:14, fontWeight:600, color:"var(--muted)", marginTop:8 }}>Sin ventas registradas</div></div></td></tr>
            )}
          </tbody>
        </table>
      </div>

      {editClientFor && (
        <POSClientModal initial={editClientFor.clientId ? CLIENTS.find(c=>c.id===editClientFor.clientId) : null}
          onPick={(c)=>{ onUpdateSaleClient(editClientFor.id, c); setEditClientFor(null); }}
          onClose={()=>setEditClientFor(null)} />
      )}

      {confirm && (
        <ModalShell title={confirm.type==="void"?"Anular venta":"Eliminar venta"} onClose={()=>setConfirm(null)} maxWidth={420}>
          <div style={{ padding:"20px 22px" }}>
            <div style={{ display:"flex", alignItems:"flex-start", gap:11, padding:"12px 14px", borderRadius:10, background:"var(--danger-soft)", marginBottom:14 }}>
              <Icon name="warning" size={18} style={{ color:"var(--danger)", flexShrink:0, marginTop:1 }} />
              <div style={{ fontSize:13, color:"var(--ink-2)", lineHeight:1.5 }}>
                {confirm.type==="void"
                  ? <>Se anulará la venta <strong className="mono">#{confirm.sale.num}</strong>, se <strong>devolverá el stock</strong> de los productos al inventario y se restará de los ingresos en Finanzas. La venta quedará en el historial marcada como anulada.</>
                  : <>Se eliminará por completo la venta <strong className="mono">#{confirm.sale.num}</strong>{!confirm.sale.voided && <> y se devolverá el stock al inventario</>}. Esta acción no se puede deshacer.</>}
              </div>
            </div>
            <div style={{ display:"flex", justifyContent:"flex-end", gap:10 }}>
              <Btn variant="secondary" onClick={()=>setConfirm(null)}>Cancelar</Btn>
              <Btn variant="danger" icon={confirm.type==="void"?"refresh":"trash"} onClick={doConfirm}>{confirm.type==="void"?"Anular venta":"Eliminar"}</Btn>
            </div>
          </div>
        </ModalShell>
      )}
    </Card>
  );
}

// ===== POS: pick existing client or register a new one =====
function POSClientModal({ initial, onPick, onClose, startMode }){
  const [mode, setMode] = React.useState(startMode || "buscar"); // buscar | nuevo
  const [q, setQ] = React.useState("");
  const [f, setF] = React.useState(initial && !initial.id ? initial : { name:"", cedula:"", phone:"", email:"" });
  const list = CLIENTS.filter(c => !q || (c.name+" "+(c.cedula||"")+" "+(c.phone||"")+" "+(c.email||"")).toLowerCase().includes(q.toLowerCase()));
  function up(k,v){ setF(p=>({ ...p, [k]:v })); }
  const valid = f.name.trim() || f.cedula.trim() || f.phone.trim();

  return (
    <ModalShell title="Cliente de la venta" onClose={onClose} maxWidth={460}>
      <div style={{ display:"flex", gap:4, padding:"12px 22px 0" }}>
        {[["buscar","Cliente existente"],["nuevo","Nuevo cliente"]].map(([id,l])=>(
          <button key={id} onClick={()=>setMode(id)} style={{ padding:"8px 14px", borderRadius:9, border:"none", fontSize:13.5, fontWeight:600, cursor:"pointer",
            background: mode===id?"var(--accent-soft)":"transparent", color: mode===id?"var(--accent-ink)":"var(--muted)" }}>{l}</button>
        ))}
      </div>

      {mode==="buscar" ? (
        <div style={{ padding:"14px 22px 20px" }}>
          <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 por nombre, cédula o teléfono…" style={{ paddingLeft:37 }} />
          </div>
          <div style={{ display:"flex", flexDirection:"column", gap:7, maxHeight:320, overflowY:"auto" }}>
            {list.map(c=>(
              <button key={c.id} onClick={()=>onPick(c)} style={{ display:"flex", alignItems:"center", gap:12, padding:"10px 12px", borderRadius:10, textAlign:"left", cursor:"pointer", border:"1px solid var(--line)", background:"var(--surface)" }}
                onMouseEnter={e=>e.currentTarget.style.borderColor="var(--accent)"} onMouseLeave={e=>e.currentTarget.style.borderColor="var(--line)"}>
                <Avatar name={c.name} hue={256} size={38} />
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontSize:14, fontWeight:700 }}>{c.name}</div>
                  <div style={{ fontSize:12, color:"var(--muted)" }} className="mono">{c.cedula || "—"} · {c.phone || "sin tel."}</div>
                </div>
                <span style={{ fontSize:11.5, color:"var(--faint)", fontWeight:600 }}>Elegir →</span>
              </button>
            ))}
            {list.length===0 && <div style={{ padding:"24px", textAlign:"center", color:"var(--faint)", fontSize:13 }}>Sin coincidencias. Usa "Nuevo cliente".</div>}
          </div>
        </div>
      ) : (
        <div style={{ padding:"16px 22px 20px", display:"flex", flexDirection:"column", gap:13 }}>
          <Field label="Nombre completo" hint="Opcional — déjalo vacío para venta de mostrador">
            <TextInput value={f.name} autoFocus onChange={e=>up("name",e.target.value)} placeholder="ej. María Fernández" />
          </Field>
          <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:13 }}>
            <Field label="Cédula / RUC">
              <TextInput value={f.cedula} onChange={e=>up("cedula",e.target.value)} placeholder="0000-0000-00000" style={{ fontFamily:"var(--mono)" }} />
            </Field>
            <Field label="Teléfono">
              <TextInput value={f.phone} onChange={e=>up("phone",e.target.value)} placeholder="+503 7000-0000" style={{ fontFamily:"var(--mono)" }} />
            </Field>
          </div>
          <Field label="E-mail">
            <TextInput type="email" value={f.email} onChange={e=>up("email",e.target.value)} placeholder="correo@ejemplo.com" />
          </Field>
          <div style={{ display:"flex", alignItems:"center", gap:8, fontSize:12, color:"var(--muted)", padding:"8px 11px", borderRadius:9, background:"var(--surface-2)" }}>
            <Icon name="clients" size={15} /> Se guardará en tu base de clientes al cobrar.
          </div>
          <Btn icon="check" disabled={!valid} onClick={()=>onPick({ ...f })} style={{ width:"100%" }}>Usar este cliente</Btn>
        </div>
      )}
    </ModalShell>
  );
}

// ===== Invoice / receipt (printable) =====
function InvoiceModal({ sale, onClose }){
  const today = new Date(sale.date);
  function print(){ window.print(); }
  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:420, background:"var(--surface)", borderRadius:16, boxShadow:"var(--shadow-lg)", animation:"popIn .18s ease", overflow:"hidden", display:"flex", flexDirection:"column", maxHeight:"90vh" }}>
        <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between", padding:"14px 18px", borderBottom:"1px solid var(--line)" }}>
          <span style={{ display:"inline-flex", alignItems:"center", gap:8, fontSize:13.5, fontWeight:700, color:"var(--st-listo)" }}><Icon name="check" size={17} /> Venta registrada</span>
          <IconBtn icon="x" size={18} onClick={onClose} />
        </div>

        <div style={{ overflowY:"auto", padding:"20px" }}>
          {/* printable area */}
          <div id="print-area">
            <div style={{ textAlign:"center", borderBottom:"1px dashed var(--line)", paddingBottom:14, marginBottom:14 }}>
              <img src="casepoint-logo.png" alt="Casepoint" style={{ width:150, height:"auto", margin:"0 auto 8px" }} />
              <div style={{ fontSize:12, color:"var(--muted)", lineHeight:1.5 }}>Taller Casepoint · Reparación y accesorios<br/>Col. Escalón, San Salvador · +503 2200-0000</div>
            </div>

            <div style={{ display:"flex", justifyContent:"space-between", fontSize:12.5, marginBottom:4 }}>
              <span style={{ color:"var(--muted)" }}>Factura N°</span><span className="mono" style={{ fontWeight:700 }}>#{sale.num}</span>
            </div>
            <div style={{ display:"flex", justifyContent:"space-between", fontSize:12.5, marginBottom:4 }}>
              <span style={{ color:"var(--muted)" }}>Fecha</span><span>{today.toLocaleDateString("es-ES",{day:"2-digit",month:"long",year:"numeric"})} · {fmtClock(sale.date)}</span>
            </div>
            <div style={{ display:"flex", justifyContent:"space-between", fontSize:12.5, marginBottom:4 }}>
              <span style={{ color:"var(--muted)" }}>Cliente</span><span style={{ fontWeight:600 }}>{sale.clientName}</span>
            </div>
            {sale.clientCedula && <div style={{ display:"flex", justifyContent:"space-between", fontSize:12.5, marginBottom:4 }}>
              <span style={{ color:"var(--muted)" }}>Cédula / RUC</span><span className="mono">{sale.clientCedula}</span>
            </div>}
            {sale.clientPhone && <div style={{ display:"flex", justifyContent:"space-between", fontSize:12.5, marginBottom:4 }}>
              <span style={{ color:"var(--muted)" }}>Teléfono</span><span className="mono">{sale.clientPhone}</span>
            </div>}
            {sale.clientCedula && <div style={{ display:"flex", justifyContent:"space-between", fontSize:12.5, marginBottom:4 }}>
              <span style={{ color:"var(--muted)" }}>Cédula / RUC</span><span className="mono">{sale.clientCedula}</span>
            </div>}
            {sale.clientPhone && <div style={{ display:"flex", justifyContent:"space-between", fontSize:12.5, marginBottom:4 }}>
              <span style={{ color:"var(--muted)" }}>Teléfono</span><span className="mono">{sale.clientPhone}</span>
            </div>}
            {sale.cashier && <div style={{ display:"flex", justifyContent:"space-between", fontSize:12.5 }}>
              <span style={{ color:"var(--muted)" }}>Atendió</span><span>{sale.cashier}</span>
            </div>}

            <table style={{ width:"100%", borderCollapse:"collapse", margin:"16px 0", fontSize:12.5 }}>
              <thead>
                <tr style={{ borderBottom:"1px solid var(--line)" }}>
                  <th style={{ textAlign:"left", padding:"6px 0", color:"var(--muted)", fontWeight:600 }}>Producto</th>
                  <th style={{ textAlign:"center", padding:"6px 0", color:"var(--muted)", fontWeight:600, width:36 }}>Cant.</th>
                  <th style={{ textAlign:"right", padding:"6px 0", color:"var(--muted)", fontWeight:600, width:70 }}>Importe</th>
                </tr>
              </thead>
              <tbody>
                {sale.items.map((it,i)=>(
                  <tr key={i} style={{ borderBottom:"1px solid var(--line-2)" }}>
                    <td style={{ padding:"8px 0" }}>
                      <div style={{ fontWeight:600 }}>{it.name}</div>
                      <div className="mono" style={{ fontSize:11, color:"var(--faint)" }}>{fmtMoney(it.price)} c/u</div>
                    </td>
                    <td style={{ textAlign:"center" }} className="mono">{it.qty}</td>
                    <td style={{ textAlign:"right", fontWeight:600 }} className="mono">{fmtMoney(it.price*it.qty)}</td>
                  </tr>
                ))}
              </tbody>
            </table>

            <div style={{ display:"flex", justifyContent:"space-between", alignItems:"baseline", borderTop:"1px dashed var(--line)", paddingTop:12 }}>
              <span style={{ fontSize:15, fontWeight:800 }}>TOTAL</span>
              <span className="mono" style={{ fontSize:22, fontWeight:800 }}>{fmtMoney(sale.total)}</span>
            </div>
            <div style={{ fontSize:12, color:"var(--muted)", marginTop:6, textTransform:"capitalize" }}>Pago: {sale.method}</div>

            <div style={{ textAlign:"center", fontSize:11.5, color:"var(--faint)", marginTop:18, borderTop:"1px dashed var(--line)", paddingTop:12 }}>
              ¡Gracias por su compra!<br/>Garantía de accesorios: 7 días con esta factura.
            </div>
          </div>
        </div>

        <div style={{ display:"flex", gap:10, padding:"14px 18px", borderTop:"1px solid var(--line)" }}>
          <Btn variant="secondary" style={{ flex:1 }} onClick={onClose}>Cerrar</Btn>
          <Btn icon="print" style={{ flex:1.4 }} onClick={print}>Imprimir factura</Btn>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { POS, InvoiceModal, POSClientModal, SalesHistory });
