// ─── Cajas: overview multi-caja ─────────────────────────────────────────────

// Metadatos de presentación por nombre ENUM (color, label y alias no existen en Prisma)
const CAJA_META = {
  CAJA_CHICA:  { id: 'chica',  label: 'Caja Chica',      color: '#10b981', alias: null },
  CAJA_ALVARO: { id: 'alvaro', label: 'Caja Álvaro',      color: '#6366f1', alias: null },
  CAJA_MAY:    { id: 'may',    label: 'Caja May',          color: '#f59e0b', alias: null },
  BANCO:       { id: 'banco',  label: 'Cuenta Bancaria',   color: '#3b82f6', alias: 'Galicia · 0010-4421-3' },
};

function adaptarCaja(c) {
  const meta = CAJA_META[c.nombre] ?? { id: c.id, label: c.nombre, color: '#677A88', alias: null };
  return {
    id:            meta.id,
    nombre:        meta.label,
    tipo:          c.tipo === 'BANCO' ? 'banco' : 'efectivo',
    ars:           Number(c.saldoARS),
    usd:           Number(c.saldoUSD),
    color:         meta.color,
    alias:         meta.alias,
    solo_reservas: c.soloReservas,
  };
}

function Cajas() {
  const [selected, setSelected]         = useState('todas');
  const [cajasLive, setCajasLive]       = useState([]);
  const [cajasRawById, setCajasRawById] = useState({});   // cuid → dato crudo de API (para lookup de transferencias)
  const [transferencias, setTransferencias] = useState([]);
  const [loading, setLoading]           = useState(true);
  const [error, setError]               = useState(null);

  useEffect(() => {
    Promise.all([
      fetch(`${API_BASE}/api/cajas`,              { credentials: 'include' }).then(r => r.json()),
      fetch(`${API_BASE}/api/cajas/transferencias`, { credentials: 'include' }).then(r => r.json()),
    ])
      .then(([cajasJson, transJson]) => {
        const cajasArr = Array.isArray(cajasJson) ? cajasJson : (cajasJson.data ?? []);
        setCajasLive(cajasArr.map(adaptarCaja));
        setCajasRawById(Object.fromEntries(cajasArr.map(c => [c.id, c])));
        setTransferencias(Array.isArray(transJson) ? transJson : []);
        setLoading(false);
      })
      .catch(err => {
        console.error('[cajas fetch]', err);
        setError('Error al cargar cajas.');
        setLoading(false);
      });
  }, []);

  const totals = useMemo(() => ({
    ars: cajasLive.reduce((s, c) => s + c.ars, 0),
    usd: cajasLive.reduce((s, c) => s + c.usd, 0),
  }), [cajasLive]);

  // Build unified movement log from gastos, ingresos, transferencias reales
  const log = useMemo(() => {
    const items = [];
    INGRESOS.forEach(i => items.push({
      kind: 'Ingreso', id: i.id, fecha: i.fecha, concepto: i.concepto,
      caja: i.caja, ars: i.moneda === 'ARS' ? i.monto : null, usd: i.moneda === 'USD' ? i.monto : null,
    }));
    GASTOS.forEach(g => items.push({
      kind: 'Gasto', id: g.id, fecha: g.fecha, concepto: g.desc,
      caja: g.caja, ars: g.moneda === 'ARS' ? -g.monto : null, usd: g.moneda === 'USD' ? -g.monto : null,
    }));
    // Transferencias reales: dos entradas por registro (salida + entrada)
    transferencias.forEach(t => {
      const nombreOrigen  = cajasRawById[t.cajaOrigenId]?.nombre;
      const nombreDestino = cajasRawById[t.cajaDestinoId]?.nombre;
      const metaOrigen    = CAJA_META[nombreOrigen];
      const metaDestino   = CAJA_META[nombreDestino];
      const labelOrigen   = metaOrigen?.label  ?? nombreOrigen  ?? t.cajaOrigenId;
      const labelDestino  = metaDestino?.label ?? nombreDestino ?? t.cajaDestinoId;
      const cajaOrigenId  = metaOrigen?.id  ?? t.cajaOrigenId;
      const cajaDestinoId = metaDestino?.id ?? t.cajaDestinoId;
      const fecha         = (t.creadoEn ?? '').slice(0, 10);
      items.push({
        kind: 'Movimiento', id: t.id, fecha,
        concepto: `→ ${labelDestino}`,
        caja: cajaOrigenId,
        ars: t.monedaOrigen  === 'ARS' ? -Number(t.montoOrigen)  : null,
        usd: t.monedaOrigen  === 'USD' ? -Number(t.montoOrigen)  : null,
      });
      items.push({
        kind: 'Movimiento', id: t.id, fecha,
        concepto: `← ${labelOrigen}`,
        caja: cajaDestinoId,
        ars: t.monedaDestino === 'ARS' ?  Number(t.montoDestino) : null,
        usd: t.monedaDestino === 'USD' ?  Number(t.montoDestino) : null,
      });
    });
    return items.sort((a, b) => b.fecha.localeCompare(a.fecha));
  }, [transferencias, cajasRawById]);

  const filtered = selected === 'todas' ? log : log.filter(l => l.caja === selected);

  const columns = [
    { key: 'fecha', label: 'Fecha' },
    { key: 'id', label: 'ID' },
    { key: 'kind', label: 'Tipo' },
    { label: 'Caja', value: l => CAJAS_BY_ID[l.caja]?.nombre },
    { key: 'concepto', label: 'Concepto' },
    { key: 'ars', label: 'ARS' },
    { key: 'usd', label: 'USD' },
  ];

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

  return (
    <div className="fade-in">
      <PageHeader
        crumbs={['Inicio', 'Finanzas', 'Cajas']}
        title="Cajas y cuentas"
        sub="Saldos consolidados · doble moneda"
        actions={
          <>
            <ExportButton filename={`lanven-cajas-${new Date().toISOString().slice(0,10)}`} rows={filtered} columns={columns} count={filtered.length} />
            <Button variant="outline" size="md">Conciliar</Button>
          </>
        }
      />

      {/* Totals strip */}
      <div className="bg-white rounded-md border border-slate-100 shadow-card p-5 mb-4 flex items-center gap-8">
        <div>
          <div className="text-[10px] uppercase tracking-[0.14em] text-slate-500 font-medium">Total consolidado</div>
          <div className="font-serif text-[10px] text-slate-400 mt-0.5">4 cajas y cuentas</div>
        </div>
        <div className="w-px h-10 bg-slate-100" />
        <div>
          <div className="text-[10px] uppercase tracking-[0.12em] text-slate-400">Pesos</div>
          <div className="font-mono text-[22px] text-ink leading-none mt-1">{ARS(totals.ars)}</div>
        </div>
        <div className="w-px h-10 bg-slate-100" />
        <div>
          <div className="text-[10px] uppercase tracking-[0.12em] text-slate-400">Dólares</div>
          <div className="font-mono text-[22px] text-ink leading-none mt-1">{USD(totals.usd)}</div>
        </div>
        <div className="w-px h-10 bg-slate-100" />
        <div>
          <div className="text-[10px] uppercase tracking-[0.12em] text-slate-400">Equivalente USD</div>
          <div className="font-mono text-[22px] text-gold-deep leading-none mt-1">{USD(Math.round(totals.ars / 1180.5 + totals.usd))}</div>
          <div className="text-[10px] text-slate-400 mt-0.5">TC $1.180,50</div>
        </div>
      </div>

      {/* Caja cards */}
      <div className="grid grid-cols-4 gap-4 mb-6">
        <CajaTile c={{ id: 'todas', nombre: 'Todas', alias: 'vista consolidada', color: '#1F2A33', ars: totals.ars, usd: totals.usd, tipo: '' }}
          active={selected === 'todas'} onClick={() => setSelected('todas')} />
        {cajasLive.map(c => (
          <CajaTile key={c.id} c={c} active={selected === c.id} onClick={() => setSelected(c.id)} />
        ))}
      </div>

      {/* Banner regla Caja May — visible cuando la caja seleccionada sólo admite reservas */}
      {selected !== 'todas' && CAJAS_BY_ID[selected]?.solo_reservas && (
        <CajaSoloReservasBanner caja={CAJAS_BY_ID[selected]} />
      )}

      {/* Movement log */}
      <Card pad="p-0"
        title={selected === 'todas' ? 'Movimientos · todas las cajas' : `Movimientos · ${CAJAS_BY_ID[selected].nombre}`}
        action={<span className="text-[11px] text-slate-400">{filtered.length} registros</span>}>
        <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">Fecha</th>
              <th className="font-medium">Tipo</th>
              <th className="font-medium">ID</th>
              <th className="font-medium">Caja</th>
              <th className="font-medium">Concepto</th>
              <th className="font-medium text-right">ARS</th>
              <th className="font-medium text-right pr-5">USD</th>
            </tr>
          </thead>
          <tbody>
            {filtered.slice(0, 20).map((l, i) => (
              <tr key={l.id + '-' + i} className="border-t border-slate-100 tr-hover">
                <td className="py-3 px-5 text-slate-600 font-mono text-[11.5px]">{l.fecha.slice(5)}</td>
                <td><KindBadge kind={l.kind} /></td>
                <td className="font-mono text-[11.5px] text-slate-500">{l.id}</td>
                <td className="text-slate-700 text-[12px]">
                  <span className="inline-flex items-center gap-1.5">
                    <span className="w-1.5 h-1.5 rounded-full" style={{ background: CAJAS_BY_ID[l.caja]?.color ?? '#677A88' }} />
                    {CAJAS_BY_ID[l.caja]?.nombre ?? '—'}
                  </span>
                </td>
                <td className="text-ink">{l.concepto}</td>
                <td className={`text-right font-mono ${l.ars < 0 ? 'text-rose-700' : l.ars > 0 ? 'text-emerald-700' : 'text-slate-300'}`}>{l.ars != null ? (l.ars > 0 ? '+ ' : '− ') + ARS(Math.abs(l.ars)) : '—'}</td>
                <td className={`text-right font-mono pr-5 ${l.usd < 0 ? 'text-rose-700' : l.usd > 0 ? 'text-emerald-700' : 'text-slate-300'}`}>{l.usd != null ? (l.usd > 0 ? '+ ' : '− ') + USD(Math.abs(l.usd)) : '—'}</td>
              </tr>
            ))}
          </tbody>
        </table>
        {filtered.length > 20 && (
          <div className="px-5 py-3 border-t border-slate-100 text-center text-[11px] text-slate-500">
            Mostrando 20 de {filtered.length} · <button className="text-slate-700 hover:text-ink font-medium">Ver todos</button>
          </div>
        )}
      </Card>
    </div>
  );
}

function CajaTile({ c, active, onClick }) {
  const isBank = c.tipo === 'banco';
  const isAll = c.id === 'todas';
  return (
    <button onClick={onClick}
      className={`relative text-left bg-white rounded-md border shadow-card p-5 transition-all hover:-translate-y-0.5 hover:shadow-pop ${active ? 'border-slate-700' : 'border-slate-100 hover:border-slate-200'}`}>
      {active && <span className="absolute top-0 left-5 right-5 h-0.5 rounded-b" style={{ background: c.color }} />}
      <div className="flex items-start justify-between">
        <div>
          <div className="flex items-center gap-2">
            <span className="w-2 h-2 rounded-full" style={{ background: c.color }} />
            <span className="text-[12.5px] font-semibold text-ink">{c.nombre}</span>
          </div>
          {c.alias && <div className="text-[10px] text-slate-500 mt-0.5 font-mono">{c.alias}</div>}
        </div>
        <span className="text-[9px] uppercase tracking-[0.12em] text-slate-400 font-medium">
          {isAll ? 'Total' : isBank ? 'Banco' : 'Efectivo'}
        </span>
      </div>
      {/* Etiqueta "Solo reservas" — regla de negocio específica de Caja May */}
      {c.solo_reservas && (
        <div className="mt-2 inline-flex items-center gap-1.5 text-[10px] font-medium px-1.5 py-0.5 rounded"
          style={{ background: '#C9A96120', color: '#A88A47' }}>
          <I.Bookmark size={10} sw={2} />
          Solo reservas
        </div>
      )}
      <div className="mt-4">
        <div className="text-[10px] uppercase tracking-[0.12em] text-slate-400">ARS</div>
        <div className="font-mono text-[18px] text-ink leading-none mt-1">{ARS(c.ars)}</div>
      </div>
      <div className="mt-3">
        <div className="text-[10px] uppercase tracking-[0.12em] text-slate-400">USD</div>
        <div className="font-mono text-[18px] text-ink leading-none mt-1">{USD(c.usd)}</div>
      </div>
    </button>
  );
}

// ── Banner Caja May ── reglas + intento de movimiento no-reserva
function CajaSoloReservasBanner({ caja }) {
  const [attempt, setAttempt] = useState(null);   // null | 'Gasto' | 'Ingreso' | 'Movimiento'
  const tipos = [
    { id: 'Reserva',    label: 'Reserva',    allowed: true,  glyph: '◆' },
    { id: 'Ingreso',    label: 'Ingreso',    allowed: false, glyph: '+' },
    { id: 'Gasto',      label: 'Gasto',      allowed: false, glyph: '−' },
    { id: 'Movimiento', label: 'Movimiento', allowed: false, glyph: '⇄' },
  ];
  return (
    <div className="mb-6 bg-white border border-slate-100 shadow-card rounded-md overflow-hidden">
      <div className="px-5 py-4 flex items-start gap-4 border-b border-slate-100">
        <span className="inline-flex items-center justify-center w-9 h-9 rounded-full flex-shrink-0"
          style={{ background: caja.color + '20', color: caja.color }}>
          <I.Bookmark size={16} sw={1.8} />
        </span>
        <div className="flex-1">
          <div className="flex items-center gap-2">
            <h3 className="text-[14px] font-semibold text-ink">{caja.nombre} · solo reservas</h3>
            <span className="inline-flex items-center gap-1 text-[10px] font-medium px-1.5 py-0.5 rounded"
              style={{ background: '#C9A96120', color: '#A88A47' }}>
              <span className="w-1 h-1 rounded-full" style={{ background: '#A88A47' }} />
              Regla activa
            </span>
          </div>
          <p className="text-[12px] text-slate-600 mt-1 leading-snug">
            Esta caja acepta únicamente movimientos de tipo <span className="font-medium text-ink">reserva</span>. Cualquier otro tipo de movimiento será rechazado al guardar.
          </p>
        </div>
      </div>
      <div className="px-5 py-3 bg-canvas/40 flex items-center gap-3 flex-wrap">
        <span className="text-[10.5px] uppercase tracking-[0.12em] text-slate-500 font-medium">Registrar movimiento</span>
        {tipos.map(t => (
          <button key={t.id}
            onClick={() => setAttempt(t.allowed ? null : t.id)}
            className={`inline-flex items-center gap-1.5 text-[11.5px] px-2.5 py-1 rounded border transition-colors ${
              t.allowed ? 'bg-white border-emerald-200 text-emerald-800 hover:border-emerald-300' :
                          'bg-white border-slate-200 text-slate-500 hover:border-rose-300 hover:text-rose-700'
            }`}>
            <span className="font-mono text-[10px] opacity-70">{t.glyph}</span>
            {t.label}
            {!t.allowed && <I.Lock size={10} sw={2} className="opacity-60" />}
          </button>
        ))}
        <div className="flex-1" />
        {attempt && (
          <div className="inline-flex items-center gap-2 text-[11.5px] px-3 py-1.5 rounded border border-rose-200 bg-rose-50 text-rose-800">
            <I.X size={12} sw={2.5} />
            <span><span className="font-medium">Caja May solo admite reservas.</span> No se puede registrar un movimiento de tipo {attempt.toLowerCase()}.</span>
            <button onClick={() => setAttempt(null)} className="text-rose-700/70 hover:text-rose-900 ml-1"><I.X size={11} /></button>
          </div>
        )}
      </div>
    </div>
  );
}

function KindBadge({ kind }) {
  const map = {
    Ingreso:    { bg: 'bg-emerald-50',  fg: 'text-emerald-800' },
    Gasto:      { bg: 'bg-rose-50',     fg: 'text-rose-800'    },
    Movimiento: { bg: 'bg-slate-100',   fg: 'text-slate-700'   },
  };
  const s = map[kind] || map.Movimiento;
  return <span className={`inline-block px-2 py-0.5 rounded text-[10px] font-medium ${s.bg} ${s.fg}`}>{kind}</span>;
}

window.Cajas = Cajas;
window.KindBadge = KindBadge;
