// ── METALES & PRECIOS CONFIGURABLES ─────────────────

function Metales() {
  const { useState } = React;

  // Precios configurables — el usuario elige su precio de trabajo
  // Precios de trabajo por defecto — actualizados 29-abr-2026 (cotizacionrealoro.com · SII)
  // compra = lo que paga la tienda cuando compra oro al cliente (~95% del spot)
  // venta  = precio de trabajo para costear fabricación (≈ spot bolsa)
  const [preciosWork, setPreciosWork] = useState(() => lsGet('precios_trabajo', {
    'Oro 18K':        { compra:  94500, venta:  99443 },
    'Oro 14K':        { compra:  73000, venta:  76903 },
    'Oro Blanco 18K': { compra:  99000, venta: 104415 },
    'Oro Rosado 18K': { compra:  94500, venta:  99443 },
    'Plata 925':      { compra:   1800, venta:   1903 },
    'Platino 950':    { compra:  25000, venta:  26700 },
    'Paladio':        { compra:  24000, venta:  25400 },
    'Cobre':          { compra:      8, venta:     10 },
    'Latón':          { compra:      5, venta:      7 },
  }));
  const [editandoMetal, setEditandoMetal] = useState(null);
  const [editVal,       setEditVal]       = useState({ compra:0, venta:0 });
  const [compras,       setCompras]       = useState(COMPRAS_METAL);
  const [modalNuevo,    setModal]         = useState(false);
  const [calcMetal,     setCalcMetal]     = useState('Oro 18K');
  const [calcGramos,    setCalcGramos]    = useState('');
  const [calcTipo,      setCalcTipo]      = useState('Compra');
  const [activeTab,     setActiveTab]     = useState('precios'); // precios | calculadora | registro
  const [nuevo, setNuevo] = useState({
    tipo:'Compra', metal:'Oro 18K', gramos:'', cliente:'', observacion:''
  });

  // ── Datos live (mindicador.cl + metals.live) ───────────────────────────────
  const [liveData,   setLiveData]   = useState(null);   // {usdClp, uf, gold, silver, platinum, palladium}
  const [liveStatus, setLiveStatus] = useState('idle'); // idle | loading | ok | error
  const [liveTime,   setLiveTime]   = useState(null);

  async function fetchLiveSpot() {
    setLiveStatus('loading');
    try {
      const OZ = 31.1035; // troy oz → gramos
      const [dolarRes, ufRes, metalRes] = await Promise.all([
        fetch('https://api.mindicador.cl/api/dolar').then(r => r.json()).catch(() => null),
        fetch('https://api.mindicador.cl/api/uf').then(r => r.json()).catch(() => null),
        fetch('https://api.metals.live/v1/spot').then(r => r.json()).catch(() => null),
      ]);
      const usdClp    = dolarRes?.serie?.[0]?.valor || INDICADORES.dolar.valor;
      const uf        = ufRes?.serie?.[0]?.valor    || INDICADORES.uf.valor;
      const metals    = Array.isArray(metalRes) ? metalRes[0] : (metalRes || {});
      const goldUsd   = metals.gold      || metals.XAU || 3300;
      const silverUsd = metals.silver    || metals.XAG || 33;
      const platUsd   = metals.platinum  || metals.XPT || 1000;
      const palUsd    = metals.palladium || metals.XPD || 1050;

      // Calcular precios spot CLP/g por metal
      // ── Spot CLP/g — fórmula validada con cotizacionrealoro.com ─────────────
      // 14K = 58% (no 58.33%) según cotizacionrealoro.com
      // Silver: API da USD/oz → divido por 31.1035 → USD/g → × 0.925 → 925 → × usdClp
      const s24k  = goldUsd   * usdClp / OZ;              // 24K puro
      const s18k  = Math.round(s24k * 0.750);             // 18K
      const sPure = silverUsd * usdClp / OZ;              // Plata pura
      const spotClp = {
        'Oro 18K':        s18k,
        'Oro 14K':        Math.round(s24k * 0.580),       // 58% según sitio ref
        'Oro Blanco 18K': Math.round(s18k * 1.050),       // +5% rodio
        'Oro Rosado 18K': s18k,
        'Plata 925':      Math.round(sPure * 0.925),
        'Platino 950':    Math.round(platUsd * usdClp / OZ * 0.950),
        'Paladio':        Math.round(palUsd  * usdClp / OZ * 0.950),
      };
      // ── Precio mercado local Chile (spot × factor) ─────────────────────────
      // Factores calculados desde cotizacionrealoro.com: mercado local ÷ spot
      const mercadoClp = {
        'Oro 18K':        Math.round(s18k * 1.23),
        'Oro 14K':        Math.round(spotClp['Oro 14K'] * 1.23),
        'Oro Blanco 18K': Math.round(spotClp['Oro Blanco 18K'] * 1.22),
        'Oro Rosado 18K': Math.round(s18k * 1.24),
        'Plata 925':      Math.round(spotClp['Plata 925'] * 1.68),
        'Platino 950':    Math.round(spotClp['Platino 950'] * 1.20),
        'Paladio':        Math.round(spotClp['Paladio'] * 1.22),
      };

      setLiveData({ usdClp, uf, goldUsd, silverUsd, platUsd, palUsd, spotClp, mercadoClp });
      setLiveStatus('ok');
      setLiveTime(new Date());
    } catch(e) {
      setLiveStatus('error');
    }
  }

  // Auto-fetch al montar
  React.useEffect(() => { fetchLiveSpot(); }, []);

  // Formatear tiempo transcurrido
  function tiempoDesde(t) {
    if (!t) return '';
    const mins = Math.floor((Date.now() - t.getTime()) / 60000);
    return mins < 1 ? 'hace unos segundos' : `hace ${mins} min`;
  }

  function guardarPrecios(metal, vals) {
    const next = { ...preciosWork, [metal]: vals };
    setPreciosWork(next); lsSet('precios_trabajo', next);
    setEditandoMetal(null);
    // Actualizar PRECIO_METALES global para que calculadora y argollas los usen
    if (window.PRECIO_METALES && window.PRECIO_METALES[metal]) {
      window.PRECIO_METALES[metal].valor = vals.venta;
    }
  }

  const precioCalc = preciosWork[calcMetal]?.[calcTipo==='Compra'?'compra':'venta'] || 0;
  const totalCalc  = Math.round(precioCalc * (parseFloat(calcGramos)||0));

  function registrarMovimiento() {
    const id = `CM-${String(compras.length+1).padStart(3,'0')}`;
    const g  = parseFloat(nuevo.gramos)||0;
    const p  = preciosWork[nuevo.metal]?.[nuevo.tipo==='Compra'?'compra':'venta'] || 0;
    const nueva = { ...nuevo, id, fecha:hoy(), gramos:g, precioPorGramo:p, total:Math.round(p*g) };
    setCompras(prev => [nueva, ...prev]);
    setModal(false);
    setNuevo({ tipo:'Compra', metal:'Oro 18K', gramos:'', cliente:'', observacion:'' });
    // Imprimir ticket duplicado
    imprimirTicketMetal(nueva);
  }

  function imprimirTicketMetal(mov) {
    const win = window.open('','_blank','width=380,height=500');
    if (!win) return;
    const copia = (lbl) => `
      <div class="copia">
        <div class="c b lgo">✦ NAVARRO ✦</div>
        <div class="c sub">COMPRA/VENTA METALES</div>
        <hr class="hr">
        <div class="c tit">${mov.tipo.toUpperCase()} DE METAL</div>
        <div class="c fol">${mov.id} · ${mov.fecha}</div>
        <hr class="hr">
        <div class="row"><span>Metal:</span><span><b>${mov.metal}</b></span></div>
        <div class="row"><span>Gramos:</span><span>${mov.gramos}g</span></div>
        <div class="row"><span>Precio/g:</span><span>$${mov.precioPorGramo.toLocaleString('es-CL')}</span></div>
        <hr class="hr">
        <div class="row b tot"><span>TOTAL:</span><span>$${mov.total.toLocaleString('es-CL')}</span></div>
        <hr class="hr">
        <div class="row"><span>${mov.tipo==='Compra'?'Cliente:':'Proveedor:'}</span><span>${mov.cliente||'—'}</span></div>
        ${mov.observacion?`<div class="obs">${mov.observacion}</div>`:''}
        <hr class="hr">
        <div class="c etq">COPIA: ${lbl}</div>
        <div class="c pie">✦ navarro-joyeria.cl ✦</div>
      </div>
      <div class="cut">✂ ─ ─ ─ ─ SEMICORTE ─ ─ ─ ─ ✂</div>`;
    win.document.write(`<!DOCTYPE html><html><head><meta charset="utf-8"><title>SPRT_${mov.id}</title>
    <style>
      @page { margin:2mm 3mm; size:80mm auto; }
      body { font-family:'Courier New',monospace; font-size:11px; width:74mm; margin:0 auto; }
      .c { text-align:center; } .b { font-weight:bold; }
      .hr { border:none; border-top:1px dashed #000; margin:3px 0; }
      .row { display:flex; justify-content:space-between; margin:2px 0; font-size:10px; }
      .lgo { font-size:14px; letter-spacing:2px; margin:3px 0; }
      .sub { font-size:8px; } .tit { font-size:12px; margin:2px 0; } .fol { font-size:9px; color:#444; }
      .tot { font-size:14px; }
      .obs { font-size:9px; color:#555; } .etq { font-size:9px; font-style:italic; } .pie { font-size:8px; color:#555; }
      .copia { page-break-after:always; } .copia:last-of-type { page-break-after:auto; }
      .cut { text-align:center; font-size:9px; color:#888; border-top:1px dotted #aaa; border-bottom:1px dotted #aaa; padding:2px 0; page-break-after:always; }
      @media print { .info { display:none; } }
    </style></head><body>
    <div class="info" style="background:#1a3a2a;color:#fff;padding:5px;font-size:9px;margin-bottom:4px;border-radius:3px;">
      🖨 SPRT SP-POS88 · Duplicado · Semicorte automático
    </div>
    ${copia('JOYERÍA')}
    ${copia('CLIENTE')}
    <script>window.onload=function(){setTimeout(function(){window.print();},400)}<\/script>
    </body></html>`);
    win.document.close();
  }

  const S = metStyles;
  const TABS = [
    { id:'precios',     label:'⚖ Precios de Trabajo' },
    { id:'calculadora', label:'🧮 Calculadora' },
    { id:'registro',    label:'📋 Registro Mov.' },
  ];

  return (
    <div style={{ display:'flex', flexDirection:'column', height:'100%', overflow:'hidden' }}>

      {/* Tabs */}
      <div style={{ display:'flex', gap:'2px', padding:'8px 14px 0', borderBottom:'1px solid var(--border)', background:'var(--bg-card)', flexShrink:0 }}>
        {TABS.map(t => (
          <button key={t.id} onClick={() => setActiveTab(t.id)}
            style={{ padding:'7px 14px', background:'none', border:'none',
              borderBottom: activeTab===t.id ? '2px solid var(--gold)' : '2px solid transparent',
              color: activeTab===t.id ? 'var(--cream)' : 'var(--cream-3)',
              cursor:'pointer', fontSize:'11px', fontFamily:'Inter,sans-serif', marginBottom:'-1px' }}>
            {t.label}
          </button>
        ))}
      </div>

      <div style={{ flex:1, overflowY:'auto', padding:'16px' }}>

        {/* ── TAB PRECIOS ── */}
        {activeTab === 'precios' && (
          <div className="fade-in">
            <div style={{ fontFamily:'Cormorant Garamond,serif', fontSize:'20px', fontWeight:600, color:'var(--cream)', marginBottom:'4px' }}>
              Centro de Precios — Metales
            </div>
            <div style={{ color:'var(--cream-3)', fontSize:'11px', marginBottom:'12px' }}>
              Los precios de <strong style={{color:'var(--gold)'}}>COMPRA</strong> y <strong style={{color:'var(--gold)'}}>VENTA</strong> que configures aquí se usarán en toda la app (calculadora, argollas, hechuras, etc.)
            </div>

            {/* Agente IA precios */}
            {(()=>{
              const [iaStatus, setIaStatus] = React.useState('idle'); // idle | loading | done | error
              const [iaMsg, setIaMsg] = React.useState('');
              async function fetchPreciosIA() {
                setIaStatus('loading'); setIaMsg('');
                try {
                  const resp = await window.claude.complete({
                    messages:[{role:'user',content:`Eres un experto en mercado de metales preciosos en Chile. Proporciona los precios actuales de metales para joyería en Chile al ${new Date().toLocaleDateString('es-CL')} en CLP por gramo. Incluye: Oro 24K spot bolsa, Oro 18K mercado local joyería, Oro 14K mercado local, Plata 925 mercado local joyería, Platino 950. Basa los cálculos en: precio spot internacional USD/oz, tipo de cambio USD/CLP actual (~$965), pureza del metal. Formato: metal | spot_bolsa | precio_calle | mayorista | mercado_local_joyeria | premium. Sé directo y numérico. Justifica brevemente con el spot internacional.`}]
                  });
                  setIaMsg(resp); setIaStatus('done');
                } catch(e) { setIaStatus('error'); setIaMsg('Error al consultar IA. Verifica conexión.'); }
              }
              return (
                <div style={{background:'rgba(201,168,76,0.06)',border:'1px solid rgba(201,168,76,0.2)',borderRadius:'10px',padding:'12px',marginBottom:'16px'}}>
                  <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:'8px'}}>
                    <div style={{color:'var(--gold)',fontWeight:600,fontSize:'12px'}}>✦ Agente IA — Cotización en tiempo real</div>
                    <button onClick={fetchPreciosIA} disabled={iaStatus==='loading'}
                      style={{background:'var(--gold)',color:'var(--bg)',border:'none',borderRadius:'7px',padding:'5px 13px',fontWeight:600,fontSize:'11px',cursor:iaStatus==='loading'?'wait':'pointer',fontFamily:'Inter,sans-serif',opacity:iaStatus==='loading'?0.7:1}}>
                      {iaStatus==='loading'?'Consultando...':'🔍 Consultar precios reales'}
                    </button>
                  </div>
                  {iaStatus==='idle'&&<div style={{fontSize:'10px',color:'var(--cream-3)'}}>El agente consulta precios de mercado internacional y calcula valores para Chile basado en spot actual, tipo de cambio y márgenes del mercado local.</div>}
                  {iaStatus==='loading'&&<div style={{fontSize:'11px',color:'var(--cream-2)',display:'flex',alignItems:'center',gap:'6px'}}><span style={{animation:'pulse 1s infinite'}}>◆</span> Analizando mercado internacional y precios Chile...</div>}
                  {iaMsg&&<div style={{marginTop:'8px',fontSize:'11px',color:'var(--cream)',lineHeight:'1.7',whiteSpace:'pre-wrap',maxHeight:'200px',overflowY:'auto',background:'var(--surface)',padding:'10px',borderRadius:'6px'}}>{iaMsg}</div>}
                </div>
              );
            })()}

            {/* Indicadores live */}
            <div style={{ marginBottom:'14px' }}>
              {/* Barra de estado live */}
              <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:'8px' }}>
                <div style={{ fontSize:'11px', fontWeight:600, color:'var(--cream-3)' }}>
                  Indicadores de mercado
                </div>
                <div style={{ display:'flex', alignItems:'center', gap:'8px' }}>
                  {liveStatus==='ok' && liveTime && (
                    <span style={{ fontSize:'10px', color:'#27ae60' }}>
                      ● En vivo · {tiempoDesde(liveTime)}
                    </span>
                  )}
                  {liveStatus==='error' && (
                    <span style={{ fontSize:'10px', color:'#e67e22' }}>⚠ Sin conexión · datos base</span>
                  )}
                  {liveStatus==='loading' && (
                    <span style={{ fontSize:'10px', color:'var(--gold)', animation:'pulse 1s infinite' }}>◆ Cargando...</span>
                  )}
                  <button onClick={fetchLiveSpot} disabled={liveStatus==='loading'}
                    style={{ padding:'3px 10px', background:'var(--surface)', border:'1px solid var(--border)',
                      borderRadius:'5px', color:'var(--cream-3)', fontSize:'10px', cursor:'pointer',
                      fontFamily:'Inter,sans-serif', opacity: liveStatus==='loading' ? 0.5 : 1 }}>
                    ↻ Actualizar
                  </button>
                </div>
              </div>

              <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr 1fr', gap:'6px' }}>
                {[
                  { l:'USD/CLP', v:`$${(liveData?.usdClp || INDICADORES.dolar.valor).toLocaleString('es-CL')}`, sub:'Tipo de cambio', live: !!liveData },
                  { l:'UF',      v:(liveData?.uf || INDICADORES.uf.valor).toLocaleString('es-CL',{maximumFractionDigits:2}), sub:'Unidad de Fomento', live: !!liveData },
                  { l:'XAU/oz',  v:`USD ${(liveData?.goldUsd||3300).toLocaleString('en-US')}`, sub:'Oro troy oz', live: !!liveData },
                  { l:'XAG/oz',  v:`USD ${(liveData?.silverUsd||33).toFixed(2)}`, sub:'Plata troy oz', live: !!liveData },
                ].map(i => (
                  <div key={i.l} style={{ background:'var(--surface)', borderRadius:'8px', padding:'10px', border:'1px solid var(--border)' }}>
                    <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:'2px' }}>
                      <div style={{ color:'var(--cream-3)', fontSize:'9px', fontWeight:600 }}>{i.l}</div>
                      {i.live && <div style={{ width:'5px', height:'5px', borderRadius:'50%', background:'#27ae60' }}/>}
                    </div>
                    <div style={{ color:'var(--cream)', fontWeight:700, fontSize:'13px' }}>{i.v}</div>
                    <div style={{ color:'var(--cream-3)', fontSize:'9px', marginTop:'1px' }}>{i.sub}</div>
                  </div>
                ))}
              </div>
              {liveData && (
                <div style={{ marginTop:'6px', fontSize:'10px', color:'var(--cream-3)', textAlign:'right' }}>
                  Fuentes: <span style={{ color:'var(--cream-2)' }}>mindicador.cl</span> (USD, UF) · <span style={{ color:'var(--cream-2)' }}>metals.live</span> (XAU, XAG) · actualizados {tiempoDesde(liveTime)}
                </div>
              )}
            </div>

            {/* Tabla de precios */}
            <div style={{ display:'flex', flexDirection:'column', gap:'8px' }}>
              {Object.entries(PRECIO_METALES).map(([metal, info]) => {
                const work = preciosWork[metal] || { compra: info.valor * 0.85, venta: info.valor };
                const isEdit = editandoMetal === metal;
                return (
                  <div key={metal} style={{ background:'var(--bg-card)', border:`1px solid ${isEdit?'var(--gold)':'var(--border)'}`, borderRadius:'12px', padding:'14px', transition:'border-color 0.15s' }}>
                    {/* Header metal */}
                    <div style={{ display:'flex', alignItems:'center', gap:'8px', marginBottom:'12px' }}>
                      <div style={{ width:'12px', height:'12px', borderRadius:'50%', background:info.color, flexShrink:0 }}/>
                      <div style={{ flex:1 }}>
                        <div style={{ color:'var(--cream)', fontWeight:600, fontSize:'13px' }}>{metal}</div>
                        <div style={{ color:'var(--cream-3)', fontSize:'9px' }}>{info.nota || 'por gramo (CLP)'}</div>
                      </div>
                      <div style={{ display:'flex', gap:'6px' }}>
                        {!isEdit && (
                          <button onClick={() => { setEditandoMetal(metal); setEditVal({ compra:work.compra, venta:work.venta }); }}
                            style={{ ...invStyles.btnEdit, fontSize:'10px' }}>✏ Editar</button>
                        )}
                        {isEdit && (
                          <>
                            <button onClick={() => guardarPrecios(metal, editVal)}
                              style={{ ...inv2Styles.btnGold, fontSize:'10px' }}>✓ Guardar</button>
                            <button onClick={() => setEditandoMetal(null)}
                              style={{ ...invStyles.btnEdit, fontSize:'10px' }}>✕</button>
                          </>
                        )}
                      </div>
                    </div>

                    {/* Precios referencia */}
                    <div style={{ display:'grid', gridTemplateColumns:'repeat(5,1fr)', gap:'4px', marginBottom:'12px' }}>
                      {info.tiers && Object.entries(info.tiers).map(([k, t]) => (
                        <div key={k} style={{ background:'var(--surface)', borderRadius:'6px', padding:'6px 5px', textAlign:'center', cursor:'pointer', border:'1px solid var(--border)' }}
                          onClick={() => { if(isEdit) setEditVal(ev => ({...ev, venta: t.v})); }}>
                          <div style={{ color:'var(--cream-3)', fontSize:'8px', marginBottom:'2px', lineHeight:'1.2' }}>{t.label}</div>
                          <div style={{ color:'var(--cream)', fontSize:'11px', fontWeight:600 }}>{clp(t.v)}</div>
                          {isEdit && <div style={{ fontSize:'8px', color:'var(--gold)', marginTop:'1px' }}>↑ usar</div>}
                        </div>
                      ))}
                    </div>

                    {/* Precios de trabajo */}
                    <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'10px' }}>
                      <div style={{ background: isEdit ? 'rgba(39,174,96,0.08)' : 'var(--surface)', borderRadius:'8px', padding:'10px', border:`1px solid ${isEdit?'rgba(39,174,96,0.3)':'var(--border)'}` }}>
                        <div style={{ fontSize:'9px', color:'#27ae60', fontWeight:600, letterSpacing:'0.5px', marginBottom:'4px' }}>📥 PRECIO COMPRA (lo que pagas)</div>
                        {isEdit
                          ? <input type="number" value={editVal.compra} onChange={e => setEditVal(v => ({...v, compra: parseInt(e.target.value)||0}))}
                              style={{ ...calcStyles.input, fontSize:'18px', fontWeight:700, color:'#27ae60', textAlign:'center' }}/>
                          : <div style={{ color:'#27ae60', fontWeight:700, fontSize:'20px' }}>{clp(work.compra)}/g</div>
                        }
                      </div>
                      <div style={{ background: isEdit ? 'rgba(201,168,76,0.08)' : 'var(--surface)', borderRadius:'8px', padding:'10px', border:`1px solid ${isEdit?'var(--gold)':'var(--border)'}` }}>
                        <div style={{ fontSize:'9px', color:'var(--gold)', fontWeight:600, letterSpacing:'0.5px', marginBottom:'4px' }}>📤 PRECIO VENTA (lo que cobras)</div>
                        {isEdit
                          ? <input type="number" value={editVal.venta} onChange={e => setEditVal(v => ({...v, venta: parseInt(e.target.value)||0}))}
                              style={{ ...calcStyles.input, fontSize:'18px', fontWeight:700, color:'var(--gold)', textAlign:'center' }}/>
                          : <div style={{ color:'var(--gold)', fontWeight:700, fontSize:'20px' }}>{clp(work.venta)}/g</div>
                        }
                      </div>
                    </div>
                    {!isEdit && (
                      <div style={{ marginTop:'6px', display:'flex', justifyContent:'space-between', alignItems:'center' }}>
                        <span style={{ fontSize:'10px', color:'var(--cream-3)' }}>
                          Margen: <span style={{ color:'#27ae60', fontWeight:600 }}>
                            {work.venta > work.compra ? `+${Math.round((work.venta/work.compra-1)*100)}%` : '—'}
                          </span>
                        </span>
                        {liveData?.spotClp?.[metal] && (
                          <span style={{ fontSize:'10px', color:'var(--cream-3)', display:'flex', flexDirection:'column', alignItems:'flex-end', gap:'1px' }}>
                            <span>
                              Spot puro:{' '}
                              <span style={{ color:'var(--cream-2)', fontWeight:600 }}>
                                {clp(liveData.spotClp[metal])}/g
                              </span>
                            </span>
                            {liveData.mercadoClp?.[metal] && (
                              <span>
                                Mercado ref:{' '}
                                <span style={{ color: liveData.mercadoClp[metal] > work.venta ? '#e67e22' : '#27ae60', fontWeight:600 }}>
                                  {clp(liveData.mercadoClp[metal])}/g
                                </span>
                                {liveData.mercadoClp[metal] > work.venta * 1.1 && (
                                  <span style={{ color:'#e67e22', marginLeft:'4px' }}>↑ revisa precio</span>
                                )}
                              </span>
                            )}
                          </span>
                        )}
                      </div>
                    )}
                  </div>
                );
              })}
            </div>

            <div style={{ marginTop:'12px', padding:'10px 14px', background:'rgba(201,168,76,0.06)', border:'1px solid rgba(201,168,76,0.2)', borderRadius:'8px', fontSize:'11px', color:'var(--cream-3)' }}>
              💡 <strong style={{color:'var(--cream)'}}>Tip:</strong> Haz click en cualquier precio de referencia para usarlo como precio de venta. Los cambios se aplican inmediatamente a calculadora, argollas y hechuras.
            </div>
          </div>
        )}

        {/* ── TAB CALCULADORA ── */}
        {activeTab === 'calculadora' && (
          <div className="fade-in" style={{ maxWidth:'420px' }}>
            <div style={{ fontFamily:'Cormorant Garamond,serif', fontSize:'20px', fontWeight:600, color:'var(--cream)', marginBottom:'16px' }}>
              Calculadora de Metales
            </div>
            <div style={{ display:'flex', gap:'6px', marginBottom:'14px' }}>
              {['Compra','Venta'].map(t => (
                <button key={t} onClick={() => setCalcTipo(t)}
                  style={{ ...posStyles.descBtn, flex:1, ...(calcTipo===t ? posStyles.descBtnActive : {}) }}>
                  {t === 'Compra' ? '📥 Compra cliente' : '📤 Venta al cliente'}
                </button>
              ))}
            </div>
            <div style={{ marginBottom:'12px' }}>
              <div style={{ fontSize:'10px', color:'var(--cream-3)', marginBottom:'5px' }}>Metal</div>
              <select style={{ ...invStyles.select, width:'100%' }} value={calcMetal} onChange={e => setCalcMetal(e.target.value)}>
                {Object.keys(PRECIO_METALES).map(m => <option key={m}>{m}</option>)}
              </select>
            </div>
            <div style={{ marginBottom:'12px' }}>
              <div style={{ fontSize:'10px', color:'var(--cream-3)', marginBottom:'5px' }}>Gramos</div>
              <input type="number" step="0.1" placeholder="0.0 g" style={{ ...calcStyles.input }}
                value={calcGramos} onChange={e => setCalcGramos(e.target.value)}/>
            </div>
            <div style={{ background:'var(--surface)', borderRadius:'12px', padding:'20px', textAlign:'center', marginBottom:'12px' }}>
              <div style={{ color:'var(--cream-3)', fontSize:'11px', marginBottom:'6px' }}>
                {calcTipo === 'Compra' ? 'PAGAR al cliente' : 'COBRAR al cliente'}
              </div>
              <div style={{ color:'var(--gold)', fontWeight:700, fontSize:'34px' }}>{clp(totalCalc)}</div>
              <div style={{ color:'var(--cream-3)', fontSize:'11px', marginTop:'4px' }}>
                {calcGramos||0}g × {clp(precioCalc)}/g ({calcTipo === 'Compra' ? 'precio compra' : 'precio venta'})
              </div>
            </div>
            <button onClick={() => setModal(true)} style={{ ...posStyles.cobrarBtn, width:'100%', fontSize:'12px' }}>
              + Registrar este movimiento
            </button>
          </div>
        )}

        {/* ── TAB REGISTRO ── */}
        {activeTab === 'registro' && (
          <div className="fade-in">
            <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:'14px' }}>
              <div style={{ fontFamily:'Cormorant Garamond,serif', fontSize:'20px', fontWeight:600, color:'var(--cream)' }}>
                Registro Movimientos
              </div>
              <button onClick={() => setModal(true)} style={{ ...invStyles.btnAdd }}>+ Registrar</button>
            </div>
            <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:'8px', marginBottom:'14px' }}>
              {[
                { l:'Compras hoy', v: clp(compras.filter(c=>c.tipo==='Compra'&&c.fecha===hoy()).reduce((s,c)=>s+c.total,0)) },
                { l:'Ventas hoy',  v: clp(compras.filter(c=>c.tipo==='Venta'&&c.fecha===hoy()).reduce((s,c)=>s+c.total,0)) },
                { l:'Total registros', v: compras.length },
              ].map(s => (
                <div key={s.l} style={{ background:'var(--bg-card)', border:'1px solid var(--border)', borderRadius:'8px', padding:'12px', textAlign:'center' }}>
                  <div style={{ color:'var(--gold)', fontWeight:700, fontSize:'16px' }}>{s.v}</div>
                  <div style={{ color:'var(--cream-3)', fontSize:'10px' }}>{s.l}</div>
                </div>
              ))}
            </div>
            <table style={{ width:'100%', borderCollapse:'collapse' }}>
              <thead>
                <tr>{['ID','Fecha','Op.','Metal','Gramos','$/g','Total','Cliente','Obs.'].map(h=>(
                  <th key={h} style={invStyles.th}>{h}</th>
                ))}</tr>
              </thead>
              <tbody>
                {compras.map(c => (
                  <tr key={c.id} style={invStyles.tr}>
                    <td style={invStyles.td}><span style={{fontFamily:'monospace',fontSize:'10px',color:'var(--cream-3)'}}>{c.id}</span></td>
                    <td style={invStyles.td}><span style={{color:'var(--cream-3)',fontSize:'11px'}}>{c.fecha}</span></td>
                    <td style={invStyles.td}>
                      <span style={{padding:'2px 7px',borderRadius:'20px',fontSize:'10px',fontWeight:600,
                        background:c.tipo==='Compra'?'rgba(39,174,96,0.15)':'rgba(41,128,185,0.15)',
                        color:c.tipo==='Compra'?'#27ae60':'#2980b9'}}>
                        {c.tipo}
                      </span>
                    </td>
                    <td style={invStyles.td}><span style={{color:'var(--cream)',fontSize:'12px'}}>{c.metal}</span></td>
                    <td style={invStyles.td}><span style={{color:'var(--cream-2)',fontSize:'12px'}}>{c.gramos}g</span></td>
                    <td style={invStyles.td}><span style={{color:'var(--cream-3)',fontSize:'12px'}}>{clp(c.precioPorGramo)}</span></td>
                    <td style={invStyles.td}><span style={{color:'var(--gold)',fontWeight:600,fontSize:'12px'}}>{clp(c.total)}</span></td>
                    <td style={invStyles.td}><span style={{color:'var(--cream-3)',fontSize:'11px'}}>{c.cliente||'—'}</span></td>
                    <td style={invStyles.td}>
                      <button onClick={() => imprimirTicketMetal(c)}
                        style={{...invStyles.btnEdit,fontSize:'9px',padding:'2px 6px'}}>🖨</button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Modal registrar */}
      {modalNuevo && (
        <div style={posStyles.overlay} onClick={e => e.target===e.currentTarget && setModal(false)}>
          <div style={{ ...posStyles.modalBox, maxWidth:'400px' }}>
            <div style={{ ...posStyles.modalHeader, marginBottom:'16px' }}>
              <span style={{ fontFamily:'Cormorant Garamond,serif', fontSize:'20px', fontWeight:600 }}>Registrar Metal</span>
              <button onClick={() => setModal(false)} style={posStyles.clearBtn}>✕</button>
            </div>
            <div style={{ display:'flex', gap:'6px', marginBottom:'12px' }}>
              {['Compra','Venta'].map(t => (
                <button key={t} onClick={() => setNuevo(n => ({...n,tipo:t}))}
                  style={{ ...posStyles.descBtn, flex:1, ...(nuevo.tipo===t ? posStyles.descBtnActive : {}) }}>
                  {t==='Compra' ? '📥 Compra' : '📤 Venta'}
                </button>
              ))}
            </div>
            {[
              { label:'Metal', key:'metal', type:'select', opts:Object.keys(PRECIO_METALES) },
              { label:'Gramos', key:'gramos', type:'number', ph:'0.0' },
              { label:'Cliente / Proveedor', key:'cliente', type:'text', ph:'Nombre' },
              { label:'Observación', key:'observacion', type:'text', ph:'Ej: anillo viejo, cadena' },
            ].map(f => (
              <div key={f.key} style={{ marginBottom:'10px' }}>
                <div style={{ fontSize:'11px', color:'var(--cream-3)', marginBottom:'4px' }}>{f.label}</div>
                {f.type==='select'
                  ? <select style={{ ...invStyles.select, width:'100%' }} value={nuevo[f.key]}
                      onChange={e => setNuevo(n => ({...n,[f.key]:e.target.value}))}>
                      {f.opts.map(o => <option key={o}>{o}</option>)}
                    </select>
                  : <input type={f.type} placeholder={f.ph} style={calcStyles.input}
                      value={nuevo[f.key]} onChange={e => setNuevo(n => ({...n,[f.key]:e.target.value}))}/>
                }
              </div>
            ))}
            {nuevo.metal && nuevo.gramos && (
              <div style={{ background:'var(--surface)', borderRadius:'8px', padding:'12px', marginBottom:'12px', textAlign:'center' }}>
                <div style={{ color:'var(--cream-3)', fontSize:'11px' }}>Total estimado</div>
                <div style={{ color:'var(--gold)', fontWeight:700, fontSize:'22px' }}>
                  {clp(Math.round((preciosWork[nuevo.metal]?.[nuevo.tipo==='Compra'?'compra':'venta']||0) * (parseFloat(nuevo.gramos)||0)))}
                </div>
                <div style={{ fontSize:'9px', color:'var(--cream-3)', marginTop:'3px' }}>
                  Se imprimirá ticket duplicado (SPRT SP-POS88)
                </div>
              </div>
            )}
            <button onClick={registrarMovimiento} style={{ ...posStyles.cobrarBtn, width:'100%' }}>
              ✦ Registrar + Imprimir Ticket
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

const metStyles = {
  wrap:{ display:'flex', height:'100%', overflow:'hidden' },
  leftCol:{ width:'300px', overflowY:'auto', borderRight:'1px solid var(--border)', padding:'16px', display:'flex', flexDirection:'column', gap:'16px' },
  rightCol:{ flex:1, display:'flex', flexDirection:'column', overflow:'hidden' },
  section:{ background:'var(--bg-card)', borderRadius:'12px', padding:'14px', border:'1px solid var(--border)' },
  secTitle:{ fontFamily:'Cormorant Garamond,serif', fontSize:'15px', fontWeight:600, color:'var(--cream)', marginBottom:'12px', paddingBottom:'8px', borderBottom:'1px solid var(--border)' },
  indicadorChip:{ background:'var(--surface)', borderRadius:'8px', padding:'12px', border:'1px solid var(--border)' },
  metalRow:{ display:'flex', justifyContent:'space-between', alignItems:'center', padding:'8px', background:'var(--surface)', borderRadius:'8px', border:'1px solid var(--border)' },
};

Object.assign(window, { Metales });
