// ── GRABADO LÁSER — con preview 3D de pieza + grabado ─

function GrabadoLaser() {
  const { useState, useEffect, useRef } = React;

  const [texto,      setTexto]     = useState('');
  const [fuente,     setFuente]    = useState('Script');
  const [posicion,   setPosicion]  = useState('Interior');
  const [material,   setMaterial]  = useState('Plata 925');
  const [tipoPieza,  setTipoPieza] = useState('Anillo');
  const [tamano,     setTamano]    = useState(12);
  const [profundidad,setProfundidad]=useState('Media'); // Leve | Media | Profunda
  const [pedidos,    setPedidos]   = useState(()=>lsGet('grabados',[]));
  const [modalNuevo, setModal]     = useState(false);
  const [nuevoCliente,setNuevoCliente]=useState('');
  const [preview3d,  setPreview3d] = useState(true);
  const canvasRef = useRef();

  const FUENTES = [
    {id:'Script',  label:'Script',  family:'Cormorant Garamond,serif', style:'italic',  spacing:'0.5px'},
    {id:'Serif',   label:'Clásica', family:'Georgia,serif',             style:'normal',  spacing:'0.5px'},
    {id:'Sans',    label:'Sans',    family:'Inter,sans-serif',          style:'normal',  spacing:'0.5px'},
    {id:'Bloque',  label:'Bloque',  family:'Inter,sans-serif',          style:'normal',  spacing:'3px',  weight:'700'},
    {id:'Mono',    label:'Mono',    family:'Courier New,monospace',     style:'normal',  spacing:'1px'},
    {id:'Fino',    label:'Fino',    family:'Cormorant Garamond,serif',  style:'normal',  weight:'300',   spacing:'2px'},
  ];
  const TIPOS_PIEZA = ['Anillo','Argolla','Pulsera','Brazalete','Colgante','Medalla','Placa','Esclava','Otro'];
  const MATERIALES  = ['Plata 925','Oro 18K','Oro 14K','Cobre','Acero Inox','Bronce','Latón','Platino'];

  const precios = {'Plata 925':10000,'Oro 18K':22000,'Oro 14K':18000,
    'Cobre':6000,'Acero Inox':8000,'Bronce':6000,'Latón':7000,'Platino':25000};
  const precioBase  = precios[material]||10000;
  const precioExtra = posicion==='Ambos lados'?Math.round(precioBase*0.6):0;
  const precioTotal = precioBase+precioExtra;

  const fuenteAct = FUENTES.find(f=>f.id===fuente)||FUENTES[0];

  // ── Render Canvas 3D simulado ──────────────────────
  useEffect(()=>{
    if(!canvasRef.current) return;
    const canvas=canvasRef.current;
    const ctx=canvas.getContext('2d');
    const W=canvas.width, H=canvas.height;
    ctx.clearRect(0,0,W,H);

    // Fondo oscuro cálido
    ctx.fillStyle='#0e0b08';
    ctx.fillRect(0,0,W,H);

    // Sombra suelo
    const grad=ctx.createRadialGradient(W/2,H*0.85,10,W/2,H*0.85,90);
    grad.addColorStop(0,'rgba(0,0,0,0.5)');
    grad.addColorStop(1,'transparent');
    ctx.fillStyle=grad;
    ctx.fillRect(0,0,W,H);

    // Color metal
    const metalColors={
      'Plata 925':'#C0C0D0','Oro 18K':'#D4AF37','Oro 14K':'#CDA434',
      'Cobre':'#B87333','Acero Inox':'#A8A9AC','Bronce':'#CD7F32',
      'Latón':'#CDB53B','Platino':'#E5E4E2'
    };
    const mc=metalColors[material]||'#C0C0D0';

    // Función para dibujar pieza
    const cx=W/2, cy=H/2;

    if(tipoPieza==='Anillo'||tipoPieza==='Argolla'||tipoPieza==='Esclava') {
      // Anillo / aro en perspectiva 3D
      const R=80, t=18;
      // Cuerpo del aro (elipse exterior - interior)
      ctx.save();
      ctx.translate(cx,cy);

      // Sombra
      const shadowGrad=ctx.createRadialGradient(0,R*0.55,0,0,R*0.55,40);
      shadowGrad.addColorStop(0,'rgba(0,0,0,0.4)');
      shadowGrad.addColorStop(1,'transparent');
      ctx.fillStyle=shadowGrad;
      ctx.ellipse(0,R*0.55,R*0.6,R*0.18,0,0,Math.PI*2);
      ctx.fill();

      // Aro — cara frontal con gradiente metálico
      for(let angle=Math.PI*0.1; angle<Math.PI*0.9; angle+=0.015){
        const x1=Math.cos(angle)*R, y1=Math.sin(angle)*R*0.38;
        const x2=Math.cos(angle)*(R-t), y2=Math.sin(angle)*(R-t)*0.38;
        const x3=Math.cos(angle+0.02)*(R-t), y3=Math.sin(angle+0.02)*(R-t)*0.38;
        const x4=Math.cos(angle+0.02)*R, y4=Math.sin(angle+0.02)*R*0.38;
        const bright=0.6+Math.cos(angle)*0.4;
        ctx.beginPath();
        ctx.moveTo(x1,y1); ctx.lineTo(x2,y2);
        ctx.lineTo(x3,y3); ctx.lineTo(x4,y4);
        ctx.closePath();
        ctx.fillStyle=hexAdjust(mc,bright);
        ctx.fill();
      }

      // Aro cara superior (ancho)
      for(let angle=0; angle<Math.PI*2; angle+=0.015){
        const x1=Math.cos(angle)*R, y1=Math.sin(angle)*R*0.38;
        const x2=Math.cos(angle+0.02)*R, y2=Math.sin(angle+0.02)*R*0.38;
        ctx.beginPath();
        ctx.moveTo(x1,y1); ctx.lineTo(x2,y2);
        ctx.lineTo(x2,y2-t*0.4); ctx.lineTo(x1,y1-t*0.4);
        ctx.closePath();
        const bright=0.5+Math.cos(angle+Math.PI/4)*0.5;
        ctx.fillStyle=hexAdjust(mc,bright*1.2);
        ctx.fill();
      }

      // Reflejo superior
      ctx.beginPath();
      ctx.ellipse(0,-t*0.4,R,R*0.38,0,0,Math.PI*2);
      ctx.ellipse(0,-t*0.4,R-t,( R-t)*0.38,0,0,Math.PI*2,true);
      const refGrad=ctx.createLinearGradient(-R,-t*0.4-10,R,-t*0.4+10);
      refGrad.addColorStop(0,'transparent');
      refGrad.addColorStop(0.3,'rgba(255,255,255,0.25)');
      refGrad.addColorStop(0.7,'rgba(255,255,255,0.1)');
      refGrad.addColorStop(1,'transparent');
      ctx.fillStyle=refGrad;
      ctx.fill('evenodd');

      // ── GRABADO ──
      if(texto) {
        const fSize=tamano*(posicion==='Exterior'?1:0.8);
        ctx.font=`${fuenteAct.weight||'400'} ${fSize}px ${fuenteAct.family}`;
        ctx.textAlign='center';
        ctx.textBaseline='middle';

        if(posicion==='Interior'){
          // Interior del aro — texto arqueado en la parte inferior visible
          ctx.save();
          ctx.beginPath();
          ctx.ellipse(0,0,R-t,( R-t)*0.38,0,0,Math.PI*2);
          ctx.clip();
          // Mostrar texto con curva leve
          const grabColor=material.includes('Oro')?'rgba(100,70,0,0.7)':'rgba(255,255,255,0.15)';
          ctx.fillStyle=grabColor;
          ctx.shadowColor=material.includes('Oro')?'rgba(0,0,0,0.5)':'rgba(200,200,200,0.3)';
          ctx.shadowBlur=2;
          // Texto en arco
          const txt=texto.slice(0,22);
          const arcR=R-t-5;
          const totalAngle=Math.min(txt.length*0.11, Math.PI*0.7);
          let startA=Math.PI*0.5-totalAngle/2;
          for(let i=0;i<txt.length;i++){
            const a=startA+(i/txt.length)*totalAngle;
            ctx.save();
            ctx.translate(Math.cos(a)*arcR*0.5, Math.sin(a)*(arcR*0.38)*0.7);
            ctx.rotate(a+Math.PI/2);
            ctx.fillText(txt[i],0,0);
            ctx.restore();
          }
          ctx.restore();
        } else {
          // Exterior — texto arqueado visible
          const grabColor=material.includes('Oro')?'rgba(80,50,0,0.9)':'rgba(160,160,180,0.9)';
          ctx.fillStyle=grabColor;
          ctx.shadowColor='rgba(0,0,0,0.6)';
          ctx.shadowBlur=3;
          const txt=texto.slice(0,20);
          const arcR=R*0.98;
          const totalAngle=Math.min(txt.length*0.12, Math.PI*0.6);
          let startA=Math.PI*1.5-totalAngle/2;
          for(let i=0;i<txt.length;i++){
            const a=startA+(i/txt.length)*totalAngle;
            ctx.save();
            ctx.translate(Math.cos(a)*arcR, Math.sin(a)*arcR*0.38-t*0.4);
            ctx.rotate(a-Math.PI/2);
            ctx.fillText(txt[i],0,0);
            ctx.restore();
          }
        }
      }
      ctx.restore();
    }

    else if(tipoPieza==='Pulsera'||tipoPieza==='Brazalete') {
      // Vista frontal de pulsera
      ctx.save();
      ctx.translate(cx,cy);
      const W2=120,H2=22;
      // Gradiente metálico
      const mg=ctx.createLinearGradient(0,-H2,0,H2);
      mg.addColorStop(0,hexAdjust(mc,1.4));
      mg.addColorStop(0.3,hexAdjust(mc,1.1));
      mg.addColorStop(0.7,hexAdjust(mc,0.8));
      mg.addColorStop(1,hexAdjust(mc,0.5));
      ctx.fillStyle=mg;
      ctx.beginPath();
      ctx.roundRect(-W2,-H2,W2*2,H2*2,H2*0.3);
      ctx.fill();
      // Reflejo
      ctx.fillStyle='rgba(255,255,255,0.15)';
      ctx.beginPath();
      ctx.roundRect(-W2+4,-H2+2,W2*2-8,H2*0.6,4);
      ctx.fill();
      // Grabado
      if(texto){
        ctx.font=`${fuenteAct.weight||'400'} ${tamano}px ${fuenteAct.family}`;
        ctx.textAlign='center'; ctx.textBaseline='middle';
        ctx.fillStyle=material.includes('Oro')?'rgba(80,50,0,0.7)':'rgba(200,200,220,0.5)';
        ctx.shadowColor='rgba(0,0,0,0.5)'; ctx.shadowBlur=2;
        ctx.fillText(texto.slice(0,28),0,0);
      }
      ctx.restore();
    }

    else if(tipoPieza==='Colgante'||tipoPieza==='Medalla') {
      ctx.save();
      ctx.translate(cx,cy+10);
      const r=65;
      // Sombra
      ctx.beginPath(); ctx.ellipse(0,r*0.85,r*0.5,r*0.1,0,0,Math.PI*2);
      const sg=ctx.createRadialGradient(0,r*0.85,0,0,r*0.85,r*0.5);
      sg.addColorStop(0,'rgba(0,0,0,0.4)'); sg.addColorStop(1,'transparent');
      ctx.fillStyle=sg; ctx.fill();
      // Círculo
      const cg=ctx.createRadialGradient(-r*0.3,-r*0.3,r*0.1,0,0,r);
      cg.addColorStop(0,hexAdjust(mc,1.4));
      cg.addColorStop(0.5,hexAdjust(mc,1.0));
      cg.addColorStop(1,hexAdjust(mc,0.5));
      ctx.beginPath(); ctx.arc(0,0,r,0,Math.PI*2);
      ctx.fillStyle=cg; ctx.fill();
      // Borde
      ctx.beginPath(); ctx.arc(0,0,r,0,Math.PI*2);
      ctx.strokeStyle=hexAdjust(mc,1.6); ctx.lineWidth=2; ctx.stroke();
      // Argolla
      ctx.beginPath(); ctx.arc(0,-r-8,10,0,Math.PI*2);
      ctx.fillStyle=hexAdjust(mc,0.9); ctx.fill();
      ctx.beginPath(); ctx.arc(0,-r-8,10,0,Math.PI*2);
      ctx.strokeStyle=hexAdjust(mc,1.3); ctx.lineWidth=3; ctx.stroke();
      // Grabado
      if(texto){
        ctx.font=`${fuenteAct.weight||'400'} ${tamano}px ${fuenteAct.family}`;
        ctx.textAlign='center'; ctx.textBaseline='middle';
        ctx.fillStyle=material.includes('Oro')?'rgba(80,50,0,0.75)':'rgba(200,200,220,0.6)';
        ctx.shadowColor='rgba(0,0,0,0.5)'; ctx.shadowBlur=2;
        ctx.fillText(texto.slice(0,14),0,-8);
        if(texto.length>14) ctx.fillText(texto.slice(14,28),0,8+tamano);
      }
      ctx.restore();
    }

    else { // Placa / genérico
      ctx.save();
      ctx.translate(cx,cy);
      const pw=130,ph=70;
      const pg=ctx.createLinearGradient(-pw,-ph,pw,ph);
      pg.addColorStop(0,hexAdjust(mc,1.4));
      pg.addColorStop(0.5,hexAdjust(mc,0.9));
      pg.addColorStop(1,hexAdjust(mc,0.6));
      ctx.fillStyle=pg;
      ctx.beginPath(); ctx.roundRect(-pw,-ph,pw*2,ph*2,8); ctx.fill();
      ctx.strokeStyle=hexAdjust(mc,1.5); ctx.lineWidth=1.5;
      ctx.beginPath(); ctx.roundRect(-pw+4,-ph+4,pw*2-8,ph*2-8,5); ctx.stroke();
      if(texto){
        ctx.font=`${fuenteAct.weight||'400'} ${tamano}px ${fuenteAct.family}`;
        ctx.textAlign='center'; ctx.textBaseline='middle';
        ctx.fillStyle=material.includes('Oro')?'rgba(80,50,0,0.75)':'rgba(200,200,220,0.6)';
        ctx.shadowColor='rgba(0,0,0,0.5)'; ctx.shadowBlur=2;
        ctx.fillText(texto.slice(0,22),0,0);
      }
      ctx.restore();
    }

    // Info overlay
    ctx.fillStyle='rgba(201,168,76,0.5)';
    ctx.font='10px Inter,sans-serif';
    ctx.textAlign='left';
    ctx.fillText(`NAVARRO ✦ ${tipoPieza} · ${material}`,10,H-10);
    ctx.textAlign='right';
    ctx.fillStyle='rgba(201,168,76,0.3)';
    ctx.fillText(posicion==='Interior'?'Vista interior →':'Vista exterior',W-10,H-10);

  },[texto,fuente,posicion,material,tipoPieza,tamano,profundidad]);

  // Helper: hex adjust brightness
  function hexAdjust(hex,factor){
    const r=parseInt(hex.slice(1,3),16),g=parseInt(hex.slice(3,5),16),b=parseInt(hex.slice(5,7),16);
    const nr=Math.min(255,Math.round(r*factor));
    const ng=Math.min(255,Math.round(g*factor));
    const nb=Math.min(255,Math.round(b*factor));
    return `rgb(${nr},${ng},${nb})`;
  }

  function crearPedido(){
    if(!texto||!nuevoCliente) return;
    const id=`GL-${String(pedidos.length+1).padStart(3,'0')}`;
    const nueva=[{id,cliente:nuevoCliente,texto,fuente,pieza:tipoPieza,
      material,posicion,profundidad,precio:precioTotal,estado:'Recibido',
      fecha:hoy(),tecnico:'Valentina T.'},...pedidos].slice(0,200);
    setPedidos(nueva); lsSet('grabados',nueva);
    setModal(false); setTexto(''); setNuevoCliente('');
  }

  const S = grabStyles;

  return (
    <div style={{display:'flex',height:'100%',overflow:'hidden'}}>
      {/* Config */}
      <div style={S.leftCol}>
        <div style={{fontFamily:'Cormorant Garamond,serif',fontSize:'20px',fontWeight:600,
          color:'var(--cream)',marginBottom:'3px'}}>Grabado Láser</div>
        <div style={{color:'var(--cream-3)',fontSize:'11px',marginBottom:'16px'}}>
          Preview en tiempo real · Visualiza cómo quedará
        </div>

        <div style={S.grupo}>
          <div style={S.label}>Tipo de pieza</div>
          <div style={{display:'flex',flexWrap:'wrap',gap:'4px'}}>
            {TIPOS_PIEZA.map(t=>(
              <button key={t} onClick={()=>setTipoPieza(t)}
                style={{...calcStyles2.chip,...(tipoPieza===t?calcStyles2.chipAct:{})}}>
                {t}
              </button>
            ))}
          </div>
        </div>

        <div style={S.grupo}>
          <div style={S.label}>Material</div>
          <div style={{display:'flex',flexWrap:'wrap',gap:'4px'}}>
            {MATERIALES.map(m=>(
              <button key={m} onClick={()=>setMaterial(m)}
                style={{...calcStyles2.chip,...(material===m?calcStyles2.chipAct:{})}}>
                {m}
              </button>
            ))}
          </div>
        </div>

        <div style={S.grupo}>
          <div style={S.label}>Posición</div>
          <div style={{display:'flex',gap:'5px'}}>
            {['Interior','Exterior','Ambos lados'].map(p=>(
              <button key={p} onClick={()=>setPosicion(p)}
                style={{...calcStyles2.chip,flex:1,textAlign:'center',...(posicion===p?calcStyles2.chipAct:{})}}>
                {p}
              </button>
            ))}
          </div>
        </div>

        <div style={S.grupo}>
          <div style={S.label}>Tipografía</div>
          <div style={{display:'flex',flexDirection:'column',gap:'3px'}}>
            {FUENTES.map(f=>(
              <button key={f.id} onClick={()=>setFuente(f.id)}
                style={{...calcStyles2.chip,textAlign:'left',padding:'5px 10px',
                  ...(fuente===f.id?calcStyles2.chipAct:{})}}>
                <span style={{fontFamily:f.family,fontStyle:f.style,
                  fontWeight:f.weight||'400',letterSpacing:f.spacing,fontSize:'13px'}}>
                  {f.label} — Ej: {texto||'Para siempre'}
                </span>
              </button>
            ))}
          </div>
        </div>

        <div style={S.grupo}>
          <div style={{display:'flex',justifyContent:'space-between',marginBottom:'5px'}}>
            <div style={S.label}>Tamaño texto</div>
            <span style={{color:'var(--gold)',fontSize:'11px',fontWeight:600}}>{tamano}pt</span>
          </div>
          <input type="range" min="8" max="20" step="1" value={tamano}
            onChange={e=>setTamano(parseInt(e.target.value))}
            style={{width:'100%',accentColor:'var(--gold)'}}/>
        </div>

        <div style={S.grupo}>
          <div style={S.label}>Profundidad de grabado</div>
          <div style={{display:'flex',gap:'5px'}}>
            {['Leve','Media','Profunda'].map(p=>(
              <button key={p} onClick={()=>setProfundidad(p)}
                style={{...calcStyles2.chip,flex:1,textAlign:'center',...(profundidad===p?calcStyles2.chipAct:{})}}>
                {p}
              </button>
            ))}
          </div>
          <div style={{fontSize:'9px',color:'var(--cream-3)',marginTop:'3px'}}>
            {profundidad==='Leve'?'Marcado superficial, uso diario':profundidad==='Profunda'?'Grabado permanente de alta durabilidad':'Estándar para uso habitual'}
          </div>
        </div>

        <div style={S.grupo}>
          <div style={S.label}>Texto a grabar ({texto.length}/30)</div>
          <input style={{...calcStyles2.input,fontSize:'13px'}}
            placeholder="Ej: Para siempre · 14.02.2026"
            value={texto} onChange={e=>setTexto(e.target.value.slice(0,30))}
            maxLength={30}/>
          {texto.length>24&&<div style={{fontSize:'9px',color:'#f39c12',marginTop:'2px'}}>
            ⚠ Texto largo — considera reducir tamaño o usar 2 líneas
          </div>}
        </div>

        {/* Precio */}
        <div style={{background:'var(--bg-card)',border:'1px solid var(--border)',
          borderRadius:'10px',padding:'12px',marginTop:'4px'}}>
          <div style={{fontSize:'10px',color:'var(--cream-3)',marginBottom:'6px',fontWeight:600}}>
            PRECIO DEL SERVICIO
          </div>
          <div style={{display:'flex',justifyContent:'space-between',fontSize:'11px',marginBottom:'3px'}}>
            <span style={{color:'var(--cream-3)'}}>Base ({material})</span>
            <span style={{color:'var(--cream)'}}>{clp(precioBase)}</span>
          </div>
          {precioExtra>0&&<div style={{display:'flex',justifyContent:'space-between',fontSize:'11px',marginBottom:'3px'}}>
            <span style={{color:'var(--cream-3)'}}>Doble posición</span>
            <span style={{color:'var(--cream)'}}>{clp(precioExtra)}</span>
          </div>}
          <div style={{display:'flex',justifyContent:'space-between',fontWeight:700,fontSize:'18px',
            borderTop:'1px solid var(--border)',paddingTop:'7px',marginTop:'7px'}}>
            <span style={{color:'var(--cream)'}}>Total</span>
            <span style={{color:'var(--gold)'}}>{clp(precioTotal)}</span>
          </div>
        </div>

        <button onClick={()=>setModal(true)}
          style={{...posStyles.cobrarBtn,width:'100%',marginTop:'12px',fontSize:'12px'}}>
          ✦ Crear Pedido de Grabado
        </button>
      </div>

      {/* Preview Canvas */}
      <div style={{flex:1,display:'flex',flexDirection:'column',overflow:'hidden',
        borderRight:'1px solid var(--border)'}}>
        <div style={{padding:'12px 14px',borderBottom:'1px solid var(--border)',
          display:'flex',justifyContent:'space-between',alignItems:'center'}}>
          <div style={{fontFamily:'Cormorant Garamond,serif',fontSize:'16px',fontWeight:600,color:'var(--cream)'}}>
            Vista Previa — Cómo quedará el grabado
          </div>
          <span style={{fontSize:'10px',color:'var(--cream-3)'}}>
            Preview referencial — el grabado real puede variar levemente
          </span>
        </div>
        <div style={{flex:1,display:'flex',alignItems:'center',justifyContent:'center',
          background:'#0e0b08',position:'relative'}}>
          <canvas ref={canvasRef} width={420} height={380}
            style={{borderRadius:'12px',boxShadow:'0 4px 24px rgba(0,0,0,0.6)'}}/>
          {/* Overlay info */}
          <div style={{position:'absolute',bottom:'16px',left:'50%',transform:'translateX(-50%)',
            background:'rgba(0,0,0,0.6)',backdropFilter:'blur(4px)',
            padding:'5px 14px',borderRadius:'20px',fontSize:'10px',color:'var(--cream-3)'}}>
            {tipoPieza} · {material} · Grabado {posicion.toLowerCase()}
          </div>
        </div>
        {/* Muestra tipografías */}
        <div style={{padding:'12px 16px',borderTop:'1px solid var(--border)',
          background:'var(--bg-card)',display:'flex',gap:'12px',overflowX:'auto',scrollbarWidth:'none'}}>
          {FUENTES.map(f=>(
            <div key={f.id} style={{flexShrink:0,textAlign:'center',
              cursor:'pointer',padding:'6px 10px',borderRadius:'6px',
              background:fuente===f.id?'var(--gold-dim)':'transparent',
              border:fuente===f.id?'1px solid var(--gold)':'1px solid transparent'}}
              onClick={()=>setFuente(f.id)}>
              <div style={{fontFamily:f.family,fontStyle:f.style,fontWeight:f.weight||'400',
                letterSpacing:f.spacing,fontSize:'14px',color:'var(--cream)',marginBottom:'2px'}}>
                {texto||'Navarro'}
              </div>
              <div style={{fontSize:'9px',color:'var(--cream-3)'}}>{f.label}</div>
            </div>
          ))}
        </div>
      </div>

      {/* Pedidos */}
      <div style={S.pedidosCol}>
        <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',
          marginBottom:'10px',paddingBottom:'8px',borderBottom:'1px solid var(--border)'}}>
          <div style={{fontFamily:'Cormorant Garamond,serif',fontSize:'15px',fontWeight:600}}>
            Pedidos
          </div>
          <span style={{fontSize:'10px',color:'var(--cream-3)'}}>{pedidos.length} registros</span>
        </div>
        {pedidos.length===0&&(
          <div style={{textAlign:'center',color:'var(--cream-3)',padding:'24px',fontSize:'11px'}}>
            <div style={{fontSize:'24px',marginBottom:'6px'}}>✨</div>
            Sin pedidos aún.<br/>Crea el primero con el formulario.
          </div>
        )}
        {pedidos.map(p=>(
          <div key={p.id} style={{background:'var(--surface)',borderRadius:'9px',padding:'10px',
            marginBottom:'6px',border:'1px solid var(--border)'}}>
            <div style={{display:'flex',justifyContent:'space-between',marginBottom:'4px'}}>
              <span style={{color:'var(--cream)',fontWeight:500,fontSize:'11px'}}>{p.cliente}</span>
              <span style={estadoBadge(p.estado)}>{p.estado}</span>
            </div>
            <div style={{fontFamily:FUENTES.find(f=>f.id===p.fuente)?.family||'Inter',
              fontStyle:FUENTES.find(f=>f.id===p.fuente)?.style||'normal',
              fontSize:'12px',color:'var(--gold)',marginBottom:'5px',
              background:'var(--bg-card)',padding:'5px 7px',borderRadius:'5px',
              border:'1px solid var(--border)'}}>
              "{p.texto}"
            </div>
            <div style={{color:'var(--cream-3)',fontSize:'9px',lineHeight:'1.7'}}>
              {p.pieza} · {p.material} · {p.posicion}<br/>
              {p.id} · {p.fecha}
            </div>
            <div style={{display:'flex',justifyContent:'space-between',marginTop:'5px'}}>
              <span style={{color:'var(--gold)',fontWeight:700,fontSize:'12px'}}>{clp(p.precio)}</span>
              <div style={{display:'flex',gap:'4px'}}>
                <button onClick={()=>imprimirReciboTaller({
                  titulo:'PEDIDO GRABADO LÁSER', folio:p.id, fecha:p.fecha,
                  cliente:p.cliente, tienda:'Navarro Joyería',
                  items:[
                    {label:`${p.pieza} · ${p.material}`,detalle:`Posición: ${p.posicion}`},
                    {label:`Tipografía: ${p.fuente} · ${p.tamano}pt · ${p.profundidad}`,detalle:`Texto: "${p.texto}"`},
                  ],
                  total:p.precio, notas:p.notas||null, fechaEntrega:p.entrega||null,
                })} style={{padding:'2px 7px',background:'var(--surface-2)',border:'1px solid var(--border)',borderRadius:'4px',color:'var(--cream-3)',cursor:'pointer',fontSize:'9px'}}>
                  🖨
                </button>
                <button onClick={()=>setPedidos(prev=>{
                  const l=prev.map(x=>x.id===p.id?{...x,estado:'Listo'}:x);
                  lsSet('grabados',l); return l;
                })} style={{padding:'2px 7px',background:'var(--surface-2)',border:'1px solid var(--border)',
                  borderRadius:'4px',color:'var(--cream-3)',cursor:'pointer',fontSize:'9px'}}>
                  → Listo
                </button>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Modal nuevo pedido */}
      {modalNuevo&&(
        <div style={posStyles.overlay} onClick={e=>e.target===e.currentTarget&&setModal(false)}>
          <div style={{...posStyles.modalBox,maxWidth:'360px'}}>
            <div style={{...posStyles.modalHeader,marginBottom:'14px'}}>
              <span style={{fontFamily:'Cormorant Garamond,serif',fontSize:'19px',fontWeight:600}}>
                Nuevo Pedido Grabado
              </span>
              <button onClick={()=>setModal(false)} style={posStyles.clearBtn}>✕</button>
            </div>
            <div style={{marginBottom:'10px'}}>
              <div style={{fontSize:'10px',color:'var(--cream-3)',marginBottom:'3px'}}>Cliente</div>
              <input style={posStyles.clienteInput} placeholder="Nombre del cliente"
                value={nuevoCliente} onChange={e=>setNuevoCliente(e.target.value)}/>
            </div>
            <div style={{background:'var(--surface)',borderRadius:'8px',padding:'10px',
              marginBottom:'12px',fontSize:'11px',color:'var(--cream-2)',lineHeight:'1.8'}}>
              <div style={{color:'var(--cream)',fontWeight:500,marginBottom:'3px'}}>Resumen:</div>
              <div>{tipoPieza} · {material} · {posicion}</div>
              <div>Tipografía: {fuente} · {tamano}pt · {profundidad}</div>
              <div style={{fontFamily:fuenteAct.family,fontStyle:fuenteAct.style,
                color:'var(--gold)',marginTop:'3px',fontSize:'13px'}}>
                "{texto||'(sin texto)'}"
              </div>
            </div>
            <div style={{display:'flex',justifyContent:'space-between',fontWeight:700,
              fontSize:'17px',marginBottom:'14px'}}>
              <span style={{color:'var(--cream)'}}>Total</span>
              <span style={{color:'var(--gold)'}}>{clp(precioTotal)}</span>
            </div>
            <button onClick={crearPedido}
              style={{...posStyles.cobrarBtn,width:'100%',margin:0,
                ...((!texto||!nuevoCliente)?{opacity:0.4,cursor:'not-allowed'}:{})}}>
              ✦ Confirmar Pedido
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

// Estilos compartidos para calculadora (renombrados para no colisionar)
const calcStyles2 = {
  chip:{padding:'4px 10px',borderRadius:'20px',border:'1px solid var(--border)',
    background:'var(--surface)',color:'var(--cream-3)',fontSize:'11px',cursor:'pointer',
    fontFamily:'Inter,sans-serif'},
  chipAct:{background:'var(--gold-dim)',border:'1px solid var(--gold)',color:'var(--gold)',fontWeight:600},
  input:{width:'100%',background:'var(--surface)',border:'1px solid var(--border)',
    borderRadius:'8px',padding:'8px 11px',color:'var(--cream)',fontSize:'14px',outline:'none'},
};

const grabStyles = {
  leftCol:{width:'300px',overflowY:'auto',padding:'16px',borderRight:'1px solid var(--border)',flexShrink:0},
  pedidosCol:{width:'240px',overflowY:'auto',padding:'14px',flexShrink:0},
  grupo:{marginBottom:'14px'},
  label:{fontSize:'10px',color:'var(--cream-3)',fontWeight:600,textTransform:'uppercase',
    letterSpacing:'0.5px',marginBottom:'6px'},
};

Object.assign(window,{GrabadoLaser,calcStyles2});
