// ── PEDIDOS CATÁLOGO ─────────────────────────────────

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

  const [pedidos,   setPedidos]   = useState(() => lsGet('pedidos_catalogo', []));
  const [selId,     setSel]       = useState(null);
  const [modal,     setModal]     = useState(false);
  const [busqueda,  setBusqueda]  = useState('');
  const [filtroEst, setFiltroEst] = useState('Todos');
  const fileRef = useRef();

  const ESTADOS = ['Buscando','Encontrado','Presentado al cliente','Comprado','Vendido','Cancelado'];
  const TIPOS   = ['Anillo','Argolla','Aros','Collar','Pulsera','Colgante','Prendedor','Otro'];
  const COLOR_EST = {
    'Buscando':'#f39c12','Encontrado':'#2980b9','Presentado al cliente':'#8e44ad',
    'Comprado':'#27ae60','Vendido':'#c9a84c','Cancelado':'var(--cream-3)'
  };

  const [nuevo, setNuevo] = useState({
    cliente:'', rut:'', telefono:'', email:'',
    tipo:'Anillo', descripcion:'', links:'', medidas:'',
    metal:'', presupuesto:0, estado:'Buscando',
    observaciones:'', foto_url:'', fechaIngreso: hoy(),
  });

  function set(k, v) { setNuevo(n => ({ ...n, [k]: v })); }

  function guardar() {
    const id = `PC-${Date.now().toString().slice(-5)}`;
    const p  = { ...nuevo, id, fechaIngreso: hoy() };
    const nuevos = [p, ...pedidos];
    setPedidos(nuevos); lsSet('pedidos_catalogo', nuevos);
    setModal(false);
    setSel(id);
    setNuevo({ cliente:'', rut:'', telefono:'', email:'', tipo:'Anillo', descripcion:'', links:'', medidas:'', metal:'', presupuesto:0, estado:'Buscando', observaciones:'', foto_url:'', fechaIngreso:hoy() });
  }

  function cambiarEstado(id, est) {
    const upd = pedidos.map(p => p.id===id ? {...p, estado:est} : p);
    setPedidos(upd); lsSet('pedidos_catalogo', upd);
  }

  function handleFoto(e) {
    const f = e.target.files[0]; if (!f) return;
    const r = new FileReader();
    r.onload = ev => set('foto_url', ev.target.result);
    r.readAsDataURL(f);
  }

  const filtrados = pedidos.filter(p => {
    const q = busqueda.toLowerCase();
    const matchQ = !q || p.cliente?.toLowerCase().includes(q) || p.descripcion?.toLowerCase().includes(q) || p.tipo?.toLowerCase().includes(q);
    const matchE = filtroEst==='Todos' || p.estado===filtroEst;
    return matchQ && matchE;
  });

  const sel = pedidos.find(p => p.id === selId);

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

      {/* Lista */}
      <div style={{ width:'300px', flexShrink:0, display:'flex', flexDirection:'column', borderRight:'1px solid var(--border)', overflow:'hidden' }}>
        <div style={{ padding:'10px 12px', borderBottom:'1px solid var(--border)' }}>
          <div style={{ fontFamily:'Cormorant Garamond,serif', fontSize:'16px', fontWeight:600, color:'var(--cream)', marginBottom:'7px' }}>Pedidos Catálogo</div>
          <input style={{ ...inv2Styles.searchInput, width:'100%', marginBottom:'6px' }}
            placeholder="Buscar cliente o joya…" value={busqueda} onChange={e => setBusqueda(e.target.value)}/>
          <div style={{ display:'flex', gap:'4px', flexWrap:'wrap' }}>
            {['Todos', ...ESTADOS].map(e => (
              <button key={e} onClick={() => setFiltroEst(e)}
                style={{ padding:'2px 7px', borderRadius:'20px', border:'1px solid var(--border)', fontSize:'9px', cursor:'pointer', fontFamily:'Inter,sans-serif',
                  background: filtroEst===e ? 'var(--gold-dim)' : 'transparent',
                  color: filtroEst===e ? 'var(--gold)' : 'var(--cream-3)' }}>
                {e}
              </button>
            ))}
          </div>
        </div>
        <div style={{ flex:1, overflowY:'auto', padding:'6px' }}>
          {filtrados.length === 0 && (
            <div style={{ textAlign:'center', color:'var(--cream-3)', padding:'24px', fontSize:'11px' }}>
              <div style={{ fontSize:'28px', marginBottom:'8px' }}>🔍</div>
              {pedidos.length === 0 ? 'Sin pedidos todavía' : 'Sin resultados'}
            </div>
          )}
          {filtrados.map(p => (
            <div key={p.id} onClick={() => setSel(p.id===selId ? null : p.id)}
              style={{ padding:'10px', background: selId===p.id?'rgba(201,168,76,0.07)':'var(--surface)', border:`1px solid ${selId===p.id?'var(--gold)':'var(--border)'}`, borderRadius:'8px', marginBottom:'5px', cursor:'pointer' }}>
              <div style={{ display:'flex', justifyContent:'space-between', marginBottom:'3px' }}>
                <span style={{ color:'var(--cream)', fontWeight:600, fontSize:'12px' }}>{p.cliente}</span>
                <span style={{ padding:'1px 6px', borderRadius:'20px', fontSize:'9px', fontWeight:600, background: COLOR_EST[p.estado]+'22', color: COLOR_EST[p.estado] }}>
                  {p.estado}
                </span>
              </div>
              <div style={{ color:'var(--cream-3)', fontSize:'10px', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>
                {p.tipo} {p.metal?'· '+p.metal:''} {p.presupuesto?'· '+clp(p.presupuesto):''}
              </div>
              <div style={{ color:'var(--cream-3)', fontSize:'9px', marginTop:'2px' }}>{p.fechaIngreso} · {p.id}</div>
            </div>
          ))}
        </div>
        <div style={{ padding:'8px', borderTop:'1px solid var(--border)' }}>
          <button onClick={() => setModal(true)}
            style={{ ...posStyles.cobrarBtn, width:'100%', margin:0, fontSize:'12px' }}>
            + Nuevo Pedido Catálogo
          </button>
        </div>
      </div>

      {/* Detalle */}
      <div style={{ flex:1, overflowY:'auto', padding:'18px' }}>
        {!sel && (
          <div style={{ display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', height:'100%', color:'var(--cream-3)', gap:'12px' }}>
            <div style={{ fontSize:'44px', opacity:0.2 }}>🔍</div>
            <div style={{ fontSize:'13px', textAlign:'center', maxWidth:'280px', lineHeight:'1.7' }}>
              Registra solicitudes de clientes que buscan una joya específica.<br/>
              <span style={{ fontSize:'11px' }}>Cada semana puedes buscar joyas similares para comprar y ofrecer.</span>
            </div>
          </div>
        )}
        {sel && (
          <div className="fade-in">
            <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:'16px' }}>
              <div>
                <div style={{ fontFamily:'Cormorant Garamond,serif', fontSize:'22px', fontWeight:600, color:'var(--cream)' }}>{sel.cliente}</div>
                <div style={{ color:'var(--cream-3)', fontSize:'11px' }}>{sel.id} · {sel.fechaIngreso}</div>
              </div>
              <div style={{ display:'flex', gap:'6px', flexWrap:'wrap' }}>
                {ESTADOS.map(e => (
                  <button key={e} onClick={() => cambiarEstado(sel.id, e)}
                    style={{ padding:'4px 10px', borderRadius:'20px', border:'1px solid var(--border)', fontSize:'10px', cursor:'pointer', fontFamily:'Inter,sans-serif',
                      background: sel.estado===e ? COLOR_EST[e]+'22' : 'transparent',
                      color: sel.estado===e ? COLOR_EST[e] : 'var(--cream-3)',
                      borderColor: sel.estado===e ? COLOR_EST[e]+'44' : 'var(--border)' }}>
                    {e}
                  </button>
                ))}
              </div>
            </div>

            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'10px', marginBottom:'14px' }}>
              {/* Foto referencia */}
              <div style={{ gridColumn:'1/-1', display:'flex', gap:'12px', alignItems:'flex-start' }}>
                <div style={{ width:'100px', height:'100px', borderRadius:'10px', overflow:'hidden', border:'1px solid var(--border)', background:'var(--surface)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                  {sel.foto_url
                    ? <img src={sel.foto_url} alt="" style={{ width:'100%', height:'100%', objectFit:'cover' }} onError={e=>e.target.style.display='none'}/>
                    : <div style={{ textAlign:'center', color:'var(--cream-3)', fontSize:'11px' }}>📷<br/>Sin foto</div>
                  }
                </div>
                <div style={{ flex:1 }}>
                  <div style={{ fontFamily:'Cormorant Garamond,serif', fontSize:'15px', fontWeight:600, color:'var(--cream)', marginBottom:'5px' }}>
                    {sel.tipo} {sel.metal?'· '+sel.metal:''}
                  </div>
                  <div style={{ color:'var(--cream-2)', fontSize:'12px', lineHeight:'1.7' }}>{sel.descripcion}</div>
                  {sel.links && <div style={{ marginTop:'5px', fontSize:'11px', color:'#2980b9' }}>{sel.links}</div>}
                </div>
              </div>

              {[
                { l:'RUT',         v:sel.rut||'—' },
                { l:'Teléfono',    v:sel.telefono||'—' },
                { l:'Medidas',     v:sel.medidas||'—' },
                { l:'Presupuesto', v:clp(sel.presupuesto||0) },
              ].map(f => (
                <div key={f.l} style={{ background:'var(--bg-card)', borderRadius:'8px', padding:'10px', border:'1px solid var(--border)' }}>
                  <div style={{ fontSize:'9px', color:'var(--cream-3)', marginBottom:'2px' }}>{f.l}</div>
                  <div style={{ color:'var(--cream)', fontSize:'12px', fontWeight:500 }}>{f.v}</div>
                </div>
              ))}
            </div>

            {sel.observaciones && (
              <div style={{ background:'var(--surface)', borderRadius:'8px', padding:'12px', marginBottom:'12px', borderLeft:'2px solid var(--gold)' }}>
                <div style={{ fontSize:'10px', color:'var(--cream-3)', marginBottom:'4px' }}>OBSERVACIONES</div>
                <div style={{ color:'var(--cream-2)', fontSize:'12px', lineHeight:'1.7' }}>{sel.observaciones}</div>
              </div>
            )}

            <div style={{ display:'flex', gap:'8px' }}>
              <button onClick={() => {
                setPedidos(pedidos.filter(p => p.id !== sel.id));
                lsSet('pedidos_catalogo', pedidos.filter(p => p.id !== sel.id));
                setSel(null);
              }} style={{ ...invStyles.btnEdit, padding:'9px 16px', color:'#c0392b' }}>
                🗑 Eliminar
              </button>
            </div>
          </div>
        )}
      </div>

      {/* Modal nuevo */}
      {modal && (
        <div style={posStyles.overlay} onClick={e => e.target===e.currentTarget && setModal(false)}>
          <div style={{ ...posStyles.modalBox, maxWidth:'520px' }}>
            <div style={{ ...posStyles.modalHeader, marginBottom:'14px' }}>
              <span style={{ fontFamily:'Cormorant Garamond,serif', fontSize:'20px', fontWeight:600 }}>Nuevo Pedido Catálogo</span>
              <button onClick={() => setModal(false)} style={posStyles.clearBtn}>✕</button>
            </div>

            {/* Foto */}
            <div style={{ marginBottom:'12px', display:'flex', gap:'10px', alignItems:'center' }}>
              <div style={{ width:'70px', height:'70px', borderRadius:'8px', overflow:'hidden', border:'1px solid var(--border)', background:'var(--surface)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0, cursor:'pointer' }}
                onClick={() => fileRef.current.click()}>
                {nuevo.foto_url
                  ? <img src={nuevo.foto_url} alt="" style={{ width:'100%', height:'100%', objectFit:'cover' }}/>
                  : <div style={{ textAlign:'center', fontSize:'10px', color:'var(--cream-3)' }}>📷<br/>Foto ref.</div>
                }
              </div>
              <input ref={fileRef} type="file" accept="image/*" style={{ display:'none' }} onChange={handleFoto}/>
              <div>
                <div style={{ fontSize:'11px', color:'var(--cream)', fontWeight:500, marginBottom:'3px' }}>Foto o imagen de referencia</div>
                <div style={{ fontSize:'10px', color:'var(--cream-3)' }}>Click para subir. Puede ser foto del cliente, captura de web, etc.</div>
                <input style={{ ...calcStyles.input, marginTop:'6px', fontSize:'11px' }}
                  placeholder="O pega URL: https://…" value={nuevo.foto_url?.startsWith('data:')?'':nuevo.foto_url||''}
                  onChange={e => set('foto_url', e.target.value)}/>
              </div>
            </div>

            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'8px' }}>
              {[
                { l:'Cliente *',    k:'cliente',     t:'text',   ph:'Nombre completo' },
                { l:'RUT',          k:'rut',         t:'text',   ph:'12.345.678-9' },
                { l:'Teléfono/WA',  k:'telefono',    t:'text',   ph:'+56 9 xxxx xxxx' },
                { l:'Email',        k:'email',       t:'text',   ph:'correo@mail.com' },
                { l:'Presupuesto',  k:'presupuesto', t:'number', ph:'0' },
                { l:'Medidas',      k:'medidas',     t:'text',   ph:'Talla, largo, etc.' },
              ].map(f => (
                <div key={f.k}>
                  <div style={{ fontSize:'10px', color:'var(--cream-3)', marginBottom:'3px' }}>{f.l}</div>
                  <input type={f.t} placeholder={f.ph} style={calcStyles.input}
                    value={nuevo[f.k]||''} onChange={e => set(f.k, f.t==='number'?parseInt(e.target.value)||0:e.target.value)}/>
                </div>
              ))}
              <div>
                <div style={{ fontSize:'10px', color:'var(--cream-3)', marginBottom:'3px' }}>Tipo de joya</div>
                <select style={{ ...invStyles.select, width:'100%' }} value={nuevo.tipo} onChange={e => set('tipo', e.target.value)}>
                  {TIPOS.map(t => <option key={t}>{t}</option>)}
                </select>
              </div>
              <div>
                <div style={{ fontSize:'10px', color:'var(--cream-3)', marginBottom:'3px' }}>Metal deseado</div>
                <input style={calcStyles.input} placeholder="Oro 18K, Plata…" value={nuevo.metal}
                  onChange={e => set('metal', e.target.value)}/>
              </div>
              <div style={{ gridColumn:'1/-1' }}>
                <div style={{ fontSize:'10px', color:'var(--cream-3)', marginBottom:'3px' }}>Descripción / Referencia *</div>
                <textarea rows={3} style={{ ...calcStyles.input, resize:'vertical' }}
                  placeholder="Describir la joya buscada, características, referencias…"
                  value={nuevo.descripcion} onChange={e => set('descripcion', e.target.value)}/>
              </div>
              <div style={{ gridColumn:'1/-1' }}>
                <div style={{ fontSize:'10px', color:'var(--cream-3)', marginBottom:'3px' }}>Links de referencia</div>
                <input style={calcStyles.input} placeholder="URLs separadas por coma"
                  value={nuevo.links} onChange={e => set('links', e.target.value)}/>
              </div>
              <div style={{ gridColumn:'1/-1' }}>
                <div style={{ fontSize:'10px', color:'var(--cream-3)', marginBottom:'3px' }}>Observaciones</div>
                <textarea rows={2} style={{ ...calcStyles.input, resize:'vertical' }}
                  placeholder="Notas adicionales, urgencia, etc."
                  value={nuevo.observaciones} onChange={e => set('observaciones', e.target.value)}/>
              </div>
            </div>

            <button onClick={guardar} disabled={!nuevo.cliente || !nuevo.descripcion}
              style={{ ...posStyles.cobrarBtn, width:'100%', marginTop:'14px', opacity:(!nuevo.cliente||!nuevo.descripcion)?0.5:1 }}>
              ✦ Guardar Pedido Catálogo
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { PedidosCatalogo });
