// ── AJUSTES v2 — 8 tabs completos ────────────────────

function Ajustes({ tiendaId }) {
  const { useState, useRef, useEffect } = React;
  const [tab, setTab] = useState('general');
  const tienda = TIENDAS.find(t=>t.id===tiendaId)||TIENDAS[0];

  // ── Config general por tienda ──
  const [config, setConfigState] = useState(() => lsGet('ajustes_config', {
    navarro: {
      nombreComercial:'Navarro Joyería Fina', razonSocial:'Joyería Navarro Limitada',
      rut:'76.543.210-K', direccion:'Calle Comercio 123, Santa Cruz',
      telefono:'+56 72 234 5678', email:'contacto@navarro-joyeria.cl',
      web:'navarro-joyeria.cl', moneda:'CLP', iva:19,
      textoTicket:'Gracias por su preferencia · navarro-joyeria.cl',
      logoEnTodos: true,
    },
    rubi: {
      nombreComercial:'Joyería Rubí · Taller', razonSocial:'Joyería Navarro Limitada',
      rut:'76.543.210-K', direccion:'Calle Comercio 125, Santa Cruz',
      telefono:'+56 72 234 5679', email:'taller@navarro-joyeria.cl',
      web:'navarro-joyeria.cl', moneda:'CLP', iva:19,
      textoTicket:'Gracias por confiar en nuestro taller',
      logoEnTodos: true,
    },
  }));
  const cfg = config[tiendaId]||config.navarro;
  function setCfg(k,v) {
    const next = {...config,[tiendaId]:{...config[tiendaId],[k]:v}};
    setConfigState(next); lsSet('ajustes_config', next);
  }

  // ── Horarios predefinidos ──
  const HORARIOS = [
    'Lun–Vie 09:00–18:00','Lun–Sáb 09:00–18:00','Lun–Sáb 10:00–19:00',
    'Lun–Sáb 10:00–20:00','Lun–Dom 10:00–20:00','Lun–Vie 08:30–17:30',
    'Personalizado'
  ];
  const [horarioCustom, setHorarioCustom] = useState(cfg.horario||'Lun–Sáb 10:00–19:00');
  const [horarioSel, setHorarioSel] = useState('Lun–Sáb 10:00–19:00');

  // ── Impresoras ──
  const [impresoras, setImpresoras] = useState(() => lsGet('ajustes_impresoras', [
    { id:'godex1', nombre:'Godex GE300 — Etiquetas', tipo:'etiquetas',
      modelo:'Godex GE300', puerto:'USB', estado:'Configurada', tienda:'navarro', predeterminada:true,
      config:{ ancho:55, alto:12, margenIzq:0, margenSup:0, zonaPrecio:20, fontSize:8, mostrarPrecio:true, mostrarSKU:true, mostrarNombre:true, mostrarBarcode:true } },
    { id:'ticket1', nombre:'SPRT SP-POS88 — Tickets', tipo:'tickets',
      modelo:'SPRT SP-POS88', puerto:'USB', estado:'Configurada', tienda:'navarro', predeterminada:true,
      config:{ anchoMm:80, margen:3, copias:3, autoCorte:true } },
    { id:'epson1', nombre:'Epson L3250 — Documentos', tipo:'documentos',
      modelo:'Epson L3250', puerto:'USB/WiFi', estado:'Configurada', tienda:'navarro', predeterminada:true,
      config:{ formato:'A4', orientacion:'Vertical', colorMode:'Color', calidad:'Normal' } },
    { id:'ticket2', nombre:'Impresora Tickets — Rubí', tipo:'tickets',
      modelo:'Genérica 58mm', puerto:'Bluetooth', estado:'Pendiente', tienda:'rubi', predeterminada:false,
      config:{ anchoMm:58, margen:2, copias:3, autoCorte:false } },
  ]));

  // ── Lector barcode ──
  const [lector, setLector] = useState(() => lsGet('ajustes_lector', {
    activo:true, tipo:'USB HID', velocidad:'Alta', prefijo:'', sufijo:'\n',
    accion:'Buscar en inventario', codigosActivos:['EAN-13','Code 128','QR','EAN-8','Code 39','ITF'],
    timeout:100
  }));
  const [lectorTestVal, setLectorTestVal] = useState('');
  const [lectorTestResult, setLectorTestResult] = useState(null);
  const lectorRef = useRef(null);

  // ── Redes & APIs state (must be at component top, never in conditionals) ──
  const [redesVals, setRedesVals] = useState(()=>{
    const v={};
    ['correo','instagram','facebook','tiktok','youtube','whatsapp','spotify','deezer','openai','gemini','claude','stability','mercadopago','transbank','sii'].forEach(id=>{v[id]=lsGet('red_'+id,'');});
    return v;
  });
  const [redesShow, setRedesShow] = useState({});

  // ── Etiqueta designer (legacy config, kept for compat) ──
  const [etqConfig, setEtqConfig] = useState(() => lsGet('ajustes_etiqueta', {ancho:55, alto:12}));

  // ── Tipo de barcode ──────────────────────────────────────────────────────────
  const [barcodeType, setBarcodeTypeState] = useState(() => {
    try { return localStorage.getItem('godex_barcode_type') || 'datamatrix'; } catch(e) { return 'datamatrix'; }
  });
  function saveBarcodeType(t) {
    try { localStorage.setItem('godex_barcode_type', t); } catch(e) {}
    setBarcodeTypeState(t);
  }

  // ── Label layout drag-and-drop (godex_label_layout) ──
  const LBL_V = 6;  // debe coincidir con LABEL_V en data.jsx
  // Layout v6: izquierda = precio + SKU texto, derecha = Data Matrix
  const LBL_DEFAULT = { precio:{x:18,y:42,size:42,visible:true}, nombre:{x:18,y:75,size:18,visible:false}, barcode:{x:67,y:4,w:34,h:88,dmSize:10.5,visible:true}, sku:{x:18,y:88,size:14,visible:true} };
  const [labelLayout, setLabelLayout] = useState(() => {
    try {
      const stored = JSON.parse(localStorage.getItem('godex_label_layout')||'null')||{};
      if (!stored._v || stored._v < LBL_V) return {...LBL_DEFAULT};
      const { _v, ...rest } = stored;
      return Object.assign({}, LBL_DEFAULT, rest);
    } catch(e) { return {...LBL_DEFAULT}; }
  });
  const labelDragRef = useRef(null);  // { key, startX, startY, origX, origY }
  const labelContainerRef = useRef(null);

  function saveLabelLayout(next) {
    localStorage.setItem('godex_label_layout', JSON.stringify({...next, _v: LBL_V}));
    setLabelLayout({...next});
    // Forzar re-render del preview borrando caché de godexEtiquetaSVG si existe
  }
  function updLbl(key, patch) {
    saveLabelLayout({...labelLayout, [key]: {...labelLayout[key], ...patch}});
  }

  useEffect(() => {
    function onMove(e) {
      const d = labelDragRef.current;
      if (!d || !labelContainerRef.current) return;
      const rect = labelContainerRef.current.getBoundingClientRect();
      const xPct = Math.round(Math.max(0, Math.min(100, (e.clientX - rect.left) / rect.width * 100)));
      const yPct = Math.round(Math.max(0, Math.min(100, (e.clientY - rect.top)  / rect.height * 100)));
      setLabelLayout(prev => ({...prev, [d.key]: {...prev[d.key], x: xPct, y: yPct}}));
    }
    function onUp() {
      if (!labelDragRef.current) return;
      setLabelLayout(prev => { localStorage.setItem('godex_label_layout', JSON.stringify(prev)); return prev; });
      labelDragRef.current = null;
    }
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);
    return () => { window.removeEventListener('mousemove', onMove); window.removeEventListener('mouseup', onUp); };
  }, []);

  // ── Historial ──
  const [histTab, setHistTab] = useState('ots');
  const [historial] = useState([
    { id:'HI-001', fecha:'2026-04-20 14:32', tipo:'etiquetas', subtipo:'Etiquetas', documento:'Lote 5 productos', impresora:'Godex GE300', usuario:'Admin', estado:'OK', copias:5 },
    { id:'HI-002', fecha:'2026-04-20 14:15', tipo:'ventas', subtipo:'Boleta', documento:'V-2026-0419', impresora:'SPRT 80mm', usuario:'Admin', estado:'OK', copias:1 },
    { id:'HI-003', fecha:'2026-04-19 16:50', tipo:'ots', subtipo:'OT Argollas', documento:'OT-2026-006', impresora:'SPRT 80mm', usuario:'Admin', estado:'Error papel', copias:0 },
    { id:'HI-004', fecha:'2026-04-19 15:20', tipo:'ots', subtipo:'OT Grabado', documento:'OT-2026-005', impresora:'SPRT 80mm', usuario:'Admin', estado:'OK', copias:1 },
    { id:'HI-005', fecha:'2026-04-18 11:05', tipo:'ventas', subtipo:'Factura', documento:'F-2026-0088', impresora:'Epson L3250', usuario:'Vendedor', estado:'OK', copias:1 },
    { id:'HI-006', fecha:'2026-04-18 10:30', tipo:'papeleria', subtipo:'Cotización', documento:'COT-2026-012', impresora:'Epson L3250', usuario:'Admin', estado:'OK', copias:1 },
    { id:'HI-007', fecha:'2026-04-17 09:15', tipo:'etiquetas', subtipo:'Etiquetas', documento:'Lote 3 anillos', impresora:'Godex GE300', usuario:'Admin', estado:'OK', copias:3 },
  ]);

  // ── Redes sociales ──
  const [redes, setRedes] = useState(() => lsGet('ajustes_redes', {}));

  // ── Ticket designer state ──
  const [ticketCfg, setTicketCfg] = useState(() => lsGet('ajustes_ticket', {
    mostrarLogo:true, mostrarDireccion:true, mostrarTelefono:true, mostrarWeb:true,
    mostrarFolio:true, mostrarCajero:true, mostrarRut:false, mostrarCodigoBarras:false,
    piePagina:'Gracias por su preferencia · navarro-joyeria.cl',
    fuente:'Courier New', tamanoPapel:80
  }));

  // ── Documento designer state ──
  const [docCfg, setDocCfg] = useState(() => lsGet('ajustes_doc', {
    mostrarLogo:true, mostrarFirma:false, mostrarCondiciones:true,
    colorHeader:'#1a1410', formatoPapel:'A4', orientacion:'Vertical',
    piePagina:'Navarro Joyería Fina · Santa Cruz · navarro-joyeria.cl',
    incluirDetalle:true, incluirIVA:true
  }));

  const S = ajStyles;

  const TABS = [
    {id:'general',    label:'⚙ General'},
    {id:'hardware',   label:'🖨 Hardware'},
    {id:'etiquetas',  label:'🏷 Etiquetas'},
    {id:'tickets',    label:'🧾 Tickets'},
    {id:'documentos', label:'📄 Documentos'},
    {id:'reimpresion',label:'🗂 Historial'},
    {id:'usuarios',   label:'👤 Usuarios'},
    {id:'redes',      label:'🌐 Redes & APIs'},
  ];

  // ── Helpers ──
  function testImpresora(imp) {
    if (imp.tipo === 'etiquetas') {
      imprimirEtiquetaGodex([{sku:'SKU-TEST',nombre:'Prueba Etiqueta Joyería',precio:20000}], imp.config);
    } else if (imp.tipo === 'tickets') {
      const win = window.open('','_blank','width=340,height=500');
      if (!win) return;
      const mm = imp.config.anchoMm || 80;
      win.document.write(`<html><head><style>
        body{font-family:'Courier New',monospace;margin:0;padding:8px;width:${mm*3.78}px;font-size:12px;}
        .c{text-align:center;} .b{font-weight:bold;} .sep{border-top:1px dashed #000;margin:6px 0;}
      </style></head><body>
        <div class="c b" style="font-size:15px">✦ NAVARRO ✦</div>
        <div class="c" style="font-size:9px">JOYERÍA · TEST IMPRESORA</div>
        <div class="sep"></div>
        <div class="c b">PRUEBA DE IMPRESIÓN</div>
        <div>Modelo: ${imp.modelo}</div>
        <div>Puerto: ${imp.puerto}</div>
        <div>Ancho: ${mm}mm</div>
        <div class="sep"></div>
        <div class="c" style="font-size:9px">Si ves esto, la impresora funciona ✓</div>
        <div class="c" style="font-size:9px">${new Date().toLocaleString('es-CL')}</div>
      </body></html>`);
      win.document.close(); win.print();
    } else if (imp.tipo === 'documentos') {
      const win = window.open('','_blank','width=794,height=1100');
      if (!win) return;
      win.document.write(`<html><head><style>
        body{font-family:Arial,sans-serif;margin:40px;color:#111;}
        .header{display:flex;justify-content:space-between;border-bottom:2px solid #1a1410;padding-bottom:16px;margin-bottom:24px;}
        .logo{font-family:Georgia,serif;font-size:24px;font-weight:bold;letter-spacing:3px;}
        h2{color:#1a1410;} table{width:100%;border-collapse:collapse;}
        td,th{border:1px solid #ccc;padding:8px;font-size:12px;}
      </style></head><body>
        <div class="header">
          <div><div class="logo">✦ NAVARRO</div><div style="font-size:10px;color:#666">JOYERÍA · TEST DOCUMENTO</div></div>
          <div style="text-align:right;font-size:11px;color:#666">Fecha: ${new Date().toLocaleDateString('es-CL')}<br>Impresora: ${imp.modelo}<br>Papel: ${imp.config.formato || 'A4'}</div>
        </div>
        <h2>Prueba de Impresión — Epson L3250</h2>
        <p>Este documento es una prueba del sistema Navarro ERP. Si puede leer este texto claramente, la impresora está funcionando correctamente.</p>
        <table><tr><th>Producto</th><th>Cantidad</th><th>Precio</th><th>Total</th></tr>
        <tr><td>Anillo Plata 925</td><td>1</td><td>$25.000</td><td>$25.000</td></tr>
        <tr><td>Aros Oro 18K</td><td>1</td><td>$85.000</td><td>$85.000</td></tr>
        <tr><td colspan="3" style="text-align:right"><b>Total</b></td><td><b>$110.000</b></td></tr></table>
        <p style="font-size:9px;margin-top:40px;text-align:center;color:#666">Navarro Joyería Fina · Santa Cruz · navarro-joyeria.cl</p>
      </body></html>`);
      win.document.close(); win.print();
    }
  }

  // ── Vista previa etiqueta — usa godexEtiquetaSVG canónica ──────────────────
  function EtiquetaHusoPreview({ escala=5.8, sku='AGCR3344', precio=20000, nombre='Dije de cobre de cadena con piedra reconstituida' }) {
    const svgStr = (typeof godexEtiquetaSVG === 'function')
      ? godexEtiquetaSVG(sku, precio, nombre, { scale: 1 })
      : `<svg xmlns="http://www.w3.org/2000/svg" width="439" height="96"><rect width="439" height="96" fill="white" stroke="#ccc"/><text x="10" y="55" font-size="18" fill="#999">Cargando…</text></svg>`;
    const url = 'data:image/svg+xml,' + encodeURIComponent(svgStr);
    const dW = Math.round(55 * escala), dH = Math.round(12 * escala);
    return (
      <div style={{display:'flex',justifyContent:'center',alignItems:'center',padding:'20px',
        background:'#f0ede8',borderRadius:'8px'}}>
        <div style={{boxShadow:'0 2px 8px rgba(0,0,0,0.18)',lineHeight:0}}>
          <img src={url} style={{width:`${dW}px`,height:`${dH}px`,imageRendering:'crisp-edges',display:'block'}} alt={sku}/>
        </div>
      </div>
    );
  }

  // ── Editor de etiqueta drag-and-drop ─────────────────────────────────────
  function EtiquetaEditorPreview() {
    const CW = 550, CH = 120;  // canvas en px (10× la etiqueta 55×12mm)
    const svgStr = typeof godexEtiquetaSVG === 'function'
      ? godexEtiquetaSVG('AGCR3344', 20000, 'Anillo plata circón', {scale:1})
      : '';
    const svgUrl = svgStr ? 'data:image/svg+xml,' + encodeURIComponent(svgStr) : '';
    const ELS = [
      {key:'precio',  label:'💰 Precio',   color:'#c9a84c'},
      {key:'nombre',  label:'📝 Nombre',   color:'#3b82f6'},
      {key:'barcode', label:'▓ Código',    color:'#059669'},
      {key:'sku',     label:'# SKU',       color:'#8b5cf6'},
    ];
    return (
      <div style={{display:'flex',flexDirection:'column',alignItems:'center',gap:'6px'}}>
        {/* Canvas drag area */}
        <div ref={labelContainerRef} style={{position:'relative',width:`${CW}px`,height:`${CH}px`,
          border:'2px solid #c9a84c',borderRadius:'4px',overflow:'hidden',
          background:'white',userSelect:'none',cursor:'default',flexShrink:0}}>
          {svgUrl && <img src={svgUrl} style={{position:'absolute',top:0,left:0,width:'100%',height:'100%',opacity:0.35,pointerEvents:'none'}} alt=""/>}
          {/* Doblez central */}
          <div style={{position:'absolute',left:'50%',top:0,bottom:0,borderLeft:'1px dashed #bbb',pointerEvents:'none'}}/>
          {/* Elementos arrastrables */}
          {ELS.map(({key,label,color}) => {
            const el = labelLayout[key];
            if (!el || el.visible === false) return null;
            const left = el.x / 100 * CW;
            const top  = el.y / 100 * CH;
            return (
              <div key={key}
                onMouseDown={e=>{ e.preventDefault(); labelDragRef.current = {key}; }}
                style={{position:'absolute',left:`${left}px`,top:`${top}px`,
                  transform:'translate(-50%,-50%)',background:color,color:'#fff',
                  fontSize:'9px',fontWeight:'bold',padding:'2px 6px',borderRadius:'3px',
                  cursor:'grab',whiteSpace:'nowrap',boxShadow:'0 1px 4px rgba(0,0,0,0.35)',
                  border:'1.5px solid rgba(255,255,255,0.5)',zIndex:10}}>
                {label}
              </div>
            );
          })}
        </div>
        <div style={{fontSize:'9px',color:'#888',textAlign:'center'}}>
          Arrastra los elementos · línea punteada = doblez central
        </div>
      </div>
    );
  }

  // ── Preview Ticket ──
  function TicketPreview() {
    const mm = ticketCfg.tamanoPapel || 80;
    const px = Math.min(mm * 2.8, 280);
    return (
      <div style={{background:'#fff',width:`${px}px`,fontFamily:`'${ticketCfg.fuente}',monospace`,
        fontSize:'11px',color:'#111',padding:'10px',boxShadow:'0 2px 12px rgba(0,0,0,0.3)',
        borderRadius:'4px',margin:'0 auto'}}>
        {ticketCfg.mostrarLogo && <div style={{textAlign:'center',fontWeight:'bold',fontSize:'15px',marginBottom:'2px'}}>✦ NAVARRO ✦</div>}
        <div style={{textAlign:'center',fontSize:'8px',marginBottom:'4px'}}>JOYERÍA FINA</div>
        {ticketCfg.mostrarDireccion && <div style={{textAlign:'center',fontSize:'8px'}}>Calle Comercio 123, Santa Cruz</div>}
        {ticketCfg.mostrarTelefono && <div style={{textAlign:'center',fontSize:'8px'}}>+56 72 234 5678</div>}
        {ticketCfg.mostrarWeb && <div style={{textAlign:'center',fontSize:'8px',marginBottom:'4px'}}>navarro-joyeria.cl</div>}
        <div style={{borderTop:'1px dashed #000',margin:'5px 0'}}/>
        {ticketCfg.mostrarFolio && <div style={{display:'flex',justifyContent:'space-between',fontSize:'9px'}}><span>BOLETA N°</span><span>V-2026-0001</span></div>}
        <div style={{display:'flex',justifyContent:'space-between',fontSize:'9px'}}><span>Fecha</span><span>{new Date().toLocaleDateString('es-CL')}</span></div>
        {ticketCfg.mostrarCajero && <div style={{display:'flex',justifyContent:'space-between',fontSize:'9px'}}><span>Cajero</span><span>Admin</span></div>}
        <div style={{borderTop:'1px dashed #000',margin:'5px 0'}}/>
        <div style={{fontSize:'9px',marginBottom:'2px',fontWeight:'bold'}}>DETALLE:</div>
        <div style={{fontSize:'9px',display:'flex',justifyContent:'space-between'}}><span>1x Anillo plata 925</span><span>$25.000</span></div>
        <div style={{fontSize:'9px',display:'flex',justifyContent:'space-between'}}><span>1x Aros oro 18K</span><span>$85.000</span></div>
        <div style={{borderTop:'1px dashed #000',margin:'5px 0'}}/>
        <div style={{display:'flex',justifyContent:'space-between',fontWeight:'bold'}}><span>TOTAL</span><span>$110.000</span></div>
        <div style={{fontSize:'8px',display:'flex',justifyContent:'space-between'}}><span>IVA 19%</span><span>$17.563</span></div>
        <div style={{borderTop:'1px dashed #000',margin:'5px 0'}}/>
        <div style={{textAlign:'center',fontSize:'8px',marginTop:'4px'}}>{ticketCfg.piePagina}</div>
      </div>
    );
  }

  // ── Preview Documento ──
  function DocumentoPreview() {
    return (
      <div style={{background:'white',width:'100%',maxWidth:'400px',margin:'0 auto',
        fontFamily:'Arial,sans-serif',fontSize:'10px',color:'#111',padding:'16px',
        boxShadow:'0 2px 12px rgba(0,0,0,0.3)',borderRadius:'4px',minHeight:'340px'}}>
        {/* Header */}
        <div style={{display:'flex',justifyContent:'space-between',borderBottom:'2px solid #1a1410',paddingBottom:'10px',marginBottom:'12px'}}>
          <div>
            <div style={{fontFamily:'Georgia,serif',fontSize:'15px',fontWeight:'bold',letterSpacing:'2px'}}>✦ NAVARRO</div>
            <div style={{fontSize:'7px',color:'#666',marginTop:'1px'}}>JOYERÍA FINA · SANTA CRUZ</div>
            {docCfg.mostrarLogo && <div style={{marginTop:'4px',width:'36px',height:'20px',background:'#f5f0e8',border:'1px dashed #ccc',display:'flex',alignItems:'center',justifyContent:'center',fontSize:'6px',color:'#999'}}>LOGO</div>}
          </div>
          <div style={{textAlign:'right',fontSize:'8px',color:'#666'}}>
            <div style={{fontWeight:'bold',color:'#1a1410',fontSize:'10px'}}>COTIZACIÓN</div>
            <div>N° COT-2026-001</div>
            <div>Fecha: {new Date().toLocaleDateString('es-CL')}</div>
          </div>
        </div>
        {/* Cliente */}
        <div style={{marginBottom:'10px',padding:'6px',background:'#f9f7f4',borderRadius:'3px'}}>
          <div style={{fontWeight:'bold',fontSize:'9px',marginBottom:'3px'}}>CLIENTE</div>
          <div>María González · RUT 12.345.678-9</div>
          <div style={{color:'#666'}}>Santa Cruz, Chile</div>
        </div>
        {/* Tabla */}
        <table style={{width:'100%',borderCollapse:'collapse',fontSize:'8px',marginBottom:'10px'}}>
          <thead><tr style={{background:'#1a1410',color:'white'}}>
            <th style={{padding:'4px 6px',textAlign:'left'}}>Producto</th>
            <th style={{padding:'4px 3px',textAlign:'center'}}>Cant</th>
            <th style={{padding:'4px 3px',textAlign:'right'}}>Precio</th>
            <th style={{padding:'4px 3px',textAlign:'right'}}>Total</th>
          </tr></thead>
          <tbody>
            <tr style={{borderBottom:'1px solid #eee'}}><td style={{padding:'3px 6px'}}>Anillo plata 925 circón</td><td style={{padding:'3px',textAlign:'center'}}>1</td><td style={{padding:'3px',textAlign:'right'}}>$25.000</td><td style={{padding:'3px',textAlign:'right'}}>$25.000</td></tr>
            <tr style={{borderBottom:'1px solid #eee'}}><td style={{padding:'3px 6px'}}>Aros oro 18K</td><td style={{padding:'3px',textAlign:'center'}}>1</td><td style={{padding:'3px',textAlign:'right'}}>$85.000</td><td style={{padding:'3px',textAlign:'right'}}>$85.000</td></tr>
          </tbody>
        </table>
        {docCfg.incluirIVA && <div style={{textAlign:'right',fontSize:'8px',marginBottom:'2px'}}><span style={{color:'#666'}}>Subtotal: $110.000 · IVA 19%: $17.563 · </span><b>Total: $127.563</b></div>}
        {docCfg.mostrarCondiciones && <div style={{fontSize:'7px',color:'#888',borderTop:'1px solid #eee',paddingTop:'6px',marginTop:'6px'}}>Cotización válida por 15 días. Precio sujeto a disponibilidad.</div>}
        <div style={{fontSize:'7px',color:'#aaa',textAlign:'center',marginTop:'10px'}}>{docCfg.piePagina}</div>
      </div>
    );
  }

  const HIST_TIPOS = [
    {id:'ots',       label:'OT\'s / Taller'},
    {id:'ventas',    label:'Ventas'},
    {id:'etiquetas', label:'Etiquetas'},
    {id:'papeleria', label:'Papelería interna'},
  ];

  const CODIGOS_TIPOS = ['EAN-13','EAN-8','Code 128','Code 39','QR','ITF','PDF417','Aztec','Data Matrix'];

  const REDES_CONFIG = [
    {id:'correo',    icon:'✉', label:'Email / SMTP',       color:'#ea4335', ph:'smtp.gmail.com / API Key', desc:'Para envío automático de documentos y notificaciones'},
    {id:'instagram', icon:'📸', label:'Instagram',          color:'#e1306c', ph:'@navarro_joyeria', desc:'Publicaciones automáticas de productos y promociones'},
    {id:'facebook',  icon:'👥', label:'Facebook / Meta',    color:'#1877f2', ph:'ID de página o token', desc:'Posts, catálogo y marketplace'},
    {id:'tiktok',    icon:'🎵', label:'TikTok',             color:'#ff0050', ph:'@navarro_joyeria', desc:'Videos y TikTok Shop'},
    {id:'youtube',   icon:'▶', label:'YouTube',             color:'#ff0000', ph:'ID canal o API Key', desc:'Videos de productos y tutoriales'},
    {id:'whatsapp',  icon:'💬', label:'WhatsApp Business',  color:'#25d366', ph:'+56 9 1234 5678', desc:'Atención al cliente y notificaciones automáticas'},
    {id:'spotify',   icon:'🎧', label:'Spotify',            color:'#1db954', ph:'Client ID / Secret', desc:'Playlist ambiente tienda y taller'},
    {id:'deezer',    icon:'🎶', label:'Deezer',             color:'#ff6200', ph:'App ID / Token', desc:'Música ambiente alternativa'},
    {id:'openai',    icon:'🤖', label:'OpenAI / ChatGPT',   color:'#10a37f', ph:'sk-...', desc:'IA para textos, cotizaciones y análisis'},
    {id:'gemini',    icon:'✦', label:'Google Gemini',       color:'#4285f4', ph:'AIza...', desc:'IA alternativa Google'},
    {id:'claude',    icon:'◆', label:'Claude (Anthropic)',  color:'#7c3aed', ph:'sk-ant-...', desc:'IA principal del sistema (activa)'},
    {id:'stability', icon:'🎨', label:'Stability AI',       color:'#ea580c', ph:'sk-...', desc:'Generación de imágenes de joyas'},
    {id:'mercadopago',icon:'💳',label:'Mercado Pago',       color:'#009ee3', ph:'Access Token', desc:'Pagos digitales y terminal MP'},
    {id:'transbank', icon:'💳', label:'Transbank / Webpay', color:'#e30613', ph:'Commerce Code / API Key', desc:'Débito y crédito Transbank'},
    {id:'sii',       icon:'🏛', label:'SII / Facturación',  color:'#1a5276', ph:'Certificado digital', desc:'Facturación electrónica DTE'},
  ];

  return (
    <div style={{display:'flex',flexDirection:'column',height:'100%',overflow:'hidden'}}>
      {/* Tabs */}
      <div style={{...S.tabs,overflowX:'auto',flexWrap:'nowrap'}}>
        {TABS.map(t=>(
          <button key={t.id} onClick={()=>setTab(t.id)}
            style={{...S.tab,...(tab===t.id?S.tabAct:{}),whiteSpace:'nowrap'}}>
            {t.label}
          </button>
        ))}
        <div style={{marginLeft:'auto',padding:'0 16px',display:'flex',alignItems:'center',gap:'8px',flexShrink:0}}>
          <div style={{width:'8px',height:'8px',borderRadius:'50%',background:tienda.color}}/>
          <span style={{fontSize:'11px',color:'var(--cream-3)',whiteSpace:'nowrap'}}>{tienda.nombre}</span>
        </div>
      </div>

      {/* ════ GENERAL ════ */}
      {tab==='general' && (
        <div style={{flex:1,overflowY:'auto',padding:'20px',maxWidth:'700px'}}>
          <div style={S.title}>Configuración General — {tienda.nombre}</div>

          {/* Datos empresa */}
          <div style={S.section}>
            <div style={S.sectionTitle}>🏪 Datos de la Empresa</div>
            <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:'10px'}}>
              {[
                {l:'Nombre comercial',k:'nombreComercial'},{l:'Razón social',k:'razonSocial'},
                {l:'RUT',k:'rut'},{l:'Teléfono',k:'telefono'},
                {l:'Email',k:'email'},{l:'Web',k:'web'},
                {l:'Dirección',k:'direccion'},
              ].map(f=>(
                <div key={f.k} style={f.k==='direccion'?{gridColumn:'1/-1'}:{}}>
                  <div style={S.label}>{f.l}</div>
                  <input style={S.input} value={cfg[f.k]||''}
                    onChange={e=>setCfg(f.k,e.target.value)}/>
                </div>
              ))}
              {/* Horario seleccionable */}
              <div style={{gridColumn:'1/-1'}}>
                <div style={S.label}>Horario de atención</div>
                <div style={{display:'flex',gap:'8px',flexWrap:'wrap',marginBottom:'6px'}}>
                  {HORARIOS.map(h=>(
                    <button key={h} onClick={()=>{setHorarioSel(h);if(h!=='Personalizado')setCfg('horario',h);}}
                      style={{padding:'4px 10px',borderRadius:'20px',border:`1px solid ${horarioSel===h?'var(--gold)':'var(--border)'}`,background:horarioSel===h?'var(--gold-dim)':'var(--surface)',color:horarioSel===h?'var(--gold)':'var(--cream-3)',fontSize:'10px',cursor:'pointer'}}>
                      {h}
                    </button>
                  ))}
                </div>
                {horarioSel==='Personalizado' && (
                  <input style={S.input} placeholder="Ej: Lun–Sáb 09:30–19:30" value={horarioCustom}
                    onChange={e=>{setHorarioCustom(e.target.value);setCfg('horario',e.target.value);}}/>
                )}
                <div style={{fontSize:'10px',color:'var(--cream-3)',marginTop:'4px'}}>Activo: <span style={{color:'var(--gold)'}}>{cfg.horario||horarioCustom}</span></div>
              </div>
              <div style={{gridColumn:'1/-1'}}>
                <div style={S.label}>Texto al pie de todos los tickets</div>
                <input style={S.input} value={cfg.textoTicket||''}
                  onChange={e=>setCfg('textoTicket',e.target.value)}/>
              </div>
            </div>
          </div>

          {/* Logo impresión */}
          <div style={S.section}>
            <div style={S.sectionTitle}>🖼 Logo para Impresiones</div>
            <div style={{display:'flex',gap:'14px',alignItems:'flex-start'}}>
              <div onClick={()=>{const inp=document.createElement('input');inp.type='file';inp.accept='image/*';inp.onchange=e=>{const f=e.target.files[0];if(!f)return;const r=new FileReader();r.onload=ev=>{localStorage.setItem('navarro_logo',ev.target.result);alert('Logo guardado ✓');};r.readAsDataURL(f);};inp.click();}}
                style={{width:'72px',height:'44px',border:'2px dashed var(--border)',borderRadius:'7px',display:'flex',alignItems:'center',justifyContent:'center',color:'var(--cream-3)',fontSize:'10px',cursor:'pointer',background:'var(--surface)',flexShrink:0,textAlign:'center',lineHeight:1.3}}>
                📷<br/>Logo
              </div>
              <div style={{flex:1}}>
                <div style={{fontSize:'11px',color:'var(--cream-2)',marginBottom:'8px'}}>PNG transparente ideal. Se usará en <b>todos</b> los documentos imprimibles.</div>
                <div style={{display:'flex',gap:'8px',flexWrap:'wrap'}}>
                  {['Tickets SPRT','Boletas','Facturas','OT\'s','Cotizaciones','Etiquetas Godex'].map(doc=>(
                    <div key={doc} style={{display:'flex',alignItems:'center',gap:'4px',fontSize:'10px',color:'var(--cream-3)'}}>
                      <input type="checkbox" defaultChecked style={{accentColor:'var(--gold)'}}/>
                      {doc}
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>

          {/* Fiscal */}
          <div style={S.section}>
            <div style={S.sectionTitle}>⚖ Configuración Fiscal</div>
            <div style={{display:'grid',gridTemplateColumns:'1fr 1fr 1fr',gap:'8px'}}>
              <div><div style={S.label}>IVA %</div>
                <input type="number" min="0" max="50" style={S.input} value={cfg.iva||19} onChange={e=>setCfg('iva',parseInt(e.target.value)||19)}/></div>
              <div><div style={S.label}>Moneda</div>
                <input style={S.input} value="CLP" readOnly/></div>
              <div><div style={S.label}>País</div>
                <input style={S.input} value="Chile" readOnly/></div>
            </div>
          </div>

          {/* Mercado Pago */}
          <div style={S.section}>
            <div style={S.sectionTitle}>💳 Integración Mercado Pago</div>
            {[{l:'Estado API',v:'● Conectado',c:'#27ae60'},{l:'Terminal',v:'MP-POS Bluetooth'},{l:'Comisión',v:'2% por transacción'}].map(r=>(
              <div key={r.l} style={{display:'flex',justifyContent:'space-between',fontSize:'12px',padding:'5px 0',borderBottom:'1px solid var(--border)'}}>
                <span style={{color:'var(--cream-3)'}}>{r.l}</span>
                <span style={{color:r.c||'var(--cream)'}}>{r.v}</span>
              </div>
            ))}
          </div>

          <button onClick={()=>alert('Configuración guardada ✓')}
            style={{...S.btn,width:'100%',marginTop:'12px'}}>✦ Guardar Configuración</button>
        </div>
      )}

      {/* ════ HARDWARE ════ */}
      {tab==='hardware' && (
        <div style={{flex:1,overflowY:'auto',padding:'20px'}}>
          <div style={S.title}>Hardware & Impresoras</div>

          <div style={{display:'flex',flexDirection:'column',gap:'12px',marginBottom:'24px'}}>
            {impresoras.map(imp=>(
              <div key={imp.id} style={S.card}>
                <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',marginBottom:'10px'}}>
                  <div>
                    <div style={{color:'var(--cream)',fontWeight:600,fontSize:'14px'}}>{imp.nombre}</div>
                    <div style={{color:'var(--cream-3)',fontSize:'11px'}}>{imp.modelo} · {imp.puerto} · {TIENDAS.find(t=>t.id===imp.tienda)?.sigla}</div>
                  </div>
                  <div style={{display:'flex',gap:'6px',alignItems:'center'}}>
                    <span style={{fontSize:'10px',padding:'2px 9px',borderRadius:'20px',fontWeight:600,
                      background:imp.estado==='Configurada'?'rgba(39,174,96,0.15)':'rgba(192,57,43,0.15)',
                      color:imp.estado==='Configurada'?'#27ae60':'#c0392b'}}>
                      {imp.estado==='Configurada'?'● Activa':'⚠ '+imp.estado}
                    </span>
                    {imp.predeterminada&&<span style={{fontSize:'10px',color:'var(--gold)'}}>★ Default</span>}
                  </div>
                </div>

                {/* Godex — etiquetas */}
                {imp.tipo==='etiquetas' && (<>
                  <div style={{padding:'12px',background:'var(--surface)',borderRadius:'8px',marginBottom:'10px'}}>
                    <div style={{fontSize:'10px',color:'var(--gold)',fontWeight:600,marginBottom:'8px'}}>Configuración etiqueta 55×12mm (huso/pesa)</div>
                    <div style={{display:'grid',gridTemplateColumns:'repeat(4,1fr)',gap:'8px',marginBottom:'12px'}}>
                      {[{l:'Ancho (mm)',k:'ancho',def:55},{l:'Alto (mm)',k:'alto',def:12},{l:'Zona precio (mm)',k:'zonaPrecio',def:20},{l:'Margen (mm)',k:'margenIzq',def:0}].map(f=>(
                        <div key={f.k}>
                          <div style={{fontSize:'10px',color:'var(--cream-3)',marginBottom:'3px'}}>{f.l}</div>
                          <input type="number" step="0.5" style={{...S.input,padding:'4px 6px',fontSize:'12px'}}
                            value={imp.config[f.k]??f.def}
                            onChange={e=>setImpresoras(prev=>prev.map(x=>x.id===imp.id?{...x,config:{...x.config,[f.k]:parseFloat(e.target.value)||f.def}}:x))}/>
                        </div>
                      ))}
                    </div>
                    <div style={{fontSize:'10px',color:'var(--cream-3)',marginBottom:'6px',fontWeight:600}}>Vista previa etiqueta — Formato huso real:</div>
                    <EtiquetaHusoPreview/>
                    <div style={{fontSize:'9px',color:'var(--cream-3)',marginTop:'5px',textAlign:'center'}}>
                      Etiqueta huso 55×12mm — Doblez al centro · Precio izquierda · SKU+barcode derecha
                    </div>
                  </div>
                </>)}

                {/* Tickets SPRT */}
                {imp.tipo==='tickets' && (
                  <div style={{padding:'12px',background:'var(--surface)',borderRadius:'8px',marginBottom:'10px'}}>
                    <div style={{fontSize:'10px',color:'var(--gold)',fontWeight:600,marginBottom:'8px'}}>Configuración impresora tickets</div>
                    <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:'8px',marginBottom:'8px'}}>
                      <div><div style={S.labelSm}>Ancho papel (mm)</div>
                        <input type="number" style={{...S.input,padding:'4px 6px',fontSize:'12px'}} value={imp.config.anchoMm||80}
                          onChange={e=>setImpresoras(prev=>prev.map(x=>x.id===imp.id?{...x,config:{...x.config,anchoMm:parseInt(e.target.value)||80}}:x))}/></div>
                      <div><div style={S.labelSm}>Copias</div>
                        <input type="number" min="1" max="5" style={{...S.input,padding:'4px 6px',fontSize:'12px'}} value={imp.config.copias||3}
                          onChange={e=>setImpresoras(prev=>prev.map(x=>x.id===imp.id?{...x,config:{...x.config,copias:parseInt(e.target.value)||3}}:x))}/></div>
                      <div><div style={S.labelSm}>Margen (mm)</div>
                        <input type="number" style={{...S.input,padding:'4px 6px',fontSize:'12px'}} value={imp.config.margen||3}
                          onChange={e=>setImpresoras(prev=>prev.map(x=>x.id===imp.id?{...x,config:{...x.config,margen:parseInt(e.target.value)||3}}:x))}/></div>
                    </div>
                    <label style={{display:'flex',alignItems:'center',gap:'6px',fontSize:'11px',color:'var(--cream-2)',cursor:'pointer'}}>
                      <input type="checkbox" checked={imp.config.autoCorte!==false} style={{accentColor:'var(--gold)'}}
                        onChange={e=>setImpresoras(prev=>prev.map(x=>x.id===imp.id?{...x,config:{...x.config,autoCorte:e.target.checked}}:x))}/>
                      Corte automático entre copias
                    </label>
                  </div>
                )}

                {/* Epson — documentos */}
                {imp.tipo==='documentos' && (
                  <div style={{padding:'12px',background:'var(--surface)',borderRadius:'8px',marginBottom:'10px'}}>
                    <div style={{fontSize:'10px',color:'var(--gold)',fontWeight:600,marginBottom:'8px'}}>Configuración Epson L3250</div>
                    <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:'8px'}}>
                      {[{l:'Formato',k:'formato',opts:['A4','Carta','A5']},{l:'Color',k:'colorMode',opts:['Color','Grises','B/N']},{l:'Calidad',k:'calidad',opts:['Borrador','Normal','Alta','Foto']}].map(f=>(
                        <div key={f.k}><div style={S.labelSm}>{f.l}</div>
                          <select style={{...S.input,padding:'4px 6px',fontSize:'12px'}} value={imp.config[f.k]||f.opts[1]}
                            onChange={e=>setImpresoras(prev=>prev.map(x=>x.id===imp.id?{...x,config:{...x.config,[f.k]:e.target.value}}:x))}>
                            {f.opts.map(o=><option key={o}>{o}</option>)}
                          </select>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                <div style={{display:'flex',gap:'6px'}}>
                  <button onClick={()=>testImpresora(imp)} style={S.btnSm}>🖨 Test</button>
                  <button onClick={()=>setImpresoras(prev=>prev.map(x=>({...x,predeterminada:x.id===imp.id&&x.tipo===imp.tipo})))}
                    style={S.btnSm}>★ Predeterminada</button>
                </div>
              </div>
            ))}
          </div>

          {/* ── Lector de códigos ── */}
          <div style={{...S.card,borderColor:'rgba(41,128,185,0.35)'}}>
            <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:'12px'}}>
              <div style={{color:'var(--cream)',fontWeight:600,fontSize:'14px'}}>📡 Lector de Códigos / Barras</div>
              <span style={{fontSize:'11px',padding:'3px 10px',borderRadius:'20px',
                background:lector.activo?'rgba(39,174,96,0.15)':'rgba(100,100,100,0.15)',
                color:lector.activo?'#27ae60':'var(--cream-3)',fontWeight:600,cursor:'pointer'}}
                onClick={()=>setLector(prev=>{const n={...prev,activo:!prev.activo};lsSet('ajustes_lector',n);return n;})}>
                {lector.activo?'● Activo':'○ Inactivo'}
              </span>
            </div>
            <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:'10px',marginBottom:'12px'}}>
              <div>
                <div style={S.labelSm}>Tipo de lector</div>
                <select style={{...S.input,fontSize:'12px'}} value={lector.tipo}
                  onChange={e=>setLector(prev=>{const n={...prev,tipo:e.target.value};lsSet('ajustes_lector',n);return n;})}>
                  {['USB HID','USB Virtual COM','Bluetooth HID','RS-232'].map(o=><option key={o}>{o}</option>)}
                </select>
              </div>
              <div>
                <div style={S.labelSm}>Velocidad lectura</div>
                <select style={{...S.input,fontSize:'12px'}} value={lector.velocidad}
                  onChange={e=>setLector(prev=>{const n={...prev,velocidad:e.target.value};lsSet('ajustes_lector',n);return n;})}>
                  {['Baja','Media','Alta','Máxima'].map(o=><option key={o}>{o}</option>)}
                </select>
              </div>
              <div>
                <div style={S.labelSm}>Acción al leer código</div>
                <select style={{...S.input,fontSize:'12px'}} value={lector.accion}
                  onChange={e=>setLector(prev=>{const n={...prev,accion:e.target.value};lsSet('ajustes_lector',n);return n;})}>
                  {['Buscar en inventario','Agregar a venta POS','Abrir ficha producto','Solo registrar'].map(o=><option key={o}>{o}</option>)}
                </select>
              </div>
              <div>
                <div style={S.labelSm}>Timeout entre lecturas (ms)</div>
                <input type="number" min="50" max="500" step="50" style={{...S.input,fontSize:'12px'}} value={lector.timeout||100}
                  onChange={e=>setLector(prev=>{const n={...prev,timeout:parseInt(e.target.value)||100};lsSet('ajustes_lector',n);return n;})}/>
              </div>
            </div>
            {/* Tipos de código */}
            <div style={{marginBottom:'12px'}}>
              <div style={S.labelSm}>Tipos de código habilitados</div>
              <div style={{display:'flex',flexWrap:'wrap',gap:'6px',marginTop:'4px'}}>
                {CODIGOS_TIPOS.map(tipo=>(
                  <label key={tipo} style={{display:'flex',alignItems:'center',gap:'4px',fontSize:'10px',color:'var(--cream-2)',cursor:'pointer',
                    padding:'3px 8px',borderRadius:'20px',border:`1px solid ${lector.codigosActivos?.includes(tipo)?'var(--gold)':'var(--border)'}`,
                    background:lector.codigosActivos?.includes(tipo)?'var(--gold-dim)':'var(--surface)'}}>
                    <input type="checkbox" style={{display:'none'}} checked={lector.codigosActivos?.includes(tipo)||false}
                      onChange={e=>{const next={...lector,codigosActivos:e.target.checked?[...(lector.codigosActivos||[]),tipo]:(lector.codigosActivos||[]).filter(x=>x!==tipo)};setLector(next);lsSet('ajustes_lector',next);}}/>
                    {tipo}
                  </label>
                ))}
              </div>
            </div>
            {/* Test de lectura */}
            <div style={{padding:'10px',background:'var(--surface)',borderRadius:'6px'}}>
              <div style={{fontSize:'11px',color:'var(--gold)',fontWeight:600,marginBottom:'6px'}}>🔍 Test de lectura en vivo</div>
              <div style={{fontSize:'10px',color:'var(--cream-3)',marginBottom:'6px'}}>Haz click en el campo y escanea un código con el lector:</div>
              <input ref={lectorRef} style={{...S.input,width:'100%',fontFamily:'monospace',fontSize:'13px',letterSpacing:'1px'}}
                placeholder="Escanear aquí → apunta el lector a este campo..."
                value={lectorTestVal}
                onChange={e=>setLectorTestVal(e.target.value)}
                onKeyDown={e=>{if(e.key==='Enter'&&lectorTestVal){setLectorTestResult({codigo:lectorTestVal,tiempo:new Date().toLocaleTimeString('es-CL'),ok:true});setLectorTestVal('');}}}/>
              {lectorTestResult && (
                <div style={{marginTop:'8px',padding:'8px',background:'rgba(39,174,96,0.08)',border:'1px solid rgba(39,174,96,0.2)',borderRadius:'6px',fontSize:'11px'}}>
                  <span style={{color:'#27ae60',fontWeight:600}}>✓ Lectura OK</span>
                  <span style={{color:'var(--cream-3)',marginLeft:'8px'}}>Código: <b style={{color:'var(--cream)',fontFamily:'monospace'}}>{lectorTestResult.codigo}</b></span>
                  <span style={{color:'var(--cream-3)',marginLeft:'8px'}}>a las {lectorTestResult.tiempo}</span>
                  <button onClick={()=>setLectorTestResult(null)} style={{...S.btnSm,marginLeft:'8px',fontSize:'9px',padding:'1px 6px'}}>✕</button>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* ════ ETIQUETAS ════ */}
      {tab==='etiquetas' && (
        <div style={{flex:1,overflowY:'auto',padding:'20px'}}>
          <div style={S.title}>Diseñador de Etiqueta — Godex GE300 55×12mm</div>
          <div style={{fontSize:'11px',color:'var(--cream-3)',marginBottom:'14px'}}>
            Arrastra cada elemento en el canvas. Los cambios se guardan automáticamente y se usan al imprimir.
          </div>

          {/* ── Tipo de código de barras ─────────────────────────────────────── */}
          <div style={{...S.card,padding:'14px',marginBottom:'14px'}}>
            <div style={{fontSize:'12px',fontWeight:700,color:'var(--cream)',marginBottom:'10px'}}>
              Formato de código de barras
            </div>
            <div style={{display:'flex',gap:'10px',flexWrap:'wrap'}}>
              {[
                {val:'datamatrix', label:'Data Matrix ECC200', sub:'2D compacto · recomendado joyería · requiere lector 2D', icon:'▓▒', gold:true},
                {val:'code128',    label:'Code 128',            sub:'1D lineal · lector estándar',                           icon:'▐▌▐▌'},
                {val:'qr',         label:'QR Code',             sub:'2D matricial · lector 2D/cámara',                       icon:'⬛'},
              ].map(opt=>(
                <label key={opt.val} style={{
                  display:'flex',alignItems:'center',gap:'10px',cursor:'pointer',
                  padding:'10px 14px',borderRadius:'8px',flex:1,minWidth:'160px',
                  border:`2px solid ${barcodeType===opt.val?'var(--gold)':'var(--border)'}`,
                  background:barcodeType===opt.val?'rgba(201,168,76,0.08)':'var(--surface-2)',
                  transition:'all 0.15s',
                }}>
                  <input type="radio" name="barcodeType" value={opt.val}
                    checked={barcodeType===opt.val}
                    onChange={()=>saveBarcodeType(opt.val)}
                    style={{accentColor:'var(--gold)',width:'16px',height:'16px'}}/>
                  <div>
                    <div style={{fontSize:'12px',fontWeight:700,color:'var(--cream)',fontFamily:'monospace',display:'flex',alignItems:'center',gap:'5px'}}>
                      {opt.icon} {opt.label}
                      {opt.gold && <span style={{fontSize:'9px',background:'var(--gold)',color:'#1a0a00',borderRadius:'3px',padding:'1px 5px',fontFamily:'sans-serif'}}>✓ DEFAULT</span>}
                    </div>
                    <div style={{fontSize:'10px',color:'var(--cream-3)',marginTop:'2px'}}>{opt.sub}</div>
                  </div>
                </label>
              ))}
            </div>

            {/* Aviso lector 2D */}
            {(barcodeType === 'datamatrix' || barcodeType === 'qr') && (
              <div style={{marginTop:'12px',padding:'10px 14px',borderRadius:'6px',
                background:'rgba(251,191,36,0.08)',border:'1px solid rgba(251,191,36,0.3)',
                fontSize:'11px',color:'#fbbf24',lineHeight:1.6}}>
                ⚠️ <b>Lector 2D requerido</b> — Data Matrix y QR Code solo los leen pistolas <b>imager 2D</b>.
                Los lectores láser 1D (Code 39 / Code 128) <b>no los pueden leer</b>.
                Para joyería se recomienda: Zebra DS2208, Honeywell 1470g, o similar.
              </div>
            )}

            {/* Tamaño Data Matrix */}
            {barcodeType === 'datamatrix' && (
              <div style={{marginTop:'12px'}}>
                <div style={{fontSize:'11px',fontWeight:600,color:'var(--cream-2)',marginBottom:'8px'}}>
                  Tamaño Data Matrix — zona derecha de la etiqueta
                </div>
                <div style={{display:'flex',gap:'8px'}}>
                  {[7,8,9,10,11].map(mm=>{
                    const cur = (labelLayout.barcode && labelLayout.barcode.dmSize) || 10.5;
                    const sel = cur === mm;
                    return (
                      <button key={mm} onClick={()=>updLbl('barcode',{dmSize:mm})}
                        style={{flex:1,padding:'8px 4px',borderRadius:'6px',cursor:'pointer',
                          border:`2px solid ${sel?'var(--gold)':'var(--border)'}`,
                          background:sel?'rgba(201,168,76,0.12)':'var(--surface)',
                          color:sel?'var(--gold)':'var(--cream-3)',
                          fontSize:'12px',fontWeight:sel?700:400}}>
                        {mm}mm
                      </button>
                    );
                  })}
                </div>
                <div style={{fontSize:'10px',color:'var(--cream-3)',marginTop:'6px'}}>
                  Recomendado 9mm para SKUs de 6–8 chars · 11mm para SKUs largos
                </div>
              </div>
            )}
          </div>

          {/* Canvas drag editor — ancho completo */}
          <div style={S.card}>
            <EtiquetaEditorPreview/>
          </div>

          {/* Controles por elemento */}
          <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:'14px',marginTop:'14px'}}>
            {[
              {key:'precio',  label:'💰 Precio',    color:'#c9a84c', hasSize:true},
              {key:'nombre',  label:'📝 Nombre',    color:'#3b82f6', hasSize:true},
              {key:'barcode', label:'▓ Código 2D/1D', color:'#059669', hasWH:true},
              {key:'sku',     label:'# SKU',         color:'#8b5cf6', hasSize:true},
            ].map(({key,label,color,hasSize,hasWH})=>{
              const el = labelLayout[key] || {};
              return (
                <div key={key} style={{...S.card,padding:'12px',borderTop:`3px solid ${color}`}}>
                  <div style={{display:'flex',alignItems:'center',gap:'8px',marginBottom:'10px'}}>
                    <label style={{display:'flex',alignItems:'center',gap:'6px',cursor:'pointer'}}>
                      <input type="checkbox" checked={el.visible !== false}
                        onChange={e=>updLbl(key,{visible:e.target.checked})}
                        style={{accentColor:color,width:'14px',height:'14px'}}/>
                      <span style={{fontSize:'12px',fontWeight:600,color:'var(--cream)'}}>{label}</span>
                    </label>
                  </div>
                  <div style={{fontSize:'10px',color:'var(--cream-3)',marginBottom:'4px'}}>
                    Pos: x={el.x||0}% · y={el.y||0}%
                  </div>
                  {hasSize && (
                    <div style={{marginBottom:'6px'}}>
                      <div style={{display:'flex',justifyContent:'space-between',fontSize:'10px',color:'var(--cream-3)',marginBottom:'2px'}}>
                        <span>Tamaño fuente</span><span style={{color:color,fontWeight:600}}>{el.size||16}%</span>
                      </div>
                      <input type="range" min="5" max="80" step="1" value={el.size||16}
                        onChange={e=>updLbl(key,{size:parseInt(e.target.value)})}
                        style={{width:'100%',accentColor:color}}/>
                    </div>
                  )}
                  {hasWH && (
                    <>
                      <div style={{marginBottom:'6px'}}>
                        <div style={{display:'flex',justifyContent:'space-between',fontSize:'10px',color:'var(--cream-3)',marginBottom:'2px'}}>
                          <span>Ancho (%)</span><span style={{color:color,fontWeight:600}}>{el.w||32}%</span>
                        </div>
                        <input type="range" min="5" max="60" step="1" value={el.w||32}
                          onChange={e=>updLbl(key,{w:parseInt(e.target.value)})}
                          style={{width:'100%',accentColor:color}}/>
                      </div>
                      <div>
                        <div style={{display:'flex',justifyContent:'space-between',fontSize:'10px',color:'var(--cream-3)',marginBottom:'2px'}}>
                          <span>Alto (%)</span><span style={{color:color,fontWeight:600}}>{el.h||72}%</span>
                        </div>
                        <input type="range" min="20" max="95" step="1" value={el.h||72}
                          onChange={e=>updLbl(key,{h:parseInt(e.target.value)})}
                          style={{width:'100%',accentColor:color}}/>
                      </div>
                    </>
                  )}
                </div>
              );
            })}
          </div>

          {/* Acciones */}
          <div style={{display:'flex',gap:'10px',marginTop:'14px',flexWrap:'wrap'}}>
            <button onClick={()=>{
              imprimirEtiquetaGodex([{sku:'AGCR3344',nombre:'Anillo plata circón',precio:20000}],{});
            }} style={{...S.btn,flex:1}}>🖨 Test etiqueta</button>
            <button onClick={()=>{
              // Imprime 5 variantes de tamaño para calibrar DM
              imprimirEtiquetaGodex([
                {sku:'DM07MM',nombre:'Test 7mm',precio:7000},
                {sku:'DM08MM',nombre:'Test 8mm',precio:8000},
                {sku:'DM09MM',nombre:'Test 9mm',precio:9000},
                {sku:'DM10MM',nombre:'Test 10mm',precio:10000},
                {sku:'AGCR3344',nombre:'Anillo plata',precio:20000},
              ],{});
            }} style={{...S.btn,background:'var(--surface)',color:'var(--cream-2)',border:'1px solid var(--gold)',flex:1}}>
              🧪 Test 5 tamaños DM
            </button>
            <button onClick={()=>saveLabelLayout({...LBL_DEFAULT})}
              style={{...S.btn,background:'var(--surface)',color:'var(--cream-3)',border:'1px solid var(--border)',flex:'0 0 auto'}}>
              ↺ Reset layout
            </button>
          </div>
          <div style={{fontSize:'9px',color:'var(--cream-3)',textAlign:'center',marginTop:'6px'}}>
            Godex GE300 · 203 DPI · 55×12mm · Huso/Pesa Joyería · doblez en el centro
            {barcodeType === 'datamatrix' && ' · Data Matrix ECC200 (ISO 16022)'}
          </div>
        </div>
      )}

      {/* ════ TICKETS ════ */}
      {tab==='tickets' && (
        <div style={{flex:1,overflowY:'auto',padding:'20px'}}>
          <div style={S.title}>Editor de Tickets</div>
          <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:'20px'}}>
            {/* Configuración */}
            <div style={S.card}>
              <div style={{fontFamily:'Cormorant Garamond,serif',fontSize:'15px',fontWeight:600,color:'var(--cream)',marginBottom:'14px'}}>Elementos del Ticket</div>
              <div style={{display:'flex',gap:'8px',marginBottom:'12px'}}>
                {[58,80].map(w=>(
                  <button key={w} onClick={()=>setTicketCfg(prev=>{const n={...prev,tamanoPapel:w};lsSet('ajustes_ticket',n);return n;})}
                    style={{flex:1,padding:'6px',borderRadius:'6px',border:`1px solid ${ticketCfg.tamanoPapel===w?'var(--gold)':'var(--border)'}`,
                    background:ticketCfg.tamanoPapel===w?'var(--gold-dim)':'var(--surface)',
                    color:ticketCfg.tamanoPapel===w?'var(--gold)':'var(--cream-3)',fontSize:'11px',cursor:'pointer'}}>
                    {w}mm
                  </button>
                ))}
              </div>
              {[
                {k:'mostrarLogo',l:'Logo empresa'},
                {k:'mostrarDireccion',l:'Dirección'},
                {k:'mostrarTelefono',l:'Teléfono'},
                {k:'mostrarWeb',l:'Sitio web'},
                {k:'mostrarFolio',l:'Número de folio'},
                {k:'mostrarCajero',l:'Nombre cajero'},
                {k:'mostrarRut',l:'RUT cliente'},
                {k:'mostrarCodigoBarras',l:'Código de barras folio'},
              ].map(f=>(
                <label key={f.k} style={{display:'flex',alignItems:'center',gap:'8px',marginBottom:'8px',cursor:'pointer',fontSize:'12px',color:'var(--cream-2)'}}>
                  <input type="checkbox" checked={ticketCfg[f.k]||false} style={{accentColor:'var(--gold)',width:'13px',height:'13px'}}
                    onChange={e=>{const n={...ticketCfg,[f.k]:e.target.checked};setTicketCfg(n);lsSet('ajustes_ticket',n);}}/>
                  {f.l}
                </label>
              ))}
              <div style={{marginTop:'10px'}}>
                <div style={S.labelSm}>Fuente</div>
                <select style={{...S.input,width:'100%'}} value={ticketCfg.fuente||'Courier New'}
                  onChange={e=>{const n={...ticketCfg,fuente:e.target.value};setTicketCfg(n);lsSet('ajustes_ticket',n);}}>
                  {['Courier New','Arial','Verdana','Times New Roman'].map(f=><option key={f}>{f}</option>)}
                </select>
              </div>
              <div style={{marginTop:'8px'}}>
                <div style={S.labelSm}>Texto pie de ticket</div>
                <input style={S.input} value={ticketCfg.piePagina||''} onChange={e=>{const n={...ticketCfg,piePagina:e.target.value};setTicketCfg(n);lsSet('ajustes_ticket',n);}}/>
              </div>
              <button onClick={()=>{
                const mm=ticketCfg.tamanoPapel||80;
                const px=Math.round(mm*3.78);
                const w=window.open('','_blank','width=420,height=600');
                if(!w){alert('Permite ventanas emergentes');return;}
                const logo=getLogo();
                const cfg2=lsGet('ajustes_config',{});
                const cfgT=cfg2[tiendaId]||cfg2.navarro||{};
                w.document.write(`<!DOCTYPE html><html><head><meta charset="utf-8"><title>Test_Ticket_${mm}mm</title>
                <style>@page{margin:0;size:${mm}mm auto;}*{box-sizing:border-box;}body{font-family:'${ticketCfg.fuente||'Courier New'}',monospace;font-size:11px;width:${px}px;margin:0 auto;padding:6px;background:#f0f0f0;}.sep{border-top:1px dashed #000;margin:5px 0;}.c{text-align:center;}.b{font-weight:bold;}.row{display:flex;justify-content:space-between;font-size:10px;margin:2px 0;}.info{background:#1a2f1a;color:#fff;padding:5px;font-size:10px;margin-bottom:6px;border-radius:4px;}@media print{.info{display:none;}body{background:white;}}</style></head><body>
                <div class="info">🖨 Test SPRT ${mm}mm</div>
                ${ticketCfg.mostrarLogo&&logo?`<div class="c"><img src="${logo}" style="height:36px;margin-bottom:3px;"/></div>`:'<div class="c b" style="font-size:15px">✦ NAVARRO ✦</div>'}
                <div class="c" style="font-size:8px">JOYERÍA FINA</div>
                ${ticketCfg.mostrarDireccion?`<div class="c" style="font-size:8px">${cfgT.direccion||'Calle Comercio 123, Santa Cruz'}</div>`:''}
                ${ticketCfg.mostrarTelefono?`<div class="c" style="font-size:8px">${cfgT.telefono||'+56 72 234 5678'}</div>`:''}
                ${ticketCfg.mostrarWeb?`<div class="c" style="font-size:8px">${cfgT.web||'navarro-joyeria.cl'}</div>`:''}
                <div class="sep"></div>
                ${ticketCfg.mostrarFolio?'<div class="row"><span>BOLETA N°</span><span>V-TEST-0001</span></div>':''}
                <div class="row"><span>Fecha</span><span>${new Date().toLocaleDateString('es-CL')}</span></div>
                ${ticketCfg.mostrarCajero?'<div class="row"><span>Cajero</span><span>Admin</span></div>':''}
                <div class="sep"></div>
                <div style="font-size:9px;font-weight:bold;margin-bottom:2px">DETALLE:</div>
                <div class="row"><span>1x Anillo plata 925</span><span>$25.000</span></div>
                <div class="row"><span>1x Aros oro 18K</span><span>$85.000</span></div>
                <div class="sep"></div>
                <div class="row b"><span>TOTAL</span><span>$110.000</span></div>
                <div class="sep"></div>
                <div class="c" style="font-size:8px;margin-top:4px">${ticketCfg.piePagina||''}</div>
                <script>window.onload=function(){setTimeout(function(){window.print();},600)}<\/script>
                </body></html>`);
                w.document.close();
              }} style={{...S.btn,width:'100%',marginTop:'12px'}}>🖨 Test impresión ticket</button>
            </div>
            {/* Preview */}
            <div style={S.card}>
              <div style={{fontFamily:'Cormorant Garamond,serif',fontSize:'15px',fontWeight:600,color:'var(--cream)',marginBottom:'14px'}}>Vista Previa</div>
              <TicketPreview/>
            </div>
          </div>
        </div>
      )}

      {/* ════ DOCUMENTOS ════ */}
      {tab==='documentos' && (
        <div style={{flex:1,overflowY:'auto',padding:'20px'}}>
          <div style={S.title}>Editor de Documentos (Epson L3250)</div>
          <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:'20px'}}>
            <div style={S.card}>
              <div style={{fontFamily:'Cormorant Garamond,serif',fontSize:'15px',fontWeight:600,color:'var(--cream)',marginBottom:'14px'}}>Tipos de Documento</div>
              {/* Selector de tipo */}
              <div style={{display:'flex',flexWrap:'wrap',gap:'5px',marginBottom:'12px'}}>
                {['Cotización','Factura','Boleta','Orden de Trabajo','Presupuesto','Certificado de garantía'].map(t=>(
                  <button key={t} style={{padding:'4px 9px',borderRadius:'20px',fontSize:'10px',cursor:'pointer',border:'1px solid var(--border)',background:'var(--surface)',color:'var(--cream-3)'}}>
                    {t}
                  </button>
                ))}
              </div>
              {[
                {k:'mostrarLogo',l:'Logo empresa'},
                {k:'mostrarFirma',l:'Línea de firma'},
                {k:'mostrarCondiciones',l:'Condiciones generales'},
                {k:'incluirDetalle',l:'Tabla de detalle'},
                {k:'incluirIVA',l:'Desglose IVA'},
              ].map(f=>(
                <label key={f.k} style={{display:'flex',alignItems:'center',gap:'8px',marginBottom:'8px',cursor:'pointer',fontSize:'12px',color:'var(--cream-2)'}}>
                  <input type="checkbox" checked={docCfg[f.k]||false} style={{accentColor:'var(--gold)',width:'13px',height:'13px'}}
                    onChange={e=>{const n={...docCfg,[f.k]:e.target.checked};setDocCfg(n);lsSet('ajustes_doc',n);}}/>
                  {f.l}
                </label>
              ))}
              <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:'8px',marginTop:'8px'}}>
                <div><div style={S.labelSm}>Formato papel</div>
                  <select style={{...S.input,width:'100%'}} value={docCfg.formatoPapel||'A4'}
                    onChange={e=>{const n={...docCfg,formatoPapel:e.target.value};setDocCfg(n);lsSet('ajustes_doc',n);}}>
                    {['A4','Carta','A5'].map(f=><option key={f}>{f}</option>)}
                  </select>
                </div>
                <div><div style={S.labelSm}>Orientación</div>
                  <select style={{...S.input,width:'100%'}} value={docCfg.orientacion||'Vertical'}
                    onChange={e=>{const n={...docCfg,orientacion:e.target.value};setDocCfg(n);lsSet('ajustes_doc',n);}}>
                    {['Vertical','Horizontal'].map(f=><option key={f}>{f}</option>)}
                  </select>
                </div>
              </div>
              <div style={{marginTop:'8px'}}>
                <div style={S.labelSm}>Pie de página</div>
                <input style={S.input} value={docCfg.piePagina||''} onChange={e=>{const n={...docCfg,piePagina:e.target.value};setDocCfg(n);lsSet('ajustes_doc',n);}}/>
              </div>
              <button onClick={()=>testImpresora(impresoras.find(x=>x.tipo==='documentos'))} style={{...S.btn,width:'100%',marginTop:'12px'}}>🖨 Test impresión documento</button>
            </div>
            <div style={S.card}>
              <div style={{fontFamily:'Cormorant Garamond,serif',fontSize:'15px',fontWeight:600,color:'var(--cream)',marginBottom:'14px'}}>Vista Previa</div>
              <DocumentoPreview/>
            </div>
          </div>
        </div>
      )}

      {/* ════ HISTORIAL / REIMPRESIÓN ════ */}
      {tab==='reimpresion' && (
        <div style={{flex:1,display:'flex',flexDirection:'column',overflow:'hidden'}}>
          <div style={{padding:'12px 20px',borderBottom:'1px solid var(--border)',display:'flex',justifyContent:'space-between',alignItems:'center'}}>
            <div style={{fontFamily:'Cormorant Garamond,serif',fontSize:'18px',fontWeight:600}}>Reimpresión / Historial</div>
            <span style={{color:'var(--cream-3)',fontSize:'11px'}}>{historial.length} registros totales</span>
          </div>
          {/* Sub-tabs */}
          <div style={{display:'flex',gap:'0',borderBottom:'1px solid var(--border)',background:'var(--bg-card)',flexShrink:0}}>
            {HIST_TIPOS.map(t=>{
              const count = historial.filter(h=>h.tipo===t.id).length;
              return (
                <button key={t.id} onClick={()=>setHistTab(t.id)}
                  style={{padding:'8px 16px',background:'transparent',border:'none',borderBottom:`2px solid ${histTab===t.id?'var(--gold)':'transparent'}`,
                  color:histTab===t.id?'var(--cream)':'var(--cream-3)',cursor:'pointer',fontSize:'11px',fontFamily:'Inter,sans-serif',display:'flex',alignItems:'center',gap:'5px'}}>
                  {t.label}
                  {count>0&&<span style={{background:'var(--surface)',borderRadius:'10px',padding:'1px 6px',fontSize:'9px',color:'var(--cream-3)'}}>{count}</span>}
                </button>
              );
            })}
          </div>
          <div style={{flex:1,overflowY:'auto',padding:'12px 20px'}}>
            <table style={{width:'100%',borderCollapse:'collapse'}}>
              <thead>
                <tr>{['ID','Fecha','Subtipo','Documento','Impresora','Usuario','Estado','Copias',''].map(h=>(
                  <th key={h} style={invStyles.th}>{h}</th>
                ))}</tr>
              </thead>
              <tbody>
                {historial.filter(h=>h.tipo===histTab).map(h=>(
                  <tr key={h.id} style={invStyles.tr}>
                    <td style={invStyles.td}><span style={{fontFamily:'monospace',fontSize:'10px',color:'var(--cream-3)'}}>{h.id}</span></td>
                    <td style={invStyles.td}><span style={{fontSize:'10px',color:'var(--cream-3)'}}>{h.fecha}</span></td>
                    <td style={invStyles.td}><span style={{fontSize:'10px',color:'var(--cream-2)',padding:'1px 6px',background:'var(--surface)',borderRadius:'4px'}}>{h.subtipo}</span></td>
                    <td style={invStyles.td}><span style={{fontSize:'11px'}}>{h.documento}</span></td>
                    <td style={invStyles.td}><span style={{fontSize:'10px',color:'var(--cream-3)'}}>{h.impresora}</span></td>
                    <td style={invStyles.td}><span style={{fontSize:'10px',color:'var(--cream-3)'}}>{h.usuario}</span></td>
                    <td style={invStyles.td}><span style={{fontSize:'10px',fontWeight:600,padding:'2px 6px',borderRadius:'20px',
                      background:h.estado==='OK'?'rgba(39,174,96,0.12)':'rgba(192,57,43,0.12)',
                      color:h.estado==='OK'?'#27ae60':'#c0392b'}}>{h.estado}</span></td>
                    <td style={invStyles.td}><span style={{fontSize:'10px',color:'var(--cream-3)'}}>{h.copias}</span></td>
                    <td style={invStyles.td}><button style={S.btnSm}>🔄 Reimprimir</button></td>
                  </tr>
                ))}
                {historial.filter(h=>h.tipo===histTab).length===0&&(
                  <tr><td colSpan="9" style={{...invStyles.td,textAlign:'center',color:'var(--cream-3)',padding:'30px',fontSize:'12px'}}>Sin registros en esta categoría</td></tr>
                )}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* ════ USUARIOS ════ */}
      {tab==='usuarios' && <TabUsuarios />}

      {/* ════ REDES SOCIALES & APIs ════ */}
      {tab==='redes' && (
        <div style={{flex:1,overflowY:'auto',padding:'20px'}}>
          <div style={S.title}>Redes Sociales & APIs</div>
          <div style={{fontSize:'11px',color:'var(--cream-3)',marginBottom:'16px'}}>
            Conecta las cuentas de la joyería para automatizaciones de marketing, pagos, facturación e IA.
          </div>
          <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:'10px'}}>
            {REDES_CONFIG.map(red=>{
              const val = redesVals[red.id]||'';
              const show = redesShow[red.id]||false;
              const isConnected = val && val.length > 4;
              return (
                <div key={red.id} style={{background:'var(--bg-card)',border:`1px solid ${isConnected?'rgba(39,174,96,0.3)':'var(--border)'}`,borderRadius:'10px',padding:'12px'}}>
                  <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',marginBottom:'8px'}}>
                    <div style={{display:'flex',alignItems:'center',gap:'7px'}}>
                      <span style={{fontSize:'16px'}}>{red.icon}</span>
                      <div>
                        <div style={{color:'var(--cream)',fontWeight:600,fontSize:'12px'}}>{red.label}</div>
                        <div style={{color:'var(--cream-3)',fontSize:'9px'}}>{red.desc}</div>
                      </div>
                    </div>
                    {isConnected&&<span style={{fontSize:'9px',padding:'2px 7px',borderRadius:'10px',background:'rgba(39,174,96,0.12)',color:'#27ae60',flexShrink:0}}>✓ Conectado</span>}
                  </div>
                  <div style={{display:'flex',gap:'5px'}}>
                    <input type={show?'text':'password'} placeholder={red.ph} value={val}
                      onChange={e=>{const nv={...redesVals,[red.id]:e.target.value};setRedesVals(nv);lsSet('red_'+red.id,e.target.value);}}
                      style={{...S.input,flex:1,fontFamily:'monospace',fontSize:'10px'}}/>
                    <button onClick={()=>setRedesShow(s=>({...s,[red.id]:!s[red.id]}))} style={{...S.btnSm,padding:'4px 7px'}}>{show?'🙈':'👁'}</button>
                    {val&&<button onClick={()=>{const nv={...redesVals,[red.id]:''};setRedesVals(nv);lsSet('red_'+red.id,'');}} style={{...S.btnSm,color:'#c0392b',padding:'4px 7px'}}>✕</button>}
                  </div>
                </div>
              );
            })}
          </div>
          <div style={{marginTop:'14px',padding:'12px',background:'rgba(41,128,185,0.06)',border:'1px solid rgba(41,128,185,0.2)',borderRadius:'8px',fontSize:'11px',color:'var(--cream-3)'}}>
            <b style={{color:'var(--cream)'}}>ℹ Seguridad:</b> Todas las claves se guardan localmente en este navegador. Nunca se envían a servidores externos.
          </div>

          {/* ── Base de datos en la nube (Supabase) — integrada aquí junto a las demás conexiones ── */}
          <div style={{marginTop:'22px',paddingTop:'18px',borderTop:'1px solid var(--border)'}}>
            <div style={{...S.title,marginBottom:'4px'}}>☁ Base de datos en la nube</div>
            <div style={{fontSize:'11px',color:'var(--cream-3)',marginBottom:'14px'}}>
              Conexión a Supabase — sincroniza inventario, ventas, clientes y más entre todos los dispositivos y regiones.
            </div>
            <SupabaseGuia/>
          </div>
        </div>
      )}
    </div>
  );
}

const ajStyles = {
  tabs:{ display:'flex', borderBottom:'1px solid var(--border)', background:'var(--bg-card)', flexShrink:0, alignItems:'center' },
  tab:{ padding:'10px 14px', background:'transparent', border:'none', color:'var(--cream-3)', cursor:'pointer', fontSize:'11px', fontFamily:'Inter,sans-serif', borderBottom:'2px solid transparent' },
  tabAct:{ color:'var(--cream)', borderBottom:'2px solid var(--gold)' },
  hwCard:{ background:'var(--bg-card)', border:'1px solid var(--border)', borderRadius:'12px', padding:'16px' },
  card:{ background:'var(--bg-card)', border:'1px solid var(--border)', borderRadius:'12px', padding:'16px' },
  title:{ fontFamily:'Cormorant Garamond,serif', fontSize:'20px', fontWeight:600, color:'var(--cream)', marginBottom:'16px' },
  section:{ background:'var(--bg-card)', border:'1px solid var(--border)', borderRadius:'10px', padding:'14px', marginBottom:'12px' },
  sectionTitle:{ color:'var(--gold)', fontWeight:600, fontSize:'12px', marginBottom:'10px' },
  label:{ fontSize:'11px', color:'var(--cream-3)', marginBottom:'4px' },
  labelSm:{ fontSize:'10px', color:'var(--cream-3)', marginBottom:'3px' },
  input:{ background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'6px', padding:'6px 9px', color:'var(--cream)', fontFamily:'Inter,sans-serif', fontSize:'12px', width:'100%', outline:'none' },
  btn:{ background:'var(--gold)', color:'var(--bg)', border:'none', borderRadius:'8px', padding:'9px 16px', fontFamily:'Inter,sans-serif', fontWeight:600, fontSize:'12px', cursor:'pointer' },
  btnSm:{ background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'6px', padding:'4px 9px', color:'var(--cream-2)', fontFamily:'Inter,sans-serif', fontSize:'11px', cursor:'pointer' },
};

// ── Bitácora de accesos + estado de bloqueo (seguridad de login) ──────────
function BitacoraAccesos() {
  const { useState } = React;
  const [tick, setTick] = useState(0);
  const log = lsGet('login_bitacora', []);
  const intentos = lsGet('login_intentos', {});
  const bloqueados = Object.entries(intentos)
    .map(([usr, r]) => ({ usr, ...r }))
    .filter(r => r.bloqueadoHasta && r.bloqueadoHasta > Date.now());

  function limpiarBloqueos() {
    if (!confirm('¿Desbloquear todas las cuentas bloqueadas por intentos fallidos?')) return;
    lsSet('login_intentos', {});
    setTick(t => t+1);
  }

  return (
    <div style={{ marginTop:'14px' }}>
      {bloqueados.length > 0 && (
        <div style={{ padding:'12px', background:'rgba(192,57,43,0.08)', border:'1px solid rgba(192,57,43,0.3)',
          borderRadius:'10px', marginBottom:'10px' }}>
          <div style={{ color:'#c0392b', fontWeight:600, fontSize:'12px', marginBottom:'6px' }}>🔒 Cuentas bloqueadas temporalmente</div>
          {bloqueados.map(b => (
            <div key={b.usr} style={{ fontSize:'11px', color:'var(--cream-3)' }}>
              <b style={{ color:'var(--cream)' }}>{b.usr}</b> — por {b.fallos} intentos fallidos. Se desbloquea {new Date(b.bloqueadoHasta).toLocaleTimeString('es-CL')}
            </div>
          ))}
          <button onClick={limpiarBloqueos} style={{ ...ajStyles.btnSm, marginTop:'8px', color:'#c0392b' }}>Desbloquear ahora</button>
        </div>
      )}

      <div style={{ padding:'14px', background:'var(--bg-card)', border:'1px solid var(--border)', borderRadius:'10px' }}>
        <div style={{ color:'var(--cream)', fontWeight:600, fontSize:'12px', marginBottom:'8px' }}>🛡 Seguridad de acceso — bitácora</div>
        <div style={{ fontSize:'10px', color:'var(--cream-3)', marginBottom:'10px', lineHeight:1.6 }}>
          Tras <b>5 intentos fallidos</b> seguidos, la cuenta se bloquea automáticamente por 5 minutos.
          Las sesiones expiran tras 12 horas de inactividad. Aquí se registran los últimos accesos (correctos y fallidos).
        </div>
        {log.length === 0 ? (
          <div style={{ fontSize:'11px', color:'var(--cream-3)', textAlign:'center', padding:'10px' }}>Sin registros aún.</div>
        ) : (
          <div style={{ maxHeight:'180px', overflowY:'auto' }}>
            {log.slice(0, 40).map((e,i) => (
              <div key={i} style={{ display:'flex', justifyContent:'space-between', fontSize:'10px', padding:'4px 0', borderBottom:'1px solid rgba(255,255,255,0.05)' }}>
                <span style={{ color:'var(--cream-2)' }}>{e.usuario}{e.nombre?` (${e.nombre})`:''}</span>
                <span style={{ color: e.resultado==='ok' ? '#27ae60' : '#c0392b', fontWeight:600 }}>{e.resultado==='ok' ? '✓ acceso' : '✕ fallido'}</span>
                <span style={{ color:'var(--cream-3)' }}>{new Date(e.ts).toLocaleString('es-CL')}</span>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

// ── TAB USUARIOS — gestión real de cuentas ─────────────────────────────────
function TabUsuarios() {
  const { useState } = React;
  const ROLES = ['admin','vendedor','taller'];

  const [usuarios, setUsuarios] = useState(() => lsGet('usuarios', USUARIOS_DEFAULT));
  const [editId,   setEditId]   = useState(null);   // id del usuario en edición
  const [draft,    setDraft]    = useState(null);    // copia editable
  const [modalNuevo, setModalNuevo] = useState(false);
  const [verClave, setVerClave] = useState({});
  const [toast,    setToast]    = useState('');
  const [nuevo,    setNuevo]    = useState({
    nombre:'', usuario:'', clave:'', rol:'vendedor', tienda:'navarro',
  });

  function showToast(msg) { setToast(msg); setTimeout(() => setToast(''), 2800); }

  function guardar() {
    if (!draft.nombre.trim() || !draft.usuario.trim() || !draft.clave.trim()) {
      alert('Nombre, usuario y contraseña son obligatorios.'); return;
    }
    // Verificar usuario único
    const dup = usuarios.find(u => u.usuario === draft.usuario.trim() && u.id !== draft.id);
    if (dup) { alert('Ya existe un usuario con ese nombre de usuario.'); return; }
    const next = usuarios.map(u => u.id === draft.id ? { ...draft, usuario: draft.usuario.trim(), nombre: draft.nombre.trim(), clave: draft.clave.trim() } : u);
    setUsuarios(next);
    lsSet('usuarios', next);
    setEditId(null); setDraft(null);
    showToast('✓ Usuario actualizado');
  }

  function agregarUsuario() {
    if (!nuevo.nombre.trim() || !nuevo.usuario.trim() || !nuevo.clave.trim()) {
      alert('Nombre, usuario y contraseña son obligatorios.'); return;
    }
    if (usuarios.find(u => u.usuario === nuevo.usuario.trim())) {
      alert('Ya existe un usuario con ese nombre.'); return;
    }
    const u = { ...nuevo, id: 'u-' + Date.now(), nombre: nuevo.nombre.trim(), usuario: nuevo.usuario.trim(), clave: nuevo.clave.trim(), color: '#c9a84c' };
    const next = [...usuarios, u];
    setUsuarios(next); lsSet('usuarios', next);
    setModalNuevo(false);
    setNuevo({ nombre:'', usuario:'', clave:'', rol:'vendedor', tienda:'navarro' });
    showToast('✓ Usuario creado: ' + u.usuario);
  }

  function eliminar(id) {
    const admins = usuarios.filter(u => u.rol === 'admin');
    if (admins.length === 1 && admins[0].id === id) {
      alert('No puedes eliminar el único administrador.'); return;
    }
    if (!confirm('¿Eliminar este usuario? No se podrá deshacer.')) return;
    const next = usuarios.filter(u => u.id !== id);
    setUsuarios(next); lsSet('usuarios', next);
    showToast('Usuario eliminado');
  }

  function resetearPorDefecto() {
    if (!confirm('¿Restaurar los usuarios por defecto? Esto eliminará todos los cambios.')) return;
    setUsuarios(USUARIOS_DEFAULT); lsSet('usuarios', USUARIOS_DEFAULT);
    showToast('✓ Usuarios restaurados a valores por defecto');
  }

  const S = ajStyles;
  const rolColor = r => r==='admin'?'rgba(201,168,76,0.2)':r==='vendedor'?'rgba(41,128,185,0.2)':'rgba(155,107,107,0.2)';
  const rolText  = r => r==='admin'?'var(--gold)':r==='vendedor'?'#2980b9':'#9b6b6b';

  return (
    <div style={{ flex:1, overflowY:'auto', padding:'24px', maxWidth:'580px', position:'relative' }}>
      {toast && (
        <div style={{ position:'fixed', bottom:'20px', left:'50%', transform:'translateX(-50%)',
          background:'#1a3a2a', color:'#c9a84c', padding:'9px 20px', borderRadius:'8px',
          fontSize:'12px', fontWeight:600, zIndex:300, boxShadow:'0 4px 20px rgba(0,0,0,0.5)',
          border:'1px solid rgba(201,168,76,0.3)', pointerEvents:'none' }}>
          {toast}
        </div>
      )}

      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:'16px' }}>
        <div style={S.title}>👤 Usuarios y Contraseñas</div>
        <button onClick={() => setModalNuevo(true)} style={S.btn}>+ Nuevo usuario</button>
      </div>

      {/* Lista usuarios */}
      {usuarios.map(u => {
        const isEdit = editId === u.id;
        return (
          <div key={u.id} style={{ ...S.card, marginBottom:'10px' }}>
            {isEdit ? (
              /* ── Formulario edición ── */
              <div>
                <div style={{ fontSize:'11px', color:'var(--gold)', fontWeight:600, marginBottom:'12px', letterSpacing:'0.5px' }}>
                  EDITANDO: {u.nombre}
                </div>
                <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'10px' }}>
                  <div>
                    <div style={S.labelSm}>Nombre completo</div>
                    <input style={S.input} value={draft.nombre}
                      onChange={e => setDraft(d => ({...d, nombre:e.target.value}))}/>
                  </div>
                  <div>
                    <div style={S.labelSm}>Usuario (login)</div>
                    <input style={S.input} value={draft.usuario}
                      onChange={e => setDraft(d => ({...d, usuario:e.target.value}))}
                      autoComplete="off"/>
                  </div>
                  <div>
                    <div style={S.labelSm}>Contraseña nueva</div>
                    <div style={{ position:'relative' }}>
                      <input type={verClave[u.id]?'text':'password'} style={{...S.input, paddingRight:'32px'}}
                        value={draft.clave}
                        onChange={e => setDraft(d => ({...d, clave:e.target.value}))}
                        autoComplete="new-password"/>
                      <button type="button"
                        onClick={() => setVerClave(v => ({...v,[u.id]:!v[u.id]}))}
                        style={{ position:'absolute', right:'8px', top:'50%', transform:'translateY(-50%)',
                          background:'none', border:'none', cursor:'pointer', color:'var(--cream-3)', fontSize:'12px' }}>
                        {verClave[u.id]?'🙈':'👁'}
                      </button>
                    </div>
                  </div>
                  <div>
                    <div style={S.labelSm}>Rol</div>
                    <select style={{...S.input, cursor:'pointer'}} value={draft.rol}
                      onChange={e => setDraft(d => ({...d, rol:e.target.value}))}>
                      {ROLES.map(r => <option key={r} value={r}>{r}</option>)}
                    </select>
                  </div>
                  <div>
                    <div style={S.labelSm}>Tienda</div>
                    <select style={{...S.input, cursor:'pointer'}} value={draft.tienda}
                      onChange={e => setDraft(d => ({...d, tienda:e.target.value}))}>
                      {TIENDAS.map(t => <option key={t.id} value={t.id}>{t.sigla} — {t.nombre}</option>)}
                    </select>
                  </div>
                </div>
                <div style={{ display:'flex', gap:'8px', marginTop:'14px' }}>
                  <button onClick={guardar}
                    style={{ ...S.btn, flex:1 }}>✓ Guardar cambios</button>
                  <button onClick={() => { setEditId(null); setDraft(null); }}
                    style={{ ...S.btnSm, padding:'9px 16px' }}>Cancelar</button>
                </div>
              </div>
            ) : (
              /* ── Vista normal ── */
              <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
                <div style={{ flex:1 }}>
                  <div style={{ display:'flex', alignItems:'center', gap:'8px', marginBottom:'3px' }}>
                    <div style={{ color:'var(--cream)', fontWeight:600, fontSize:'13px' }}>{u.nombre}</div>
                    <span style={{ fontSize:'9px', padding:'1px 7px', borderRadius:'20px',
                      background: rolColor(u.rol), color: rolText(u.rol), fontWeight:600 }}>
                      {u.rol}
                    </span>
                  </div>
                  <div style={{ color:'var(--cream-3)', fontSize:'11px', display:'flex', gap:'12px' }}>
                    <span>👤 <strong style={{ color:'var(--cream-2)' }}>{u.usuario}</strong></span>
                    <span>🔑 {'•'.repeat(Math.min(u.clave?.length||6, 8))}</span>
                    <span>🏪 {TIENDAS.find(t=>t.id===u.tienda)?.sigla || u.tienda}</span>
                  </div>
                </div>
                <div style={{ display:'flex', gap:'6px' }}>
                  <button onClick={() => { setEditId(u.id); setDraft({...u}); }}
                    style={{ ...S.btnSm, fontSize:'11px' }}>✏ Editar</button>
                  <button onClick={() => eliminar(u.id)}
                    style={{ ...S.btnSm, color:'#c0392b', border:'1px solid rgba(192,57,43,0.3)' }}>🗑</button>
                </div>
              </div>
            )}
          </div>
        );
      })}

      {/* Info credenciales actuales */}
      <div style={{ marginTop:'14px', padding:'14px', background:'rgba(201,168,76,0.06)',
        border:'1px solid rgba(201,168,76,0.2)', borderRadius:'10px', fontSize:'11px', color:'var(--cream-3)', lineHeight:'1.8' }}>
        <div style={{ color:'var(--gold)', fontWeight:600, marginBottom:'6px' }}>📋 Credenciales actuales</div>
        {usuarios.map(u => (
          <div key={u.id} style={{ display:'flex', gap:'16px', padding:'3px 0', borderBottom:'1px solid rgba(255,255,255,0.05)' }}>
            <span style={{ width:'70px', color:'var(--cream-2)', fontWeight:600 }}>{u.usuario}</span>
            <span style={{ fontFamily:'monospace', color:'var(--cream)' }}>{u.clave}</span>
            <span style={{ color: rolText(u.rol), fontSize:'10px' }}>{u.rol}</span>
          </div>
        ))}
        <div style={{ marginTop:'8px', fontSize:'10px', color:'var(--cream-3)', fontStyle:'italic' }}>
          ⚠ Estas credenciales son visibles solo para el administrador.
        </div>
      </div>

      {/* ── Seguridad de acceso: bitácora + bloqueo automático ── */}
      <BitacoraAccesos/>

      <button onClick={resetearPorDefecto}
        style={{ ...S.btnSm, marginTop:'10px', width:'100%', padding:'8px', textAlign:'center', color:'var(--cream-3)' }}>
        ↺ Restaurar usuarios por defecto
      </button>

      {/* ── Modal Nuevo Usuario ── */}
      {modalNuevo && (
        <div style={posStyles.overlay} onClick={e => e.target===e.currentTarget && setModalNuevo(false)}>
          <div style={{ ...posStyles.modalBox, maxWidth:'420px' }}>
            <div style={{ ...posStyles.modalHeader, marginBottom:'16px' }}>
              <span style={{ fontFamily:'Cormorant Garamond,serif', fontSize:'20px', fontWeight:600 }}>Nuevo Usuario</span>
              <button onClick={() => setModalNuevo(false)} style={posStyles.clearBtn}>✕</button>
            </div>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'10px' }}>
              <div style={{ gridColumn:'1/-1' }}>
                <div style={ajStyles.labelSm}>Nombre completo</div>
                <input style={ajStyles.input} placeholder="Ej: María González"
                  value={nuevo.nombre} onChange={e => setNuevo(n => ({...n,nombre:e.target.value}))} autoFocus/>
              </div>
              <div>
                <div style={ajStyles.labelSm}>Usuario (login)</div>
                <input style={ajStyles.input} placeholder="Ej: maria"
                  value={nuevo.usuario} onChange={e => setNuevo(n => ({...n,usuario:e.target.value}))}
                  autoComplete="off"/>
              </div>
              <div>
                <div style={ajStyles.labelSm}>Contraseña</div>
                <input type="text" style={ajStyles.input} placeholder="Mínimo 4 caracteres"
                  value={nuevo.clave} onChange={e => setNuevo(n => ({...n,clave:e.target.value}))}
                  autoComplete="off"/>
              </div>
              <div>
                <div style={ajStyles.labelSm}>Rol</div>
                <select style={{...ajStyles.input, cursor:'pointer'}} value={nuevo.rol}
                  onChange={e => setNuevo(n => ({...n,rol:e.target.value}))}>
                  {ROLES.map(r => <option key={r} value={r}>{r}</option>)}
                </select>
              </div>
              <div>
                <div style={ajStyles.labelSm}>Tienda</div>
                <select style={{...ajStyles.input, cursor:'pointer'}} value={nuevo.tienda}
                  onChange={e => setNuevo(n => ({...n,tienda:e.target.value}))}>
                  {TIENDAS.map(t => <option key={t.id} value={t.id}>{t.sigla} — {t.nombre}</option>)}
                </select>
              </div>
            </div>
            <button onClick={agregarUsuario}
              style={{ ...posStyles.cobrarBtn, width:'100%', marginTop:'16px' }}>
              ✦ Crear usuario
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { Ajustes });
