// ─────────────────────────────────────────────────────
// INC-003 — Reclamaciones y garantía (módulo 'reclamaciones', /api/reclamaciones).
// Cada reclamación va SIEMPRE enlazada a un expediente existente; desde ella
// se abre el expediente y, en la ficha del expediente, la pestaña
// «Reclamaciones» lista las suyas con «Nueva» ya enlazada.
//
// Adjuntos: se suben por /api/archivos como documentos del expediente
// (carpeta REC_CARPETA) y se vinculan con POST /api/reclamaciones/:id/adjuntos,
// así salen también en Documentos del expediente.
//
// Expone window.ReclamacionesView, window.ReclamacionesPanel y
// window.puedeVerReclamaciones. Reutiliza ArchivoThumb/archivoSize
// (archivos.jsx), ComboBuscador (combobox.jsx) y los modales de sistema.jsx.
// ─────────────────────────────────────────────────────

const REC_CARPETA = '07 RECLAMACIONES Y GARANTIA';
const REC_ESTADOS = {
  abierta:  { label: 'Abierta',  cls: 'warn' },
  en_curso: { label: 'En curso', cls: 'info' },
  resuelta: { label: 'Resuelta', cls: 'ok' },
  cerrada:  { label: 'Cerrada',  cls: '' },
};
const REC_TIPOS = {
  reclamacion: { label: 'Reclamación', cls: 'err' },
  garantia:    { label: 'Garantía',    cls: 'info' },
};
const REC_FILTROS = [
  ['pendientes', 'Pendientes'],
  ['abierta', 'Abiertas'],
  ['en_curso', 'En curso'],
  ['resuelta', 'Resueltas'],
  ['cerrada', 'Cerradas'],
  ['todas', 'Todas'],
];
const REC_ACCEPT = '.jpg,.jpeg,.png,.webp,.gif,.heic,.pdf,.doc,.docx,.xls,.xlsx,.csv,.ppt,.pptx,.txt,.dwg,.dxf,.dwf,.step,.stp,.iges,.igs,.3dm,.skp,.zip';

function puedeVerReclamaciones() {
  const u = (window.API && API.getUser && API.getUser()) || {};
  if (u.rol === 'admin') return true;
  const eff = (Array.isArray(u.permisosEfectivos) && u.permisosEfectivos.length) ? u.permisosEfectivos : (u.permisos || []);
  return eff.includes('*') || eff.includes('reclamaciones');
}

const recFecha = (f) => {
  if (!f) return '—';
  const [y, m, d] = String(f).slice(0, 10).split('-');
  return y && m && d ? `${d}/${m}/${y}` : String(f);
};
const recEuros = (v) => (v == null || v === '' ? '—'
  : Number(v).toLocaleString('es-ES', { style: 'currency', currency: 'EUR' }));
const recHoy = () => {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
};

const RecPill = ({ map, v }) => {
  const x = map[v] || { label: v || '—', cls: '' };
  return <span className={`pill ${x.cls}`}><span className="d" />{x.label}</span>;
};

// Sube los ficheros a la carpeta de reclamaciones del expediente (de 5 en 5,
// límite de /api/archivos) y los vincula a la reclamación.
async function recSubirAdjuntos(rec, files) {
  const ids = [];
  for (let i = 0; i < files.length; i += 5) {
    const fd = new FormData();
    fd.append('entity_type', 'expedientes');
    fd.append('entity_id', String(rec.pedido_id));
    fd.append('categoria', REC_CARPETA);
    files.slice(i, i + 5).forEach(f => fd.append('files', f));
    const r = await API.upload('/api/archivos', fd);
    ((r && r.uploaded) || []).forEach(a => ids.push(a.id));
  }
  if (ids.length) await API.post(`/api/reclamaciones/${rec.id}/adjuntos`, { archivo_ids: ids });
}

// Selector de ficheros: lista lo elegido y permite quitar antes de guardar.
const RecFilePicker = ({ files, onChange }) => {
  const inputRef = React.useRef(null);
  const add = (ev) => {
    onChange([...files, ...Array.from(ev.target.files || [])]);
    if (inputRef.current) inputRef.current.value = '';
  };
  return (
    <div>
      <label className="btn ghost sm" style={{ cursor: 'pointer' }}>
        <Icon name="upload" size={12} /> Adjuntar fotos / PDF
        <input ref={inputRef} type="file" multiple accept={REC_ACCEPT} style={{ display: 'none' }} onChange={add} />
      </label>
      <span className="muted" style={{ fontSize: 11.5, marginLeft: 8 }}>Se guardan también en Documentos del expediente</span>
      {files.length > 0 && (
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 8 }}>
          {files.map((f, i) => (
            <span key={i} className="pill" style={{ gap: 6 }}>
              {f.name} <span className="muted">· {archivoSize(f.size)}</span>
              <button type="button" className="icon-btn" style={{ width: 16, height: 16 }} title="Quitar"
                onClick={() => onChange(files.filter((_, j) => j !== i))}><Icon name="x" size={10} /></button>
            </span>
          ))}
        </div>
      )}
    </div>
  );
};

// Listas compartidas por los formularios (se cargan una vez por sesión).
let recCacheUsuarios = null;
const useRecUsuarios = () => {
  const [u, setU] = React.useState(recCacheUsuarios || []);
  React.useEffect(() => {
    if (recCacheUsuarios) return;
    API.get('/api/reclamaciones/usuarios').then(r => { recCacheUsuarios = r || []; setU(recCacheUsuarios); }).catch(() => {});
  }, []);
  return u;
};
const useRecExpedientes = (activo) => {
  const [rows, setRows] = React.useState([]);
  React.useEffect(() => {
    if (!activo) return;
    API.get('/api/reclamaciones/expedientes').then(r => setRows(r || [])).catch(() => {});
  }, [activo]);
  return rows.map(e => ({ id: e.id, mono: e.numero_expediente, label: e.cliente || '(sin cliente)' }));
};

// Alta y edición. `pedido` = { id, numero_expediente, cliente } fija el
// expediente (alta desde la ficha del expediente); en edición no se cambia.
const RecFormModal = ({ inicial, pedido, onClose, onSaved, onToast }) => {
  const editando = !!inicial;
  const fijo = editando ? { id: inicial.pedido_id, numero_expediente: inicial.numero_expediente, cliente: inicial.cliente } : pedido;
  const [pedidoId, setPedidoId] = React.useState(fijo ? fijo.id : null);
  const [tipo, setTipo] = React.useState(inicial ? inicial.tipo : 'reclamacion');
  const [fecha, setFecha] = React.useState(inicial ? inicial.fecha : recHoy());
  const [estado, setEstado] = React.useState(inicial ? inicial.estado : 'abierta');
  const [responsable, setResponsable] = React.useState(inicial && inicial.responsable_id ? String(inicial.responsable_id) : '');
  const [descripcion, setDescripcion] = React.useState(inicial ? inicial.descripcion : '');
  const [resolucion, setResolucion] = React.useState(inicial ? (inicial.resolucion || '') : '');
  const [coste, setCoste] = React.useState(inicial && inicial.coste != null ? String(inicial.coste) : '');
  const [files, setFiles] = React.useState([]);
  const [saving, setSaving] = React.useState(false);
  const usuarios = useRecUsuarios();
  const expedientes = useRecExpedientes(!fijo);

  const submit = async (e) => {
    e.preventDefault();
    if (!pedidoId) { onToast('Elige el expediente al que pertenece', true); return; }
    setSaving(true);
    const body = {
      tipo, fecha, estado, descripcion, resolucion, coste,
      responsable_id: responsable ? Number(responsable) : null,
    };
    try {
      if (editando) {
        await API.put(`/api/reclamaciones/${inicial.id}`, body);
        onToast(`${inicial.numero} guardada ✓`);
        onSaved(inicial.id);
      } else {
        const r = await API.post('/api/reclamaciones', { ...body, pedido_id: pedidoId });
        try {
          if (files.length) await recSubirAdjuntos(r, files);
          onToast(`${r.numero} creada ✓`);
        } catch (err) {
          onToast(`${r.numero} creada, pero falló algún adjunto: ${err.message}`, true);
        }
        onSaved(r.id);
      }
      onClose();
    } catch (err) {
      onToast(err.message || 'Error al guardar', true);
    } finally {
      setSaving(false);
    }
  };

  // zIndex 220: por encima del drawer del expediente (210) al abrirse desde su pestaña.
  const overlay = sysOverlay(() => onClose());
  return ReactDOM.createPortal(
    <div className="modal-bg open" {...overlay} style={{ ...overlay.style, zIndex: 220 }}>
      <div className="modal" {...sysModal(640)}>
        <SysModalHeader title={editando ? `Editar ${inicial.numero}` : 'Nueva reclamación / garantía'} onClose={onClose} />
        <form onSubmit={submit} autoComplete="off">
          <div className="fields-grid" style={{ padding: '16px 18px' }}>
            <div className="field full">
              <label>Expediente *</label>
              {fijo
                ? <div className="v"><span className="mono strong">{fijo.numero_expediente}</span> · {fijo.cliente || '—'}</div>
                : <ComboBuscador value={pedidoId} items={expedientes} onChange={(it) => setPedidoId(it ? it.id : null)}
                    placeholder="Busca por nº de expediente o cliente…" />}
            </div>
            <div className="field">
              <label>Tipo</label>
              <div className="seg">
                {Object.entries(REC_TIPOS).map(([k, t]) => (
                  <button type="button" key={k} className={tipo === k ? 'on' : ''} onClick={() => setTipo(k)}>{t.label}</button>
                ))}
              </div>
            </div>
            <div className="field">
              <label>Fecha</label>
              <input type="date" required value={fecha} onChange={e => setFecha(e.target.value)} />
            </div>
            <div className="field">
              <label>Estado</label>
              <select value={estado} onChange={e => setEstado(e.target.value)}>
                {Object.entries(REC_ESTADOS).map(([k, x]) => <option key={k} value={k}>{x.label}</option>)}
              </select>
            </div>
            <div className="field">
              <label>Responsable</label>
              <select value={responsable} onChange={e => setResponsable(e.target.value)}>
                <option value="">— Sin asignar —</option>
                {usuarios.map(u => <option key={u.id} value={u.id}>{u.username}</option>)}
              </select>
            </div>
            <div className="field full">
              <label>Descripción *</label>
              <textarea rows={5} required autoFocus={!!fijo} value={descripcion} onChange={e => setDescripcion(e.target.value)}
                placeholder="Qué reclama el cliente o qué falla, en qué elemento y desde cuándo." />
            </div>
            <div className="field full">
              <label>Resolución</label>
              <textarea rows={3} value={resolucion} onChange={e => setResolucion(e.target.value)}
                placeholder="Qué se ha hecho para resolverla (se puede rellenar más tarde)." />
            </div>
            <div className="field">
              <label>Coste (€, opcional)</label>
              <input type="number" min="0" step="0.01" value={coste} onChange={e => setCoste(e.target.value)} placeholder="0,00" />
            </div>
            {!editando && (
              <div className="field full">
                <label>Adjuntos</label>
                <RecFilePicker files={files} onChange={setFiles} />
              </div>
            )}
          </div>
          <SysModalFooter onClose={onClose} saving={saving} label={editando ? 'Guardar' : 'Crear'} />
        </form>
      </div>
    </div>,
    document.body
  );
};

// Adjuntos ya subidos: clic → se abre en otra pestaña con el enlace firmado.
const RecAdjuntos = ({ files, onToast }) => {
  if (!files || !files.length) return <p className="muted" style={{ fontSize: 12 }}>Sin adjuntos.</p>;
  const abrir = async (f) => {
    const w = window.open('', '_blank');
    try {
      const { url } = await API.post(`/api/archivos/${f.id}/link`);
      if (w) w.location = url;
    } catch (e) {
      if (w) w.close();
      onToast(e.message || 'Error al abrir archivo', true);
    }
  };
  return (
    <div className="archivos-grid" style={{ marginTop: 8 }}>
      {files.map(f => (
        <button key={f.id} type="button" className="archivo-card" onClick={() => abrir(f)} title={f.original_name}>
          <span className="archivo-thumb"><ArchivoThumb file={f} /></span>
          <span className="archivo-meta">
            <span className="archivo-name">{f.original_name}</span>
            <span className="archivo-sub">{archivoSize(f.size)}</span>
          </span>
        </button>
      ))}
    </div>
  );
};

// Ficha lateral. Se pinta en document.body para poder abrirse también desde
// dentro del panel del expediente (que es otro drawer).
const RecDrawer = ({ recId, user, onClose, onChanged, onToast, desdeExpediente }) => {
  const [data, setData] = React.useState(null);
  const [editar, setEditar] = React.useState(false);
  const [files, setFiles] = React.useState([]);
  const [subiendo, setSubiendo] = React.useState(false);

  const load = async () => {
    try { setData(await API.get(`/api/reclamaciones/${recId}`)); }
    catch (e) { onToast(e.message || 'Error', true); }
  };
  React.useEffect(() => { setData(null); setFiles([]); if (recId) load(); }, [recId]);
  const tras = () => { load(); onChanged && onChanged(); };

  const cambiarEstado = async (estado) => {
    try {
      await API.put(`/api/reclamaciones/${recId}`, { estado });
      onToast(`Estado: ${REC_ESTADOS[estado].label} ✓`);
      tras();
    } catch (e) { onToast(e.message || 'Error', true); }
  };
  const subir = async () => {
    if (!files.length) return;
    setSubiendo(true);
    try {
      await recSubirAdjuntos(data, files);
      setFiles([]);
      onToast('Adjuntos subidos ✓');
      tras();
    } catch (e) { onToast(e.message || 'Error al subir', true); }
    finally { setSubiendo(false); }
  };
  const borrar = async () => {
    if (!confirm(`¿Borrar ${data.numero}? Los adjuntos se quedan en Documentos del expediente.`)) return;
    try {
      await API.del(`/api/reclamaciones/${recId}`);
      onToast(`${data.numero} borrada`);
      onChanged && onChanged();
      onClose();
    } catch (e) { onToast(e.message || 'Error', true); }
  };
  const abrirExpediente = () => {
    const pid = data.pedido_id;
    onClose();
    if (!desdeExpediente) window.dispatchEvent(new CustomEvent('erp:open-expediente', { detail: { pedidoId: pid, tab: 'reclamaciones' } }));
  };

  const open = !!recId;
  const esAdmin = user && user.rol === 'admin';
  const Dato = ({ l, children }) => (
    <div className="field"><label>{l}</label><div className="v">{children}</div></div>
  );

  return ReactDOM.createPortal(
    <>
      <div className={`drawer-bg ${open ? 'open' : ''}`} onClick={onClose} />
      <div className={`drawer ${open ? 'open' : ''}`} style={{ width: 'min(760px, 100%)' }}>
        <div className="dr-head">
          {data && <span className="id mono">{data.numero}</span>}
          <h2>{data ? (data.cliente || '—') : 'Cargando…'}</h2>
          {data && <RecPill map={REC_TIPOS} v={data.tipo} />}
          {data && <RecPill map={REC_ESTADOS} v={data.estado} />}
          <div className="actions">
            {data && <button className="icon-btn" title="Editar" onClick={() => setEditar(true)}><Icon name="edit" /></button>}
            {data && esAdmin && <button className="icon-btn" title="Borrar (solo admin)" style={{ color: 'var(--err)' }} onClick={borrar}><Icon name="trash" /></button>}
            <button className="icon-btn" onClick={onClose}><Icon name="x" /></button>
          </div>
        </div>
        <div className="dr-body">
          {open && !data && <div style={{ padding: 24, textAlign: 'center', color: 'var(--ink-3)' }}>Cargando…</div>}
          {data && (
            <div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', marginBottom: 14,
                border: '1px solid var(--line)', borderRadius: 8, padding: '10px 12px', background: 'var(--surface)' }}>
                <Icon name="package" size={14} />
                <span>Expediente <strong className="mono">{data.numero_expediente}</strong> · {data.cliente || '—'}</span>
                <div style={{ flex: 1 }} />
                <button className="btn sm" onClick={abrirExpediente}>{desdeExpediente ? 'Volver al expediente' : 'Abrir expediente'}</button>
              </div>

              <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', marginBottom: 14 }}>
                <span className="muted" style={{ fontSize: 12 }}>Cambiar estado:</span>
                <div className="seg">
                  {Object.entries(REC_ESTADOS).map(([k, x]) => (
                    <button type="button" key={k} className={data.estado === k ? 'on' : ''}
                      onClick={() => data.estado !== k && cambiarEstado(k)}>{x.label}</button>
                  ))}
                </div>
              </div>

              <div className="fields-grid cols-3" style={{ marginBottom: 14 }}>
                <Dato l="Fecha">{recFecha(data.fecha)}</Dato>
                <Dato l="Responsable">{data.responsable || '—'}</Dato>
                <Dato l="Coste">{recEuros(data.coste)}</Dato>
              </div>

              <div className="section-title">Descripción</div>
              <div style={{ whiteSpace: 'pre-wrap', fontSize: 13.5, lineHeight: 1.5, marginBottom: 14 }}>
                {data.descripcion || <span className="muted">Sin descripción.</span>}
              </div>

              <div className="section-title">Resolución</div>
              <div style={{ whiteSpace: 'pre-wrap', fontSize: 13.5, lineHeight: 1.5, marginBottom: 14 }}>
                {data.resolucion || <span className="muted">Pendiente.</span>}
              </div>

              <div className="section-title">Adjuntos</div>
              <RecAdjuntos files={data.archivos} onToast={onToast} />
              <div style={{ display: 'flex', gap: 8, alignItems: 'flex-start', marginTop: 10, flexWrap: 'wrap' }}>
                <RecFilePicker files={files} onChange={setFiles} />
                {files.length > 0 && (
                  <button className="btn primary sm" onClick={subir} disabled={subiendo}>
                    {subiendo ? 'Subiendo…' : `Subir ${files.length}`}
                  </button>
                )}
              </div>
              <p className="muted" style={{ fontSize: 11.5, marginTop: 8 }}>
                Los adjuntos están en Documentos del expediente, carpeta «{REC_CARPETA}».
              </p>

              <p className="muted" style={{ fontSize: 11.5, marginTop: 14 }}>
                Abierta por {data.autor || '—'} · última modificación {new Date(data.updated_at).toLocaleString('es-ES')}
              </p>
            </div>
          )}
        </div>
      </div>
      {editar && data && (
        <RecFormModal inicial={data} onClose={() => setEditar(false)} onSaved={() => tras()} onToast={onToast} />
      )}
    </>,
    document.body
  );
};

// Tabla compartida por la vista y el panel del expediente.
const RecTabla = ({ rows, loading, conExpediente, onOpen, vacio }) => (
  <div className="tbl-wrap">
    <div className="tbl-scroll">
      <table className="tbl">
        <thead>
          <tr>
            <th style={{ width: 120 }}>Nº</th>
            <th style={{ width: 110 }}>Tipo</th>
            <th style={{ width: 95 }}>Fecha</th>
            {conExpediente && <th style={{ width: 110 }}>Expediente</th>}
            {conExpediente && <th>Cliente</th>}
            <th>Descripción</th>
            <th style={{ width: 105 }}>Estado</th>
            <th style={{ width: 120 }}>Responsable</th>
            <th style={{ width: 90, textAlign: 'right' }}>Coste</th>
            <th style={{ width: 60, textAlign: 'right' }} title="Adjuntos"><Icon name="file" size={12} /></th>
          </tr>
        </thead>
        <tbody>
          {loading && <tr><td colSpan={10} style={{ padding: '24px 16px', textAlign: 'center', color: 'var(--ink-3)' }}>Cargando…</td></tr>}
          {!loading && rows.map(r => (
            <tr key={r.id} onClick={() => onOpen(r.id)} style={{ cursor: 'pointer' }}>
              <td><code style={{ fontSize: 12 }}>{r.numero}</code></td>
              <td><span className={`pill ${(REC_TIPOS[r.tipo] || {}).cls || ''}`}>{(REC_TIPOS[r.tipo] || {}).label || r.tipo}</span></td>
              <td className="muted" style={{ fontSize: 12 }}>{recFecha(r.fecha)}</td>
              {conExpediente && <td className="mono strong">{r.numero_expediente}</td>}
              {conExpediente && <td className="truncate">{r.cliente || '—'}</td>}
              <td className="truncate" style={{ maxWidth: 320 }} title={r.descripcion}>{r.descripcion}</td>
              <td><RecPill map={REC_ESTADOS} v={r.estado} /></td>
              <td className="muted">{r.responsable || '—'}</td>
              <td className="num muted" style={{ textAlign: 'right' }}>{r.coste != null ? recEuros(r.coste) : '—'}</td>
              <td className="muted" style={{ textAlign: 'right' }}>{r.n_adjuntos || '—'}</td>
            </tr>
          ))}
          {!loading && !rows.length && (
            <tr><td colSpan={10} style={{ padding: '24px 16px', textAlign: 'center', color: 'var(--ink-3)' }}>{vacio}</td></tr>
          )}
        </tbody>
      </table>
    </div>
  </div>
);

// Vista principal: Operaciones › Reclamaciones y garantía.
const ReclamacionesView = ({ user, onToast }) => {
  const [rows, setRows] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [estado, setEstado] = React.useState(() => {
    try { const v = localStorage.getItem('rec_estado'); return REC_FILTROS.some(f => f[0] === v) ? v : 'pendientes'; }
    catch { return 'pendientes'; }
  });
  const [tipo, setTipo] = React.useState('');
  const [cliente, setCliente] = React.useState('');
  const [pedidoId, setPedidoId] = React.useState(null);
  const [search, setSearch] = React.useState('');
  const [abierta, setAbierta] = React.useState(null);
  const [nueva, setNueva] = React.useState(false);
  const expedientes = useRecExpedientes(true);
  const [reloadKey, setReloadKey] = React.useState(0);
  const reload = () => setReloadKey(k => k + 1);

  React.useEffect(() => {
    let alive = true;
    const t = setTimeout(() => {
      setLoading(true);
      const params = {};
      if (estado !== 'todas') params.estado = estado;
      if (tipo) params.tipo = tipo;
      if (cliente.trim()) params.cliente = cliente.trim();
      if (pedidoId) params.pedido_id = pedidoId;
      if (search.trim()) params.search = search.trim();
      API.get('/api/reclamaciones', params)
        .then(r => { if (alive) setRows(r || []); })
        .catch(e => onToast(e.message || 'Error', true))
        .finally(() => { if (alive) setLoading(false); });
    }, 250);
    return () => { alive = false; clearTimeout(t); };
  }, [estado, tipo, cliente, pedidoId, search, reloadKey]);

  const onEstado = (v) => { setEstado(v); try { localStorage.setItem('rec_estado', v); } catch {} };
  const hayFiltros = tipo || cliente || pedidoId || search;

  return (
    <>
      <div className="page-h">
        <div>
          <h1>Reclamaciones y garantía</h1>
          <div className="sub">Siempre enlazadas a su expediente · {rows.length} {rows.length === 1 ? 'resultado' : 'resultados'}</div>
        </div>
        <div className="page-h-actions">
          <button className="btn primary" onClick={() => setNueva(true)}><Icon name="plus" /> Nueva</button>
        </div>
      </div>

      <div className="toolbar" style={{ flexWrap: 'wrap', gap: 8 }}>
        <div className="seg">
          {REC_FILTROS.map(([k, l]) => (
            <button type="button" key={k} className={estado === k ? 'on' : ''} onClick={() => onEstado(k)}>{l}</button>
          ))}
        </div>
        <select value={tipo} onChange={e => setTipo(e.target.value)} className="tb-select"
          style={{ padding: '5px 8px', border: '1px solid var(--line)', borderRadius: 6, background: 'var(--surface)', fontSize: 12.5 }}>
          <option value="">Reclamación y garantía</option>
          <option value="reclamacion">Solo reclamaciones</option>
          <option value="garantia">Solo garantías</option>
        </select>
        <div className="tb-search" style={{ minWidth: 160 }}>
          <Icon name="leads" />
          <input placeholder="Cliente…" value={cliente} onChange={e => setCliente(e.target.value)} />
        </div>
        <div style={{ width: 240 }}>
          <ComboBuscador value={pedidoId} items={expedientes} allowEmpty vacio="— Todos los expedientes —"
            onChange={(it) => setPedidoId(it ? it.id : null)} placeholder="Expediente…" />
        </div>
        <div className="tb-search">
          <Icon name="search" />
          <input placeholder="Nº RG, descripción…" value={search} onChange={e => setSearch(e.target.value)} />
        </div>
        {hayFiltros && (
          <button className="btn ghost sm" onClick={() => { setTipo(''); setCliente(''); setPedidoId(null); setSearch(''); }}>Quitar filtros</button>
        )}
      </div>

      <RecTabla rows={rows} loading={loading} conExpediente onOpen={setAbierta}
        vacio={hayFiltros || estado !== 'pendientes' ? 'Sin resultados.' : 'No hay reclamaciones pendientes.'} />

      <RecDrawer recId={abierta} user={user} onClose={() => setAbierta(null)} onChanged={reload} onToast={onToast} />
      {nueva && (
        <RecFormModal onClose={() => setNueva(false)} onSaved={(id) => { reload(); setAbierta(id); }} onToast={onToast} />
      )}
    </>
  );
};

// Pestaña «Reclamaciones» de la ficha del expediente.
const ReclamacionesPanel = ({ expediente, onToast }) => {
  const [rows, setRows] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [abierta, setAbierta] = React.useState(null);
  const [nueva, setNueva] = React.useState(false);
  const user = (window.API && API.getUser && API.getUser()) || {};

  const load = React.useCallback(() => {
    if (!expediente || !expediente.id) return;
    setLoading(true);
    API.get('/api/reclamaciones', { pedido_id: expediente.id })
      .then(r => setRows(r || []))
      .catch(e => onToast(e.message || 'Error', true))
      .finally(() => setLoading(false));
  }, [expediente && expediente.id]);
  React.useEffect(() => { load(); }, [load]);

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
        <div className="section-title" style={{ margin: 0 }}>Reclamaciones y garantía</div>
        <span className="muted" style={{ fontSize: 12 }}>{rows.length}</span>
        <div style={{ flex: 1 }} />
        <button className="btn primary sm" onClick={() => setNueva(true)}><Icon name="plus" size={12} /> Nueva</button>
      </div>
      <RecTabla rows={rows} loading={loading} onOpen={setAbierta} vacio="Este expediente no tiene reclamaciones ni garantías." />
      <p className="muted" style={{ fontSize: 11.5, marginTop: 8 }}>
        Los adjuntos de cada reclamación se guardan en Documentos › «{REC_CARPETA}».
      </p>
      <RecDrawer recId={abierta} user={user} desdeExpediente onClose={() => setAbierta(null)} onChanged={load} onToast={onToast} />
      {nueva && (
        <RecFormModal pedido={expediente} onClose={() => setNueva(false)} onSaved={(id) => { load(); setAbierta(id); }} onToast={onToast} />
      )}
    </div>
  );
};

window.REC_CARPETA = REC_CARPETA;
window.puedeVerReclamaciones = puedeVerReclamaciones;
window.ReclamacionesView = ReclamacionesView;
window.ReclamacionesPanel = ReclamacionesPanel;
