// ─── Reservas ───────────────────────────────────────────────────────────────

const CAJA_META_ID = {
  CAJA_CHICA:  'chica',
  CAJA_ALVARO: 'alvaro',
  CAJA_MAY:    'may',
  BANCO:       'banco',
};

const CAJA_META_ENUM = Object.fromEntries(Object.entries(CAJA_META_ID).map(([k, v]) => [v, k]));

function adaptarReserva(r) {
  return {
    id:               r.id,
    propiedad:        r.propiedad?.direccion ?? '—',
    propiedadId:      r.propiedadId,
    cliente:          r.cliente ?? '—',
    sena_usd:         r.moneda === 'USD' ? Number(r.monto) : null,
    monto:            Number(r.monto),
    moneda:           r.moneda,
    fecha:            r.fechaReserva?.slice(0, 10) ?? '—',
    fechaVencimiento: r.fechaVencimiento?.slice(0, 10) ?? '',
    brokerId:         r.brokerId,
    doc:              null,
    direccion:        r.direccion ?? null,
    monto_sobre:      r.montoSobre  ? Number(r.montoSobre)  : null,
    moneda_sobre:     r.monedaSobre ?? null,
    caja:             r.cajaDestino ? CAJA_META_ID[r.cajaDestino] : null,
    brokerSobreId:    r.brokerSobreId ?? null,
    broker_sobre:     r.brokerSobre
                        ? `${r.brokerSobre.nombre} ${r.brokerSobre.apellido}`
                        : null,
    estado:           r.estado,
    notas:            r.notas ?? '',
  };
}

const COLUMNAS_OPCIONALES = [
  { key: 'direccion',    label: 'Dirección' },
  { key: 'broker_sobre', label: 'Broker sobre' },
  { key: 'monto_sobre',  label: 'Monto sobre' },
  { key: 'caja',         label: 'Caja' },
];

function Reservas() {
  const [reservas, setReservas] = useState([]);
  const [loading, setLoading]   = useState(true);
  const [error, setError]       = useState(null);
  const [extras, setExtras] = useState(() => new Set(['caja', 'broker_sobre']));
  const [detail, setDetail] = useState(null);
  const [creating, setCreating] = useState(false);
  const [propiedades, setPropiedades] = useState([]);
  const [brokers, setBrokers]         = useState([]);

  useEffect(() => {
    fetch(`${API_BASE}/api/reservas`, { credentials: 'include' })
      .then(r => r.json())
      .then(data => {
        setReservas((Array.isArray(data) ? data : (data.data ?? [])).map(adaptarReserva));
        setLoading(false);
      })
      .catch(err => {
        console.error('[reservas fetch]', err);
        setError('Error al cargar reservas.');
        setLoading(false);
      });
  }, []);

  useEffect(() => {
    Promise.all([
      fetch(`${API_BASE}/api/propiedades`, { credentials: 'include' }).then(r => r.json()),
      fetch(`${API_BASE}/api/usuarios?rol=BROKER`, { credentials: 'include' }).then(r => r.json()),
    ]).then(([props, users]) => {
      setPropiedades(Array.isArray(props) ? props : []);
      setBrokers(Array.isArray(users) ? users : []);
    }).catch(err => console.error('[reservas aux fetch]', err));
  }, []);

  const toggleCol = (k) => setExtras(prev => {
    const next = new Set(prev);
    next.has(k) ? next.delete(k) : next.add(k);
    return next;
  });

  const columns = [
    { key: 'id', label: 'ID' },
    { key: 'propiedad', label: 'Propiedad' },
    { key: 'cliente', label: 'Cliente' },
    { key: 'sena_usd', label: 'Seña USD' },
    { key: 'fecha', label: 'Fecha' },
    { key: 'doc', label: 'Documento' },
    { key: 'direccion', label: 'Dirección reserva' },
    { label: 'Broker sobre', value: r => r.broker_sobre ?? '' },
    { label: 'Monto sobre',  value: r => r.monto_sobre ? `${r.moneda_sobre} ${r.monto_sobre}` : '' },
    { label: 'Caja',         value: r => CAJAS_BY_ID[r.caja]?.nombre || '' },
  ];

  const onCreate = (nueva) => {
    setReservas(prev => [nueva, ...prev]);
    setCreating(false);
  };

  const onUpdate = (actualizada) => {
    setReservas(prev => prev.map(r => r.id === actualizada.id ? actualizada : r));
    setDetail(actualizada); // actualizar el detail abierto
  };

  const handleAnularReserva = (data) => {
    setReservas(prev => prev.map(r => r.id === data.id ? adaptarReserva(data) : r));
    setDetail(null);
  };

  if (loading) return <div className="p-8 text-slate-500">Cargando reservas…</div>;
  if (error)   return <div className="p-8 text-red-500">{error}</div>;

  return (
    <div className="fade-in">
      <PageHeader
        crumbs={['Inicio', 'Finanzas', 'Reservas']}
        title="Reservas"
        sub={`${reservas.length} reservas activas · ${USD(reservas.reduce((s, r) => s + (r.sena_usd || 0), 0))} en señas`}
        actions={
          <>
            <ExportButton filename={`lanven-reservas-${new Date().toISOString().slice(0,10)}`} rows={reservas} columns={columns} count={reservas.length} />
            <Button variant="primary" size="md" icon={<I.Plus size={14} sw={2} />} onClick={() => setCreating(true)}>Nueva reserva</Button>
          </>
        }
      />

      <div className="mb-4 bg-white border border-slate-100 shadow-card rounded-md px-4 py-2.5 flex items-center gap-3 flex-wrap">
        <span className="text-[10.5px] uppercase tracking-[0.12em] text-slate-500 font-medium">Columnas opcionales</span>
        {COLUMNAS_OPCIONALES.map(c => (
          <button key={c.key} onClick={() => toggleCol(c.key)}
            className={`text-[11.5px] inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full border transition-colors ${
              extras.has(c.key)
                ? 'bg-slate-700 border-slate-700 text-white'
                : 'bg-white border-slate-200 text-slate-700 hover:border-slate-300'
            }`}>
            {extras.has(c.key) && <I.Check size={10} sw={2.5} />}
            {c.label}
          </button>
        ))}
        <div className="flex-1" />
        <span className="text-[10.5px] text-slate-400 font-mono">{extras.size}/{COLUMNAS_OPCIONALES.length} visibles</span>
      </div>

      <Card pad="p-0">
        <table className="w-full text-[12.5px]">
          <thead className="bg-slate-50/60">
            <tr className="text-[10px] uppercase tracking-[0.1em] text-slate-500 text-left">
              <th className="font-medium py-3 px-5">ID</th>
              <th className="font-medium">Propiedad</th>
              <th className="font-medium">Cliente</th>
              {extras.has('direccion')    && <th className="font-medium">Dirección reserva</th>}
              {extras.has('broker_sobre') && <th className="font-medium">Broker sobre</th>}
              {extras.has('monto_sobre')  && <th className="font-medium text-right">Monto sobre</th>}
              {extras.has('caja')         && <th className="font-medium">Caja</th>}
              <th className="font-medium text-right">Seña</th>
              <th className="font-medium">Fecha</th>
              <th className="font-medium">Documento</th>
              <th className="font-medium px-3"></th>
            </tr>
          </thead>
          <tbody>
            {reservas.map(r => (
              <tr key={r.id} onClick={() => setDetail(r)} className="border-t border-slate-100 tr-hover cursor-pointer">
                <td className="py-3.5 px-5 font-mono text-[11.5px] text-slate-500">{r.id}</td>
                <td className="text-ink">{r.propiedad}</td>
                <td className="text-slate-700">{r.cliente}</td>
                {extras.has('direccion') && (
                  <td className="text-slate-600 text-[12px] max-w-[220px] truncate" title={r.direccion}>{r.direccion || '—'}</td>
                )}
                {extras.has('broker_sobre') && (
                  <td>{r.broker_sobre
                    ? <span className="text-[12px] text-slate-700">{r.broker_sobre}</span>
                    : <span className="text-slate-300">—</span>}
                  </td>
                )}
                {extras.has('monto_sobre') && (
                  <td className="text-right font-mono text-slate-700 text-[12px]">
                    {r.monto_sobre ? (r.moneda_sobre === 'USD' ? USD(r.monto_sobre) : ARS(r.monto_sobre)) : <span className="text-slate-300">—</span>}
                  </td>
                )}
                {extras.has('caja') && (
                  <td>{r.caja ? <CajaPill cajaId={r.caja} /> : <span className="text-slate-300">—</span>}</td>
                )}
                <td className="text-right font-mono text-ink">{USD(r.sena_usd)}</td>
                <td className="text-slate-600 font-mono text-[11.5px]">{r.fecha}</td>
                <td><span className="inline-flex items-center gap-1.5 text-[11.5px] text-slate-600"><I.Doc size={13} />{r.doc ?? '—'}</span></td>
                <td className="px-3 text-slate-400"><I.Chevron size={14} /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>

      {detail   && (
        <ReservaDetail
          reserva={detail}
          propiedades={propiedades}
          brokers={brokers}
          onClose={() => setDetail(null)}
          onAnular={handleAnularReserva}
          onUpdate={onUpdate}
        />
      )}
      {creating && <ReservaForm onClose={() => setCreating(false)} onSave={onCreate} propiedades={propiedades} brokers={brokers} />}
    </div>
  );
}

// ── Caja pill ─────────────────────────────────────────────────────────────
function CajaPill({ cajaId }) {
  if (!cajaId) return <span className="text-slate-300">—</span>;
  const c = CAJAS_BY_ID[cajaId];
  if (!c) return <span className="text-slate-300">—</span>;
  return (
    <span className="inline-flex items-center gap-1.5 px-2 py-0.5 rounded text-[11px] font-medium"
      style={{ background: c.color + '14', color: c.color }}>
      <span className="w-1.5 h-1.5 rounded-full" style={{ background: c.color }} />
      {c.nombre}
      {c.solo_reservas && <span className="text-[9px] opacity-70 ml-0.5">• solo reservas</span>}
    </span>
  );
}

// ── Detalle lateral ───────────────────────────────────────────────────────
function ReservaDetail({ reserva, propiedades, brokers, onClose, onAnular, onUpdate }) {
  const [editing, setEditing] = useState(false);

  const handleAnular = () => {
    if (!confirm('¿Anular esta reserva?')) return;
    fetch(`${API_BASE}/api/reservas/${reserva.id}`, {
      method: 'PUT',
      credentials: 'include',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ estado: 'CANCELADA' }),
    })
      .then(r => r.json())
      .then(data => {
        if (data.error) { alert(data.error); return; }
        onAnular(data);
      })
      .catch(err => {
        console.error('[reservas.anular]', err);
        alert('Error al anular reserva.');
      });
  };

  if (editing) {
    return (
      <ReservaForm
        reserva={reserva}
        onClose={() => setEditing(false)}
        onSave={(actualizada) => { onUpdate(actualizada); setEditing(false); }}
        propiedades={propiedades}
        brokers={brokers}
      />
    );
  }

  return (
    <div className="fixed inset-0 z-30 flex">
      <div className="absolute inset-0 bg-ink/30 backdrop-blur-[2px]" onClick={onClose} />
      <div className="relative ml-auto h-full w-[480px] bg-white shadow-pop flex flex-col fade-in">
        <div className="px-6 py-5 border-b border-slate-100 flex items-start justify-between">
          <div>
            <div className="font-mono text-[11px] text-slate-500">{reserva.id}</div>
            <h2 className="font-serif text-[24px] leading-tight text-ink mt-0.5">{reserva.propiedad}</h2>
            <div className="mt-2 text-[12px] text-slate-500">Cliente · {reserva.cliente}</div>
          </div>
          <button onClick={onClose} className="p-1.5 -mr-1.5 rounded hover:bg-slate-100 text-slate-500"><I.X size={16} /></button>
        </div>

        <div className="flex-1 overflow-y-auto px-6 py-5">
          <div className="grid grid-cols-2 gap-4 mb-6">
            <Field label="Seña">
              <span className="font-mono text-[20px] text-ink">{USD(reserva.sena_usd)}</span>
            </Field>
            <Field label="Fecha">
              <span className="font-mono text-[14px] text-ink">{reserva.fecha}</span>
            </Field>
          </div>

          <div className="text-[10px] uppercase tracking-[0.14em] text-slate-500 font-medium mb-3 pt-3 border-t border-slate-100">
            Datos del sobre
          </div>
          <div className="grid grid-cols-2 gap-4 mb-6">
            <Field label="Dirección de la reserva" full>
              <div className="text-[13px] text-ink leading-snug">{reserva.direccion || <span className="text-slate-400">— sin cargar —</span>}</div>
            </Field>
            <Field label="Broker que entregó">
              {reserva.broker_sobre
                ? <span className="text-[13px] text-ink">{reserva.broker_sobre}</span>
                : <span className="text-slate-400 text-[12px]">— sin cargar —</span>}
            </Field>
            <Field label="Monto del sobre">
              {reserva.monto_sobre
                ? <span className="font-mono text-[18px] text-ink">{reserva.moneda_sobre === 'USD' ? USD(reserva.monto_sobre) : ARS(reserva.monto_sobre)} <span className="text-[11px] text-slate-400 ml-1">{reserva.moneda_sobre}</span></span>
                : <span className="text-slate-400 text-[12px]">— sin cargar —</span>}
            </Field>
            <Field label="Caja donde se guardó" full>
              {reserva.caja
                ? <CajaPill cajaId={reserva.caja} />
                : <span className="text-slate-400 text-[12px]">— sin cargar —</span>}
            </Field>
          </div>

          <div className="text-[10px] uppercase tracking-[0.14em] text-slate-500 font-medium mb-3 pt-3 border-t border-slate-100">
            Documento adjunto
          </div>
          <div className="flex items-center gap-3 p-3 rounded bg-canvas border border-slate-100">
            <span className="w-9 h-9 rounded bg-white border border-slate-200 inline-flex items-center justify-center text-slate-500">
              <I.Doc size={16} />
            </span>
            <div className="flex-1 min-w-0">
              <div className="text-[12.5px] text-ink truncate">{reserva.doc}</div>
              <div className="text-[10.5px] text-slate-500 font-mono">PDF · subido {reserva.fecha}</div>
            </div>
            <Button variant="outline" size="sm">Ver</Button>
          </div>
        </div>

        <div className="px-6 py-4 border-t border-slate-100 bg-canvas flex items-center gap-2">
          {window.CURRENT_USER?.rol === 'admin' && (
            <Button variant="outline" size="md" onClick={() => setEditing(true)}>Editar</Button>
          )}
          <Button variant="danger" size="md" onClick={handleAnular}>Anular</Button>
          <div className="flex-1" />
          <Button variant="gold" size="md">Convertir en operación</Button>
        </div>
      </div>
    </div>
  );
}

function Field({ label, children, full }) {
  return (
    <div className={full ? 'col-span-2' : ''}>
      <div className="text-[10px] uppercase tracking-[0.12em] text-slate-400">{label}</div>
      <div className="mt-1.5">{children}</div>
    </div>
  );
}

// ── Form: crear y editar reserva ──────────────────────────────────────────
function ReservaForm({ reserva, onClose, onSave, propiedades, brokers }) {
  const isEdit  = !!reserva;
  const today    = new Date().toISOString().slice(0, 10);
  const nextWeek = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10);

  const [form, setForm] = useState({
    propiedadId:      reserva?.propiedadId       || '',
    brokerId:         reserva?.brokerId          || '',
    cliente:          reserva?.cliente === '—'   ? '' : (reserva?.cliente || ''),
    direccion:        reserva?.direccion         || '',
    brokerSobreCode:  '',  // no reversible desde ID → code mock
    monto_sobre:      reserva?.monto_sobre       ? String(reserva.monto_sobre) : '',
    moneda_sobre:     reserva?.moneda_sobre      || 'USD',
    caja:             reserva?.caja              || '',
    sena_usd:         reserva?.sena_usd          ? String(reserva.sena_usd) : '',
    fechaReserva:     reserva?.fecha             || today,
    fechaVencimiento: reserva?.fechaVencimiento  || nextWeek,
    notas:            reserva?.notas             || '',
    estado:           reserva?.estado            || 'PENDIENTE',
  });
  const [touched, setTouched] = useState({});
  const [saving, setSaving]   = useState(false);
  const [err, setErr]         = useState(null);

  const set = (k, v) => setForm(p => ({ ...p, [k]: v }));

  const REQ = isEdit
    ? ['sena_usd', 'fechaReserva', 'fechaVencimiento']
    : ['propiedadId', 'brokerId', 'sena_usd', 'fechaReserva', 'fechaVencimiento'];
  const errors = {};
  REQ.forEach(k => { if (!form[k] || String(form[k]).trim() === '') errors[k] = 'Requerido'; });
  const valid = Object.keys(errors).length === 0;
  const showErr = (k) => (touched[k] || touched.__submit) && errors[k];

  const CAJA_TO_ENUM = { alvaro: 'CAJA_ALVARO', may: 'CAJA_MAY', chica: 'CAJA_CHICA', banco: 'BANCO' };

  const submit = () => {
    setTouched(p => ({ ...p, __submit: true }));
    if (!valid) return;
    setSaving(true);
    setErr(null);

    const brokerSobreId = form.brokerSobreCode
      ? (window.BROKERS[form.brokerSobreCode]?.id ?? undefined)
      : (isEdit ? reserva.brokerSobreId : undefined);

    const body = isEdit ? {
      monto:            Number(form.sena_usd),
      moneda:           'USD',
      fechaReserva:     form.fechaReserva,
      fechaVencimiento: form.fechaVencimiento,
      estado:           form.estado,
      cliente:          form.cliente          || undefined,
      direccion:        form.direccion        || undefined,
      brokerSobreId:    brokerSobreId         || undefined,
      montoSobre:       form.monto_sobre      ? Number(form.monto_sobre) : undefined,
      monedaSobre:      form.moneda_sobre,
      cajaDestino:      CAJA_TO_ENUM[form.caja] || undefined,
      notas:            form.notas            || undefined,
    } : {
      propiedadId:      form.propiedadId,
      brokerId:         form.brokerId,
      cliente:          form.cliente          || undefined,
      monto:            Number(form.sena_usd),
      moneda:           'USD',
      fechaReserva:     form.fechaReserva,
      fechaVencimiento: form.fechaVencimiento,
      direccion:        form.direccion        || undefined,
      brokerSobreId:    brokerSobreId,
      montoSobre:       form.monto_sobre      ? Number(form.monto_sobre) : undefined,
      monedaSobre:      form.moneda_sobre,
      cajaDestino:      CAJA_TO_ENUM[form.caja] ?? undefined,
      notas:            form.notas            || undefined,
    };

    const url    = isEdit ? `${API_BASE}/api/reservas/${reserva.id}` : `${API_BASE}/api/reservas`;
    const method = isEdit ? 'PUT' : 'POST';

    fetch(url, {
      method,
      credentials: 'include',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body),
    })
      .then(r => r.json())
      .then(data => {
        if (data.error) { setErr(data.error); setSaving(false); return; }
        onSave(adaptarReserva(data));
      })
      .catch(e => {
        console.error('[reserva.save]', e);
        setErr('Error al guardar reserva.');
        setSaving(false);
      });
  };

  return (
    <div className="fixed inset-0 z-30 flex">
      <div className="absolute inset-0 bg-ink/30 backdrop-blur-[2px]" onClick={onClose} />
      <div className="relative ml-auto h-full w-[520px] bg-white shadow-pop flex flex-col fade-in">
        <div className="px-6 py-5 border-b border-slate-100 flex items-start justify-between">
          <div>
            <div className="text-[10px] uppercase tracking-[0.14em] text-slate-400 font-medium">
              {isEdit ? 'Editar reserva' : 'Nueva reserva'}
            </div>
            <h2 className="font-serif text-[24px] leading-tight text-ink mt-1">
              {isEdit ? 'Modificar reserva' : 'Cargar reserva'}
            </h2>
            {!isEdit && <div className="mt-1 text-[11.5px] text-slate-500">Los 4 campos del sobre son obligatorios.</div>}
          </div>
          <button onClick={onClose} className="p-1.5 -mr-1.5 rounded hover:bg-slate-100 text-slate-500"><I.X size={16} /></button>
        </div>

        <div className="flex-1 overflow-y-auto px-6 py-5">
          <div className="grid grid-cols-2 gap-x-4">

            {/* ── Columna izquierda: Identificación ────────────────────── */}
            <div>
              <FormSection title="Identificación">
                {!isEdit && (
                  <>
                    <FormRow label="Propiedad" error={showErr('propiedadId')} required>
                      <select value={form.propiedadId} onChange={e => set('propiedadId', e.target.value)} onBlur={() => setTouched(p => ({ ...p, propiedadId: true }))}
                        className="w-full px-3 py-2 text-[13px] bg-white border border-slate-200 rounded focus:outline-none focus:border-slate-400">
                        <option value="">Seleccioná propiedad…</option>
                        {(propiedades || []).map(p => <option key={p.id} value={p.id}>{p.direccion}</option>)}
                      </select>
                    </FormRow>
                    <FormRow label="Broker" error={showErr('brokerId')} required>
                      <select value={form.brokerId} onChange={e => set('brokerId', e.target.value)} onBlur={() => setTouched(p => ({ ...p, brokerId: true }))}
                        className="w-full px-3 py-2 text-[13px] bg-white border border-slate-200 rounded focus:outline-none focus:border-slate-400">
                        <option value="">Seleccioná broker…</option>
                        {(brokers || []).map(b => <option key={b.id} value={b.id}>{b.nombre} {b.apellido}</option>)}
                      </select>
                    </FormRow>
                  </>
                )}
                {isEdit && (
                  <>
                    <FormRow label="Propiedad (referencia)">
                      <div className="px-3 py-2 text-[13px] bg-canvas border border-slate-100 rounded text-ink">
                        {reserva?.propiedad ?? '—'}
                      </div>
                    </FormRow>
                    <FormRow label="Estado">
                      <select value={form.estado} onChange={e => set('estado', e.target.value)}
                        className="w-full px-3 py-2 text-[13px] bg-white border border-slate-200 rounded focus:outline-none focus:border-slate-400">
                        <option value="PENDIENTE">Pendiente</option>
                        <option value="CONFIRMADA">Confirmada</option>
                        <option value="VENCIDA">Vencida</option>
                        <option value="CANCELADA">Cancelada</option>
                      </select>
                    </FormRow>
                  </>
                )}
                <FormRow label="Cliente">
                  <input value={form.cliente} onChange={e => set('cliente', e.target.value)}
                    placeholder="Nombre y apellido"
                    className="w-full px-3 py-2 text-[13px] bg-white border border-slate-200 rounded focus:outline-none focus:border-slate-400" />
                </FormRow>
                <FormRow label="Seña (USD)" error={showErr('sena_usd')} required>
                  <input value={form.sena_usd} onChange={e => set('sena_usd', e.target.value.replace(/[^0-9]/g, ''))} onBlur={() => setTouched(p => ({ ...p, sena_usd: true }))}
                    placeholder="0"
                    className="w-full px-3 py-2 text-[13px] bg-white border border-slate-200 rounded focus:outline-none focus:border-slate-400 font-mono" />
                </FormRow>
                <FormRow label="Fecha de reserva" error={showErr('fechaReserva')} required>
                  <input type="date" value={form.fechaReserva} onChange={e => set('fechaReserva', e.target.value)} onBlur={() => setTouched(p => ({ ...p, fechaReserva: true }))}
                    className="w-full px-3 py-2 text-[13px] bg-white border border-slate-200 rounded focus:outline-none focus:border-slate-400" />
                </FormRow>
                <FormRow label="Fecha de vencimiento" error={showErr('fechaVencimiento')} required>
                  <input type="date" value={form.fechaVencimiento} onChange={e => set('fechaVencimiento', e.target.value)} onBlur={() => setTouched(p => ({ ...p, fechaVencimiento: true }))}
                    className="w-full px-3 py-2 text-[13px] bg-white border border-slate-200 rounded focus:outline-none focus:border-slate-400" />
                </FormRow>
              </FormSection>
            </div>

            {/* ── Columna derecha: Datos del sobre ─────────────────────── */}
            <div>
              <FormSection title="Datos del sobre" pill={!isEdit ? 'Nuevo' : undefined}>
                <FormRow label="Dirección de la reserva">
                  <input value={form.direccion} onChange={e => set('direccion', e.target.value)}
                    placeholder="Dirección exacta (calle, número, piso)"
                    className="w-full px-3 py-2 text-[13px] bg-white border border-slate-200 rounded focus:outline-none focus:border-slate-400" />
                </FormRow>

                <FormRow label="Broker que entregó el sobre">
                  <div className="flex flex-wrap gap-1.5">
                    {Object.entries(BROKERS).map(([code, b]) => {
                      const sel = form.brokerSobreCode === code;
                      return (
                        <button key={code} onClick={() => { set('brokerSobreCode', code); setTouched(p => ({ ...p, brokerSobreCode: true })); }}
                          className={`inline-flex items-center gap-2 text-[12px] px-2.5 py-1 rounded border transition-colors ${sel ? 'border-transparent text-white' : 'bg-white border-slate-200 text-slate-700 hover:border-slate-300'}`}
                          style={sel ? { background: b.color } : undefined}>
                          <span className="w-4 h-4 rounded-full inline-flex items-center justify-center text-white font-semibold text-[9px]"
                            style={{ background: sel ? 'rgba(255,255,255,0.2)' : b.color }}>
                            {code}
                          </span>
                          {b.nombre.split(' ')[0]}
                        </button>
                      );
                    })}
                    {isEdit && reserva.broker_sobre && !form.brokerSobreCode && (
                      <span className="text-[11.5px] text-slate-500 self-center ml-1">(actual: {reserva.broker_sobre})</span>
                    )}
                  </div>
                </FormRow>

                <FormRow label="Monto del sobre">
                  <div className="flex items-stretch gap-2">
                    <input value={form.monto_sobre} onChange={e => set('monto_sobre', e.target.value.replace(/[^0-9]/g, ''))} onBlur={() => setTouched(p => ({ ...p, monto_sobre: true }))}
                      placeholder="0"
                      className="flex-1 px-3 py-2 text-[13px] bg-white border border-slate-200 rounded focus:outline-none focus:border-slate-400 font-mono" />
                    <div className="inline-flex items-center bg-slate-50 rounded p-0.5 text-[11px] font-medium">
                      {['ARS','USD'].map(m => (
                        <button key={m} onClick={() => set('moneda_sobre', m)}
                          className={`px-3 py-1.5 rounded transition-colors ${form.moneda_sobre === m ? 'bg-white text-ink shadow-card' : 'text-slate-500 hover:text-ink'}`}>
                          {m}
                        </button>
                      ))}
                    </div>
                  </div>
                </FormRow>

                <FormRow label="Caja donde se guardó">
                  <div className="grid grid-cols-2 gap-2">
                    {['alvaro','may'].map(id => {
                      const c = CAJAS_BY_ID[id];
                      const sel = form.caja === id;
                      return (
                        <button key={id} onClick={() => { set('caja', id); setTouched(p => ({ ...p, caja: true })); }}
                          className={`text-left px-3 py-2.5 rounded border transition-colors ${sel ? 'border-transparent text-white' : 'bg-white border-slate-200 text-slate-700 hover:border-slate-300'}`}
                          style={sel ? { background: c.color } : undefined}>
                          <div className="flex items-center gap-2">
                            <span className="w-1.5 h-1.5 rounded-full" style={{ background: sel ? '#fff' : c.color }} />
                            <span className="text-[12.5px] font-medium">{c.nombre}</span>
                          </div>
                          <div className={`text-[10.5px] mt-0.5 ${sel ? 'text-white/70' : 'text-slate-500'}`}>
                            {c.solo_reservas ? 'Solo acepta reservas' : 'Acepta cualquier tipo'}
                          </div>
                        </button>
                      );
                    })}
                  </div>
                  {form.caja === 'may' && (
                    <div className="mt-2.5 text-[11px] text-amber-800 bg-amber-50 border border-amber-200 rounded px-2.5 py-1.5 inline-flex items-center gap-1.5">
                      <I.Lock size={11} sw={2} />
                      Caja May solo admite reservas — tipo de movimiento fijado en <span className="font-medium">Reserva</span>.
                    </div>
                  )}
                </FormRow>
              </FormSection>
            </div>

          </div>
          {err && <div className="text-[12px] text-rose-700 bg-rose-50 border border-rose-200 rounded px-3 py-2 mt-4">{err}</div>}
        </div>

        <div className="px-6 py-4 border-t border-slate-100 bg-canvas flex items-center gap-2">
          <Button variant="outline" size="md" onClick={onClose}>Cancelar</Button>
          <div className="flex-1" />
          {!valid && touched.__submit && (
            <span className="text-[11px] text-rose-700 mr-2">Faltan campos obligatorios</span>
          )}
          <Button variant="gold" size="md" onClick={submit} disabled={saving}>
            {saving ? 'Guardando…' : (isEdit ? 'Guardar cambios' : 'Guardar reserva')}
          </Button>
        </div>
      </div>
    </div>
  );
}

function FormSection({ title, pill, children }) {
  return (
    <div>
      <div className="flex items-center gap-2 mb-3">
        <div className="text-[10px] uppercase tracking-[0.14em] text-slate-500 font-semibold">{title}</div>
        {pill && (
          <span className="text-[9px] uppercase tracking-[0.1em] font-medium px-1.5 py-0.5 rounded"
            style={{ background: '#C9A96120', color: '#A88A47' }}>{pill}</span>
        )}
      </div>
      <div className="space-y-3">{children}</div>
    </div>
  );
}

function FormRow({ label, required, error, children }) {
  return (
    <label className="block">
      <div className="flex items-center justify-between mb-1">
        <span className="text-[11px] text-slate-600 font-medium">
          {label}{required && <span className="text-rose-500 ml-0.5">*</span>}
        </span>
        {error && <span className="text-[10.5px] text-rose-600">{error}</span>}
      </div>
      {children}
    </label>
  );
}

window.Reservas = Reservas;
window.CajaPill = CajaPill;
