// ===== Inventario: repuestos & insumos =====
function Inventario({ inventory, setInventory, currentUser, onRestock }){
  const [cat, setCat] = React.useState("todas");
  const [q, setQ] = React.useState("");
  const [modal, setModal] = React.useState(null); // null | {new:true} | item
  const canEdit = ROLES[currentUser.roleId]?.perms.includes("config");

  const lowStock = inventory.filter(i => i.stock <= i.min);
  const totalValue = inventory.reduce((s,i)=> s + i.stock*i.cost, 0);

  let rows = inventory;
  if(cat!=="todas") rows = rows.filter(i=>i.cat===cat);
  if(q.trim()) rows = rows.filter(i=>(i.name+i.sku+i.supplier).toLowerCase().includes(q.toLowerCase()));

  function save(item){
    setInventory(prev => prev.some(x=>x.id===item.id) ? prev.map(x=>x.id===item.id?item:x) : [...prev, item]);
    setModal(null);
  }
  function remove(id){ setInventory(prev => prev.filter(x=>x.id!==id)); setModal(null); }
  function adjustStock(id, delta){ setInventory(prev => prev.map(x => x.id===id ? { ...x, stock: Math.max(0, x.stock+delta) } : x)); }

  const cats = [{ id:"todas", label:"Todas" }, ...INV_CATEGORIES];

  return (
    <div style={{ display:"flex", flexDirection:"column", gap:16, animation:"fadeUp .35s ease" }}>
      {/* summary */}
      <div style={{ display:"grid", gridTemplateColumns:"repeat(3,1fr)", gap:14 }}>
        <SumCard icon="box" hue={256} value={inventory.length} label="Artículos en catálogo" sub={`${inventory.reduce((s,i)=>s+i.stock,0)} unidades en total`} />
        <SumCard icon="chart" hue={155} value={fmtMoney(totalValue)} label="Valor del inventario" sub="a precio de costo" mono />
        <SumCard icon="warning" hue={lowStock.length?30:155} value={lowStock.length} label="Bajo stock mínimo" sub={lowStock.length?"requieren compra":"todo abastecido"} emph={lowStock.length>0} />
      </div>

      {lowStock.length>0 && (
        <Card pad={14} style={{ borderColor:"oklch(0.85 0.08 60)", background:"var(--st-entrada-soft)" }}>
          <div style={{ display:"flex", alignItems:"center", gap:10, flexWrap:"wrap" }}>
            <Icon name="warning" size={18} style={{ color:"var(--st-entrada)" }} />
            <span style={{ fontSize:13.5, fontWeight:700, color:"var(--st-entrada)" }}>Repuestos por reabastecer:</span>
            {lowStock.map(i=>(
              <span key={i.id} style={{ fontSize:12.5, fontWeight:600, color:"var(--ink-2)", padding:"3px 9px", borderRadius:99, background:"var(--surface)", border:"1px solid var(--line)" }}>
                {i.name} <span className="mono" style={{ color:"var(--st-entrada)" }}>({i.stock}/{i.min})</span>
              </span>
            ))}
          </div>
        </Card>
      )}

      <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 repuesto, SKU o proveedor…"
              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>
          <Btn icon="plus" size="sm" onClick={()=>setModal({new:true})}>Nuevo artículo</Btn>
        </div>

        {/* category chips */}
        <div style={{ display:"flex", gap:7, padding:"12px 18px", flexWrap:"wrap", borderBottom:"1px solid var(--line-2)" }}>
          {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={{ overflowX:"auto" }}>
          <table style={{ width:"100%", borderCollapse:"collapse", minWidth:760 }}>
            <thead>
              <tr style={{ height:38, background:"var(--surface-2)" }}>
                {["Artículo","Categoría","Stock","Costo","Precio venta","Proveedor",""].map((h,i)=>(
                  <th key={i} style={{ textAlign: i>=2&&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((it,idx)=>{
                const low = it.stock<=it.min;
                return (
                  <tr key={it.id} style={{ height:58, borderBottom: idx<rows.length-1?"1px solid var(--line-2)":"none" }}>
                    <td style={{ padding:"0 16px" }}>
                      <div style={{ fontSize:13.5, fontWeight:700 }}>{it.name}</div>
                      <div style={{ fontSize:12, color:"var(--muted)" }} className="mono">{it.sku}</div>
                    </td>
                    <td style={{ padding:"0 16px" }}>
                      <span style={{ display:"inline-flex", alignItems:"center", gap:6, fontSize:12.5, color:"var(--ink-2)" }}><Icon name={getInvCat(it.cat).icon} size={15} />{getInvCat(it.cat).label}</span>
                    </td>
                    <td style={{ padding:"0 16px", textAlign:"right" }}>
                      <div style={{ display:"inline-flex", alignItems:"center", gap:7 }}>
                        <IconBtn icon="x" size={13} title="Restar 1" onClick={()=>adjustStock(it.id,-1)} />
                        <span className="mono" style={{ fontSize:14, fontWeight:700, color: low?"var(--st-entrada)":"var(--ink)", minWidth:22, textAlign:"center" }}>{it.stock}</span>
                        <IconBtn icon="plus" size={13} title="Sumar 1" onClick={()=>adjustStock(it.id,1)} />
                        {low && <span title="Bajo el mínimo" style={{ color:"var(--st-entrada)" }}><Icon name="warning" size={15} /></span>}
                      </div>
                      <div style={{ fontSize:11, color:"var(--faint)" }}>mín. {it.min}</div>
                    </td>
                    <td style={{ padding:"0 16px", textAlign:"right" }}><span className="mono" style={{ fontSize:13, color:"var(--muted)" }}>{fmtMoney(it.cost)}</span></td>
                    <td style={{ padding:"0 16px", textAlign:"right" }}><span className="mono" style={{ fontSize:13.5, fontWeight:600 }}>{it.price>0?fmtMoney(it.price):"—"}</span></td>
                    <td style={{ padding:"0 16px", fontSize:12.5, color:"var(--ink-2)" }}>{it.supplier}</td>
                    <td style={{ padding:"0 12px", textAlign:"right" }}>
                      <div style={{ display:"flex", gap:2, justifyContent:"flex-end" }}>
                        <IconBtn icon="refresh" size={15} title="Reabastecer (registra compra)" onClick={()=>onRestock(it)} />
                        <IconBtn icon="edit" size={15} title="Editar" onClick={()=>setModal(it)} />
                      </div>
                    </td>
                  </tr>
                );
              })}
              {rows.length===0 && (
                <tr><td colSpan={7}><div style={{ padding:"48px", textAlign:"center", color:"var(--faint)" }}><Icon name="box" size={32} style={{ opacity:0.4 }} /><div style={{ fontSize:14, fontWeight:600, color:"var(--muted)", marginTop:8 }}>Sin artículos en esta categoría</div></div></td></tr>
              )}
            </tbody>
          </table>
        </div>
      </Card>

      {modal && <InvModal item={modal.new?null:modal} onSave={save} onClose={()=>setModal(null)} onDelete={remove} />}
    </div>
  );
}

function SumCard({ icon, hue, value, label, sub, mono, emph }){
  return (
    <Card pad={18} style={emph?{ borderColor:`oklch(0.85 0.08 ${hue})` }:{}}>
      <div style={{ width:38, height:38, borderRadius:10, display:"flex", alignItems:"center", justifyContent:"center", background:`oklch(0.95 0.04 ${hue})`, color:`oklch(0.5 0.13 ${hue})` }}><Icon name={icon} size={20} /></div>
      <div style={{ fontSize:28, fontWeight:800, marginTop:13, letterSpacing:"-0.02em" }} className={mono?"mono":""}>{value}</div>
      <div style={{ fontSize:13.5, fontWeight:600, color:"var(--ink-2)" }}>{label}</div>
      <div style={{ fontSize:12.5, color:"var(--faint)", marginTop:2 }}>{sub}</div>
    </Card>
  );
}

function InvModal({ item, onSave, onClose, onDelete }){
  const editing = !!item;
  const [f, setF] = React.useState(item || { sku:"", name:"", cat:"pantallas", stock:0, min:1, cost:"", price:"", supplier:"" });
  const [touched, setTouched] = React.useState(false);
  function up(k,v){ setF(p=>({ ...p, [k]:v })); }
  const valid = f.name.trim() && f.sku.trim();
  function save(){
    setTouched(true); if(!valid) return;
    onSave({ id:item?.id || "i_"+Date.now(), sku:f.sku.trim().toUpperCase(), name:f.name.trim(), cat:f.cat,
      stock:+f.stock||0, min:+f.min||0, cost:+f.cost||0, price:+f.price||0, supplier:f.supplier.trim()||"—" });
  }
  return (
    <ModalShell title={editing?"Editar artículo":"Nuevo artículo"} onClose={onClose} maxWidth={480}>
      <div style={{ padding:"20px 22px", display:"flex", flexDirection:"column", gap:14, maxHeight:"68vh", overflowY:"auto" }}>
        <Field label="Nombre del repuesto / insumo" required>
          <TextInput value={f.name} onChange={e=>up("name",e.target.value)} placeholder="ej. Pantalla iPhone 13" style={touched&&!f.name.trim()?{borderColor:"var(--danger)"}:{}} />
        </Field>
        <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:14 }}>
          <Field label="SKU / Código" required>
            <TextInput value={f.sku} onChange={e=>up("sku",e.target.value)} placeholder="PNT-IP13" style={{ fontFamily:"var(--mono)", ...(touched&&!f.sku.trim()?{borderColor:"var(--danger)"}:{}) }} />
          </Field>
          <Field label="Categoría">
            <div style={{ position:"relative" }}>
              <select value={f.cat} onChange={e=>up("cat",e.target.value)} style={{ ...inputStyle, appearance:"none", paddingRight:34, cursor:"pointer" }}>
                {INV_CATEGORIES.map(c=><option key={c.id} value={c.id}>{c.label}</option>)}
              </select>
              <Icon name="chevronDown" size={15} style={{ position:"absolute", right:12, top:"50%", transform:"translateY(-50%)", color:"var(--faint)", pointerEvents:"none" }} />
            </div>
          </Field>
          <Field label="Stock actual">
            <TextInput type="number" min="0" value={f.stock} onChange={e=>up("stock",e.target.value)} style={{ fontFamily:"var(--mono)" }} />
          </Field>
          <Field label="Stock mínimo" hint="Avisa cuando baje de aquí">
            <TextInput type="number" min="0" value={f.min} onChange={e=>up("min",e.target.value)} style={{ fontFamily:"var(--mono)" }} />
          </Field>
          <Field label="Costo unitario (US$)">
            <TextInput type="number" min="0" value={f.cost} onChange={e=>up("cost",e.target.value)} placeholder="0.00" style={{ fontFamily:"var(--mono)" }} />
          </Field>
          <Field label="Precio de venta (US$)" hint="0 si no se cobra aparte">
            <TextInput type="number" min="0" value={f.price} onChange={e=>up("price",e.target.value)} placeholder="0.00" style={{ fontFamily:"var(--mono)" }} />
          </Field>
        </div>
        <Field label="Proveedor">
          <TextInput value={f.supplier} onChange={e=>up("supplier",e.target.value)} placeholder="Nombre del proveedor" />
        </Field>
      </div>
      <div style={{ display:"flex", alignItems:"center", gap:10, padding:"16px 22px", borderTop:"1px solid var(--line)" }}>
        {editing && <Btn variant="danger" icon="trash" onClick={()=>onDelete(item.id)}>Eliminar</Btn>}
        <div style={{ marginLeft:"auto", display:"flex", gap:10 }}>
          <Btn variant="secondary" onClick={onClose}>Cancelar</Btn>
          <Btn icon="check" disabled={touched&&!valid} onClick={save}>{editing?"Guardar":"Agregar"}</Btn>
        </div>
      </div>
    </ModalShell>
  );
}

Object.assign(window, { Inventario, SumCard, InvModal });
