// ── HECHURAS EXCLUSIVAS ───────────────────────────────

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

  const [hechuras, setHechuras] = useState([
    { id:'HE-001', cliente:'Carlos Errázuriz', tipo:'Anillo sello', descripcion:'Anillo sello con escudo familiar grabado y diamante central 0.5ct',
      metal:'Oro 18K', presupuesto:890000, senal:400000, estado:'En proceso',
      tecnico:'Don Pedro', ingreso:'2026-04-10', entrega:'2026-05-20', urgente:false,
      etapas:[{n:'Diseño aprobado',ok:true},{n:'Fundición',ok:true},{n:'Forjado',ok:false},{n:'Pulido',ok:false},{n:'Montaje piedra',ok:false},{n:'Control calidad',ok:false}] },
    { id:'HE-002', cliente:'Sofía Larraín', tipo:'Collar personalizado', descripcion:'Collar gargantilla con 7 colgantes de la colección Viñas en escala',
      metal:'Plata 925 + Turquesa', presupuesto:320000, senal:150000, estado:'Recibido',
      tecnico:'Don Pedro', ingreso:'2026-04-18', entrega:'2026-05-30', urgente:false,
      etapas:[{n:'Diseño aprobado',ok:false},{n:'Fundición',ok:false},{n:'Forjado',ok:false},{n:'Pulido',ok:false},{n:'Montaje piedra',ok:false},{n:'Control calidad',ok:false}] },
    { id:'HE-003', cliente:'Rodrigo Fuentes', tipo:'Brazalete colección Casino', descripcion:'Brazalete articulado exclusivo con 9 fichas N grabadas en relieve',
      metal:'Oro 18K', presupuesto:1250000, senal:600000, estado:'Listo',
      tecnico:'Don Pedro', ingreso:'2026-03-15', entrega:'2026-04-30', urgente:false,
      etapas:[{n:'Diseño aprobado',ok:true},{n:'Fundición',ok:true},{n:'Forjado',ok:true},{n:'Pulido',ok:true},{n:'Montaje piedra',ok:true},{n:'Control calidad',ok:true}] },
  ]);
  const [selId, setSel] = useState('HE-001');
  const [modalNuevo, setModal] = useState(false);
  const [nuevo, setNuevo] = useState({
    cliente:'', rut:'', telefono:'', tipo:'', descripcion:'', metal:'Oro 18K',
    presupuesto:0, senal:0, tecnico:'Don Pedro',
    entrega:'', urgente:false, notas:''
  });

  const selH = hechuras.find(h=>h.id===selId);

  function toggleEtapa(hId, idx) {
    setHechuras(prev=>prev.map(h=>{
      if(h.id!==hId) return h;
      const e=[...h.etapas];
      e[idx]={...e[idx],ok:!e[idx].ok};
      let estado=h.estado;
      const pct=e.filter(x=>x.ok).length/e.length;
      if(pct===0) estado='Recibido';
      else if(pct<1) estado='En proceso';
      else estado='Listo';
      return {...h,etapas:e,estado};
    }));
  }

  function crearHechura() {
    const id=`HE-${String(hechuras.length+1).padStart(3,'0')}`;
    const nueva = {
      ...nuevo, id, estado:'Recibido', ingreso:new Date().toISOString().slice(0,10),
      etapas:[
        {n:'Diseño aprobado',ok:false},{n:'Fundición',ok:false},{n:'Forjado',ok:false},
        {n:'Pulido',ok:false},{n:'Montaje piedra',ok:false},{n:'Control calidad',ok:false}
      ]
    };
    setHechuras(prev=>[...prev, nueva]);
    setSel(id); setModal(false);
    setNuevo({cliente:'',tipo:'',descripcion:'',metal:'Oro 18K',presupuesto:0,senal:0,tecnico:'Don Pedro',entrega:'',urgente:false,notas:''});
    // Imprimir recibo automático
    imprimirReciboTaller({
      titulo:'ORDEN HECHURA EXCLUSIVA', folio:id, fecha:new Date().toISOString().slice(0,10),
      cliente:nuevo.cliente, tienda: TIENDAS.find(t=>t.id==='navarro')?.nombre||'Navarro',
      items:[
        {label:nuevo.tipo, detalle:nuevo.descripcion},
        {label:`Metal: ${nuevo.metal}`, detalle:''},
      ],
      total:nuevo.presupuesto, senal:nuevo.senal,
      saldo:nuevo.presupuesto-nuevo.senal,
      tecnico:nuevo.tecnico, fechaEntrega:nuevo.entrega, notas:nuevo.notas||null,
    });
  }

  const TIPOS = ['Anillo sello','Collar personalizado','Brazalete','Pulsera','Aretes únicos',
    'Colgante escultural','Broche','Joya escultural','Otro encargo'];

  const S = hecStyles;

  return (
    <div style={{display:'flex',height:'100%',overflow:'hidden'}}>
      {/* Lista */}
      <div style={S.lista}>
        <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',
          padding:'14px 14px 10px',borderBottom:'1px solid var(--border)'}}>
          <div style={{fontFamily:'Cormorant Garamond,serif',fontSize:'18px',fontWeight:600}}>
            Hechuras Exclusivas
          </div>
          <button onClick={()=>setModal(true)} style={invStyles.btnAdd}>+ Nueva</button>
        </div>

        {/* Stats */}
        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:'1px',
          background:'var(--border)',borderBottom:'1px solid var(--border)'}}>
          {[
            {l:'En producción', v:hechuras.filter(h=>h.estado==='En proceso').length},
            {l:'Valor total',   v:clp(hechuras.filter(h=>h.estado!=='Entregado').reduce((s,h)=>s+h.presupuesto,0))},
          ].map(s=>(
            <div key={s.l} style={{background:'var(--bg-card)',padding:'10px',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>

        <div style={{flex:1,overflowY:'auto'}}>
          {hechuras.map(h=>{
            const pct=Math.round(h.etapas.filter(e=>e.ok).length/h.etapas.length*100);
            return (
              <div key={h.id} onClick={()=>setSel(h.id)}
                style={{...S.hecCard,...(selId===h.id?S.hecCardSel:{})}}>
                <div style={{display:'flex',justifyContent:'space-between',marginBottom:'4px'}}>
                  <span style={{color:'var(--cream)',fontWeight:500,fontSize:'13px'}}>{h.cliente}</span>
                  <span style={estadoBadge(h.estado)}>{h.estado}</span>
                </div>
                <div style={{color:'var(--cream-3)',fontSize:'11px',marginBottom:'8px'}}>{h.tipo}</div>
                {/* Progress bar */}
                <div style={{height:'4px',background:'var(--surface)',borderRadius:'2px',overflow:'hidden',marginBottom:'4px'}}>
                  <div style={{height:'100%',width:`${pct}%`,
                    background:pct===100?'#27ae60':'var(--gold)',
                    borderRadius:'2px',transition:'width 0.4s'}}/>
                </div>
                <div style={{display:'flex',justifyContent:'space-between',fontSize:'10px'}}>
                  <span style={{color:'var(--cream-3)'}}>{pct}% completado</span>
                  <div style={{display:'flex',gap:'4px',alignItems:'center'}}>
                    <span style={{color:'var(--gold)',fontWeight:600}}>{clp(h.presupuesto)}</span>
                    <button onClick={e=>{e.stopPropagation();imprimirReciboTaller({
                      titulo:'ORDEN HECHURA EXCLUSIVA', folio:h.id, fecha:h.ingreso,
                      cliente:h.cliente, tienda:TIENDAS[0].nombre,
                      items:[{label:h.tipo,detalle:h.descripcion},{label:`Metal: ${h.metal}`,detalle:''}],
                      total:h.presupuesto, senal:h.senal, saldo:h.presupuesto-h.senal,
                      tecnico:h.tecnico, fechaEntrega:h.entrega, notas:h.notas||null,
                    });}} style={{padding:'1px 5px',background:'var(--surface-2)',border:'1px solid var(--border)',borderRadius:'3px',color:'var(--cream-3)',cursor:'pointer',fontSize:'9px',lineHeight:'1.4'}}>
                      🖨
                    </button>
                  </div>
                </div>
                {h.urgente&&<div style={{fontSize:'9px',color:'#c0392b',fontWeight:700,marginTop:'4px'}}>🔴 URGENTE</div>}
              </div>
            );
          })}
        </div>
      </div>

      {/* Detalle */}
      {selH && (
        <div style={{flex:1,overflowY:'auto',padding:'24px'}}>
          <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',marginBottom:'20px'}}>
            <div>
              <div style={{fontFamily:'Cormorant Garamond,serif',fontSize:'24px',fontWeight:600,
                color:'var(--cream)',marginBottom:'4px'}}>{selH.tipo}</div>
              <div style={{color:'var(--cream-3)',fontSize:'12px'}}>{selH.id} · {selH.cliente}</div>
            </div>
            <span style={estadoBadge(selH.estado)}>{selH.estado}</span>
          </div>

          {/* Info grid */}
          <div style={{display:'grid',gridTemplateColumns:'repeat(4,1fr)',gap:'8px',marginBottom:'20px'}}>
            {[
              {l:'Metal',       v:selH.metal},
              {l:'Artesano',     v:selH.tecnico},
              {l:'Ingreso',     v:selH.ingreso},
              {l:'Entrega',     v:selH.entrega},
            ].map(f=>(
              <div key={f.l} style={{background:'var(--bg-card)',border:'1px solid var(--border)',
                borderRadius:'8px',padding:'10px'}}>
                <div style={{fontSize:'10px',color:'var(--cream-3)',marginBottom:'2px'}}>{f.l}</div>
                <div style={{color:'var(--cream)',fontSize:'12px',fontWeight:500}}>{f.v}</div>
              </div>
            ))}
          </div>

          {/* Descripción */}
          <div style={{background:'var(--surface)',borderRadius:'10px',padding:'16px',
            marginBottom:'20px',borderLeft:'2px solid var(--gold)'}}>
            <div style={{fontSize:'11px',color:'var(--cream-3)',marginBottom:'6px'}}>DESCRIPCIÓN</div>
            <div style={{color:'var(--cream-2)',fontSize:'13px',lineHeight:'1.7'}}>{selH.descripcion}</div>
          </div>

          {/* Financiero */}
          <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:'8px',marginBottom:'20px'}}>
            {[
              {l:'Presupuesto',   v:clp(selH.presupuesto), c:'var(--gold)'},
              {l:'Abono recibido',v:clp(selH.senal),       c:'#27ae60'},
              {l:'Saldo pendiente',v:clp(selH.presupuesto-selH.senal),c:selH.presupuesto-selH.senal>0?'#f39c12':'#27ae60'},
            ].map(f=>(
              <div key={f.l} style={{background:'var(--bg-card)',border:'1px solid var(--border)',
                borderRadius:'10px',padding:'14px',textAlign:'center'}}>
                <div style={{color:f.c,fontWeight:700,fontSize:'18px'}}>{f.v}</div>
                <div style={{color:'var(--cream-3)',fontSize:'10px',marginTop:'2px'}}>{f.l}</div>
              </div>
            ))}
          </div>

          {/* Etapas de producción */}
          <div style={{background:'var(--bg-card)',border:'1px solid var(--border)',
            borderRadius:'12px',padding:'16px',marginBottom:'20px'}}>
            <div style={{fontFamily:'Cormorant Garamond,serif',fontSize:'16px',fontWeight:600,
              color:'var(--cream)',marginBottom:'14px'}}>Proceso de Producción</div>

            <div style={{position:'relative'}}>
              {/* Línea conectora */}
              <div style={{position:'absolute',left:'11px',top:'12px',width:'2px',
                height:`${(selH.etapas.length-1)*52}px`,background:'var(--border)'}}/>
              {selH.etapas.map((e,i)=>(
                <div key={i} style={{display:'flex',alignItems:'center',gap:'12px',
                  marginBottom:'14px',position:'relative',zIndex:1}}>
                  <button onClick={()=>toggleEtapa(selH.id,i)}
                    style={{width:'24px',height:'24px',borderRadius:'50%',flexShrink:0,
                      background:e.ok?'var(--gold)':'var(--surface)',
                      border:`2px solid ${e.ok?'var(--gold)':'var(--border)'}`,
                      cursor:'pointer',display:'flex',alignItems:'center',justifyContent:'center',
                      fontSize:'12px',color:'#0c0908',transition:'all 0.2s'}}>
                    {e.ok?'✓':''}
                  </button>
                  <div style={{flex:1}}>
                    <span style={{color:e.ok?'var(--cream)':'var(--cream-3)',fontSize:'13px',
                      textDecoration:e.ok?'none':'none',fontWeight:e.ok?500:400}}>
                      {e.n}
                    </span>
                  </div>
                  {e.ok&&<span style={{fontSize:'10px',color:'var(--gold)'}}>✦</span>}
                </div>
              ))}
            </div>

            {/* Progreso total */}
            <div style={{marginTop:'8px'}}>
              <div style={{display:'flex',justifyContent:'space-between',fontSize:'11px',
                color:'var(--cream-3)',marginBottom:'6px'}}>
                <span>Progreso total</span>
                <span>{selH.etapas.filter(e=>e.ok).length}/{selH.etapas.length} etapas</span>
              </div>
              <div style={{height:'6px',background:'var(--surface)',borderRadius:'3px',overflow:'hidden'}}>
                <div style={{height:'100%',transition:'width 0.4s',borderRadius:'3px',
                  width:`${Math.round(selH.etapas.filter(e=>e.ok).length/selH.etapas.length*100)}%`,
                  background:selH.etapas.every(e=>e.ok)?'#27ae60':'var(--gold)'}}/>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Modal nueva hechura */}
      {modalNuevo && (
        <div style={posStyles.overlay} onClick={e=>e.target===e.currentTarget&&setModal(false)}>
          <div style={{...posStyles.modalBox,maxWidth:'500px'}}>
            <div style={{...posStyles.modalHeader,marginBottom:'16px'}}>
              <span style={{fontFamily:'Cormorant Garamond,serif',fontSize:'22px',fontWeight:600}}>
                Nueva Hechura Exclusiva
              </span>
              <button onClick={()=>setModal(false)} style={posStyles.clearBtn}>✕</button>
            </div>

            {/* Búsqueda de cliente */}
            <div style={{marginBottom:'12px'}}>
              <div style={{fontSize:'11px',color:'var(--cream-3)',marginBottom:'4px'}}>Buscar cliente guardado</div>
              <div style={{position:'relative'}}>
                <input style={{...calcStyles.input,fontSize:'12px'}}
                  placeholder="Nombre o RUT del cliente…"
                  onChange={e=>{
                    const q=e.target.value.toLowerCase();
                    const clts=lsGet('clientes',[]);
                    const found=clts.find(c=>c.nombre?.toLowerCase().includes(q)||c.rut?.includes(q));
                    if(found) setNuevo(n=>({...n,cliente:found.nombre,rut:found.rut||'',telefono:found.whatsapp||''}));
                  }}/>
                <div style={{fontSize:'9px',color:'var(--cream-3)',marginTop:'3px'}}>Al escribir, autocompleta desde clientes guardados</div>
              </div>
            </div>

            <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:'10px'}}>
              {[
                {l:'Cliente',    k:'cliente',     t:'text',   ph:'Nombre del cliente'},
                {l:'RUT',        k:'rut',         t:'text',   ph:'12.345.678-9'},
                {l:'Tel/WhatsApp',k:'telefono',   t:'text',   ph:'+56 9 xxxx xxxx'},
                {l:'Entrega',    k:'entrega',     t:'date',   ph:''},
                {l:'Presupuesto',k:'presupuesto', t:'number', ph:'0'},
                {l:'Abono',      k:'senal',       t:'number', ph:'0'},
              ].map(f=>(
                <div key={f.k}>
                  <div style={{fontSize:'11px',color:'var(--cream-3)',marginBottom:'4px'}}>{f.l}</div>
                  <input type={f.t} placeholder={f.ph} style={calcStyles.input}
                    value={nuevo[f.k]||''} onChange={e=>setNuevo(n=>({...n,[f.k]:f.t==='number'?parseInt(e.target.value)||0:e.target.value}))}/>
                </div>
              ))}
              <div>
                <div style={{fontSize:'11px',color:'var(--cream-3)',marginBottom:'4px'}}>Tipo de pieza</div>
                <select style={{...invStyles.select,width:'100%'}} value={nuevo.tipo}
                  onChange={e=>setNuevo(n=>({...n,tipo:e.target.value}))}>
                  <option value="">Seleccionar…</option>
                  {TIPOS.map(t=><option key={t}>{t}</option>)}
                </select>
              </div>
              <div>
                <div style={{fontSize:'11px',color:'var(--cream-3)',marginBottom:'4px'}}>Metal</div>
                <select style={{...invStyles.select,width:'100%'}} value={nuevo.metal}
                  onChange={e=>setNuevo(n=>({...n,metal:e.target.value}))}>
                  {METALES.map(m=><option key={m}>{m}</option>)}
                </select>
              </div>
              <div>
                <div style={{fontSize:'11px',color:'var(--cream-3)',marginBottom:'4px'}}>Artesano</div>
                <select style={{...invStyles.select,width:'100%'}} value={nuevo.tecnico}
                  onChange={e=>setNuevo(n=>({...n,tecnico:e.target.value}))}>
                  {TECNICOS.map(t=><option key={t}>{t}</option>)}
                </select>
              </div>
              <div>
                <div style={{fontSize:'11px',color:'var(--cream-3)',marginBottom:'4px'}}>Urgente</div>
                <button onClick={()=>setNuevo(n=>({...n,urgente:!n.urgente}))}
                  style={{...posStyles.descBtn,...(nuevo.urgente?posStyles.descBtnActive:{}),width:'100%',padding:'8px'}}>
                  {nuevo.urgente ? '🔴 Urgente' : 'Normal'}
                </button>
              </div>
              <div style={{gridColumn:'1/-1'}}>
                <div style={{fontSize:'11px',color:'var(--cream-3)',marginBottom:'4px'}}>Descripción detallada</div>
                <textarea style={{...calcStyles.input,height:'70px'}} placeholder="Describe la pieza a fabricar…"
                  value={nuevo.descripcion} onChange={e=>setNuevo(n=>({...n,descripcion:e.target.value}))}/>
              </div>
            </div>
            {nuevo.presupuesto>0&&(
              <div style={{background:'var(--surface)',borderRadius:'8px',padding:'10px',margin:'10px 0',display:'flex',justifyContent:'space-between',fontSize:'12px'}}>
                <span style={{color:'var(--cream-3)'}}>Saldo a pagar</span>
                <span style={{color:'var(--gold)',fontWeight:700}}>{clp(nuevo.presupuesto-(nuevo.senal||0))}</span>
              </div>
            )}
            <button onClick={crearHechura}
              style={{...posStyles.cobrarBtn,width:'100%',marginTop:'8px'}}>
              ✦ Crear Hechura + Imprimir Ticket
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

const hecStyles = {
  lista:{ width:'300px', display:'flex', flexDirection:'column',
    borderRight:'1px solid var(--border)', overflow:'hidden', flexShrink:0 },
  hecCard:{ padding:'12px 14px', borderBottom:'1px solid var(--border)',
    cursor:'pointer', transition:'background 0.1s' },
  hecCardSel:{ background:'rgba(201,168,76,0.06)', borderLeft:'2px solid var(--gold)' },
};

Object.assign(window, { Hechuras });
