const { useState, useEffect, useMemo, useRef, useCallback } = React;


/* ═══════════════════════════════════════════════════
   BRAND
═══════════════════════════════════════════════════ */
const BRAND = {
  nombre: "iCompany",
  registered: true,
  direccion: "Panamericana Km 52,5, Colectora Este Ramal Pilar, Edificio Meridiano Local 15",
  ciudad: "B1630 Pilar Centro, Provincia de Buenos Aires",
  telefono: "+54 9 11 2648-1136",
  instagram: "@icompany.pilar",
  whatsappNum: "5491126481136",
  logoUrl: "/assets/logo.png",
  qrLlegar: "/assets/qr_llegar.png",
  qrInstagram: "/assets/qr_instagram.png",
  qrWhatsapp: "/assets/qr_whatsapp.png",
};

/* ═══════════════════════════════════════════════════
   FRASES BÍBLICAS (Proverbios y Eclesiastés - dominio público)
═══════════════════════════════════════════════════ */
const FRASES = [
  { texto: "El que trabaja su tierra se saciará de pan, mas el que sigue a los vagos es falto de entendimiento.", ref: "Proverbios 12:11" },
  { texto: "Los pensamientos del diligente ciertamente tienden a la abundancia; mas todo el que se apresura alocadamente, de cierto va a la pobreza.", ref: "Proverbios 21:5" },
  { texto: "Todo lo que te viniere a la mano para hacer, hazlo según tus fuerzas.", ref: "Eclesiastés 9:10" },
  { texto: "El alma del perezoso desea, y nada alcanza; mas el alma de los diligentes será prosperada.", ref: "Proverbios 13:4" },
  { texto: "El hombre que confía en sus amigos, que se inclina hacia ellos, verá que los ojos de sus hijos desfallecen.", ref: "Proverbios 17:17" },
  { texto: "La honra del hombre está en responder con sabiduría, y el necio que calla es tenido por sabio.", ref: "Proverbios 17:28" },
  { texto: "El corazón alegre constituye buen remedio; mas el espíritu triste seca los huesos.", ref: "Proverbios 17:22" },
  { texto: "Como ciudad derribada y sin muro es el hombre cuyo espíritu no tiene rienda.", ref: "Proverbios 25:28" },
  { texto: "No te jactes del día de mañana; porque no sabes qué dará de sí el día.", ref: "Proverbios 27:1" },
  { texto: "El que es fiel en lo muy poco, también en lo más es fiel; y el que en lo muy poco es injusto, también en lo más es injusto.", ref: "Lucas 16:10" },
  { texto: "El hierro se afila con el hierro, y el hombre en el trato con el hombre.", ref: "Proverbios 27:17" },
  { texto: "Mejor es el pobre que camina en su integridad que el de perversos labios y fatuo.", ref: "Proverbios 19:1" },
  { texto: "Dios ha hecho que todo sea hermoso a su tiempo; y ha puesto eternidad en el corazón de ellos.", ref: "Eclesiastés 3:11" },
  { texto: "Fíate de Jehová de todo tu corazón, y no te apoyes en tu propia prudencia.", ref: "Proverbios 3:5" },
  { texto: "La sabiduría es lo principal; adquiere sabiduría, y sobre todas tus posesiones adquiere inteligencia.", ref: "Proverbios 4:7" },
  { texto: "Una respuesta gentil aparta el furor, mas la palabra áspera hace subir la ira.", ref: "Proverbios 15:1" },
  { texto: "El inicio de la sabiduría es el temor del Señor, y conocer al Santo es la inteligencia.", ref: "Proverbios 9:10" },
  { texto: "La diligencia del hombre le hace estar delante de los reyes.", ref: "Proverbios 22:29" },
  { texto: "El corazón del entendido adquiere sabiduría, y el oído de los sabios busca la ciencia.", ref: "Proverbios 18:15" },
  { texto: "No digas a tu prójimo: Anda, y vuelve, y mañana te daré; cuando tienes contigo qué darle.", ref: "Proverbios 3:28" },
  { texto: "En toda labor hay fruto; mas las vanas palabras de los labios empobrecen.", ref: "Proverbios 14:23" },
  { texto: "El que tiene en poco la disciplina menosprecia su alma; mas el que escucha la corrección tiene entendimiento.", ref: "Proverbios 15:32" },
  { texto: "Honra a Jehová con tus bienes, y con las primicias de todos tus frutos.", ref: "Proverbios 3:9" },
  { texto: "El orgullo del hombre le abate; pero al humilde de espíritu sustenta la honra.", ref: "Proverbios 29:23" },
];

/* ═══════════════════════════════════════════════════
   SUPABASE CONFIG
═══════════════════════════════════════════════════ */
const SB_URL  = "https://ugeahpbnvbczjymrwdvg.supabase.co";
const SB_KEY  = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InVnZWFocGJudmJjemp5bXJ3ZHZnIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzYxODU5MzIsImV4cCI6MjA5MTc2MTkzMn0.ybXdBiYpoOT_-kmyFXBQHLoNzel5tPwMcTq8wwJmskQ";
const SB_HDR  = {"Content-Type":"application/json","apikey":SB_KEY,"Authorization":`Bearer ${SB_KEY}`};

// Tabla por clave lógica
const SK = {
  usuarios:"ic_usuarios", ventas:"ic_ventas",
  ordenes:"ic_ordenes",   clientes:"ic_clientes",
  catalogo:"ic_catalogo", cotiz:"ic_cotiz",
  movCaja:"ic_movcaja",
};

// Cada tabla tiene una sola fila con id="singleton" y data=jsonb
const sg = async(tabla)=>{
  try{
    const r=await fetch(`${SB_URL}/rest/v1/${tabla}?id=eq.singleton&select=data`,{headers:SB_HDR});
    const j=await r.json();
    return j&&j[0]?j[0].data:null;
  }catch{return null;}
};

const ss = async(tabla,val)=>{
  try{
    await fetch(`${SB_URL}/rest/v1/${tabla}`,{
      method:"POST",
      headers:{...SB_HDR,"Prefer":"resolution=merge-duplicates"},
      body:JSON.stringify({id:"singleton",data:val}),
    });
  }catch{}
};

/* ═══════════════════════════════════════════════════
   MÉTODOS DE PAGO (8 métodos)
═══════════════════════════════════════════════════ */
const METODOS = [
  {id:"efectivo",  label:"Efectivo",          moneda:"pesos",caja:"pesos",  esEfectivo:true },
  {id:"usd",       label:"USD",               moneda:"usd",  caja:"usd",   esEfectivo:false},
  {id:"mp_ag",     label:"MP AG",             moneda:"pesos",caja:"ninguna",esEfectivo:false},
  {id:"mp_ic",     label:"MP IC",             moneda:"pesos",caja:"ninguna",esEfectivo:false},
  {id:"ic_sa",     label:"IC SA",             moneda:"pesos",caja:"ninguna",esEfectivo:false},
  {id:"tranf_dir", label:"Tranf 3ro directo", moneda:"pesos",caja:"ninguna",esEfectivo:false},
  {id:"tranf_usd", label:"Tranf 3ro Usd",     moneda:"usd",  caja:"ninguna",esEfectivo:false},
  {id:"crypto",    label:"Crypto (USDT)",     moneda:"usd",  caja:"ninguna",esEfectivo:false},
];
const mById = id => METODOS.find(m=>m.id===id);

/* ═══════════════════════════════════════════════════
   CATEGORÍAS QUE TIENEN DESCUENTO EFECTIVO
   Solo Accesorios, Reparaciones, Servicios — NO Productos/iPhone
═══════════════════════════════════════════════════ */
const CATS_CON_DESCUENTO = ["Baterias","Cables","Cargadores","Fundas","Pantallas","Templados","camara","otro repuesto","pin de carga","vidrio trasero"];
const CATS_SIN_DESCUENTO = ["iPhone","Otro"];

const itemTieneDescuento = (item) => CATS_CON_DESCUENTO.includes(item.cat);

/* ═══════════════════════════════════════════════════
   CATÁLOGO INICIAL (413 productos de tu base)
═══════════════════════════════════════════════════ */
const CATALOGO_INICIAL = [{"id":"db1","nombre":"pantalla iphone 7","precio":58.0,"costo":0.0,"stock":0,"cat":"Pantallas","stockMin":1},{"id":"db2","nombre":"pantalla iphone 8","precio":58.0,"costo":0.0,"stock":0,"cat":"Pantallas","stockMin":1},{"id":"db3","nombre":"pantalla iphoneSE","precio":68.0,"costo":0.0,"stock":0,"cat":"Pantallas","stockMin":1},{"id":"db4","nombre":"pantalla iphone X","precio":79.0,"costo":0.0,"stock":0,"cat":"Pantallas","stockMin":1},{"id":"db5","nombre":"pantalla iphone Xr","precio":79.0,"costo":0.0,"stock":0,"cat":"Pantallas","stockMin":1},{"id":"db6","nombre":"pantalla iphone XS","precio":79.0,"costo":0.0,"stock":0,"cat":"Pantallas","stockMin":1},{"id":"db7","nombre":"pantalla iphone Xs Max","precio":92.0,"costo":0.0,"stock":0,"cat":"Pantallas","stockMin":1},{"id":"db8","nombre":"pantalla iphone 11","precio":106.0,"costo":0.0,"stock":0,"cat":"Pantallas","stockMin":1},{"id":"db9","nombre":"pantalla iphone 11Pro","precio":130.0,"costo":0.0,"stock":0,"cat":"Pantallas","stockMin":1},{"id":"db10","nombre":"pantalla iphone 11Pro Max","precio":118.0,"costo":0.0,"stock":0,"cat":"Pantallas","stockMin":1},{"id":"db11","nombre":"pantalla iphone 12mini","precio":167.0,"costo":0.0,"stock":0,"cat":"Pantallas","stockMin":1},{"id":"db12","nombre":"pantalla iphone 12/12Pro","precio":183.0,"costo":0.0,"stock":0,"cat":"Pantallas","stockMin":1},{"id":"db13","nombre":"pantalla iphone 12Pro Max","precio":210.0,"costo":0.0,"stock":0,"cat":"Pantallas","stockMin":1},{"id":"db14","nombre":"pantalla iphone 13mini","precio":157.0,"costo":0.0,"stock":0,"cat":"Pantallas","stockMin":1},{"id":"db15","nombre":"pantalla iphone 13","precio":131.0,"costo":0.0,"stock":0,"cat":"Pantallas","stockMin":1},{"id":"db16","nombre":"pantalla iphone 13 Pro","precio":210.0,"costo":0.0,"stock":0,"cat":"Pantallas","stockMin":1},{"id":"db17","nombre":"pantalla iphone 13 Pro Max","precio":233.0,"costo":0.0,"stock":0,"cat":"Pantallas","stockMin":1},{"id":"db18","nombre":"pantalla iphone 14","precio":180.0,"costo":0.0,"stock":0,"cat":"Pantallas","stockMin":1},{"id":"db19","nombre":"pantalla iphone 14 Plus","precio":210.0,"costo":0.0,"stock":0,"cat":"Pantallas","stockMin":1},{"id":"db20","nombre":"pantalla iphone 14 Pro","precio":223.0,"costo":0.0,"stock":0,"cat":"Pantallas","stockMin":1},{"id":"db21","nombre":"pantalla iphone 14 Pro Max","precio":260.0,"costo":0.0,"stock":0,"cat":"Pantallas","stockMin":1},{"id":"db22","nombre":"pantalla iphone 15","precio":210.0,"costo":0.0,"stock":0,"cat":"Pantallas","stockMin":1},{"id":"db23","nombre":"pantalla iphone 15 Pro","precio":250.0,"costo":0.0,"stock":0,"cat":"Pantallas","stockMin":1},{"id":"db24","nombre":"pantalla iphone 15 Pro Max","precio":263.0,"costo":0.0,"stock":0,"cat":"Pantallas","stockMin":1},{"id":"db25","nombre":"pantalla iphone 16","precio":0.0,"costo":0.0,"stock":0,"cat":"Pantallas","stockMin":1},{"id":"db26","nombre":"pantalla iphone 16 Pro","precio":0.0,"costo":0.0,"stock":0,"cat":"Pantallas","stockMin":1},{"id":"db27","nombre":"pantalla iphone 16 Pro Max","precio":0.0,"costo":0.0,"stock":0,"cat":"Pantallas","stockMin":1},{"id":"db30","nombre":"bateria iphone 8","precio":68.0,"costo":0.0,"stock":0,"cat":"Baterias","stockMin":1},{"id":"db31","nombre":"bateria iphone 8 Plus","precio":68.0,"costo":0.0,"stock":0,"cat":"Baterias","stockMin":1},{"id":"db32","nombre":"bateria iphone SE 2020","precio":75.0,"costo":0.0,"stock":0,"cat":"Baterias","stockMin":1},{"id":"db33","nombre":"bateria iphone SE 2022","precio":75.0,"costo":0.0,"stock":0,"cat":"Baterias","stockMin":1},{"id":"db34","nombre":"bateria iphone X","precio":75.0,"costo":0.0,"stock":0,"cat":"Baterias","stockMin":1},{"id":"db35","nombre":"bateria iphone Xr","precio":75.0,"costo":0.0,"stock":0,"cat":"Baterias","stockMin":1},{"id":"db36","nombre":"bateria iphone Xs","precio":75.0,"costo":0.0,"stock":0,"cat":"Baterias","stockMin":1},{"id":"db37","nombre":"bateria iphone XS Max","precio":75.0,"costo":0.0,"stock":0,"cat":"Baterias","stockMin":1},{"id":"db38","nombre":"bateria iphone 11","precio":110.0,"costo":0.0,"stock":0,"cat":"Baterias","stockMin":1},{"id":"db39","nombre":"bateria iphone 11Pro","precio":110.0,"costo":0.0,"stock":0,"cat":"Baterias","stockMin":1},{"id":"db40","nombre":"bateria iphone 11 Pro Max","precio":110.0,"costo":0.0,"stock":0,"cat":"Baterias","stockMin":1},{"id":"db41","nombre":"bateria iphone 12 mini","precio":110.0,"costo":0.0,"stock":0,"cat":"Baterias","stockMin":1},{"id":"db42","nombre":"bateria iphone 12/12 Pro","precio":110.0,"costo":0.0,"stock":0,"cat":"Baterias","stockMin":1},{"id":"db43","nombre":"bateria iphone 12 Pro Max","precio":110.0,"costo":0.0,"stock":0,"cat":"Baterias","stockMin":1},{"id":"db44","nombre":"bateria iphone 13mini","precio":110.0,"costo":0.0,"stock":0,"cat":"Baterias","stockMin":1},{"id":"db45","nombre":"bateria iphone 13","precio":110.0,"costo":0.0,"stock":0,"cat":"Baterias","stockMin":1},{"id":"db46","nombre":"bateria iphone 13 Pro","precio":120.0,"costo":0.0,"stock":0,"cat":"Baterias","stockMin":1},{"id":"db47","nombre":"bateria iphone 13 Pro Max","precio":125.0,"costo":0.0,"stock":0,"cat":"Baterias","stockMin":1},{"id":"db48","nombre":"bateria iphone 14","precio":105.0,"costo":0.0,"stock":0,"cat":"Baterias","stockMin":1},{"id":"db49","nombre":"bateria iphone 14 Plus","precio":120.0,"costo":0.0,"stock":0,"cat":"Baterias","stockMin":1},{"id":"db50","nombre":"bateria iphone 14 Pro","precio":129.0,"costo":0.0,"stock":0,"cat":"Baterias","stockMin":1},{"id":"db51","nombre":"bateria iphone 14 Pro Max","precio":132.0,"costo":0.0,"stock":0,"cat":"Baterias","stockMin":1},{"id":"db52","nombre":"bateria iphone 15","precio":160.0,"costo":0.0,"stock":0,"cat":"Baterias","stockMin":1},{"id":"db53","nombre":"bateria iphone 15 Pro","precio":160.0,"costo":0.0,"stock":0,"cat":"Baterias","stockMin":1},{"id":"db54","nombre":"bateria iphone 15 Pro Max","precio":160.0,"costo":0.0,"stock":0,"cat":"Baterias","stockMin":1},{"id":"db55","nombre":"bateria iphone 16","precio":0.0,"costo":0.0,"stock":0,"cat":"Baterias","stockMin":1},{"id":"db56","nombre":"bateria iphone 16 Plus","precio":0.0,"costo":0.0,"stock":0,"cat":"Baterias","stockMin":1},{"id":"db57","nombre":"bateria iphone 16 Pro","precio":0.0,"costo":0.0,"stock":0,"cat":"Baterias","stockMin":1},{"id":"db58","nombre":"bateria iphone 16 Pro Max","precio":0.0,"costo":0.0,"stock":0,"cat":"Baterias","stockMin":1},{"id":"db60","nombre":"vidrio trasero iphone 8","precio":40.0,"costo":0.0,"stock":0,"cat":"vidrio trasero","stockMin":1},{"id":"db61","nombre":"vidrio trasero iphone 8 Plus","precio":40.0,"costo":0.0,"stock":0,"cat":"vidrio trasero","stockMin":1},{"id":"db62","nombre":"vidrio trasero iphone SE","precio":60.0,"costo":0.0,"stock":0,"cat":"vidrio trasero","stockMin":1},{"id":"db63","nombre":"vidrio trasero iphone X","precio":72.0,"costo":0.0,"stock":0,"cat":"vidrio trasero","stockMin":1},{"id":"db64","nombre":"vidrio trasero iphone Xr","precio":72.0,"costo":0.0,"stock":0,"cat":"vidrio trasero","stockMin":1},{"id":"db65","nombre":"vidrio trasero iphone Xs","precio":72.0,"costo":0.0,"stock":0,"cat":"vidrio trasero","stockMin":1},{"id":"db66","nombre":"vidrio trasero iphone XS Max","precio":80.0,"costo":0.0,"stock":0,"cat":"vidrio trasero","stockMin":1},{"id":"db67","nombre":"vidrio trasero iphone 11","precio":90.0,"costo":0.0,"stock":0,"cat":"vidrio trasero","stockMin":1},{"id":"db68","nombre":"vidrio trasero iphone 11 Pro","precio":90.0,"costo":0.0,"stock":0,"cat":"vidrio trasero","stockMin":1},{"id":"db69","nombre":"vidrio trasero iphone 11 Pro Max","precio":100.0,"costo":0.0,"stock":0,"cat":"vidrio trasero","stockMin":1},{"id":"db70","nombre":"vidrio trasero iphone 12mini","precio":100.0,"costo":0.0,"stock":0,"cat":"vidrio trasero","stockMin":1},{"id":"db71","nombre":"vidrio trasero iphone 12","precio":120.0,"costo":0.0,"stock":0,"cat":"vidrio trasero","stockMin":1},{"id":"db72","nombre":"vidrio trasero iphone 12Pro","precio":117.0,"costo":0.0,"stock":0,"cat":"vidrio trasero","stockMin":1},{"id":"db73","nombre":"vidrio trasero iphone 12Pro Max","precio":117.0,"costo":0.0,"stock":0,"cat":"vidrio trasero","stockMin":1},{"id":"db74","nombre":"vidrio trasero iphone 13mini","precio":110.0,"costo":0.0,"stock":0,"cat":"vidrio trasero","stockMin":1},{"id":"db75","nombre":"vidrio trasero iphone 13","precio":110.0,"costo":0.0,"stock":0,"cat":"vidrio trasero","stockMin":1},{"id":"db76","nombre":"vidrio trasero iphone 13 Pro","precio":124.0,"costo":0.0,"stock":0,"cat":"vidrio trasero","stockMin":1},{"id":"db77","nombre":"vidrio trasero iphone 13 Pro Max","precio":124.0,"costo":0.0,"stock":0,"cat":"vidrio trasero","stockMin":1},{"id":"db78","nombre":"vidrio trasero iphone 14","precio":124.0,"costo":0.0,"stock":0,"cat":"vidrio trasero","stockMin":1},{"id":"db79","nombre":"vidrio trasero iphone 14 Plus","precio":124.0,"costo":0.0,"stock":0,"cat":"vidrio trasero","stockMin":1},{"id":"db80","nombre":"vidrio trasero iphone 14 Pro","precio":124.0,"costo":0.0,"stock":0,"cat":"vidrio trasero","stockMin":1},{"id":"db81","nombre":"vidrio trasero iphone 14Pro Max","precio":124.0,"costo":0.0,"stock":0,"cat":"vidrio trasero","stockMin":1},{"id":"db82","nombre":"vidrio trasero iphone 15","precio":124.0,"costo":0.0,"stock":0,"cat":"vidrio trasero","stockMin":1},{"id":"db83","nombre":"vidrio trasero iphone 15 Pro","precio":124.0,"costo":0.0,"stock":0,"cat":"vidrio trasero","stockMin":1},{"id":"db84","nombre":"vidrio trasero iphone 15 Pro Max","precio":124.0,"costo":0.0,"stock":0,"cat":"vidrio trasero","stockMin":1},{"id":"db85","nombre":"vidrio trasero iphone 16","precio":146.0,"costo":0.0,"stock":0,"cat":"vidrio trasero","stockMin":1},{"id":"db86","nombre":"vidrio trasero iphone 16 Plus","precio":146.0,"costo":0.0,"stock":0,"cat":"vidrio trasero","stockMin":1},{"id":"db87","nombre":"vidrio trasero iphone 16 Pro","precio":146.0,"costo":0.0,"stock":0,"cat":"vidrio trasero","stockMin":1},{"id":"db88","nombre":"vidrio trasero iphone 16 Pro Max","precio":146.0,"costo":0.0,"stock":0,"cat":"vidrio trasero","stockMin":1},{"id":"db93","nombre":"carcasa iphone Xr","precio":79.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db94","nombre":"carcasa iphone Xs","precio":79.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db95","nombre":"carcasa iphone XSMax","precio":92.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db96","nombre":"carcasa iphone 11","precio":106.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db97","nombre":"carcasa iphone 11 Pro","precio":130.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db98","nombre":"carcasa iphone 11 Pro Max","precio":118.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db99","nombre":"carcasa iphone 12mini","precio":167.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db100","nombre":"carcasa iphone 12","precio":182.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db101","nombre":"carcasa iphone 12 Pro","precio":182.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db102","nombre":"carcasa iphone 12 Pro Max","precio":209.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db103","nombre":"carcasa iphone 13mini","precio":157.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db104","nombre":"carcasa iphone 13","precio":132.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db105","nombre":"carcasa iphone 13 Pro","precio":209.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db106","nombre":"carcasa iphone 13 Pro Max","precio":233.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db107","nombre":"carcasa iphone 14","precio":180.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db108","nombre":"carcasa iphone 14 Plus","precio":209.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db109","nombre":"carcasa iphone 14 Pro","precio":223.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db110","nombre":"carcasa iphone 14 Pro Max","precio":260.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db111","nombre":"carcasa iphone 15","precio":209.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db112","nombre":"carcasa iphone 15 Pro","precio":250.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db113","nombre":"carcasa iphone 15 Pro Max","precio":263.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db114","nombre":"carcasa iphone 16","precio":0.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db115","nombre":"carcasa iphone 16 Pro","precio":0.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db116","nombre":"carcasa iphone 16 Pro Max","precio":0.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db119","nombre":"lente/parlante iphone 8","precio":42.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db120","nombre":"lente/parlante iphone SE","precio":42.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db121","nombre":"lente/parlante iphone Xr","precio":58.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db122","nombre":"lente/parlante iphone Xs","precio":58.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db123","nombre":"lente/parlante iphone XS Max","precio":74.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db124","nombre":"lente/parlante iphone 11","precio":83.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db125","nombre":"lente/parlante iphone 11 Pro","precio":92.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db126","nombre":"lente/parlante iphone 11 Pro Max","precio":92.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db127","nombre":"lente/parlante iphone 12 mini","precio":100.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db128","nombre":"lente/parlante iphone 12/12Pro","precio":112.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db129","nombre":"lente/parlante iphone 12 Pro Max","precio":112.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db130","nombre":"lente/parlante iphone 13 mini","precio":112.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db131","nombre":"lente/parlante iphone 13","precio":112.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db132","nombre":"lente/parlante iphone 13 Pro","precio":112.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db133","nombre":"lente/parlante iphone 13 Pro Max","precio":112.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db134","nombre":"lente/parlante iphone 14","precio":120.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db135","nombre":"lente/parlante iphone 14 Plus","precio":120.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db136","nombre":"lente/parlante iphone 14 Pro","precio":147.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db137","nombre":"lente/parlante iphone 14 Pro Max","precio":150.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db138","nombre":"lente/parlante iphone 15","precio":150.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db139","nombre":"lente/parlante iphone 15 Pro","precio":150.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db140","nombre":"lente/parlante iphone 15 Pro Max","precio":150.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db141","nombre":"lente/parlante iphone 16","precio":150.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db142","nombre":"lente/parlante iphone 16 Pro","precio":150.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db143","nombre":"lente/parlante iphone 16 Pro Max","precio":150.0,"costo":0.0,"stock":0,"cat":"otro repuesto","stockMin":1},{"id":"db148","nombre":"pin de carga iphone 8","precio":100.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db149","nombre":"pin de carga iphoneSE","precio":112.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db150","nombre":"pin de carga iphone Xr","precio":112.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db151","nombre":"pin de carga iphone Xs","precio":112.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db152","nombre":"pin de carga iphone Xs Max","precio":112.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db153","nombre":"pin de carga iphone 11","precio":170.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db154","nombre":"pin de carga iphone 11 Pro","precio":170.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db155","nombre":"pin de carga iphone 11 Pro Max","precio":170.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db156","nombre":"pin de carga iphone 12 Mini","precio":170.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db157","nombre":"pin de carga iphone 12/12 Pro","precio":175.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db158","nombre":"pin de carga iphone 12 Pro Max","precio":175.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db159","nombre":"pin de carga iphone 13mini","precio":175.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db160","nombre":"pin de carga iphone 13","precio":175.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db161","nombre":"pin de carga iphone 13 Pro","precio":175.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db162","nombre":"pin de carga iphone 13 Pro Max","precio":175.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db163","nombre":"pin de carga iphone 14","precio":175.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db164","nombre":"pin de carga iphone 14 Plus","precio":175.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db165","nombre":"pin de carga iphone 14 Pro","precio":175.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db166","nombre":"pin de carga iphone 14 Pro Max","precio":175.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db167","nombre":"pin de carga iphone 15","precio":175.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db168","nombre":"pin de carga iphone 15 Pro","precio":175.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db169","nombre":"pin de carga iphone 15 Pro Max","precio":175.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db170","nombre":"pin de carga iphone 16","precio":175.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db171","nombre":"pin de carga iphone 16 Plus","precio":175.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db172","nombre":"pin de carga iphone 16 Pro","precio":175.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db173","nombre":"pin de carga iphone 16 Pro Max","precio":175.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db177","nombre":"cámara principal iphone 8","precio":100.0,"costo":0.0,"stock":0,"cat":"camara","stockMin":1},{"id":"db178","nombre":"cámara principal iphone SE","precio":88.0,"costo":0.0,"stock":0,"cat":"camara","stockMin":1},{"id":"db179","nombre":"cámara principal iphone Xr","precio":88.0,"costo":0.0,"stock":0,"cat":"camara","stockMin":1},{"id":"db180","nombre":"cámara principal iphone Xs","precio":88.0,"costo":0.0,"stock":0,"cat":"camara","stockMin":1},{"id":"db181","nombre":"cámara principal iphone Xs Max","precio":88.0,"costo":0.0,"stock":0,"cat":"camara","stockMin":1},{"id":"db182","nombre":"cámara principal iphone 11","precio":134.0,"costo":0.0,"stock":0,"cat":"camara","stockMin":1},{"id":"db183","nombre":"cámara principal iphone 11 Pro","precio":134.0,"costo":0.0,"stock":0,"cat":"camara","stockMin":1},{"id":"db184","nombre":"cámara principal iphone 11 Pro Max","precio":134.0,"costo":0.0,"stock":0,"cat":"camara","stockMin":1},{"id":"db185","nombre":"cámara principal iphone 12 Mini","precio":134.0,"costo":0.0,"stock":0,"cat":"camara","stockMin":1},{"id":"db186","nombre":"cámara principal iphone 12","precio":134.0,"costo":0.0,"stock":0,"cat":"camara","stockMin":1},{"id":"db187","nombre":"cámara principal iphone 12/12 Pro","precio":134.0,"costo":0.0,"stock":0,"cat":"camara","stockMin":1},{"id":"db188","nombre":"cámara principal iphone 12 Pro Max","precio":135.0,"costo":0.0,"stock":0,"cat":"camara","stockMin":1},{"id":"db189","nombre":"cámara principal iphone 13 Mini","precio":0.0,"costo":0.0,"stock":0,"cat":"camara","stockMin":1},{"id":"db190","nombre":"cámara principal iphone 13","precio":127.0,"costo":0.0,"stock":0,"cat":"camara","stockMin":1},{"id":"db191","nombre":"cámara principal iphone 13 Pro","precio":190.0,"costo":0.0,"stock":0,"cat":"camara","stockMin":1},{"id":"db192","nombre":"cámara principal iphone 13 Pro Max","precio":280.0,"costo":0.0,"stock":0,"cat":"camara","stockMin":1},{"id":"db193","nombre":"cámara principal iphone 14","precio":190.0,"costo":0.0,"stock":0,"cat":"camara","stockMin":1},{"id":"db194","nombre":"cámara principal iphone 14 Plus","precio":172.0,"costo":0.0,"stock":0,"cat":"camara","stockMin":1},{"id":"db195","nombre":"cámara principal iphone 14 Pro","precio":190.0,"costo":0.0,"stock":0,"cat":"camara","stockMin":1},{"id":"db196","nombre":"cámara principal iphone 14 Pro Max","precio":280.0,"costo":0.0,"stock":0,"cat":"camara","stockMin":1},{"id":"db197","nombre":"cámara principal iphone 15","precio":190.0,"costo":0.0,"stock":0,"cat":"camara","stockMin":1},{"id":"db198","nombre":"cámara principal iphone 15 Pro","precio":280.0,"costo":0.0,"stock":0,"cat":"camara","stockMin":1},{"id":"db199","nombre":"cámara principal iphone 15 Pro Max","precio":190.0,"costo":0.0,"stock":0,"cat":"camara","stockMin":1},{"id":"db200","nombre":"cámara principal iphone 16","precio":342.0,"costo":0.0,"stock":0,"cat":"camara","stockMin":1},{"id":"db201","nombre":"cámara principal iphone 16 Plus","precio":0.0,"costo":0.0,"stock":0,"cat":"camara","stockMin":1},{"id":"db202","nombre":"cámara principal iphone 16 Pro","precio":0.0,"costo":0.0,"stock":0,"cat":"camara","stockMin":1},{"id":"db203","nombre":"cámara principal iphone 16 Pro Max","precio":0.0,"costo":0.0,"stock":0,"cat":"camara","stockMin":1},{"id":"db206","nombre":"cargador 20w OEM","precio":79.0,"costo":0.0,"stock":0,"cat":"Cargadores","stockMin":1},{"id":"db207","nombre":"cargador 40w OEM","precio":140.0,"costo":0.0,"stock":0,"cat":"Cargadores","stockMin":1},{"id":"db208","nombre":"cargador generico 5w","precio":38.0,"costo":0.0,"stock":0,"cat":"Cargadores","stockMin":1},{"id":"db209","nombre":"cargador generico 20w","precio":50.0,"costo":0.0,"stock":0,"cat":"Cargadores","stockMin":1},{"id":"db210","nombre":"cargador Mac 61w","precio":120.0,"costo":0.0,"stock":0,"cat":"Cargadores","stockMin":1},{"id":"db211","nombre":"Magsafe OEM","precio":105.0,"costo":0.0,"stock":0,"cat":"Cargadores","stockMin":1},{"id":"db212","nombre":"Magsafe generico","precio":60.0,"costo":0.0,"stock":0,"cat":"Cargadores","stockMin":1},{"id":"db213","nombre":"adaptador magsafe 2","precio":65.0,"costo":0.0,"stock":0,"cat":"Cargadores","stockMin":1},{"id":"db214","nombre":"robot porta cámara","precio":30.0,"costo":0.0,"stock":0,"cat":"Cargadores","stockMin":1},{"id":"db215","nombre":"robot magsafe","precio":80.0,"costo":0.0,"stock":0,"cat":"Cables","stockMin":1},{"id":"db216","nombre":"cable OEM Thunderbolt","precio":59.0,"costo":0.0,"stock":0,"cat":"Cables","stockMin":1},{"id":"db217","nombre":"cable lightning genérico","precio":32.0,"costo":0.0,"stock":0,"cat":"Cables","stockMin":1},{"id":"db218","nombre":"cable OEM lightning","precio":55.0,"costo":0.0,"stock":0,"cat":"Cables","stockMin":1},{"id":"db219","nombre":"cable OEM lightning 2mts","precio":60.0,"costo":0.0,"stock":0,"cat":"Cables","stockMin":1},{"id":"db220","nombre":"cable Anker/Ringke","precio":45.0,"costo":0.0,"stock":0,"cat":"Cables","stockMin":1},{"id":"db221","nombre":"cable usbc to lightning genérico","precio":40.0,"costo":0.0,"stock":0,"cat":"Cables","stockMin":1},{"id":"db222","nombre":"cable OEM usbc to lightning","precio":68.0,"costo":0.0,"stock":0,"cat":"Cables","stockMin":1},{"id":"db223","nombre":"cable OEM usbc","precio":60.0,"costo":0.0,"stock":0,"cat":"Cables","stockMin":1},{"id":"db224","nombre":"cable usbc genérico","precio":40.0,"costo":0.0,"stock":0,"cat":"Cables","stockMin":1},{"id":"db225","nombre":"usb y usbc watch OEM","precio":70.0,"costo":0.0,"stock":0,"cat":"Cables","stockMin":1},{"id":"db226","nombre":"cable OEM original usbc 2mts","precio":75.0,"costo":0.0,"stock":0,"cat":"Cables","stockMin":1},{"id":"db227","nombre":"cable genérico usbc 2mts","precio":40.0,"costo":0.0,"stock":0,"cat":"Cables","stockMin":1},{"id":"db228","nombre":"adaptador Mac Usb + Usbc + HDMI","precio":67.0,"costo":0.0,"stock":0,"cat":"Cables","stockMin":1},{"id":"db229","nombre":"cable adaptador Red a usbC","precio":35.0,"costo":8.0,"stock":0,"cat":"Cables","stockMin":1},{"id":"db230","nombre":"cable adaptador arg Macbook","precio":52.0,"costo":0.0,"stock":0,"cat":"Cables","stockMin":1},{"id":"db231","nombre":"cable Magsafe 3","precio":80.0,"costo":0.0,"stock":0,"cat":"Cables","stockMin":1},{"id":"db232","nombre":"cable enchufe viaje (USB,USBC)","precio":60.0,"costo":0.0,"stock":0,"cat":"Cables","stockMin":1},{"id":"db233","nombre":"ficha patas Argentinas","precio":30.0,"costo":0.0,"stock":0,"cat":"Cables","stockMin":1},{"id":"db235","nombre":"Funda puntera transparente iphone 7/8","precio":25.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db236","nombre":"Funda puntera transparente iphone SE","precio":25.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db237","nombre":"Funda puntera transparente iphone X/Xs","precio":25.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db238","nombre":"Funda puntera transparente iphone Xr/11","precio":25.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db239","nombre":"Funda puntera transparente iphone XsMax/11PM","precio":25.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db240","nombre":"Funda puntera transparente iphone 12mini","precio":25.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db241","nombre":"Funda puntera transparente iphone 12/12P","precio":30.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db242","nombre":"Funda puntera transparente iphone 12PM","precio":30.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db243","nombre":"Funda puntera transparente iphone 13mini","precio":30.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db244","nombre":"Funda puntera transparente iphone 13/13P","precio":30.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db245","nombre":"Funda puntera transparente iphone 13PM","precio":30.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db246","nombre":"Funda puntera transparente iphone 14","precio":30.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db247","nombre":"Funda puntera transparente iphone 14Plus","precio":30.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db248","nombre":"Funda puntera transparente iphone 14P","precio":30.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db249","nombre":"Funda puntera transparente iphone 14PM","precio":30.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db250","nombre":"Funda puntera transparente iphone 15+","precio":30.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db252","nombre":"Funda fotosensible iphone 11","precio":15.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db253","nombre":"Funda fotosensible iphone 13","precio":24.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db254","nombre":"Funda fotosensible iphone 14PM","precio":24.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db256","nombre":"Funda Magsafe transparente","precio":22.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db257","nombre":"Funda Magsafe transparente iphone 11","precio":22.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db258","nombre":"Funda Magsafe transparente iphone 11P","precio":22.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db259","nombre":"Funda Magsafe transparente iphone 11PM","precio":22.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db260","nombre":"Funda Magsafe transparente iphone 12/12P","precio":40.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db261","nombre":"Funda Magsafe transparente iphone 12PM","precio":40.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db262","nombre":"Funda Magsafe transparente iphone 13/16e","precio":40.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db263","nombre":"Funda Magsafe transparente iphone 13mini","precio":40.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db264","nombre":"Funda Magsafe transparente iphone 13P","precio":40.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db265","nombre":"Funda Magsafe transparente iphone 13PM","precio":40.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db266","nombre":"Funda Magsafe transparente iphone 14","precio":40.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db267","nombre":"Funda Magsafe transparente iphone 14Plus","precio":40.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db268","nombre":"Funda Magsafe transparente iphone 14P","precio":40.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db269","nombre":"Funda Magsafe transparente iphone 14PM","precio":40.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db270","nombre":"Funda Magsafe transparente iphone 15","precio":40.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db271","nombre":"Funda Magsafe transparente iphone 15P","precio":40.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db272","nombre":"Funda Magsafe transparente iphone 15PM","precio":40.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db273","nombre":"Funda Magsafe transparente iphone 16","precio":40.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db274","nombre":"Funda Magsafe transparente iphone 15plus/16plus","precio":40.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db275","nombre":"Funda Magsafe transparente iphone 16P","precio":40.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db276","nombre":"Funda Magsafe transparente iphone 16PM","precio":40.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db277","nombre":"Funda Magsafe transparente iphone 17","precio":40.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db278","nombre":"Funda Magsafe transparente iphone Air","precio":40.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db279","nombre":"Funda Magsafe transparente iphone 17P","precio":40.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db280","nombre":"Funda Magsafe transparente iphone 17PM","precio":40.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db282","nombre":"Funda ipad 10gen","precio":58.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db283","nombre":"Funda protector teclado M1","precio":25.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db284","nombre":"Llavero para airtag","precio":20.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db285","nombre":"soporte iman","precio":30.0,"costo":0.0,"stock":0,"cat":"Fundas","stockMin":1},{"id":"db287","nombre":"templado 5D 7/8","precio":20.0,"costo":0.0,"stock":0,"cat":"Templados","stockMin":1},{"id":"db288","nombre":"templado 5D 7plus/8plus","precio":20.0,"costo":0.0,"stock":0,"cat":"Templados","stockMin":1},{"id":"db289","nombre":"templado 5D Xr/11","precio":20.0,"costo":0.0,"stock":0,"cat":"Templados","stockMin":1},{"id":"db290","nombre":"templado 5D X/Xs/11Pro","precio":20.0,"costo":0.0,"stock":0,"cat":"Templados","stockMin":1},{"id":"db291","nombre":"templado 5D Xsmax/11Pro Max","precio":20.0,"costo":0.0,"stock":0,"cat":"Templados","stockMin":1},{"id":"db292","nombre":"templado 5D 12mini","precio":20.0,"costo":0.0,"stock":0,"cat":"Templados","stockMin":1},{"id":"db293","nombre":"templado 5D 12/12P","precio":20.0,"costo":0.0,"stock":0,"cat":"Templados","stockMin":1},{"id":"db294","nombre":"templado 5D 12PM","precio":20.0,"costo":0.0,"stock":0,"cat":"Templados","stockMin":1},{"id":"db295","nombre":"templado 5D 13mini","precio":45.0,"costo":0.0,"stock":0,"cat":"Templados","stockMin":1},{"id":"db296","nombre":"templado 5D 13/13P/14/16e","precio":45.0,"costo":0.0,"stock":0,"cat":"Templados","stockMin":1},{"id":"db297","nombre":"templado 5D 13PM/14plus","precio":45.0,"costo":0.0,"stock":0,"cat":"Templados","stockMin":1},{"id":"db298","nombre":"templado 5D 14P/14PM","precio":45.0,"costo":0.0,"stock":0,"cat":"Templados","stockMin":1},{"id":"db299","nombre":"templado 5D 15/16","precio":45.0,"costo":0.0,"stock":0,"cat":"Templados","stockMin":1},{"id":"db300","nombre":"templado 5D 15P","precio":45.0,"costo":0.0,"stock":0,"cat":"Templados","stockMin":1},{"id":"db301","nombre":"templado 5D 15/16plus","precio":45.0,"costo":0.0,"stock":0,"cat":"Templados","stockMin":1},{"id":"db302","nombre":"templado 5D 15PM","precio":45.0,"costo":0.0,"stock":0,"cat":"Templados","stockMin":1},{"id":"db303","nombre":"templado 5D 16P/17","precio":45.0,"costo":0.0,"stock":0,"cat":"Templados","stockMin":1},{"id":"db304","nombre":"templado 5D 16PM","precio":45.0,"costo":0.0,"stock":0,"cat":"Templados","stockMin":1},{"id":"db305","nombre":"templado 5D Air","precio":45.0,"costo":0.0,"stock":0,"cat":"Templados","stockMin":1},{"id":"db306","nombre":"templado 5D 17P","precio":45.0,"costo":0.0,"stock":0,"cat":"Templados","stockMin":1},{"id":"db307","nombre":"templado 5D 17PM","precio":45.0,"costo":0.0,"stock":0,"cat":"Templados","stockMin":1},{"id":"db309","nombre":"templado común standard","precio":16.0,"costo":0.0,"stock":0,"cat":"Templados","stockMin":1},{"id":"db311","nombre":"protector cámara 5D","precio":25.0,"costo":0.0,"stock":0,"cat":"Templados","stockMin":1},{"id":"db314","nombre":"templado para ipad","precio":52.0,"costo":0.0,"stock":0,"cat":"Templados","stockMin":1},{"id":"db317","nombre":"airpods 2da gen","precio":230.0,"costo":0.0,"stock":0,"cat":"Otro","stockMin":1},{"id":"db318","nombre":"airpods 3ra gen","precio":320.0,"costo":0.0,"stock":0,"cat":"Otro","stockMin":1},{"id":"db319","nombre":"airpods Pro 2","precio":300.0,"costo":0.0,"stock":0,"cat":"Otro","stockMin":1},{"id":"db320","nombre":"airpods 4","precio":280.0,"costo":0.0,"stock":0,"cat":"Otro","stockMin":1},{"id":"db321","nombre":"earpods","precio":52.0,"costo":0.0,"stock":0,"cat":"Otro","stockMin":1},{"id":"db322","nombre":"airtag","precio":60.0,"costo":0.0,"stock":0,"cat":"Otro","stockMin":1},{"id":"db323","nombre":"atril MacBook","precio":45.0,"costo":0.0,"stock":0,"cat":"Otro","stockMin":1},{"id":"db324","nombre":"Battery Pack","precio":0.0,"costo":0.0,"stock":0,"cat":"Otro","stockMin":1},{"id":"db325","nombre":"Pencil Usb C","precio":200.0,"costo":0.0,"stock":0,"cat":"Otro","stockMin":1},{"id":"db326","nombre":"Pencil 1era gen","precio":200.0,"costo":0.0,"stock":0,"cat":"Otro","stockMin":1},{"id":"db327","nombre":"Pencil 2da gen","precio":0.0,"costo":0.0,"stock":0,"cat":"Otro","stockMin":1},{"id":"db328","nombre":"Magic Mouse","precio":0.0,"costo":0.0,"stock":0,"cat":"Otro","stockMin":1},{"id":"db330","nombre":"pin/restauración/parlantes iphone 8","precio":28.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db331","nombre":"pin/restauración/parlantes iphone SE/X","precio":35.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db332","nombre":"pin/restauración/parlantes iphone Xr/11","precio":38.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db333","nombre":"pin/restauración/parlantes iphone 12","precio":52.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db334","nombre":"pin/restauración/parlantes iphone 13/macbook","precio":75.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db335","nombre":"pin/restauración/parlantes iphone 14","precio":75.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db336","nombre":"pin/restauración/parlantes iphone 15","precio":75.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db337","nombre":"pin/restauración/parlantes iphone 16","precio":85.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db338","nombre":"pin/restauración/parlantes iphone 17","precio":85.0,"costo":0.0,"stock":0,"cat":"pin de carga","stockMin":1},{"id":"db340","nombre":"iPhone X 64GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db341","nombre":"iPhone X 256GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db342","nombre":"iPhone XR 64GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db343","nombre":"iPhone XR 128GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db344","nombre":"iPhone XR 256GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db345","nombre":"iPhone XS 64GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db346","nombre":"iPhone XS 256GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db347","nombre":"iPhone XS 512GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db348","nombre":"iPhone XS Max 64GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db349","nombre":"iPhone XS Max 256GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db350","nombre":"iPhone XS Max 512GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db351","nombre":"iPhone 11 64GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db352","nombre":"iPhone 11 128GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db353","nombre":"iPhone 11 256GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db354","nombre":"iPhone 11 Pro 64GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db355","nombre":"iPhone 11 Pro 256GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db356","nombre":"iPhone 11 Pro 512GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db357","nombre":"iPhone 11 Pro Max 64GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db358","nombre":"iPhone 11 Pro Max 256GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db359","nombre":"iPhone 11 Pro Max 512GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db360","nombre":"iPhone SE 2da gen 64GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db361","nombre":"iPhone SE 2da gen 128GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db362","nombre":"iPhone SE 2da gen 256GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db363","nombre":"iPhone 12 mini 64GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db364","nombre":"iPhone 12 mini 128GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db365","nombre":"iPhone 12 mini 256GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db366","nombre":"iPhone 12 64GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db367","nombre":"iPhone 12 128GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db368","nombre":"iPhone 12 256GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db369","nombre":"iPhone 12 Pro 128GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db370","nombre":"iPhone 12 Pro 256GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db371","nombre":"iPhone 12 Pro 512GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db372","nombre":"iPhone 12 Pro Max 128GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db373","nombre":"iPhone 12 Pro Max 256GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db374","nombre":"iPhone 12 Pro Max 512GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db375","nombre":"iPhone 13 mini 128GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db376","nombre":"iPhone 13 mini 256GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db377","nombre":"iPhone 13 mini 512GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db378","nombre":"iPhone 13 128GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db379","nombre":"iPhone 13 256GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db380","nombre":"iPhone 13 512GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db381","nombre":"iPhone 13 Pro 128GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db382","nombre":"iPhone 13 Pro 256GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db383","nombre":"iPhone 13 Pro 512GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db384","nombre":"iPhone 13 Pro 1TB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db385","nombre":"iPhone 13 Pro Max 128GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db386","nombre":"iPhone 13 Pro Max 256GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db387","nombre":"iPhone 13 Pro Max 512GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db388","nombre":"iPhone 13 Pro Max 1TB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db389","nombre":"iPhone SE 3ra gen 64GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db390","nombre":"iPhone SE 3ra gen 128GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db391","nombre":"iPhone SE 3ra gen 256GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db392","nombre":"iPhone 14 128GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db393","nombre":"iPhone 14 256GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db394","nombre":"iPhone 14 512GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db395","nombre":"iPhone 14 Plus 128GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db396","nombre":"iPhone 14 Plus 256GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db397","nombre":"iPhone 14 Plus 512GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db398","nombre":"iPhone 14 Pro 128GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db399","nombre":"iPhone 14 Pro 256GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db400","nombre":"iPhone 14 Pro 512GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db401","nombre":"iPhone 14 Pro 1TB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db402","nombre":"iPhone 14 Pro Max 128GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db403","nombre":"iPhone 14 Pro Max 256GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db404","nombre":"iPhone 14 Pro Max 512GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db405","nombre":"iPhone 14 Pro Max 1TB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db406","nombre":"iPhone 15 128GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db407","nombre":"iPhone 15 256GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db408","nombre":"iPhone 15 512GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db409","nombre":"iPhone 15 Plus 128GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db410","nombre":"iPhone 15 Plus 256GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db411","nombre":"iPhone 15 Plus 512GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db412","nombre":"iPhone 15 Pro 128GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db413","nombre":"iPhone 15 Pro 256GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db414","nombre":"iPhone 15 Pro 512GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db415","nombre":"iPhone 15 Pro 1TB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db416","nombre":"iPhone 15 Pro Max 256GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db417","nombre":"iPhone 15 Pro Max 512GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db418","nombre":"iPhone 15 Pro Max 1TB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db419","nombre":"iPhone 16 128GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db420","nombre":"iPhone 16 256GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db421","nombre":"iPhone 16 512GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db422","nombre":"iPhone 16 Plus 128GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db423","nombre":"iPhone 16 Plus 256GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db424","nombre":"iPhone 16 Plus 512GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db425","nombre":"iPhone 16 Pro 128GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db426","nombre":"iPhone 16 Pro 256GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db427","nombre":"iPhone 16 Pro 512GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db428","nombre":"iPhone 16 Pro 1TB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db429","nombre":"iPhone 16 Pro Max 256GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db430","nombre":"iPhone 16 Pro Max 512GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db431","nombre":"iPhone 16 Pro Max 1TB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db432","nombre":"iPhone 17 128GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db433","nombre":"iPhone 17 256GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db434","nombre":"iPhone 17 512GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db435","nombre":"iPhone 17 Plus 128GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db436","nombre":"iPhone 17 Plus 256GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db437","nombre":"iPhone 17 Plus 512GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db438","nombre":"iPhone 17 Pro 128GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db439","nombre":"iPhone 17 Pro 256GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db440","nombre":"iPhone 17 Pro 512GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db441","nombre":"iPhone 17 Pro 1TB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db442","nombre":"iPhone 17 Pro Max 256GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db443","nombre":"iPhone 17 Pro Max 512GB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1},{"id":"db444","nombre":"iPhone 17 Pro Max 1TB","precio":0.0,"costo":0.0,"stock":0,"cat":"iPhone","stockMin":1}];

/* ═══════════════════════════════════════════════════
   HELPERS
═══════════════════════════════════════════════════ */
const usd = n=>`USD ${Number(n).toFixed(2)}`;
const ars = (n,c)=>c?`$${Math.round(n*c).toLocaleString("es-AR")}`:`$${Math.round(n).toLocaleString("es-AR")}`;
const newId = ()=>Date.now().toString(36)+Math.random().toString(36).slice(2,5);
const todayStr = ()=>new Date().toISOString().slice(0,10);
const fmtDate = iso=>new Date(iso).toLocaleString("es-AR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"});
const fmtDay  = iso=>new Date(iso).toLocaleDateString("es-AR",{day:"2-digit",month:"2-digit",year:"2-digit"});
const monthsAgo=(iso,n)=>new Date(iso)>=new Date(Date.now()-n*30*24*3600*1000);
const fraseDia = ()=>FRASES[new Date().getHours() % FRASES.length];

/* ═══════════════════════════════════════════════════
   ESTADOS ÓRDENES
═══════════════════════════════════════════════════ */
const ESTADOS = ["Señado","Listo para retirar","Entregado"];
const ESTADO_COLOR = {"Señado":"#f59e0b","Listo para retirar":"#10b981","Entregado":"#64748b"};

/* ═══════════════════════════════════════════════════
   DESIGN SYSTEM — MINIMALISTA CLARO
═══════════════════════════════════════════════════ */
const C = {
  bg:"#f8f9fb", surface:"#ffffff", card:"#ffffff",
  border:"#e8ecf0", borderHi:"#1a1a2e",
  text:"#1a1a2e", muted:"#8892a4", faint:"#f0f2f5",
  accent:"#1a1a2e", accentSoft:"#1a1a2e15",
  green:"#059669", red:"#dc2626", amber:"#d97706", blue:"#2563eb",
  gold:"#b8860b",
};

const inp = {
  background:"#f8f9fb", border:`1.5px solid ${C.border}`,
  borderRadius:8, color:C.text, padding:"9px 12px",
  fontSize:13, width:"100%", fontFamily:"'DM Sans',sans-serif",
};

const Card=({children,style={}})=>(
  <div style={{background:C.card,border:`1px solid ${C.border}`,borderRadius:14,padding:"18px 20px",...style}}>{children}</div>
);
const STitle=({children,sm})=>(
  <p style={{fontFamily:"'Syne',sans-serif",fontWeight:700,fontSize:sm?12:14,color:C.text,letterSpacing:"-.01em"}}>{children}</p>
);
const Chip=({children,active,onClick,color=C.accent,small})=>(
  <button onClick={onClick} style={{
    padding:small?"5px 11px":"6px 14px",borderRadius:20,fontSize:small?11:12,fontWeight:600,
    background:active?color:"transparent",
    border:`1.5px solid ${active?color:C.border}`,
    color:active?"#fff":C.muted,transition:"all .15s",
    fontFamily:"'DM Sans',sans-serif",cursor:"pointer",
  }}>{children}</button>
);
const Badge=({children,color=C.accent})=>(
  <span style={{fontSize:10,fontWeight:700,background:`${color}18`,color,borderRadius:5,padding:"2px 7px",whiteSpace:"nowrap"}}>{children}</span>
);
const Btn=({children,onClick,color=C.accent,disabled,full,sm,outline})=>(
  <button onClick={onClick} disabled={disabled} style={{
    padding:sm?"7px 14px":"10px 20px",borderRadius:9,fontSize:sm?12:13,fontWeight:600,
    background:disabled?"#e8ecf0":outline?"transparent":color,
    color:disabled?C.muted:outline?color:"#fff",
    border:outline?`1.5px solid ${color}`:"none",
    cursor:disabled?"not-allowed":"pointer",transition:"all .18s",
    width:full?"100%":"auto",fontFamily:"'DM Sans',sans-serif",
  }}>{children}</button>
);
const StatCard=({label,value,sub,color=C.accent,icon})=>(
  <div style={{background:C.surface,border:`1px solid ${C.border}`,borderRadius:12,padding:"16px 18px"}}>
    <div style={{display:"flex",alignItems:"center",gap:6,marginBottom:6}}>
      {icon&&<span style={{fontSize:16}}>{icon}</span>}
      <p style={{fontSize:11,color:C.muted,fontWeight:600,textTransform:"uppercase",letterSpacing:".07em"}}>{label}</p>
    </div>
    <p style={{fontSize:22,fontWeight:800,color,fontFamily:"'Syne',sans-serif"}}>{value}</p>
    {sub&&<p style={{fontSize:11,color:C.muted,marginTop:3}}>{sub}</p>}
  </div>
);
const MiniBar=({label,value,max,color=C.accent,right})=>(
  <div style={{marginBottom:10}}>
    <div style={{display:"flex",justifyContent:"space-between",fontSize:12,marginBottom:4}}>
      <span style={{color:C.muted}}>{label}</span>
      <span style={{color:C.text,fontWeight:600}}>{right||usd(value)}</span>
    </div>
    <div style={{background:C.faint,borderRadius:4,height:5}}>
      <div style={{width:`${max>0?Math.min(100,(value/max)*100):0}%`,background:color,height:"100%",borderRadius:4,transition:"width .6s"}}/>
    </div>
  </div>
);
const Row=({label,val,bold,accent,valColor})=>(
  <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:3}}>
    <span style={{fontSize:12,color:bold?C.text:C.muted,fontWeight:bold?600:400}}>{label}</span>
    <span style={{fontSize:bold?14:12,fontWeight:bold?700:500,color:valColor||(accent?C.accent:bold?C.text:C.muted),fontFamily:bold?"'Syne',sans-serif":undefined}}>{val}</span>
  </div>
);

/* ═══════════════════════════════════════════════════
   LOGO COMPONENT
═══════════════════════════════════════════════════ */
const Logo=({size=28,dark=true})=>(
  <div style={{display:"flex",alignItems:"center",gap:8}}>
    <img src={BRAND.logoUrl} alt="iCompany" style={{height:size,width:size,objectFit:"contain"}}
      onError={e=>{e.target.style.display="none";}}/>
    <span style={{fontFamily:"'Syne',sans-serif",fontWeight:800,fontSize:size*0.75,
      color:dark?C.text:"#fff",letterSpacing:"-.02em"}}>
      <span style={{fontWeight:400}}>i</span>Company®
    </span>
  </div>
);

/* ═══════════════════════════════════════════════════
   FRASE MOTIVACIONAL
═══════════════════════════════════════════════════ */
const FraseBanner=()=>{
  const f = fraseDia();
  return(
    <div style={{background:`linear-gradient(135deg,#1a1a2e 0%,#2d2d4e 100%)`,
      borderRadius:12,padding:"14px 18px",marginBottom:20}}>
      <p style={{fontSize:12,color:"#a0a8c0",fontStyle:"italic",lineHeight:1.6,marginBottom:4}}>
        "{f.texto}"
      </p>
      <p style={{fontSize:10,color:"#6878a0",fontWeight:600,letterSpacing:".05em"}}>— {f.ref}</p>
    </div>
  );
};

/* ═══════════════════════════════════════════════════
   APP ROOT
═══════════════════════════════════════════════════ */
function App(){
  const [session,setSession]=useState(null);
  const [usuarios,setUsuarios]=useState(null);
  const [ventas,setVentas]=useState([]);
  const [ordenes,setOrdenes]=useState([]);
  const [clientes,setClientes]=useState([]);
  const [catalogo,setCatalogo]=useState([]);
  const [cotiz,setCotiz]=useState(1000);
  const [movCaja,setMovCaja]=useState([]);
  const [ready,setReady]=useState(false);

  useEffect(()=>{
    Promise.all([sg(SK.usuarios),sg(SK.ventas),sg(SK.ordenes),sg(SK.clientes),sg(SK.catalogo),sg(SK.cotiz),sg(SK.movCaja)])
    .then(([u,v,o,cl,cat,co,mc])=>{
      const usrs=u||[{id:"owner",nombre:"Dueño",rol:"owner",pass:"1234",activo:true}];
      if(!u) ss(SK.usuarios,usrs);
      setUsuarios(usrs); setVentas(v||[]); setOrdenes(o||[]); setClientes(cl||[]);
      setCatalogo(cat||CATALOGO_INICIAL); setCotiz(co||1450); setMovCaja(mc||[]); setReady(true);
    });
  },[]);

  const persist=async(tabla,setter,val)=>{setter(val);await ss(tabla,val);};

  if(!ready) return(
    <div style={{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",
      height:"100vh",background:C.bg,gap:16}}>
      <link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=Syne:wght@700;800&display=swap" rel="stylesheet"/>
      <Logo size={40}/>
      <p style={{color:C.muted,fontSize:13,fontFamily:"'DM Sans',sans-serif"}}>Iniciando sistema…</p>
    </div>
  );

  if(!session) return <LoginScreen usuarios={usuarios} onLogin={setSession} onSetup={usrs=>persist(SK.usuarios,setUsuarios,usrs)}/>;

  const ctx={session,usuarios,setUsuarios,ventas,setVentas,ordenes,setOrdenes,
    clientes,setClientes,catalogo,setCatalogo,cotiz,setCotiz,movCaja,setMovCaja,persist,SK};

  return <MainApp ctx={ctx} onLogout={()=>setSession(null)}/>;
}

/* ═══════════════════════════════════════════════════
   LOGIN
═══════════════════════════════════════════════════ */
function LoginScreen({usuarios,onLogin,onSetup}){
  const [step,setStep]=useState("select");
  const [sel,setSel]=useState(null);
  const [pass,setPass]=useState("");
  const [np,setNp]=useState(""); const [np2,setNp2]=useState("");
  const [err,setErr]=useState("");

  const activos=(usuarios||[]).filter(u=>u.activo);
  const sel_u=u=>{setSel(u);setPass("");setErr("");setStep(u.pass?"pass":"newpass");};
  const doLogin=()=>{if(sel.pass!==pass){setErr("Contraseña incorrecta");return;}onLogin(sel);};
  const doSetPass=()=>{
    if(np.length<4){setErr("Mínimo 4 caracteres");return;}
    if(np!==np2){setErr("No coinciden");return;}
    const upd=usuarios.map(u=>u.id===sel.id?{...u,pass:np}:u);
    onSetup(upd); onLogin({...sel,pass:np});
  };

  return(
    <div style={{minHeight:"100vh",background:C.bg,display:"flex",alignItems:"center",justifyContent:"center",padding:20}}>
      <link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=Syne:wght@700;800&display=swap" rel="stylesheet"/>
      <style>{`*{box-sizing:border-box;margin:0;padding:0}button{cursor:pointer;border:none}input,select,textarea{outline:none}@keyframes fadeUp{from{opacity:0;transform:translateY(12px)}to{opacity:1;transform:translateY(0)}}.fu{animation:fadeUp .3s ease both}`}</style>
      <div className="fu" style={{width:"100%",maxWidth:400}}>
        <div style={{textAlign:"center",marginBottom:32}}>
          <img src="/assets/logo.png" alt="iCompany" style={{height:80,objectFit:"contain",marginBottom:8}}
            onError={e=>{e.target.style.display="none";}}/>
          <p style={{color:C.muted,fontSize:12,fontFamily:"'DM Sans',sans-serif"}}>Sistema de gestión · Pilar</p>
        </div>

        {/* FRASE EN LOGIN */}
        <FraseBanner/>

        <Card>
          {step==="select"&&(
            <>
              <STitle>¿Quién sos?</STitle>
              <div style={{marginTop:14,display:"flex",flexDirection:"column",gap:8}}>
                {activos.map(u=>(
                  <button key={u.id} onClick={()=>sel_u(u)} style={{
                    padding:"13px 16px",borderRadius:10,background:C.faint,
                    border:`1px solid ${C.border}`,textAlign:"left",
                    display:"flex",alignItems:"center",gap:12,transition:"all .15s",
                  }}>
                    <div style={{width:36,height:36,borderRadius:"50%",
                      background:u.rol==="owner"?"#1a1a2e":"#f0f2f5",
                      display:"flex",alignItems:"center",justifyContent:"center",
                      fontSize:16,flexShrink:0}}>
                      {u.rol==="owner"?"👑":"👤"}
                    </div>
                    <div>
                      <p style={{fontWeight:700,fontSize:14,color:C.text,fontFamily:"'DM Sans',sans-serif"}}>{u.nombre}</p>
                      <p style={{fontSize:11,color:C.muted,fontFamily:"'DM Sans',sans-serif"}}>{u.rol==="owner"?"Propietario":"Empleado"}</p>
                    </div>
                  </button>
                ))}
              </div>
            </>
          )}
          {step==="pass"&&(
            <>
              <button onClick={()=>setStep("select")} style={{background:"none",color:C.muted,fontSize:12,marginBottom:12,fontFamily:"'DM Sans',sans-serif"}}>← Volver</button>
              <STitle>Hola, {sel?.nombre} 👋</STitle>
              <p style={{fontSize:12,color:C.muted,marginTop:4,marginBottom:14,fontFamily:"'DM Sans',sans-serif"}}>Ingresá tu contraseña</p>
              <input type="password" value={pass} onChange={e=>{setPass(e.target.value);setErr("");}}
                onKeyDown={e=>e.key==="Enter"&&doLogin()} placeholder="Contraseña" style={inp}/>
              {err&&<p style={{fontSize:12,color:C.red,marginTop:6,fontFamily:"'DM Sans',sans-serif"}}>{err}</p>}
              <div style={{marginTop:12}}><Btn full onClick={doLogin}>Ingresar</Btn></div>
            </>
          )}
          {step==="newpass"&&(
            <>
              <STitle>¡Bienvenido, {sel?.nombre}!</STitle>
              <p style={{fontSize:12,color:C.muted,marginTop:4,marginBottom:14,fontFamily:"'DM Sans',sans-serif"}}>Es tu primer acceso. Elegí una contraseña.</p>
              <input type="password" value={np} onChange={e=>{setNp(e.target.value);setErr("");}}
                placeholder="Nueva contraseña (mín. 4 caracteres)" style={{...inp,marginBottom:8}}/>
              <input type="password" value={np2} onChange={e=>{setNp2(e.target.value);setErr("");}}
                placeholder="Repetir contraseña" style={inp}/>
              {err&&<p style={{fontSize:12,color:C.red,marginTop:6,fontFamily:"'DM Sans',sans-serif"}}>{err}</p>}
              <div style={{marginTop:12}}><Btn full onClick={doSetPass}>Guardar y entrar</Btn></div>
            </>
          )}
        </Card>
      </div>
    </div>
  );
}

/* ═══════════════════════════════════════════════════
   MAIN APP
═══════════════════════════════════════════════════ */
function MainApp({ctx,onLogout}){
  const isOwner=ctx.session.rol==="owner";
  const tabs=isOwner
    ?[["venta","🧾","Venta"],["ordenes","📋","Órdenes"],["clientes","👤","Clientes"],["stock","📦","Stock"],["caja","💵","Caja"],["dashboard","📊","Dashboard"]]
    :[["venta","🧾","Venta"],["ordenes","📋","Órdenes"],["clientes","👤","Clientes"],["caja","💵","Mi Caja"]];
  const [tab,setTab]=useState("venta");

  return(
    <div style={{minHeight:"100vh",background:C.bg,color:C.text,fontFamily:"'DM Sans',sans-serif"}}>
      <link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=Syne:wght@700;800&display=swap" rel="stylesheet"/>
      <style>{`*{box-sizing:border-box;margin:0;padding:0}::-webkit-scrollbar{width:4px}::-webkit-scrollbar-track{background:${C.bg}}::-webkit-scrollbar-thumb{background:${C.border};border-radius:3px}button{cursor:pointer;border:none;font-family:'DM Sans',sans-serif}input,select,textarea{outline:none;font-family:'DM Sans',sans-serif}@keyframes fadeUp{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}.fu{animation:fadeUp .25s ease both}@media print{.no-print{display:none!important}.print-only{display:block!important}}`}</style>

      <header style={{background:C.surface,borderBottom:`1px solid ${C.border}`,padding:"0 20px",
        height:54,display:"flex",alignItems:"center",justifyContent:"space-between",
        position:"sticky",top:0,zIndex:200}}>
        <Logo size={26}/>
        <nav style={{display:"flex",gap:4}}>
          {tabs.map(([k,e,l])=>(
            <button key={k} onClick={()=>setTab(k)} style={{
              padding:"5px 12px",borderRadius:7,fontSize:12,fontWeight:600,
              background:tab===k?C.accent:"transparent",
              color:tab===k?"#fff":C.muted,
              border:tab===k?"none":`1px solid transparent`,transition:"all .18s",
            }}>{e} {l}</button>
          ))}
        </nav>
        <div style={{display:"flex",alignItems:"center",gap:8}}>
          <span style={{fontSize:12,color:C.muted}}>{ctx.session.nombre}</span>
          <Btn sm outline color={C.muted} onClick={onLogout}>Salir</Btn>
        </div>
      </header>

      <div style={{maxWidth:1100,margin:"0 auto",padding:"22px 16px"}}>
        <FraseBanner/>
        {tab==="venta"    &&<VentaView ctx={ctx}/>}
        {tab==="ordenes"  &&<OrdenesView ctx={ctx}/>}
        {tab==="clientes" &&<ClientesView ctx={ctx}/>}
        {tab==="stock"    &&isOwner&&<StockView ctx={ctx}/>}
        {tab==="caja"     &&<CajaView ctx={ctx}/>}
        {tab==="dashboard"&&isOwner&&<DashView ctx={ctx}/>}
      </div>
    </div>
  );
}

/* ═══════════════════════════════════════════════════
   VISTA VENTA
═══════════════════════════════════════════════════ */
function VentaView({ctx}){
  const {session,catalogo,cotiz,ventas,setVentas,persist,SK}=ctx;
  const [items,setItems]=useState([]);
  const [pagos,setPagos]=useState([]);
  const [nota,setNota]=useState("");
  const [busq,setBusq]=useState("");
  const [catFil,setCatFil]=useState("Todos");
  const [ok,setOk]=useState(false);
  const [lastVenta,setLastVenta]=useState(null);
  const [showLastDetail,setShowLastDetail]=useState(false);
  const [custom,setCustom]=useState({show:false,nombre:"",precio:"",costo:"",cat:"Pantallas"});

  const cats=["Todos",...new Set(catalogo.map(p=>p.cat))];

  const filtrados=catalogo.filter(p=>{
    const matchCat=catFil==="Todos"||p.cat===catFil;
    const matchBusq=!busq||busq.trim().split(/\s+/).every(w=>p.nombre.toLowerCase().includes(w.toLowerCase()));
    return matchCat&&matchBusq;
  });

  // Calcular descuento: solo si TODOS los items son de cats con descuento Y solo pago en efectivo pesos
  const soloEfec=pagos.length===1&&mById(pagos[0]?.metodoId)?.esEfectivo;
  const todosConDescuento=items.length>0&&items.every(i=>itemTieneDescuento(i));
  const aplicaDescuento=soloEfec&&todosConDescuento;

  const subtotalUSD=items.reduce((s,i)=>s+i.precio*i.qty,0);
  const descuento=aplicaDescuento?subtotalUSD*0.15:0;
  const totalUSD=subtotalUSD-descuento;
  const totalPesos=totalUSD*cotiz;

  const pagadoUSD=pagos.reduce((s,p)=>{
    const m=mById(p.metodoId);if(!m)return s;
    const v=parseFloat(p.monto)||0;
    return s+(m.moneda==="usd"?v:v/cotiz);
  },0);
  const restaUSD=Math.max(0,totalUSD-pagadoUSD);
  const restaARS=restaUSD*cotiz;
  const completo=totalUSD>0&&Math.abs(restaUSD)<0.005;

  const toggleItem=p=>{
    setItems(prev=>prev.find(i=>i.id===p.id)?prev.filter(i=>i.id!==p.id):[...prev,{...p,qty:1}]);
  };
  const chQty=(id,d)=>setItems(prev=>prev.map(i=>i.id===id?{...i,qty:Math.max(1,i.qty+d)}:i));
  const rmItem=id=>setItems(prev=>prev.filter(i=>i.id!==id));

  const addCustom=()=>{
    if(!custom.nombre||!custom.precio)return;
    setItems(prev=>[...prev,{id:"c"+newId(),nombre:custom.nombre,precio:parseFloat(custom.precio),
      costo:parseFloat(custom.costo)||0,cat:custom.cat,qty:1}]);
    setCustom({show:false,nombre:"",precio:"",costo:"",cat:"Pantallas"});
  };

  const addMetodo=id=>{
    if(pagos.find(p=>p.metodoId===id))return;
    const m=mById(id);
    const sug=m.moneda==="usd"?restaUSD.toFixed(2):Math.round(restaARS).toString();
    setPagos(prev=>[...prev,{metodoId:id,monto:sug}]);
  };
  const rmMetodo=id=>setPagos(prev=>prev.filter(p=>p.metodoId!==id));
  const chMonto=(id,v)=>setPagos(prev=>prev.map(p=>p.metodoId===id?{...p,monto:v}:p));

  const guardar=async()=>{
    if(!completo||items.length===0)return;
    const gananciaUSD=items.reduce((s,i)=>s+(i.precio-(i.costo||0))*i.qty,0)-descuento;
    const v={id:newId(),fecha:new Date().toISOString(),
      empleadoId:session.id,empleadoNombre:session.nombre,
      items,pagos,nota,subtotalUSD,descuento,totalUSD,totalPesos,gananciaUSD,cotizUsada:cotiz};
    const newCat=catalogo.map(c=>{
      const it=items.find(i=>i.id===c.id);
      if(it&&c.stock<99)return{...c,stock:Math.max(0,c.stock-it.qty)};return c;
    });
    await persist(SK.catalogo,ctx.setCatalogo,newCat);
    await persist(SK.ventas,setVentas,[v,...ventas]);
    setLastVenta(v);
    setItems([]);setPagos([]);setNota("");
    setOk(true);setTimeout(()=>setOk(false),3000);
  };

  return(
    <div>
      <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",
        background:"#fffbeb",border:"1px solid #fde68a",borderRadius:10,
        padding:"10px 16px",marginBottom:16}}>
        <div style={{display:"flex",alignItems:"center",gap:8}}>
          <span style={{fontSize:16}}>💱</span>
          <span style={{fontSize:13,color:"#92400e",fontWeight:600}}>Cotización USD</span>
        </div>
        <div style={{textAlign:"right"}}>
          <span style={{fontSize:18,fontWeight:800,color:"#92400e",fontFamily:"'Syne',sans-serif"}}>
            ${cotiz.toLocaleString("es-AR")}
          </span>
          <span style={{fontSize:11,color:"#b45309",marginLeft:6}}>por dólar</span>
        </div>
        <span style={{fontSize:11,color:"#b45309",background:"#fef3c7",borderRadius:5,padding:"3px 8px"}}>
          Solo el dueño puede modificarla
        </span>
      </div>
      <div style={{display:"grid",gridTemplateColumns:"1fr 310px",gap:16,alignItems:"start"}}>
      <div style={{display:"flex",flexDirection:"column",gap:14}}>
        <Card>
          <STitle>Seleccionar ítems</STitle>
          <p style={{fontSize:11,color:C.muted,marginTop:2,marginBottom:12}}>Precios en USD · tocá para agregar</p>
          <div style={{display:"flex",gap:6,marginBottom:12,flexWrap:"wrap"}}>
            <input value={busq} onChange={e=>setBusq(e.target.value)}
              placeholder="Buscar producto…" style={{...inp,flex:1,minWidth:160}}/>
          </div>
          <div style={{display:"flex",gap:5,flexWrap:"wrap",marginBottom:14}}>
            {cats.slice(0,8).map(c=>(
              <Chip key={c} active={catFil===c} onClick={()=>setCatFil(c)} small>{c}</Chip>
            ))}
            {cats.length>8&&cats.slice(8).map(c=>(
              <Chip key={c} active={catFil===c} onClick={()=>setCatFil(c)} small>{c}</Chip>
            ))}
          </div>
          <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fill,minmax(140px,1fr))",gap:5,maxHeight:340,overflowY:"auto"}}>
            {filtrados.slice(0,120).map(p=>{
              const sel=!!items.find(i=>i.id===p.id);
              const sinStock=false;
              return(
                <button key={p.id} onClick={()=>!sinStock&&toggleItem(p)} style={{
                  padding:"9px 10px",borderRadius:9,textAlign:"left",
                  background:sel?C.accentSoft:C.faint,
                  border:`1.5px solid ${sel?C.accent:C.border}`,
                  opacity:sinStock?.45:1,transition:"all .12s",
                }}>
                  <div style={{fontSize:11,fontWeight:600,color:sel?C.accent:C.text,marginBottom:3,lineHeight:1.3}}>{p.nombre}</div>
                  <div style={{display:"flex",justifyContent:"space-between",alignItems:"center"}}>
                    <span style={{fontSize:12,color:C.accent,fontWeight:700}}>{usd(p.precio)}</span>
                    {p.stock<99&&<span style={{fontSize:9,color:p.stock<=p.stockMin?C.red:C.muted}}>×{p.stock}</span>}
                  </div>
                </button>
              );
            })}
          </div>
          <button onClick={()=>setCustom(p=>({...p,show:!p.show}))} style={{
            width:"100%",padding:"8px",borderRadius:8,background:"transparent",
            color:C.muted,border:`1.5px dashed ${C.border}`,fontSize:12,fontWeight:600,marginTop:10,
          }}>{custom.show?"✕ Cancelar":"+ Ítem personalizado"}</button>
          {custom.show&&(
            <div className="fu" style={{marginTop:10,display:"flex",flexDirection:"column",gap:7}}>
              <input value={custom.nombre} onChange={e=>setCustom(p=>({...p,nombre:e.target.value}))} placeholder="Descripción" style={inp}/>
              <div style={{display:"flex",gap:6}}>
                <input value={custom.precio} onChange={e=>setCustom(p=>({...p,precio:e.target.value}))} placeholder="Precio USD" type="number" style={{...inp,flex:1}}/>
                <input value={custom.costo} onChange={e=>setCustom(p=>({...p,costo:e.target.value}))} placeholder="Costo USD" type="number" style={{...inp,flex:1}}/>
              </div>
              <select value={custom.cat} onChange={e=>setCustom(p=>({...p,cat:e.target.value}))} style={inp}>
                {[...new Set(catalogo.map(p=>p.cat))].map(c=><option key={c}>{c}</option>)}
              </select>
              <Btn sm onClick={addCustom}>Agregar ítem</Btn>
            </div>
          )}
        </Card>
        <Card>
          <STitle sm>📝 Nota (opcional)</STitle>
          <textarea value={nota} onChange={e=>setNota(e.target.value)}
            placeholder="IMEI, nombre del cliente, observaciones…"
            style={{...inp,marginTop:8,minHeight:56,resize:"vertical"}}/>
        </Card>
      </div>

      {/* TICKET */}
      <div style={{position:"sticky",top:68,display:"flex",flexDirection:"column",gap:12}}>
        <Card>
          <STitle>Ticket</STitle>
          {items.length===0
            ?<p style={{fontSize:12,color:C.muted,textAlign:"center",padding:"20px 0"}}>Sin ítems seleccionados</p>
            :<div style={{marginTop:10,display:"flex",flexDirection:"column",gap:5}}>
              {items.map(i=>(
                <div key={i.id} style={{display:"flex",alignItems:"center",gap:5,
                  background:C.faint,borderRadius:8,padding:"7px 9px"}}>
                  <div style={{flex:1,minWidth:0}}>
                    <p style={{fontSize:11,fontWeight:600,color:C.text,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{i.nombre}</p>
                    <p style={{fontSize:11,color:C.accent}}>{usd(i.precio*i.qty)}</p>
                  </div>
                  <button onClick={()=>chQty(i.id,-1)} style={{width:20,height:20,borderRadius:4,background:C.border,color:C.text,fontSize:14,display:"flex",alignItems:"center",justifyContent:"center"}}>−</button>
                  <span style={{fontSize:12,fontWeight:700,minWidth:16,textAlign:"center"}}>{i.qty}</span>
                  <button onClick={()=>chQty(i.id,+1)} style={{width:20,height:20,borderRadius:4,background:C.border,color:C.text,fontSize:14,display:"flex",alignItems:"center",justifyContent:"center"}}>+</button>
                  <button onClick={()=>rmItem(i.id)} style={{width:20,height:20,borderRadius:4,background:"#fee2e2",color:C.red,fontSize:11,display:"flex",alignItems:"center",justifyContent:"center"}}>✕</button>
                </div>
              ))}
            </div>
          }
          {items.length>0&&(
            <div style={{marginTop:10,borderTop:`1px solid ${C.border}`,paddingTop:8}}>
              <Row label="Subtotal" val={usd(subtotalUSD)}/>
              {aplicaDescuento&&<Row label="Descuento efectivo 15%" val={`−${usd(descuento)}`} valColor={C.green}/>}
              {soloEfec&&!todosConDescuento&&<p style={{fontSize:10,color:C.amber,marginBottom:4}}>⚠️ Descuento no aplica en iPhones</p>}
              <div style={{borderTop:`1px solid ${C.border}`,marginTop:5,paddingTop:5}}>
                <Row label="TOTAL USD" val={usd(totalUSD)} bold accent/>
                <Row label={`TOTAL $ ×${cotiz.toLocaleString("es-AR")}`} val={ars(totalPesos)} bold/>
              </div>
            </div>
          )}
        </Card>

        {items.length>0&&(
          <Card>
            <STitle>Forma de pago</STitle>
            <div style={{display:"flex",flexWrap:"wrap",gap:5,marginTop:10}}>
              {METODOS.map(m=>{
                const ya=!!pagos.find(p=>p.metodoId===m.id);
                return(
                  <button key={m.id} onClick={()=>!ya&&addMetodo(m.id)} style={{
                    padding:"4px 10px",borderRadius:14,fontSize:11,fontWeight:600,
                    background:ya?"#dcfce7":"transparent",
                    border:`1.5px solid ${ya?C.green:C.border}`,
                    color:ya?C.green:C.muted,cursor:ya?"default":"pointer",transition:"all .12s",
                  }}>{ya?"✓ ":""}{m.label}</button>
                );
              })}
            </div>
            {pagos.length>0&&(
              <div style={{marginTop:10,display:"flex",flexDirection:"column",gap:9}}>
                {pagos.map((p,idx)=>{
                  const m=mById(p.metodoId);
                  const pagAnt=pagos.slice(0,idx).reduce((s,prev)=>{
                    const pm=mById(prev.metodoId);const v=parseFloat(prev.monto)||0;
                    return s+(pm.moneda==="usd"?v:v/cotiz);
                  },0);
                  const rAnt=Math.max(0,totalUSD-pagAnt);
                  return(
                    <div key={p.metodoId} className="fu">
                      <div style={{display:"flex",alignItems:"center",gap:5,marginBottom:4}}>
                        <span style={{fontSize:12,fontWeight:600,color:C.text,flex:1}}>{m.label}</span>
                        <Badge color={m.moneda==="usd"?C.amber:C.blue}>{m.moneda==="usd"?"USD":"$"}</Badge>
                        {m.caja==="ninguna"&&<Badge color={C.muted}>Digital</Badge>}
                        <button onClick={()=>rmMetodo(p.metodoId)} style={{width:18,height:18,borderRadius:4,
                          background:"#fee2e2",color:C.red,fontSize:10,display:"flex",alignItems:"center",justifyContent:"center"}}>✕</button>
                      </div>
                      {idx>0&&<p style={{fontSize:11,color:C.amber,marginBottom:4}}>
                        Resta: <strong>{m.moneda==="usd"?usd(rAnt):ars(rAnt*cotiz)}</strong>
                      </p>}
                      <input type="number" value={p.monto} onChange={e=>chMonto(p.metodoId,e.target.value)}
                        placeholder={m.moneda==="usd"?"Monto USD":"Monto $"} style={inp}/>
                    </div>
                  );
                })}
                <div style={{background:C.faint,borderRadius:8,padding:"9px 12px"}}>
                  {completo
                    ?<p style={{fontSize:13,fontWeight:700,color:C.green,textAlign:"center"}}>✓ Pago completo</p>
                    :<><p style={{fontSize:11,color:C.muted}}>Falta abonar:</p>
                      <p style={{fontSize:17,fontWeight:800,color:C.amber,fontFamily:"'Syne',sans-serif"}}>{usd(restaUSD)}</p>
                      <p style={{fontSize:11,color:C.muted}}>{ars(restaARS)}</p></>
                  }
                </div>
              </div>
            )}
          </Card>
        )}

        {ok&&<div className="fu" style={{background:"#f0fdf4",border:`1px solid ${C.green}`,borderRadius:10,padding:"11px",textAlign:"center"}}>
          <p style={{color:C.green,fontWeight:700,fontSize:13}}>✓ Venta registrada correctamente</p>
        </div>}

        <button onClick={guardar} disabled={items.length===0||!completo} style={{
          width:"100%",padding:"14px",borderRadius:12,fontSize:14,fontWeight:800,
          fontFamily:"'Syne',sans-serif",
          background:items.length>0&&completo?C.accent:"#e8ecf0",
          color:items.length>0&&completo?"#fff":C.muted,transition:"all .2s",
        }}>
          {items.length===0?"Seleccioná ítems":!completo?"Completá el pago":"Registrar venta"}
        </button>
      </div>
    </div>

    {/* ÚLTIMA VENTA */}
    {lastVenta&&(
      <div style={{position:"fixed",bottom:0,left:0,right:0,zIndex:300,
        background:C.surface,borderTop:`1.5px solid ${C.green}`,
        padding:"10px 20px",display:"flex",alignItems:"center",gap:12}}>
        <span style={{fontSize:11,background:"#f0fdf4",color:C.green,borderRadius:4,padding:"2px 8px",fontWeight:700,whiteSpace:"nowrap"}}>✓ Última venta</span>
        <div style={{flex:1,overflow:"hidden"}}>
          <p style={{fontSize:12,fontWeight:600,color:C.text,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}}>
            {lastVenta.items.map(i=>i.nombre).join(", ")}
          </p>
          <p style={{fontSize:11,color:C.muted}}>{usd(lastVenta.totalUSD)} · {fmtDate(lastVenta.fecha)}</p>
        </div>
        <button onClick={()=>setShowLastDetail(!showLastDetail)} style={{
          padding:"5px 12px",borderRadius:7,background:C.faint,border:`1px solid ${C.border}`,
          fontSize:11,fontWeight:600,color:C.text,whiteSpace:"nowrap",cursor:"pointer",
        }}>Ver detalle</button>
        <button onClick={()=>setLastVenta(null)} style={{
          width:22,height:22,borderRadius:5,background:"#fee2e2",color:C.red,
          fontSize:12,display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",border:"none",
        }}>✕</button>
      </div>
    )}

    {/* DETALLE ÚLTIMA VENTA */}
    {lastVenta&&showLastDetail&&(
      <div style={{position:"fixed",inset:0,background:"rgba(0,0,0,.4)",zIndex:400,
        display:"flex",alignItems:"center",justifyContent:"center",padding:20}}>
        <Card style={{width:"100%",maxWidth:420,maxHeight:"80vh",overflowY:"auto"}}>
          <div style={{display:"flex",justifyContent:"space-between",marginBottom:12}}>
            <STitle>Detalle de última venta</STitle>
            <button onClick={()=>setShowLastDetail(false)} style={{background:"none",color:C.muted,fontSize:14,cursor:"pointer",border:"none"}}>✕</button>
          </div>
          <p style={{fontSize:11,color:C.muted,marginBottom:10}}>{fmtDate(lastVenta.fecha)} · {lastVenta.empleadoNombre}</p>
          {lastVenta.items.map(i=>(
            <div key={i.id} style={{display:"flex",justifyContent:"space-between",
              background:C.faint,borderRadius:7,padding:"7px 10px",marginBottom:5}}>
              <span style={{fontSize:12,color:C.text}}>{i.nombre} ×{i.qty}</span>
              <span style={{fontSize:12,color:C.accent,fontWeight:600}}>{usd(i.precio*i.qty)}</span>
            </div>
          ))}
          <div style={{borderTop:`1px solid ${C.border}`,marginTop:8,paddingTop:8}}>
            {lastVenta.descuento>0&&<Row label="Descuento 15%" val={`−${usd(lastVenta.descuento)}`} valColor={C.green}/>}
            <Row label="TOTAL USD" val={usd(lastVenta.totalUSD)} bold accent/>
            <Row label={`TOTAL $`} val={ars(lastVenta.totalPesos)} bold/>
          </div>
          <div style={{marginTop:8}}>
            {lastVenta.pagos.map(p=>{const m=mById(p.metodoId);const val=parseFloat(p.monto)||0;return(
              <Row key={p.metodoId} label={m?.label} val={m?.moneda==="usd"?`USD ${val.toFixed(2)}`:ars(val)}/>
            );})}
          </div>
          {lastVenta.nota&&<p style={{fontSize:11,color:C.muted,marginTop:8,fontStyle:"italic"}}>📝 {lastVenta.nota}</p>}
        </Card>
      </div>
    )}
    </div>
  );
}

/* ═══════════════════════════════════════════════════
   ÓRDENES
═══════════════════════════════════════════════════ */
function OrdenesView({ctx}){
  const {session,ordenes,setOrdenes,clientes,setClientes,cotiz,persist,SK}=ctx;
  const isOwner=session.rol==="owner";
  const [form,setForm]=useState(null);
  const [filtro,setFiltro]=useState("activas");
  const [printOrden,setPrintOrden]=useState(null);

  const visibles=isOwner
    ?(filtro==="activas"?ordenes.filter(o=>o.estado!=="Entregado"):ordenes)
    :ordenes.filter(o=>o.estado!=="Entregado"&&monthsAgo(o.fecha,2));

  const saveOrden=async o=>{
    const existe=ordenes.find(x=>x.id===o.id);
    const next=existe?ordenes.map(x=>x.id===o.id?o:x):[o,...ordenes];
    await persist(SK.ordenes,setOrdenes,next);
    if(o.clienteNombre){
      const cl=clientes.find(c=>c.nombre.toLowerCase()===o.clienteNombre.toLowerCase());
      if(!cl){
        const nc={id:newId(),nombre:o.clienteNombre,tel:o.clienteTel||"",whatsapp:o.clienteWA||"",
          email:"",notas:"",fechaAlta:new Date().toISOString()};
        await persist(SK.clientes,setClientes,[nc,...clientes]);
      }
    }
    setForm(null);
  };

  const cambiarEstado=async(id,estado)=>{
    const next=ordenes.map(o=>o.id===id?{...o,estado}:o);
    await persist(SK.ordenes,setOrdenes,next);
  };

  // Enviar por WhatsApp
  const enviarWA=(o)=>{
    const num=(o.clienteWA||o.clienteTel||"").replace(/\D/g,"");
    if(!num){alert("La orden no tiene número de WhatsApp");return;}
    const msg=encodeURIComponent(`¡Hola ${o.clienteNombre}! 👋\nSoy de *iCompany®* — Pilar.\nTe adjunto la orden de servicio N°${o.id.slice(-6).toUpperCase()} correspondiente a tu ${o.modelo||"equipo"}.\n\n📌 *${o.descripcion}*\nSeña: ${usd(o.seña)} | Total: ${usd(o.total)}\n\nAnte cualquier consulta, estamos a tu disposición. ¡Gracias por elegirnos! 🙏`);
    window.open(`https://wa.me/${num}?text=${msg}`,"_blank");
  };

  return(
    <div>
      <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:16}}>
        <div style={{display:"flex",gap:6}}>
          {isOwner&&[["activas","Activas"],["todas","Todas"]].map(([k,l])=>(
            <Chip key={k} active={filtro===k} onClick={()=>setFiltro(k)} small>{l}</Chip>
          ))}
        </div>
        <Btn sm onClick={()=>setForm({id:newId(),fecha:new Date().toISOString(),
          estado:"Señado",empleadoId:session.id,empleadoNombre:session.nombre,
          clienteNombre:"",clienteTel:"",clienteWA:"",clienteDni:"",
          modelo:"",imei:"",descripcion:"",seña:0,total:0,fechaEntrega:"",notas:""})}>
          + Nueva orden
        </Btn>
      </div>

      {form&&<OrdenForm orden={form} onSave={saveOrden} onCancel={()=>setForm(null)} cotiz={cotiz} catalogo={ctx.catalogo}/>}

      {printOrden&&<OrdenPrint orden={printOrden} cotiz={cotiz} onClose={()=>setPrintOrden(null)}/>}

      {visibles.length===0
        ?<Card><p style={{textAlign:"center",color:C.muted,padding:"24px 0",fontSize:13}}>No hay órdenes</p></Card>
        :<div style={{display:"flex",flexDirection:"column",gap:8}}>
          {visibles.map(o=>(
            <Card key={o.id} style={{padding:"12px 16px"}}>
              <div style={{display:"flex",alignItems:"flex-start",gap:10}}>
                <div style={{flex:1}}>
                  <div style={{display:"flex",alignItems:"center",gap:8,marginBottom:4}}>
                    <span style={{fontWeight:700,fontSize:14,color:C.text}}>{o.clienteNombre||"(sin nombre)"}</span>
                    <Badge color={ESTADO_COLOR[o.estado]}>{o.estado}</Badge>
                    <span style={{fontSize:10,color:C.muted}}>#{o.id.slice(-6).toUpperCase()}</span>
                  </div>
                  <p style={{fontSize:12,color:C.muted,marginBottom:2}}>{o.modelo} {o.imei&&`· IMEI: ${o.imei}`}</p>
                  <p style={{fontSize:12,color:C.text}}>{o.descripcion}</p>
                  <div style={{display:"flex",gap:14,marginTop:6,flexWrap:"wrap"}}>
                    <span style={{fontSize:11,color:C.muted}}>Seña: <strong style={{color:C.amber}}>{usd(o.seña)}</strong></span>
                    <span style={{fontSize:11,color:C.muted}}>Total: <strong style={{color:C.accent}}>{usd(o.total)}</strong></span>
                    <span style={{fontSize:11,color:C.muted}}>Saldo: <strong style={{color:C.red}}>{usd(Math.max(0,o.total-o.seña))}</strong></span>
                    {o.fechaEntrega&&<span style={{fontSize:11,color:C.muted}}>Entrega: {fmtDay(o.fechaEntrega)}</span>}
                  </div>
                  <p style={{fontSize:10,color:C.muted,marginTop:4}}>{o.empleadoNombre} · {fmtDate(o.fecha)}</p>
                </div>
                <div style={{display:"flex",flexDirection:"column",gap:5,alignItems:"flex-end",flexShrink:0}}>
                  <Btn sm onClick={()=>setForm(o)}>Editar</Btn>
                  <Btn sm color="#25D366" onClick={()=>enviarWA(o)}>📲 WA</Btn>
                  <Btn sm color={C.muted} onClick={()=>setPrintOrden(o)}>🖨️ Imprimir</Btn>
                  {ESTADOS.filter(e=>e!==o.estado).map(e=>(
                    <button key={e} onClick={()=>cambiarEstado(o.id,e)} style={{
                      padding:"4px 8px",borderRadius:6,fontSize:10,fontWeight:600,
                      background:`${ESTADO_COLOR[e]}15`,color:ESTADO_COLOR[e],
                      border:`1px solid ${ESTADO_COLOR[e]}40`,
                    }}>→ {e}</button>
                  ))}
                </div>
              </div>
            </Card>
          ))}
        </div>
      }
    </div>
  );
}

function OrdenForm({orden,onSave,onCancel,cotiz,catalogo}){
  const prefijoDef="+54911";
  const extraerNum=(full,pref)=>{if(!full)return"";return full.startsWith(pref)?full.slice(pref.length):full;};
  const [f,setF]=useState({...orden,fecha:orden.fecha||new Date().toISOString()});
  const [pref,setPref]=useState(prefijoDef);
  const [telNum,setTelNum]=useState(extraerNum(orden.clienteTel,prefijoDef));
  const [waNum,setWaNum]=useState(extraerNum(orden.clienteWA,prefijoDef));
  const [modeloCustom,setModeloCustom]=useState(!!(orden.modelo&&!["iPhone","iphone"].some(x=>orden.modelo.toLowerCase().includes(x))));
  const [senaPagos,setSenaPagos]=useState(orden.senaPagos||[]);
  const s=(k,v)=>setF(p=>({...p,[k]:v}));

  const modelosIphone=[...new Set((catalogo||[])
    .filter(p=>p.cat==="iPhone"&&p.nombre)
    .map(p=>{const m=p.nombre.match(/^(iPhone\s[\w\s]+?)(?:\s\d+(?:GB|TB))?$/i);return m?m[1].trim():p.nombre;})
  )].filter((v,i,a)=>a.indexOf(v)===i).sort((a,b)=>a.localeCompare(b));

  const addSena=id=>{if(senaPagos.find(p=>p.metodoId===id))return;setSenaPagos(prev=>[...prev,{metodoId:id,monto:""}]);};
  const rmSena=id=>setSenaPagos(prev=>prev.filter(p=>p.metodoId!==id));
  const chSena=(id,v)=>setSenaPagos(prev=>prev.map(p=>p.metodoId===id?{...p,monto:v}:p));
  const totalSenaUSD=senaPagos.reduce((s,p)=>{const m=mById(p.metodoId);if(!m)return s;const v=parseFloat(p.monto)||0;return s+(m.moneda==="usd"?v:v/cotiz);},0);

  const handleSave=()=>onSave({...f,
    clienteTel:telNum?pref+telNum:"",
    clienteWA:waNum?pref+waNum:"",
    seña:parseFloat(totalSenaUSD.toFixed(2)),
    senaPagos,
  });

  return(
    <Card style={{marginBottom:16,border:`1.5px solid ${C.borderHi}`}}>
      <div style={{display:"flex",justifyContent:"space-between",marginBottom:14}}>
        <STitle>{f.clienteNombre?"Editar orden":"Nueva orden"}</STitle>
        <button onClick={onCancel} style={{background:"none",color:C.muted,fontSize:12,cursor:"pointer",border:"none"}}>✕</button>
      </div>

      {/* CLIENTE */}
      <p style={{fontSize:10,fontWeight:700,color:C.muted,textTransform:"uppercase",letterSpacing:".06em",marginBottom:6}}>Cliente</p>
      <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8,marginBottom:10}}>
        <input value={f.clienteNombre} onChange={e=>s("clienteNombre",e.target.value)} placeholder="Nombre y apellido" style={inp}/>
        <input value={f.clienteDni||""} onChange={e=>s("clienteDni",e.target.value)} placeholder="DNI" style={inp}/>
        <div>
          <p style={{fontSize:10,color:C.muted,marginBottom:3}}>Teléfono</p>
          <div style={{display:"flex",gap:4}}>
            <input value={pref} onChange={e=>setPref(e.target.value)} style={{...inp,width:76,flexShrink:0,fontSize:12}} placeholder="+54911"/>
            <input value={telNum} onChange={e=>setTelNum(e.target.value)} style={{...inp,flex:1}} placeholder="12345678"/>
          </div>
        </div>
        <div>
          <p style={{fontSize:10,color:C.muted,marginBottom:3}}>WhatsApp</p>
          <div style={{display:"flex",gap:4}}>
            <input value={pref} onChange={e=>setPref(e.target.value)} style={{...inp,width:76,flexShrink:0,fontSize:12}} placeholder="+54911"/>
            <input value={waNum} onChange={e=>setWaNum(e.target.value)} style={{...inp,flex:1}} placeholder="12345678"/>
          </div>
        </div>
      </div>

      {/* EQUIPO */}
      <p style={{fontSize:10,fontWeight:700,color:C.muted,textTransform:"uppercase",letterSpacing:".06em",marginBottom:6}}>Equipo</p>
      <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8,marginBottom:8}}>
        <div>
          <p style={{fontSize:10,color:C.muted,marginBottom:3}}>Modelo</p>
          {!modeloCustom?(
            <div style={{display:"flex",gap:4}}>
              <select value={f.modelo} onChange={e=>s("modelo",e.target.value)} style={{...inp,flex:1}}>
                <option value="">Seleccionar…</option>
                <optgroup label="── iPhone ──">
                  {modelosIphone.map(m=><option key={m} value={m}>{m}</option>)}
                </optgroup>
              </select>
              <button onClick={()=>{setModeloCustom(true);s("modelo","");}} style={{
                padding:"0 10px",borderRadius:8,background:C.faint,border:`1px solid ${C.border}`,
                fontSize:11,color:C.muted,cursor:"pointer",whiteSpace:"nowrap",
              }}>Otro</button>
            </div>
          ):(
            <div style={{display:"flex",gap:4}}>
              <input value={f.modelo} onChange={e=>s("modelo",e.target.value)}
                placeholder="Escribir modelo…" style={{...inp,flex:1}} autoFocus/>
              <button onClick={()=>setModeloCustom(false)} style={{
                padding:"0 10px",borderRadius:8,background:C.faint,border:`1px solid ${C.border}`,
                fontSize:11,color:C.muted,cursor:"pointer",
              }}>↩ Lista</button>
            </div>
          )}
        </div>
        <div>
          <p style={{fontSize:10,color:C.muted,marginBottom:3}}>IMEI (opcional)</p>
          <input value={f.imei||""} onChange={e=>s("imei",e.target.value)} placeholder="IMEI" style={inp}/>
        </div>
      </div>
      <textarea value={f.descripcion} onChange={e=>s("descripcion",e.target.value)}
        placeholder="Descripción del trabajo…" style={{...inp,marginBottom:10,minHeight:56,resize:"vertical"}}/>

      {/* FECHAS Y ESTADO */}
      <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:8,marginBottom:10}}>
        <div>
          <p style={{fontSize:10,color:C.muted,marginBottom:3}}>Ingreso</p>
          <input value={f.fecha?.slice(0,16)||""} onChange={e=>s("fecha",e.target.value?new Date(e.target.value).toISOString():new Date().toISOString())}
            type="datetime-local" style={inp}/>
        </div>
        <div>
          <p style={{fontSize:10,color:C.muted,marginBottom:3}}>Entrega estimada</p>
          <input value={f.fechaEntrega||""} onChange={e=>s("fechaEntrega",e.target.value)} type="date" style={inp}/>
        </div>
        <div>
          <p style={{fontSize:10,color:C.muted,marginBottom:3}}>Estado</p>
          <select value={f.estado} onChange={e=>s("estado",e.target.value)} style={inp}>
            {ESTADOS.map(st=><option key={st}>{st}</option>)}
          </select>
        </div>
      </div>

      {/* TOTAL */}
      <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8,marginBottom:10}}>
        <div>
          <p style={{fontSize:10,color:C.muted,marginBottom:3}}>Total del servicio (USD)</p>
          <input value={f.total} onChange={e=>s("total",parseFloat(e.target.value)||0)}
            placeholder="0.00" type="number" style={inp}/>
        </div>
        <div style={{background:C.faint,borderRadius:8,padding:"8px 12px",display:"flex",flexDirection:"column",justifyContent:"center"}}>
          <p style={{fontSize:10,color:C.muted}}>Equivalente en pesos</p>
          <p style={{fontSize:16,fontWeight:800,color:C.accent}}>{ars(f.total*cotiz)}</p>
        </div>
      </div>

      {/* SEÑA */}
      <p style={{fontSize:10,fontWeight:700,color:C.muted,textTransform:"uppercase",letterSpacing:".06em",marginBottom:6}}>Seña / Anticipo</p>
      <div style={{display:"flex",flexWrap:"wrap",gap:5,marginBottom:8}}>
        {METODOS.map(m=>{
          const ya=!!senaPagos.find(p=>p.metodoId===m.id);
          return(
            <button key={m.id} onClick={()=>!ya&&addSena(m.id)} style={{
              padding:"4px 10px",borderRadius:14,fontSize:11,fontWeight:600,
              background:ya?"#dcfce7":"transparent",
              border:`1.5px solid ${ya?C.green:C.border}`,
              color:ya?C.green:C.muted,cursor:ya?"default":"pointer",
            }}>{ya?"✓ ":""}{m.label}</button>
          );
        })}
      </div>
      {senaPagos.length>0&&(
        <div style={{display:"flex",flexDirection:"column",gap:7,marginBottom:8}}>
          {senaPagos.map(p=>{
            const m=mById(p.metodoId);
            return(
              <div key={p.metodoId} style={{display:"flex",gap:6,alignItems:"center"}}>
                <span style={{fontSize:12,fontWeight:600,color:C.text,minWidth:110}}>{m.label}</span>
                <Badge color={m.moneda==="usd"?C.amber:C.blue}>{m.moneda==="usd"?"USD":"$"}</Badge>
                <input type="number" value={p.monto} onChange={e=>chSena(p.metodoId,e.target.value)}
                  placeholder={m.moneda==="usd"?"Monto USD":"Monto $"} style={{...inp,flex:1}}/>
                <button onClick={()=>rmSena(p.metodoId)} style={{
                  width:22,height:22,borderRadius:5,background:"#fee2e2",color:C.red,
                  fontSize:11,display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",border:"none",
                }}>✕</button>
              </div>
            );
          })}
          <div style={{background:"#f0fdf4",border:`1px solid #bbf7d0`,borderRadius:8,padding:"8px 12px",display:"flex",justifyContent:"space-between",alignItems:"center"}}>
            <span style={{fontSize:12,color:C.green,fontWeight:600}}>Total seña</span>
            <span style={{fontSize:15,fontWeight:800,color:C.green}}>{usd(totalSenaUSD)}</span>
          </div>
          {f.total>0&&totalSenaUSD>0&&(
            <div style={{background:"#fff7ed",border:`1px solid #fed7aa`,borderRadius:8,padding:"8px 12px",display:"flex",justifyContent:"space-between",alignItems:"center"}}>
              <span style={{fontSize:12,color:C.amber,fontWeight:600}}>Saldo pendiente</span>
              <span style={{fontSize:15,fontWeight:800,color:C.amber}}>{usd(Math.max(0,f.total-totalSenaUSD))}</span>
            </div>
          )}
        </div>
      )}

      <textarea value={f.notas||""} onChange={e=>s("notas",e.target.value)}
        placeholder="Notas internas (no aparecen en la orden impresa)…" style={{...inp,marginTop:4,minHeight:36,resize:"vertical"}}/>
      <div style={{display:"flex",gap:8,marginTop:12}}>
        <Btn onClick={handleSave}>Guardar orden</Btn>
        <Btn color={C.muted} outline onClick={onCancel}>Cancelar</Btn>
      </div>
    </Card>
  );
}

/* ═══════════════════════════════════════════════════
   ORDEN IMPRIMIBLE A4
═══════════════════════════════════════════════════ */
function OrdenPrint({orden:o,cotiz,onClose}){
  const ref=useRef();
  const handlePrint=()=>{
    const w=window.open("","_blank");
    w.document.write(`<html><head><title>Orden ${o.id.slice(-6).toUpperCase()}</title>
      <link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;600;700&display=swap" rel="stylesheet"/>
      <style>
        *{box-sizing:border-box;margin:0;padding:0;font-family:'DM Sans',sans-serif;}
        body{padding:30px;color:#1a1a2e;background:#fff;font-size:13px;}
        .header{display:flex;justify-content:space-between;align-items:flex-start;border-bottom:2px solid #1a1a2e;padding-bottom:16px;margin-bottom:20px;}
        .brand{font-size:22px;font-weight:800;letter-spacing:-.02em;}
        .brand span{font-weight:400;}
        .info{font-size:11px;color:#666;margin-top:4px;line-height:1.6;}
        .qrs{display:flex;gap:12px;align-items:flex-end;}
        .qr-item{text-align:center;}
        .qr-item img{width:52px;height:52px;}
        .qr-item p{font-size:8px;color:#888;margin-top:2px;}
        .section{margin-bottom:12px;}
        .section-title{font-size:9px;font-weight:700;text-transform:uppercase;letter-spacing:.07em;color:#888;margin-bottom:6px;}
        .grid2{display:grid;grid-template-columns:1fr 1fr;gap:6px;}
        .grid4{display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:6px;}
        .field{background:#f8f9fb;border-radius:5px;padding:6px 8px;}
        .field label{font-size:9px;color:#888;display:block;margin-bottom:1px;}
        .field p{font-size:12px;font-weight:600;color:#1a1a2e;}
        .totales{background:#1a1a2e;color:#fff;border-radius:7px;padding:10px 14px;margin:12px 0;}
        .totales .row{display:flex;justify-content:space-between;margin-bottom:3px;font-size:11px;}
        .totales .total{font-size:14px;font-weight:800;border-top:1px solid rgba(255,255,255,.2);padding-top:5px;margin-top:5px;}
        .condiciones{font-size:9px;color:#666;line-height:1.65;border:1px solid #e8ecf0;border-radius:7px;padding:8px 10px;margin-top:8px;}
        .condiciones h4{font-size:10px;font-weight:700;color:#1a1a2e;margin-bottom:4px;}
        .firma-unica{border-top:1.5px solid #1a1a2e;padding-top:8px;text-align:center;font-size:11px;color:#666;margin-top:18px;width:60%;margin-left:auto;margin-right:auto;}
        @media print{@page{size:A4;margin:15mm;}}
      </style></head><body>
      <div class="header">
        <div>
          <div style="display:flex;align-items:center;gap:8px;">
            <img src="/assets/logo.png" style="height:32px;" onerror="this.style.display='none'"/>
            <div class="brand"><span>i</span>Company®</div>
          </div>
          <div class="info">
            ${BRAND.direccion}<br/>
            ${BRAND.ciudad}<br/>
            Tel: ${BRAND.telefono} · ${BRAND.instagram}
          </div>
          <div style="margin-top:6px;font-size:11px;font-weight:700;color:#1a1a2e;">
            ORDEN DE SERVICIO N° ${o.id.slice(-6).toUpperCase()} &nbsp;·&nbsp; ${new Date(o.fecha||Date.now()).toLocaleString("es-AR",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"})}
          </div>
        </div>
        <div class="qrs">
          <div class="qr-item"><img src="/assets/qr_whatsapp.png" onerror="this.style.display='none'"/><p>WhatsApp</p></div>
          <div class="qr-item"><img src="/assets/qr_instagram.png" onerror="this.style.display='none'"/><p>Instagram</p></div>
          <div class="qr-item"><img src="/assets/qr_llegar.png" onerror="this.style.display='none'"/><p>¿Cómo llegar?</p></div>
        </div>
      </div>

      <div class="section">
        <div class="section-title">Datos del cliente</div>
        <div class="grid4">
          <div class="field"><label>Nombre</label><p>${o.clienteNombre||"—"}</p></div>
          <div class="field"><label>DNI</label><p>${o.clienteDni||"—"}</p></div>
          <div class="field"><label>Teléfono</label><p>${o.clienteTel||"—"}</p></div>
          <div class="field"><label>WhatsApp</label><p>${o.clienteWA||"—"}</p></div>
        </div>
      </div>

      <div class="section">
        <div class="section-title">Datos del equipo</div>
        <div class="grid2">
          <div class="field"><label>Modelo</label><p>${o.modelo||"—"}</p></div>
          <div class="field"><label>IMEI</label><p>${o.imei||"—"}</p></div>
        </div>
        <div class="field" style="margin-top:6px"><label>Descripción del trabajo</label><p>${o.descripcion||"—"}</p></div>
        ${o.fechaEntrega?`<div class="field" style="margin-top:6px"><label>Fecha estimada de entrega</label><p>${fmtDay(o.fechaEntrega)}</p></div>`:""}
      </div>

      <div class="totales">
        ${(o.senaPagos||[]).map(p=>{
          const m=METODOS.find(x=>x.id===p.metodoId);
          const v=parseFloat(p.monto)||0;
          const enUSD=m?.moneda==="usd"?v:v/cotiz;
          return `<div class="row"><span>Seña — ${m?.label||p.metodoId}</span><span>USD ${enUSD.toFixed(2)}</span></div>`;
        }).join("")}
        <div class="row"><span>Saldo pendiente</span><span>USD ${Math.max(0,o.total-(o.seña||0)).toFixed(2)}</span></div>
        <div class="row total"><span>TOTAL</span><span>USD ${Number(o.total).toFixed(2)} &nbsp;·&nbsp; $${Math.round(o.total*cotiz).toLocaleString("es-AR")}</span></div>
      </div>

      <div class="condiciones">
        <h4>Términos y condiciones del servicio</h4>
        <p>El presupuesto tiene validez de 15 días desde la fecha de emisión. El plazo de entrega es orientativo y puede variar según disponibilidad de repuestos. iCompany® no se responsabiliza por daños preexistentes no declarados al momento de la recepción. Los equipos no retirados en 60 días serán considerados abandonados. La garantía de mano de obra es de 90 días, sin cubrir daños por caída, humedad o mal uso posterior.</p>
      </div>

      <div class="firma-unica">
        <p style="margin-bottom:28px;">&nbsp;</p>
        <p>Firma y aclaración del cliente</p>
        <p style="margin-top:4px;font-size:10px;">DNI: _______________________</p>
      </div>

      <script>window.onload=()=>{window.print();}</script>
      </body></html>`);
    w.document.close();
  };

  return(
    <div style={{position:"fixed",inset:0,background:"rgba(0,0,0,.5)",zIndex:1000,
      display:"flex",alignItems:"center",justifyContent:"center"}}>
      <Card style={{width:"100%",maxWidth:500}}>
        <STitle>🖨️ Orden #{o.id.slice(-6).toUpperCase()}</STitle>
        <p style={{fontSize:12,color:C.muted,marginTop:6,marginBottom:16}}>
          {o.clienteNombre} · {o.modelo} · {usd(o.total)}
        </p>
        <div style={{display:"flex",gap:8}}>
          <Btn onClick={handlePrint}>Imprimir / Descargar PDF</Btn>
          <Btn color={C.muted} outline onClick={onClose}>Cerrar</Btn>
        </div>
      </Card>
    </div>
  );
}

/* ═══════════════════════════════════════════════════
   CLIENTES
═══════════════════════════════════════════════════ */
function ClientesView({ctx}){
  const {clientes,setClientes,ordenes,persist,SK}=ctx;
  const [busq,setBusq]=useState("");
  const [det,setDet]=useState(null);
  const [form,setForm]=useState(null);

  const filtrados=clientes.filter(c=>
    c.nombre.toLowerCase().includes(busq.toLowerCase())||
    (c.tel||"").includes(busq)||(c.whatsapp||"").includes(busq)
  );

  const save=async cl=>{
    const existe=clientes.find(c=>c.id===cl.id);
    const next=existe?clientes.map(c=>c.id===cl.id?cl:c):[cl,...clientes];
    await persist(SK.clientes,setClientes,next);
    setForm(null);
  };

  return(
    <div style={{display:"grid",gridTemplateColumns:det?"1fr 360px":"1fr",gap:16}}>
      <div>
        <div style={{display:"flex",gap:8,marginBottom:14}}>
          <input value={busq} onChange={e=>setBusq(e.target.value)}
            placeholder="Buscar por nombre, teléfono o WhatsApp…" style={{...inp,flex:1}}/>
          <Btn sm onClick={()=>{setForm({id:newId(),nombre:"",tel:"",whatsapp:"",email:"",notas:"",fechaAlta:new Date().toISOString()});setDet(null);}}>+ Nuevo</Btn>
        </div>

        {form&&(
          <Card style={{marginBottom:12}}>
            <STitle>Nuevo cliente</STitle>
            <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:7,marginTop:10}}>
              <input value={form.nombre} onChange={e=>setForm(p=>({...p,nombre:e.target.value}))} placeholder="Nombre" style={inp}/>
              <input value={form.tel||""}  onChange={e=>setForm(p=>({...p,tel:e.target.value}))}  placeholder="Teléfono" style={inp}/>
              <input value={form.whatsapp||""} onChange={e=>setForm(p=>({...p,whatsapp:e.target.value}))} placeholder="WhatsApp" style={inp}/>
              <input value={form.email||""} onChange={e=>setForm(p=>({...p,email:e.target.value}))} placeholder="Email" style={inp}/>
            </div>
            <textarea value={form.notas||""} onChange={e=>setForm(p=>({...p,notas:e.target.value}))}
              placeholder="Notas…" style={{...inp,marginTop:7,minHeight:50,resize:"vertical"}}/>
            <div style={{display:"flex",gap:7,marginTop:10}}>
              <Btn sm onClick={()=>save(form)}>Guardar</Btn>
              <Btn sm outline color={C.muted} onClick={()=>setForm(null)}>Cancelar</Btn>
            </div>
          </Card>
        )}

        {filtrados.length===0
          ?<Card><p style={{textAlign:"center",color:C.muted,padding:"20px 0",fontSize:13}}>Sin clientes</p></Card>
          :<div style={{display:"flex",flexDirection:"column",gap:6}}>
            {filtrados.map(c=>{
              const oCli=ordenes.filter(o=>o.clienteNombre?.toLowerCase()===c.nombre.toLowerCase());
              return(
                <button key={c.id} onClick={()=>setDet(c.id===det?null:c.id)} style={{
                  background:det===c.id?C.accentSoft:C.surface,
                  border:`1px solid ${det===c.id?C.accent:C.border}`,
                  borderRadius:10,padding:"11px 14px",textAlign:"left",color:C.text,
                  display:"flex",alignItems:"center",gap:10,transition:"all .12s",
                }}>
                  <div style={{width:36,height:36,borderRadius:"50%",background:C.accentSoft,
                    display:"flex",alignItems:"center",justifyContent:"center",
                    fontSize:14,fontWeight:700,color:C.accent,flexShrink:0}}>
                    {c.nombre[0]?.toUpperCase()}
                  </div>
                  <div style={{flex:1}}>
                    <p style={{fontWeight:700,fontSize:13}}>{c.nombre}</p>
                    <p style={{fontSize:11,color:C.muted}}>{c.tel}{c.whatsapp&&` · WA: ${c.whatsapp}`}</p>
                  </div>
                  <div style={{textAlign:"right"}}>
                    <p style={{fontSize:11,color:C.muted}}>{oCli.length} órdenes</p>
                    <p style={{fontSize:10,color:C.muted}}>desde {fmtDay(c.fechaAlta)}</p>
                  </div>
                </button>
              );
            })}
          </div>
        }
      </div>

      {det&&(()=>{
        const c=clientes.find(x=>x.id===det);
        if(!c)return null;
        const oCli=ordenes.filter(o=>o.clienteNombre?.toLowerCase()===c.nombre.toLowerCase());
        return(
          <div style={{position:"sticky",top:66}}>
            <Card>
              <div style={{display:"flex",justifyContent:"space-between",alignItems:"start"}}>
                <div>
                  <p style={{fontFamily:"'Syne',sans-serif",fontWeight:800,fontSize:18,color:C.text}}>{c.nombre}</p>
                  <p style={{fontSize:12,color:C.muted,marginTop:2}}>{c.tel}</p>
                  {c.whatsapp&&<p style={{fontSize:12,color:C.muted}}>WA: {c.whatsapp}</p>}
                  {c.email&&<p style={{fontSize:12,color:C.muted}}>{c.email}</p>}
                </div>
                <button onClick={()=>setDet(null)} style={{background:"none",color:C.muted,fontSize:12}}>✕</button>
              </div>
              {c.notas&&<p style={{fontSize:12,color:C.muted,marginTop:8,fontStyle:"italic"}}>{c.notas}</p>}
              <div style={{borderTop:`1px solid ${C.border}`,marginTop:14,paddingTop:12}}>
                <p style={{fontSize:11,fontWeight:700,color:C.muted,textTransform:"uppercase",
                  letterSpacing:".06em",marginBottom:8}}>Historial de órdenes ({oCli.length})</p>
                {oCli.length===0
                  ?<p style={{fontSize:12,color:C.muted}}>Sin órdenes</p>
                  :oCli.map(o=>(
                    <div key={o.id} style={{background:C.faint,borderRadius:8,padding:"8px 10px",marginBottom:6}}>
                      <div style={{display:"flex",justifyContent:"space-between"}}>
                        <span style={{fontSize:12,fontWeight:600,color:C.text}}>{o.descripcion?.slice(0,28)||o.modelo}</span>
                        <Badge color={ESTADO_COLOR[o.estado]}>{o.estado}</Badge>
                      </div>
                      <p style={{fontSize:11,color:C.muted,marginTop:3}}>
                        Total {usd(o.total)} · {fmtDay(o.fecha)}
                      </p>
                    </div>
                  ))
                }
              </div>
            </Card>
          </div>
        );
      })()}
    </div>
  );
}

/* ═══════════════════════════════════════════════════
   STOCK
═══════════════════════════════════════════════════ */
function StockView({ctx}){
  const {catalogo,setCatalogo,persist,SK}=ctx;
  const [editId,setEditId]=useState(null);
  const [editForm,setEditForm]=useState(null);
  const [newProd,setNewProd]=useState(false);
  const [np,setNp]=useState({nombre:"",cat:"Pantallas",precio:0,costo:0,stock:0,stockMin:1});
  const [busq,setBusq]=useState("");
  const [catFil,setCatFil]=useState("Todos");
  const [newCat,setNewCat]=useState("");
  const [showNewCat,setShowNewCat]=useState(false);

  const alertas=catalogo.filter(p=>p.stock<99&&p.stock<=p.stockMin&&p.stock>0);
  const sinStock=catalogo.filter(p=>p.stock<99&&p.stock===0);
  const cats=["Todos",...new Set(catalogo.map(p=>p.cat))];

  const filtrados=catalogo.filter(p=>{
    const mc=catFil==="Todos"||p.cat===catFil;
    const mb=!busq||p.nombre.toLowerCase().includes(busq.toLowerCase());
    return mc&&mb;
  });

  const saveItem=async item=>{
    const next=catalogo.map(c=>c.id===item.id?item:c);
    await persist(SK.catalogo,setCatalogo,next);
    setEditId(null);setEditForm(null);
  };

  const addProd=async()=>{
    if(!np.nombre)return;
    const next=[...catalogo,{...np,id:"u"+newId(),stock:parseInt(np.stock)||0}];
    await persist(SK.catalogo,setCatalogo,next);
    setNp({nombre:"",cat:"Pantallas",precio:0,costo:0,stock:0,stockMin:1});setNewProd(false);
  };

  const allCats=[...new Set(catalogo.map(p=>p.cat))];

  return(
    <div>
      {(alertas.length>0||sinStock.length>0)&&(
        <div style={{background:"#fff7ed",border:"1px solid #fed7aa",borderRadius:10,padding:"12px 16px",marginBottom:14}}>
          {sinStock.length>0&&<p style={{fontSize:12,fontWeight:700,color:C.red,marginBottom:4}}>🔴 Sin stock ({sinStock.length} productos)</p>}
          {alertas.length>0&&<p style={{fontSize:12,fontWeight:700,color:C.amber,marginBottom:6}}>⚠️ Stock bajo ({alertas.length} productos)</p>}
          <div style={{display:"flex",flexWrap:"wrap",gap:4}}>
            {[...sinStock,...alertas].slice(0,12).map(p=>(
              <span key={p.id} style={{fontSize:11,background:"#fee2e2",color:C.red,borderRadius:4,padding:"2px 7px"}}>
                {p.nombre} ({p.stock})
              </span>
            ))}
          </div>
        </div>
      )}

      <div style={{display:"flex",gap:8,marginBottom:14,flexWrap:"wrap"}}>
        <input value={busq} onChange={e=>setBusq(e.target.value)} placeholder="Buscar…" style={{...inp,flex:1,minWidth:160}}/>
        <Btn sm onClick={()=>setNewProd(!newProd)}>+ Nuevo producto</Btn>
        <Btn sm outline color={C.muted} onClick={()=>setShowNewCat(!showNewCat)}>+ Categoría</Btn>
      </div>

      {showNewCat&&(
        <Card style={{marginBottom:12}}>
          <STitle sm>Nueva categoría</STitle>
          <div style={{display:"flex",gap:8,marginTop:8}}>
            <input value={newCat} onChange={e=>setNewCat(e.target.value)} placeholder="Nombre de categoría" style={{...inp,flex:1}}/>
            <Btn sm onClick={()=>{if(newCat.trim())setNp(p=>({...p,cat:newCat.trim()}));setShowNewCat(false);setNewProd(true);setNewCat("");}}>Crear y agregar producto</Btn>
          </div>
        </Card>
      )}

      {newProd&&(
        <Card style={{marginBottom:14}}>
          <STitle>Nuevo producto</STitle>
          <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:7,marginTop:10}}>
            <input value={np.nombre} onChange={e=>setNp(p=>({...p,nombre:e.target.value}))} placeholder="Nombre" style={inp}/>
            <select value={np.cat} onChange={e=>setNp(p=>({...p,cat:e.target.value}))} style={inp}>
              {allCats.map(c=><option key={c}>{c}</option>)}
              {newCat&&<option value={newCat}>{newCat} (nueva)</option>}
            </select>
            <input value={np.precio} onChange={e=>setNp(p=>({...p,precio:parseFloat(e.target.value)||0}))} placeholder="Precio USD" type="number" style={inp}/>
            <input value={np.costo}  onChange={e=>setNp(p=>({...p,costo:parseFloat(e.target.value)||0}))}  placeholder="Costo USD"  type="number" style={inp}/>
            <input value={np.stock}  onChange={e=>setNp(p=>({...p,stock:parseInt(e.target.value)||0}))}    placeholder="Stock inicial" type="number" style={inp}/>
            <input value={np.stockMin} onChange={e=>setNp(p=>({...p,stockMin:parseInt(e.target.value)||0}))} placeholder="Alerta mínimo" type="number" style={inp}/>
          </div>
          <div style={{display:"flex",gap:7,marginTop:10}}><Btn sm onClick={addProd}>Guardar</Btn><Btn sm outline color={C.muted} onClick={()=>setNewProd(false)}>Cancelar</Btn></div>
        </Card>
      )}

      <div style={{display:"flex",gap:5,flexWrap:"wrap",marginBottom:14}}>
        {cats.map(c=><Chip key={c} active={catFil===c} onClick={()=>setCatFil(c)} small>{c}</Chip>)}
      </div>

      <div style={{display:"flex",flexDirection:"column",gap:5}}>
        {filtrados.map(p=>(
          <div key={p.id}>
            {editId===p.id&&editForm?(
              <Card style={{padding:"12px 14px"}}>
                <div style={{display:"grid",gridTemplateColumns:"2fr 1fr 1fr 1fr 1fr",gap:6,alignItems:"center"}}>
                  <input value={editForm.nombre} onChange={e=>setEditForm(x=>({...x,nombre:e.target.value}))} style={inp}/>
                  <input value={editForm.precio} onChange={e=>setEditForm(x=>({...x,precio:parseFloat(e.target.value)||0}))} placeholder="Precio USD" type="number" style={inp}/>
                  <input value={editForm.costo}  onChange={e=>setEditForm(x=>({...x,costo:parseFloat(e.target.value)||0}))}  placeholder="Costo USD"  type="number" style={inp}/>
                  <input value={editForm.stock}  onChange={e=>setEditForm(x=>({...x,stock:parseInt(e.target.value)||0}))}    placeholder="Stock" type="number" style={inp}/>
                  <input value={editForm.stockMin} onChange={e=>setEditForm(x=>({...x,stockMin:parseInt(e.target.value)||0}))} placeholder="Mín" type="number" style={inp}/>
                </div>
                <div style={{display:"flex",gap:6,marginTop:8}}>
                  <Btn sm onClick={()=>saveItem(editForm)}>Guardar</Btn>
                  <Btn sm outline color={C.muted} onClick={()=>{setEditId(null);setEditForm(null);}}>Cancelar</Btn>
                </div>
              </Card>
            ):(
              <div style={{background:C.surface,border:`1px solid ${p.stock<=p.stockMin&&p.stock<99?C.red+"40":C.border}`,
                borderRadius:9,padding:"9px 14px",display:"flex",alignItems:"center",gap:10}}>
                <div style={{flex:1}}>
                  <span style={{fontSize:12,fontWeight:600,color:C.text}}>{p.nombre}</span>
                  <span style={{fontSize:11,color:C.muted,marginLeft:8}}>{p.cat}</span>
                </div>
                <span style={{fontSize:12,color:C.accent,fontWeight:600,minWidth:70,textAlign:"right"}}>{usd(p.precio)}</span>
                <span style={{fontSize:11,color:C.muted,minWidth:70,textAlign:"right"}}>Costo {usd(p.costo)}</span>
                {p.stock<99&&(
                  <span style={{fontSize:12,fontWeight:700,minWidth:60,textAlign:"center",
                    color:p.stock===0?C.red:p.stock<=p.stockMin?C.amber:C.green}}>
                    ×{p.stock}
                  </span>
                )}
                <Btn sm outline color={C.muted} onClick={()=>{setEditId(p.id);setEditForm({...p});}}>Editar</Btn>
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}

/* ═══════════════════════════════════════════════════
   CAJA CHICA
═══════════════════════════════════════════════════ */
function CajaView({ctx}){
  const {session,ventas,movCaja,setMovCaja,cotiz,persist,SK}=ctx;
  const isOwner=session.rol==="owner";
  const hoy=todayStr();

  // Ventas del día del empleado (o todas si owner)
  const ventasHoy=ventas.filter(v=>{
    const esHoy=v.fecha.slice(0,10)===hoy;
    return isOwner?esHoy:esHoy&&v.empleadoId===session.id;
  });

  // Movimientos del día del empleado
  const movsHoy=movCaja.filter(m=>{
    const esHoy=m.fecha.slice(0,10)===hoy;
    return isOwner?esHoy:esHoy&&m.empleadoId===session.id;
  });

  // Calcular caja pesos (solo efectivo) y USD
  const cajaPesosVentas=ventasHoy.reduce((s,v)=>
    s+v.pagos.filter(p=>mById(p.metodoId)?.caja==="pesos").reduce((ss,p)=>ss+(parseFloat(p.monto)||0),0),0);
  const cajaUSDVentas=ventasHoy.reduce((s,v)=>
    s+v.pagos.filter(p=>mById(p.metodoId)?.caja==="usd").reduce((ss,p)=>ss+(parseFloat(p.monto)||0),0),0);

  // Movimientos: + entra, - sale
  const movsPesos=movsHoy.filter(m=>m.moneda==="pesos").reduce((s,m)=>s+(m.tipo==="ingreso"?m.monto:-m.monto),0);
  const movsUSD=movsHoy.filter(m=>m.moneda==="usd").reduce((s,m)=>s+(m.tipo==="ingreso"?m.monto:-m.monto),0);

  const totalPesos=cajaPesosVentas+movsPesos;
  const totalUSD=cajaUSDVentas+movsUSD;

  const [form,setForm]=useState({tipo:"retiro",moneda:"pesos",monto:"",descripcion:""});

  const agregarMov=async()=>{
    if(!form.monto||parseFloat(form.monto)<=0)return;
    const mov={id:newId(),fecha:new Date().toISOString(),
      empleadoId:session.id,empleadoNombre:session.nombre,
      tipo:form.tipo,moneda:form.moneda,
      monto:parseFloat(form.monto),descripcion:form.descripcion};
    await persist(SK.movCaja,setMovCaja,[mov,...movCaja]);
    setForm({tipo:"retiro",moneda:"pesos",monto:"",descripcion:""});
  };

  const reiniciarCaja=async(moneda)=>{
    if(!window.confirm(`¿Confirmar reinicio de caja ${moneda}? Esto registra un retiro del total actual.`))return;
    const total=moneda==="pesos"?totalPesos:totalUSD;
    if(total<=0)return;
    const mov={id:newId(),fecha:new Date().toISOString(),
      empleadoId:session.id,empleadoNombre:session.nombre,
      tipo:"retiro",moneda,monto:total,descripcion:"Reinicio de caja"};
    await persist(SK.movCaja,setMovCaja,[mov,...movCaja]);
  };

  return(
    <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:16}}>
      {/* RESUMEN */}
      <div style={{display:"flex",flexDirection:"column",gap:12}}>
        <Card>
          <STitle>💵 Resumen de caja — {isOwner?"Todo el local":session.nombre}</STitle>
          <p style={{fontSize:11,color:C.muted,marginTop:2,marginBottom:14}}>{new Date().toLocaleDateString("es-AR",{weekday:"long",day:"numeric",month:"long"})}</p>
          <div style={{display:"flex",flexDirection:"column",gap:10}}>
            <div style={{background:"#f0fdf4",border:"1px solid #bbf7d0",borderRadius:10,padding:"14px 16px"}}>
              <p style={{fontSize:11,color:C.green,fontWeight:700,textTransform:"uppercase",letterSpacing:".06em"}}>Caja Pesos</p>
              <p style={{fontSize:26,fontWeight:800,color:C.green,fontFamily:"'Syne',sans-serif",marginTop:4}}>{ars(totalPesos)}</p>
              <p style={{fontSize:11,color:C.muted,marginTop:2}}>
                Ventas: {ars(cajaPesosVentas)} {movsPesos!==0&&`· Movimientos: ${movsPesos>0?"+":""}${ars(movsPesos)}`}
              </p>
              <button onClick={()=>reiniciarCaja("pesos")} style={{
                marginTop:8,padding:"5px 12px",borderRadius:6,fontSize:11,fontWeight:600,
                background:"transparent",border:"1px solid #bbf7d0",color:C.green,cursor:"pointer",
              }}>Reiniciar caja pesos</button>
            </div>
            <div style={{background:"#fffbeb",border:"1px solid #fde68a",borderRadius:10,padding:"14px 16px"}}>
              <p style={{fontSize:11,color:C.amber,fontWeight:700,textTransform:"uppercase",letterSpacing:".06em"}}>Caja USD</p>
              <p style={{fontSize:26,fontWeight:800,color:C.amber,fontFamily:"'Syne',sans-serif",marginTop:4}}>{usd(totalUSD)}</p>
              <p style={{fontSize:11,color:C.muted,marginTop:2}}>
                Ventas: {usd(cajaUSDVentas)} {movsUSD!==0&&`· Movimientos: ${movsUSD>0?"+":""}${usd(movsUSD)}`}
              </p>
              <p style={{fontSize:11,color:C.muted}}>≈ {ars(totalUSD*cotiz)} al cambio</p>
              <button onClick={()=>reiniciarCaja("usd")} style={{
                marginTop:8,padding:"5px 12px",borderRadius:6,fontSize:11,fontWeight:600,
                background:"transparent",border:"1px solid #fde68a",color:C.amber,cursor:"pointer",
              }}>Reiniciar caja USD</button>
            </div>
          </div>
        </Card>

        {/* MOVIMIENTOS HOY */}
        <Card>
          <STitle sm>Movimientos del día</STitle>
          {movsHoy.length===0
            ?<p style={{fontSize:12,color:C.muted,padding:"12px 0"}}>Sin movimientos registrados</p>
            :<div style={{marginTop:8,display:"flex",flexDirection:"column",gap:5}}>
              {movsHoy.map(m=>(
                <div key={m.id} style={{display:"flex",alignItems:"center",gap:8,
                  background:C.faint,borderRadius:7,padding:"7px 10px"}}>
                  <span style={{fontSize:16}}>{m.tipo==="ingreso"?"📥":"📤"}</span>
                  <div style={{flex:1}}>
                    <p style={{fontSize:12,fontWeight:600,color:C.text}}>{m.descripcion||m.tipo}</p>
                    <p style={{fontSize:10,color:C.muted}}>{m.empleadoNombre} · {fmtDate(m.fecha)}</p>
                  </div>
                  <span style={{fontSize:13,fontWeight:700,
                    color:m.tipo==="ingreso"?C.green:C.red}}>
                    {m.tipo==="ingreso"?"+":"-"}{m.moneda==="usd"?usd(m.monto):ars(m.monto)}
                  </span>
                </div>
              ))}
            </div>
          }
        </Card>
      </div>

      {/* REGISTRAR MOVIMIENTO / COMPRA */}
      <div style={{display:"flex",flexDirection:"column",gap:12}}>
        <Card>
          <STitle>Registrar movimiento de caja</STitle>
          <p style={{fontSize:11,color:C.muted,marginTop:2,marginBottom:14}}>Retiros, depósitos o compras</p>
          <div style={{display:"flex",gap:8,marginBottom:8}}>
            {[["retiro","📤 Retiro"],["ingreso","📥 Ingreso"],["compra","🛒 Compra"]].map(([k,l])=>(
              <Chip key={k} active={form.tipo===k} onClick={()=>setForm(p=>({...p,tipo:k}))} small>{l}</Chip>
            ))}
          </div>
          <div style={{display:"flex",gap:8,marginBottom:8}}>
            {[["pesos","$ Pesos"],["usd","USD"]].map(([k,l])=>(
              <Chip key={k} active={form.moneda===k} onClick={()=>setForm(p=>({...p,moneda:k}))} small>{l}</Chip>
            ))}
          </div>
          <input value={form.monto} onChange={e=>setForm(p=>({...p,monto:e.target.value}))}
            type="number" placeholder={form.moneda==="usd"?"Monto USD":"Monto $"} style={{...inp,marginBottom:8}}/>
          <input value={form.descripcion} onChange={e=>setForm(p=>({...p,descripcion:e.target.value}))}
            placeholder={form.tipo==="compra"?"Detalle de la compra (ej: pantallas iphone 14 x3)":"Descripción…"} style={{...inp,marginBottom:12}}/>
          <Btn full onClick={agregarMov} disabled={!form.monto||parseFloat(form.monto)<=0}>
            Registrar {form.tipo}
          </Btn>
          {form.tipo==="compra"&&(
            <p style={{fontSize:11,color:C.muted,marginTop:8}}>
              💡 Las compras se descuentan de la caja. Para actualizar el stock, editá el producto en la sección Stock.
            </p>
          )}
        </Card>

        {/* COMPRAS DEL DÍA */}
        {movsHoy.filter(m=>m.tipo==="compra").length>0&&(
          <Card>
            <STitle sm>🛒 Compras del día</STitle>
            <div style={{marginTop:8,display:"flex",flexDirection:"column",gap:5}}>
              {movsHoy.filter(m=>m.tipo==="compra").map(m=>(
                <div key={m.id} style={{background:"#fef3c7",border:"1px solid #fde68a",borderRadius:7,padding:"8px 10px"}}>
                  <p style={{fontSize:12,fontWeight:600,color:C.text}}>{m.descripcion}</p>
                  <div style={{display:"flex",justifyContent:"space-between",marginTop:3}}>
                    <span style={{fontSize:10,color:C.muted}}>{m.empleadoNombre} · {fmtDate(m.fecha)}</span>
                    <span style={{fontSize:12,fontWeight:700,color:C.red}}>−{m.moneda==="usd"?usd(m.monto):ars(m.monto)}</span>
                  </div>
                </div>
              ))}
            </div>
          </Card>
        )}
      </div>
    </div>
  );
}

/* ═══════════════════════════════════════════════════
   DASHBOARD
═══════════════════════════════════════════════════ */
function DashView({ctx}){
  const {ventas,ordenes,catalogo,cotiz,setCotiz,movCaja,persist,SK,usuarios,setUsuarios}=ctx;
  const [cotizInput,setCotizInput]=useState(cotiz.toString());
  const [periodo,setPeriodo]=useState("hoy");
  const [tab,setTab]=useState("ventas");
  const [detId,setDetId]=useState(null);

  const hoy=todayStr();
  const filtradas=useMemo(()=>ventas.filter(v=>{
    const d=v.fecha.slice(0,10);
    if(periodo==="hoy")return d===hoy;
    if(periodo==="semana"){const h=new Date();h.setDate(h.getDate()-7);return new Date(v.fecha)>=h;}
    if(periodo==="mes")return d.slice(0,7)===hoy.slice(0,7);
    return true;
  }),[ventas,periodo,hoy]);

  const totalUSD=filtradas.reduce((s,v)=>s+v.totalUSD,0);
  const gananciaUSD=filtradas.reduce((s,v)=>s+(v.gananciaUSD||0),0);

  const cajaPesos=filtradas.reduce((s,v)=>
    s+v.pagos.filter(p=>mById(p.metodoId)?.caja==="pesos").reduce((ss,p)=>ss+(parseFloat(p.monto)||0),0),0);
  const cajaUSD=filtradas.reduce((s,v)=>
    s+v.pagos.filter(p=>mById(p.metodoId)?.caja==="usd").reduce((ss,p)=>ss+(parseFloat(p.monto)||0),0),0);

  const porCat={};
  filtradas.forEach(v=>v.items.forEach(i=>{if(!porCat[i.cat])porCat[i.cat]=0;porCat[i.cat]+=i.precio*i.qty;}));
  const porMet={};
  filtradas.forEach(v=>v.pagos.forEach(p=>{
    if(!porMet[p.metodoId])porMet[p.metodoId]=0;
    const m=mById(p.metodoId);const val=parseFloat(p.monto)||0;
    porMet[p.metodoId]+=m.moneda==="usd"?val:val/cotiz;
  }));

  const scoring=useMemo(()=>{
    const map={};
    ventas.forEach(v=>{
      if(!map[v.empleadoId])map[v.empleadoId]={id:v.empleadoId,nombre:v.empleadoNombre,ganancia:0,ventas:0,trabajos:0};
      map[v.empleadoId].ganancia+=v.gananciaUSD||0;
      map[v.empleadoId].ventas+=1;
    });
    ordenes.filter(o=>o.estado==="Entregado").forEach(o=>{
      if(!map[o.empleadoId])map[o.empleadoId]={id:o.empleadoId,nombre:o.empleadoNombre,ganancia:0,ventas:0,trabajos:0};
      map[o.empleadoId].trabajos+=1;
    });
    return Object.values(map).sort((a,b)=>b.ganancia-a.ganancia);
  },[ventas,ordenes]);

  const maxGan=scoring.reduce((m,s)=>Math.max(m,s.ganancia),0);
  const alertasStock=catalogo.filter(p=>p.stock<99&&p.stock<=p.stockMin);

  const [nuevoU,setNuevoU]=useState({nombre:"",rol:"empleado"});
  const addUser=async()=>{
    if(!nuevoU.nombre)return;
    const u={id:newId(),nombre:nuevoU.nombre,rol:nuevoU.rol,pass:"",activo:true};
    await persist(SK.usuarios,setUsuarios,[...usuarios,u]);
    setNuevoU({nombre:"",rol:"empleado"});
  };
  const toggleU=async id=>persist(SK.usuarios,setUsuarios,usuarios.map(u=>u.id===id?{...u,activo:!u.activo}:u));
  const resetPass=async id=>persist(SK.usuarios,setUsuarios,usuarios.map(u=>u.id===id?{...u,pass:""}:u));

  const guardarCotiz=()=>{const n=parseFloat(cotizInput);if(n>0)persist(SK.cotiz,setCotiz,n);};

  return(
    <div style={{display:"flex",flexDirection:"column",gap:16}}>
      <div style={{display:"flex",flexWrap:"wrap",gap:10,alignItems:"center",justifyContent:"space-between"}}>
        <div style={{display:"flex",gap:5,flexWrap:"wrap"}}>
          {[["hoy","Hoy"],["semana","7 días"],["mes","Este mes"],["todo","Todo"]].map(([k,l])=>(
            <Chip key={k} active={periodo===k} onClick={()=>setPeriodo(k)} small>{l}</Chip>
          ))}
        </div>
        <div style={{display:"flex",gap:7,alignItems:"center"}}>
          <span style={{fontSize:12,color:C.muted}}>USD → $</span>
          <input value={cotizInput} onChange={e=>setCotizInput(e.target.value)}
            style={{...inp,width:100,textAlign:"right"}} type="number"/>
          <Btn sm onClick={guardarCotiz}>Guardar</Btn>
        </div>
      </div>
      <p style={{fontSize:11,color:C.muted}}>⚠️ Cambiar cotización no altera ventas ya registradas.</p>

      {alertasStock.length>0&&(
        <div style={{background:"#fff7ed",border:"1px solid #fed7aa",borderRadius:9,padding:"10px 14px"}}>
          <p style={{fontSize:12,fontWeight:700,color:C.amber}}>⚠️ {alertasStock.length} productos con stock bajo</p>
        </div>
      )}

      <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(160px,1fr))",gap:9}}>
        <StatCard label="Vendido USD"    value={usd(totalUSD)}    sub={`${filtradas.length} ventas`} color={C.accent} icon="📊"/>
        <StatCard label="Ganancia USD"   value={usd(gananciaUSD)} sub="precio − costo"              color={C.green}  icon="💹"/>
        <StatCard label="Caja Pesos"     value={ars(cajaPesos)}   sub="Solo efectivo"               color={C.green}  icon="💵"/>
        <StatCard label="Caja USD"       value={usd(cajaUSD)}     sub={`≈${ars(cajaUSD*cotiz)}`}    color={C.amber}  icon="💵"/>
      </div>

      <div style={{display:"flex",gap:5,borderBottom:`1px solid ${C.border}`,paddingBottom:10}}>
        {[["ventas","📊 Análisis"],["scoring","🏆 Scoring"],["usuarios","👥 Usuarios"],["ordenes","📋 Órdenes"]].map(([k,l])=>(
          <Chip key={k} active={tab===k} onClick={()=>setTab(k)} small>{l}</Chip>
        ))}
      </div>

      {tab==="ventas"&&(
        <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:14}}>
          <Card>
            <STitle>Por categoría</STitle>
            <div style={{marginTop:12}}>
              {Object.keys(porCat).length===0
                ?<p style={{fontSize:12,color:C.muted}}>Sin datos</p>
                :Object.entries(porCat).sort((a,b)=>b[1]-a[1]).map(([cat,v])=>(
                  <MiniBar key={cat} label={cat} value={v} max={Math.max(...Object.values(porCat))}/>
                ))
              }
            </div>
          </Card>
          <Card>
            <STitle>Por método de pago</STitle>
            <div style={{marginTop:12}}>
              {Object.keys(porMet).length===0
                ?<p style={{fontSize:12,color:C.muted}}>Sin datos</p>
                :Object.entries(porMet).sort((a,b)=>b[1]-a[1]).map(([id,v])=>{
                  const m=mById(id);
                  return<MiniBar key={id} label={m?.label||id} value={v}
                    max={Math.max(...Object.values(porMet))}
                    color={m?.caja==="pesos"?C.green:m?.caja==="usd"?C.amber:C.muted}/>;
                })
              }
            </div>
          </Card>
          <Card style={{gridColumn:"1/-1"}}>
            <STitle>Historial de ventas</STitle>
            <div style={{marginTop:10,display:"flex",flexDirection:"column",gap:4}}>
              {filtradas.length===0
                ?<p style={{fontSize:12,color:C.muted,padding:"16px 0",textAlign:"center"}}>Sin ventas en este período</p>
                :filtradas.slice().sort((a,b)=>b.fecha.localeCompare(a.fecha)).map(v=>(
                  <div key={v.id}>
                    <button onClick={()=>setDetId(detId===v.id?null:v.id)} style={{
                      width:"100%",background:C.faint,border:`1px solid ${C.border}`,
                      borderRadius:9,padding:"9px 13px",textAlign:"left",
                      display:"flex",alignItems:"center",gap:9,color:C.text,transition:"all .1s",
                    }}>
                      <span style={{fontSize:11,color:C.muted,minWidth:100}}>{fmtDate(v.fecha)}</span>
                      <span style={{fontSize:12,fontWeight:600,flex:1}}>{v.empleadoNombre}</span>
                      <span style={{fontSize:12,color:C.accent,fontWeight:700}}>{usd(v.totalUSD)}</span>
                      {v.descuento>0&&<Badge color={C.green}>-15%</Badge>}
                      <span style={{fontSize:10,color:C.muted}}>{detId===v.id?"▲":"▼"}</span>
                    </button>
                    {detId===v.id&&(
                      <div className="fu" style={{background:C.faint,border:`1px solid ${C.border}`,
                        borderRadius:9,padding:"10px 14px",margin:"2px 0 4px"}}>
                        {v.items.map(i=>(
                          <div key={i.id} style={{display:"flex",justifyContent:"space-between",marginBottom:3}}>
                            <span style={{fontSize:12,color:C.text}}>{i.nombre} ×{i.qty}</span>
                            <span style={{fontSize:12,color:C.accent,fontWeight:600}}>{usd(i.precio*i.qty)}</span>
                          </div>
                        ))}
                        <div style={{borderTop:`1px solid ${C.border}`,marginTop:7,paddingTop:7}}>
                          {v.pagos.map(p=>{const m=mById(p.metodoId);const val=parseFloat(p.monto)||0;return(
                            <div key={p.metodoId} style={{display:"flex",justifyContent:"space-between",marginBottom:2}}>
                              <span style={{fontSize:11,color:C.muted}}>{m?.label}</span>
                              <span style={{fontSize:11,fontWeight:600}}>{m?.moneda==="usd"?`USD ${val.toFixed(2)}`:ars(val)}</span>
                            </div>
                          );})}
                        </div>
                        <p style={{fontSize:10,color:C.muted,marginTop:5}}>Cotiz: ${v.cotizUsada?.toLocaleString("es-AR")} · Ganancia: {usd(v.gananciaUSD||0)}</p>
                        {v.nota&&<p style={{fontSize:11,color:C.muted,fontStyle:"italic",marginTop:3}}>📝 {v.nota}</p>}
                      </div>
                    )}
                  </div>
                ))
              }
            </div>
          </Card>
        </div>
      )}

      {tab==="scoring"&&(
        <Card>
          <STitle>🏆 Ranking por ganancia generada</STitle>
          <p style={{fontSize:11,color:C.muted,marginTop:3,marginBottom:16}}>Histórico completo · ganancia real (precio − costo)</p>
          {scoring.length===0
            ?<p style={{fontSize:12,color:C.muted}}>Sin datos aún</p>
            :scoring.map((s,i)=>(
              <div key={s.id} style={{background:C.faint,borderRadius:10,padding:"12px 14px",marginBottom:8,
                border:`1px solid ${i===0?"#fde68a":C.border}`}}>
                <div style={{display:"flex",alignItems:"center",gap:10}}>
                  <span style={{fontSize:22}}>{["🥇","🥈","🥉"][i]||"  "}</span>
                  <div style={{flex:1}}>
                    <p style={{fontWeight:700,fontSize:14}}>{s.nombre}</p>
                    <p style={{fontSize:11,color:C.muted}}>{s.ventas} ventas · {s.trabajos} órdenes entregadas</p>
                  </div>
                  <div style={{textAlign:"right"}}>
                    <p style={{fontFamily:"'Syne',sans-serif",fontWeight:800,fontSize:18,
                      color:i===0?C.gold:i===1?"#94a3b8":i===2?"#b45309":C.accent}}>
                      {usd(s.ganancia)}
                    </p>
                    <p style={{fontSize:10,color:C.muted}}>ganancia total</p>
                  </div>
                </div>
                <div style={{marginTop:8,background:C.border,borderRadius:4,height:4}}>
                  <div style={{width:`${maxGan>0?(s.ganancia/maxGan)*100:0}%`,
                    background:i===0?C.gold:i===1?"#94a3b8":i===2?"#b45309":C.accent,
                    height:"100%",borderRadius:4,transition:"width .6s"}}/>
                </div>
              </div>
            ))
          }
        </Card>
      )}

      {tab==="usuarios"&&(
        <Card>
          <STitle>👥 Gestión de usuarios</STitle>
          <div style={{marginTop:14,display:"flex",flexDirection:"column",gap:7}}>
            {usuarios.map(u=>(
              <div key={u.id} style={{background:C.faint,borderRadius:9,padding:"10px 14px",
                display:"flex",alignItems:"center",gap:10,opacity:u.activo?1:.5}}>
                <span style={{fontSize:18}}>{u.rol==="owner"?"👑":"👤"}</span>
                <div style={{flex:1}}>
                  <p style={{fontWeight:700,fontSize:13}}>{u.nombre}</p>
                  <p style={{fontSize:11,color:C.muted}}>{u.rol==="owner"?"Propietario":"Empleado"} · {u.activo?"Activo":"Inactivo"}</p>
                  <p style={{fontSize:11,color:u.pass?C.green:C.amber}}>
                    {u.pass?`Contraseña configurada (${"•".repeat(Math.min(u.pass.length,8))})`:"Sin contraseña (la elegirá al ingresar)"}
                  </p>
                </div>
                {u.rol!=="owner"&&(
                  <div style={{display:"flex",gap:6}}>
                    <Btn sm color={u.activo?C.red:C.green} onClick={()=>toggleU(u.id)}>{u.activo?"Desactivar":"Activar"}</Btn>
                    {u.pass&&<Btn sm outline color={C.amber} onClick={()=>resetPass(u.id)}>Reset pass</Btn>}
                  </div>
                )}
              </div>
            ))}
          </div>
          <div style={{marginTop:16,borderTop:`1px solid ${C.border}`,paddingTop:14}}>
            <p style={{fontSize:12,fontWeight:600,marginBottom:8}}>Agregar empleado</p>
            <div style={{display:"flex",gap:7,alignItems:"center"}}>
              <input value={nuevoU.nombre} onChange={e=>setNuevoU(p=>({...p,nombre:e.target.value}))}
                placeholder="Nombre del empleado" style={{...inp,flex:1}}/>
              <Btn sm onClick={addUser}>Agregar</Btn>
            </div>
          </div>
        </Card>
      )}

      {tab==="ordenes"&&(
        <Card>
          <STitle>📋 Estado de órdenes</STitle>
          <div style={{display:"grid",gridTemplateColumns:"repeat(3,1fr)",gap:9,marginTop:12,marginBottom:16}}>
            {ESTADOS.map(e=>(
              <div key={e} style={{background:C.faint,borderRadius:9,padding:"12px",textAlign:"center"}}>
                <p style={{fontSize:26,fontWeight:800,color:ESTADO_COLOR[e],fontFamily:"'Syne',sans-serif"}}>
                  {ordenes.filter(o=>o.estado===e).length}
                </p>
                <p style={{fontSize:11,color:C.muted,marginTop:2}}>{e}</p>
              </div>
            ))}
          </div>
          {ordenes.filter(o=>o.estado!=="Entregado").slice(0,8).map(o=>(
            <div key={o.id} style={{background:C.faint,borderRadius:8,padding:"8px 12px",
              display:"flex",alignItems:"center",gap:10,marginBottom:5}}>
              <Badge color={ESTADO_COLOR[o.estado]}>{o.estado}</Badge>
              <span style={{flex:1,fontSize:12,fontWeight:600}}>{o.clienteNombre}</span>
              <span style={{fontSize:12,color:C.accent}}>{usd(o.total)}</span>
              {o.fechaEntrega&&<span style={{fontSize:11,color:C.muted}}>{fmtDay(o.fechaEntrega)}</span>}
            </div>
          ))}
        </Card>
      )}
    </div>
  );
}
ReactDOM.createRoot(document.getElementById('root')).render(React.createElement(App));
