/* Análisis del proyecto en tres columnas: dos perspectivas intercambiables + el
   financiamiento. Cada columna tiene una hoja de cálculo (window.HOJA) que persiste
   POR CELDA en Supabase (PUT …/hojas/<hojaId>/<ref>, debounce ~500ms). El total de la
   hoja «La plata» alimenta en vivo la palabra COSTO en la hoja de financiamiento. */
const { useState, useEffect, useMemo, useRef, useCallback } = React;

const clp = (n) => window.fmtCLP(Math.round(Number(n) || 0));
const fmtNum = (n) => Number(n).toLocaleString('es-CL', { maximumFractionDigits: 2 });

function useMovil() {
  const [m, setM] = useState(() => window.matchMedia('(max-width:430px)').matches);
  useEffect(() => {
    const mq = window.matchMedia('(max-width:430px)');
    const h = () => setM(mq.matches);
    mq.addEventListener('change', h);
    return () => mq.removeEventListener('change', h);
  }, []);
  return m;
}

function Chip({ active, dim, onClick, icon, children }) {
  return (
    <button onClick={onClick} style={{
      display: 'inline-flex', alignItems: 'center', gap: 5, cursor: 'pointer',
      border: 0, borderRadius: 999, padding: '4px 10px', fontSize: 12, fontWeight: active ? 600 : 500,
      background: active ? 'var(--olive)' : 'var(--paper-2)',
      color: active ? '#fff' : 'var(--ink-3)',
      opacity: dim && !active ? 0.45 : 1,
    }}>{icon}{children}</button>
  );
}

const COL_TXT = { k: 'A', label: '', tipo: 'texto', w: 'minmax(0,1.5fr)' };

// Arma las semillas de cada perspectiva con los datos reales del proyecto.
function armarHojas(p, materiales) {
  const mats = (materiales || []).filter((m) => (m.proyecto_id || m.proyecto) === p.id);
  const barata = (m) => { const qs = (m.cotizaciones || []).map((c) => c.precio).filter((x) => x > 0); return qs.length ? Math.min(...qs) : 0; };
  const conCosto = (p.tareas || []).filter((t) => t.costo);
  const items = mats.length ? mats.map((m) => ({ n: m.nombre, c: m.cantidad, u: barata(m) }))
    : conCosto.map((t) => ({ n: t.titulo, c: 1, u: t.costo }));
  const nPlata = Math.max(items.length + 1, 7);
  const seedPlata = {};
  items.forEach((it, i) => {
    const f = i + 1;
    seedPlata['A' + f] = it.n; seedPlata['B' + f] = it.c; seedPlata['C' + f] = it.u; seedPlata['D' + f] = '=B' + f + '*C' + f;
  });
  seedPlata['A' + nPlata] = 'Total';
  seedPlata['D' + nPlata] = '=SUMA(D1:D' + (nPlata - 1) + ')';
  const horas = (p.tareas || []).filter((t) => !t.hecho).reduce((s, t) => s + Number(t.horas || 0), 0);

  return {
    plata: {
      label: 'La plata', nota: 'cuánto cuesta hacerlo', icon: 'wallet',
      cols: [{ ...COL_TXT, label: 'Ítem' }, { k: 'B', label: 'Cant', tipo: 'num', w: '46px' },
        { k: 'C', label: 'Unitario', tipo: 'clp', w: 'minmax(0,1fr)' }, { k: 'D', label: 'Total', tipo: 'clp', w: 'minmax(0,1fr)' }],
      filas: nPlata, seed: seedPlata, totalRef: 'D' + nPlata,
      ayuda: 'D es =B*C · el total es =SUMA(D1:D' + (nPlata - 1) + ')',
    },
    tiempo: {
      label: 'El tiempo', nota: 'hacerlo o encargarlo', icon: 'clock',
      cols: [{ ...COL_TXT, label: 'Qué' }, { k: 'B', label: 'Nosotros', tipo: 'num', w: 'minmax(0,1fr)' },
        { k: 'C', label: 'Encargarlo', tipo: 'num', w: 'minmax(0,1fr)' }],
      filas: 6, totalRef: 'B4', pesos: ['B2', 'B3', 'B4', 'C3'],
      seed: { A1: 'Horas de trabajo', B1: horas, A2: 'Valor de la hora', A3: 'Sale en', B3: '=B1*B2', A4: 'Diferencia', B4: '=C3-B3' },
      ayuda: 'Pon el valor de tu hora en B2 y la cotización del maestro en C3',
    },
    riesgo: {
      label: 'Los riesgos', nota: 'qué puede costar más', icon: 'warning',
      cols: [{ ...COL_TXT, label: 'Riesgo' }, { k: 'B', label: 'Probable %', tipo: 'num', w: '58px' },
        { k: 'C', label: 'Si pasa', tipo: 'clp', w: 'minmax(0,1fr)' }, { k: 'D', label: 'Esperado', tipo: 'clp', w: 'minmax(0,1fr)' }],
      filas: 6, totalRef: 'D6',
      seed: { A1: 'Se pasa del plazo', D1: '=B1*C1/100', A2: 'Sube el precio de los materiales', D2: '=B2*C2/100',
        A3: 'Falta una fuente para poder comprar', D3: '=B3*C3/100', A4: 'Hay que rehacer algo', D4: '=B4*C4/100',
        A6: 'Costo esperado', D6: '=SUMA(D1:D4)' },
      ayuda: 'D es =B*C/100 · el riesgo esperado suma los cuatro',
    },
  };
}

const FUENTES_PLATA = {
  libre: {
    label: 'Presupuesto libre', nota: 'la plata que Finanzas deja disponible',
    cols: [{ ...COL_TXT, label: 'Qué' }, { k: 'B', label: 'Monto', tipo: 'clp', w: 'minmax(0,1fr)' }],
    filas: 5, cuotaRef: null,
    seed: { A1: 'Lo que cuesta hacerlo', B1: '=COSTO', A2: 'Disponible este mes', B2: '=DISPONIBLE',
      A3: 'Queda del presupuesto', B3: '=PRESUPUESTO', A4: 'Falta para pagarlo de una vez', B4: '=MAX(0;B1-B2)' },
    ayuda: 'COSTO viene de la columna «La plata»',
  },
  credito: {
    label: 'Crédito', nota: 'lo pagas en cuotas con interés',
    cols: [{ ...COL_TXT, label: 'Qué' }, { k: 'B', label: 'Valor', tipo: 'num', w: 'minmax(0,1fr)' }],
    filas: 7, cuotaRef: 'B4', pesos: ['B1', 'B4', 'B5', 'B6'],
    seed: { A1: 'Monto a financiar', B1: '=COSTO', A2: 'Tasa mensual % (estimada)', B2: '2,1', A3: 'Cuotas', B3: 12,
      A4: 'Cuota mensual (estimada)', B4: '=CUOTA(B1;B2;B3)', A5: 'Costo total', B5: '=B4*B3', A6: 'Intereses', B6: '=B5-B1' },
    ayuda: '=CUOTA(monto;tasa mensual;cuotas) · cambia B2 por la tasa de tu banco',
  },
  prestamo: {
    label: 'Préstamo', nota: 'alguien te lo presta y lo devuelves',
    cols: [{ ...COL_TXT, label: 'Qué' }, { k: 'B', label: 'Valor', tipo: 'num', w: 'minmax(0,1fr)' }],
    filas: 5, cuotaRef: 'B3', pesos: ['B1', 'B3', 'B4'],
    seed: { A1: 'Monto', B1: '=COSTO', A2: 'En cuántas veces', B2: 6, A3: 'Cada vez', B3: '=B1/B2', A4: 'Interés', B4: 0 },
    ayuda: 'Sin interés: se devuelve en partes iguales',
  },
};

// ── Hoja de cálculo interactiva, persistida por celda ────────────────────────
function HojaCalc({ hojaId, cols, filas, inicial, externos, ayuda, pesos, onCambio, guardarCelda }) {
  const H = window.HOJA;
  const [celdas, setCeldas] = useState(inicial);
  const [foco, setFoco] = useState(null);
  const [sel, setSel] = useState(cols[0].k + '1');
  const caja = useRef(null);
  const timers = useRef({});
  const pending = useRef({});

  // Guardado por celda con debounce; flush al desmontar para no perder lo pendiente.
  useEffect(() => () => {
    Object.keys(timers.current).forEach((r) => clearTimeout(timers.current[r]));
    Object.entries(pending.current).forEach(([r, v]) => guardarCelda(hojaId, r, v));
  }, [hojaId]);

  const set = (ref, v) => {
    setCeldas((c) => { const n = { ...c, [ref]: v }; onCambio && onCambio(n); return n; });
    pending.current[ref] = v;
    clearTimeout(timers.current[ref]);
    timers.current[ref] = setTimeout(() => {
      guardarCelda(hojaId, ref, v); delete pending.current[ref]; delete timers.current[ref];
    }, 500);
  };

  const irA = (ref, dy) => {
    const m = /^([A-Z]+)(\d+)$/.exec(ref);
    const f = Math.min(filas, Math.max(1, +m[2] + dy));
    const dest = caja.current && caja.current.querySelector('[data-ref="' + m[1] + f + '"]');
    if (dest) dest.focus();
  };

  const anchos = '30px ' + cols.map((c) => c.w || 'minmax(0,1fr)').join(' ');
  const filaSel = +/\d+/.exec(sel)[0];
  const colSel = /^[A-Z]+/.exec(sel)[0];
  const crudo = celdas[sel] == null ? '' : String(celdas[sel]);
  const cabecera = {
    fontSize: 9.5, fontWeight: 600, letterSpacing: '.05em', textTransform: 'uppercase',
    color: 'var(--ink-4)', padding: '6px 7px', background: 'var(--paper)', display: 'flex', alignItems: 'center', gap: 5,
    overflow: 'hidden', whiteSpace: 'nowrap',
  };

  return (
    <div style={{ display: 'grid', gap: 8 }}>
      <div ref={caja} style={{ borderRadius: 12, overflow: 'hidden auto', maxHeight: 340, boxShadow: 'inset 0 1px 3px rgba(45,38,32,.09)', background: 'var(--line)' }}>
        <div style={{ display: 'grid', gridTemplateColumns: anchos, gap: 1, background: 'var(--line)', minWidth: 290 }}>
          <span style={{ ...cabecera, justifyContent: 'center' }}>
            <span style={{ fontFamily: 'var(--mono)', fontStyle: 'italic', textTransform: 'none' }}>fx</span>
          </span>
          {cols.map((c) => (
            <span key={c.k} style={{ ...cabecera, background: c.k === colSel ? 'var(--olive-tint)' : 'var(--paper)' }}>
              <span style={{ fontFamily: 'var(--mono)', opacity: 0.55 }}>{c.k}</span>
              <span style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>{c.label}</span>
            </span>
          ))}
          {Array.from({ length: filas }, (_, i) => i + 1).map((f) => (
            <React.Fragment key={f}>
              <span style={{ display: 'grid', placeItems: 'center', fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--ink-4)', background: f === filaSel ? 'var(--olive-tint)' : 'var(--paper)' }}>{f}</span>
              {cols.map((c) => {
                const ref = c.k + f;
                const editando = foco === ref;
                const m = H.mostrar(celdas, ref, externos);
                const num = m.txt === null;
                const esClp = c.tipo === 'clp' || (pesos && pesos.indexOf(ref) >= 0);
                const txt = editando ? (celdas[ref] == null ? '' : String(celdas[ref]))
                  : num ? (esClp ? clp(Math.round(m.n)) : c.tipo === 'pct' ? fmtNum(m.n) + '%' : fmtNum(m.n))
                    : m.txt;
                return (
                  <input key={ref} data-ref={ref} value={txt} spellCheck="false"
                    onChange={(ev) => set(ref, ev.target.value)}
                    onFocus={() => { setFoco(ref); setSel(ref); }}
                    onBlur={() => setFoco((f2) => (f2 === ref ? null : f2))}
                    onKeyDown={(ev) => {
                      if (ev.key === 'Enter') { ev.preventDefault(); ev.currentTarget.blur(); irA(ref, 1); }
                      if (ev.key === 'Escape') ev.currentTarget.blur();
                    }}
                    style={{
                      border: 0, outline: 'none', font: 'inherit', width: '100%', boxSizing: 'border-box', padding: '6px 7px', minWidth: 0,
                      fontFamily: num || c.tipo !== 'texto' ? 'var(--mono)' : 'inherit',
                      fontSize: c.tipo === 'texto' ? 11.5 : 11,
                      textAlign: c.tipo === 'texto' ? 'left' : 'right',
                      color: m.error ? 'var(--rust)' : num && m.formula ? 'var(--olive)' : 'var(--ink)',
                      background: sel === ref ? 'var(--olive-tint)' : 'var(--card-elev)',
                      backgroundImage: m.formula && !editando ? 'linear-gradient(225deg,var(--olive) 0 4px,transparent 4px)' : 'none',
                      boxShadow: sel === ref ? 'inset 0 0 0 1.5px var(--olive)' : 'none',
                    }} />
                );
              })}
            </React.Fragment>
          ))}
        </div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, minHeight: 20 }}>
        <span style={{ fontFamily: 'var(--mono)', fontSize: 11, padding: '2px 7px', border: '1px solid var(--line)', borderRadius: 6, color: 'var(--ink-3)' }}>{sel}</span>
        <span style={{ flex: 1, minWidth: 0, fontFamily: 'var(--mono)', fontSize: 10.5, color: 'var(--ink-4)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {crudo || (ayuda || 'Escribe un número, o = para calcular')}
        </span>
      </div>
    </div>
  );
}

function Columna({ titulo, nota, icon, acciones, children, pie }) {
  return (
    <div className="card" style={{ padding: 0, display: 'flex', flexDirection: 'column', minWidth: 0 }}>
      <div style={{ padding: '15px 16px 12px', borderBottom: '1px solid var(--line)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ color: 'var(--olive)' }}><Icon name={icon} size={14} /></span>
          <span style={{ fontFamily: "'Instrument Serif', serif", fontStyle: 'italic', fontSize: 16 }}>{titulo}</span>
        </div>
        <div style={{ fontSize: 11, color: 'var(--ink-4)', marginTop: 3 }}>{nota}</div>
        {acciones && <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 11 }}>{acciones}</div>}
      </div>
      <div style={{ padding: '13px 16px', minWidth: 0 }}>{children}</div>
      {pie && <div style={{ padding: '12px 16px 15px', borderTop: '1px solid var(--line)', background: 'var(--paper)' }}>{pie}</div>}
    </div>
  );
}

function AnalisisView() {
  const movil = useMovil();
  const H = window.HOJA;
  const [data, setData] = useState(null);
  const [err, setErr] = useState('');
  const [proy, setProy] = useState(null);
  const [izq, setIzq] = useState('plata');
  const [der, setDer] = useState('tiempo');
  const [fuente, setFuente] = useState('libre');
  const [hojas, setHojas] = useState({});
  const [costo, setCosto] = useState(0);
  const [toast, setToast] = useState('');

  useEffect(() => {
    window.api('/api/proyectos/app-data')
      .then((d) => { setData(d); if (d.proyectos?.length) setProy(d.proyectos[0].id); })
      .catch((e) => setErr(e.message));
  }, []);

  const cargarHojas = useCallback(async (pid) => {
    try { setHojas(await window.api(`/api/proyectos/${pid}/hojas`)); }
    catch { setHojas({}); }
  }, []);
  useEffect(() => { if (proy) cargarHojas(proy); }, [proy, cargarHojas]);

  const guardarCelda = useCallback(async (hojaId, ref, txt) => {
    if (!proy) return;
    try {
      await window.api(`/api/proyectos/${proy}/hojas/${encodeURIComponent(hojaId)}/${encodeURIComponent(ref)}`,
        { method: 'PUT', body: JSON.stringify({ txt }) });
    } catch (e) { /* piloto: última escritura gana; error silencioso */ }
  }, [proy]);

  const p = (data?.proyectos || []).find((x) => x.id === proy);
  const defs = useMemo(() => (p ? armarHojas(p, data.materiales) : null), [p, data]);
  const inicialDe = useCallback((hojaId, seed) => ({ ...seed, ...((hojas[hojaId] || {}).celdas || {}) }), [hojas]);

  // costo inicial desde la hoja de plata (semilla + lo guardado)
  useEffect(() => {
    if (!defs || !proy) return;
    setCosto(H.valor(inicialDe(`${proy}:plata`, defs.plata.seed), defs.plata.totalRef));
  }, [defs, proy, hojas]);

  if (err) return <div className="card" style={{ padding: 18, color: 'var(--rust)' }}>No se pudo cargar: {err}</div>;
  if (!data) return <div style={{ color: 'var(--ink-3)' }}>Cargando…</div>;
  if (!(data.proyectos || []).length) {
    return (
      <div className="card" style={{ padding: 40, textAlign: 'center', maxWidth: 460, margin: '30px auto' }}>
        <div style={{ opacity: 0.5, marginBottom: 12 }}><Icon name="chart" size={32} /></div>
        <h2 style={{ fontSize: 18, margin: '0 0 6px' }}>Nada que analizar todavía</h2>
        <p style={{ color: 'var(--ink-3)', fontSize: 13, margin: 0 }}>Creá un proyecto y cargale materiales y tareas primero, en la pestaña Proyectos.</p>
      </div>
    );
  }

  const disponible = Number(data.finanzas?.disponible || 0);
  const resta = (p.presupuesto || 0) - (p.gastado || 0);
  const externos = { COSTO: costo, DISPONIBLE: disponible, PRESUPUESTO: resta };
  const fdef = FUENTES_PLATA[fuente];
  const idFin = `${proy}:fin:${fuente}`;

  const leer = (id, def, ref) => H.valor(inicialDe(id, def.seed), ref, externos);
  const cuota = fdef.cuotaRef ? leer(idFin, fdef, fdef.cuotaRef) : 0;
  const falta = fuente === 'libre' ? leer(idFin, fdef, 'B4') : 0;
  const alcanza = fuente === 'libre' ? falta <= 0 : (disponible > 0 && cuota <= disponible);
  const meses = disponible > 0 ? Math.ceil(costo / disponible) : 0;

  const llevarAFinanzas = async () => {
    const cel = inicialDe(idFin, fdef.seed);
    const tasa = fuente === 'credito' ? H.valor(cel, 'B2', externos) : 0;
    const cuotas = fuente === 'credito' ? H.valor(cel, 'B3', externos) : fuente === 'prestamo' ? H.valor(cel, 'B2', externos) : 0;
    const cuotaVal = fdef.cuotaRef ? H.valor(cel, fdef.cuotaRef, externos) : 0;
    try {
      await window.api(`/api/proyectos/${proy}/plan-financiero`, {
        method: 'PUT',
        body: JSON.stringify({ fuente, monto: costo, tasa, cuotas, cuota: cuotaVal }),
      });
      setToast('Guardado como escenario propuesto en Finanzas. No se descontó nada todavía.');
    } catch (e) { setToast('No se pudo guardar: ' + e.message); }
    setTimeout(() => setToast(''), 4500);
  };

  const perspectiva = (key, setKey, otro) => {
    const def = defs[key];
    const id = `${proy}:${key}`;
    const total = def.totalRef ? leer(id, def, def.totalRef) : 0;
    return (
      <Columna titulo={def.label} nota={def.nota} icon={def.icon}
        acciones={Object.keys(defs).map((k) => (
          <Chip key={k} active={k === key} dim={k === otro} onClick={() => setKey(k)}>{defs[k].label}</Chip>
        ))}
        pie={key === 'plata' ? (
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
            <span style={{ fontSize: 11.5, color: 'var(--ink-4)' }}>Total de la hoja</span>
            <span style={{ marginLeft: 'auto', fontFamily: "'Instrument Serif', serif", fontStyle: 'italic', fontSize: 20 }}>{clp(total)}</span>
          </div>
        ) : key === 'tiempo' ? (
          <p style={{ margin: 0, fontSize: 11.5, lineHeight: 1.5, color: 'var(--ink-4)' }}>
            {total > 0 ? 'Encargarlo cuesta ' + clp(total) + ' más que hacerlo ustedes.'
              : total < 0 ? 'Encargarlo sale ' + clp(-total) + ' más barato que hacerlo ustedes.'
                : 'Pon el valor de tu hora y la cotización del maestro para comparar.'}
          </p>
        ) : (
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
            <span style={{ fontSize: 11.5, color: 'var(--ink-4)' }}>Riesgo esperado</span>
            <span style={{ marginLeft: 'auto', fontFamily: 'var(--mono)', fontSize: 14 }}>{clp(total)}</span>
          </div>
        )}>
        <HojaCalc key={id} hojaId={id} cols={def.cols} filas={def.filas} inicial={inicialDe(id, def.seed)}
          ayuda={def.ayuda} pesos={def.pesos} externos={externos}
          onCambio={key === 'plata' ? (c) => setCosto(H.valor(c, def.totalRef)) : undefined}
          guardarCelda={guardarCelda} />
      </Columna>
    );
  };

  const barPct = disponible > 0 ? Math.min(100, ((fuente === 'libre' ? costo : cuota) / disponible) * 100) : 0;

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap', marginBottom: 16 }}>
        <div>
          <h1 style={{ fontFamily: "'Instrument Serif', serif", fontStyle: 'italic', fontSize: 26, margin: 0 }}>Análisis del proyecto</h1>
          <p style={{ color: 'var(--ink-4)', fontSize: 13, margin: '2px 0 0' }}>{p.nombre} · dos perspectivas y el financiamiento, con celdas para calcular acá mismo</p>
        </div>
        <span style={{ fontFamily: 'var(--mono)', fontSize: 12, padding: '5px 10px', border: '1px solid var(--line)', borderRadius: 999, color: 'var(--ink-3)' }}>{clp(costo)} en la hoja</span>
      </div>

      <div className="card" style={{ padding: '12px 16px', marginBottom: 14 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
          <span style={{ fontSize: 11, color: 'var(--ink-4)' }}>Proyecto:</span>
          {data.proyectos.map((x) => (
            <Chip key={x.id} active={x.id === proy} onClick={() => setProy(x.id)} icon={<Icon name={x.icon || 'home'} size={12} />}>{x.nombre}</Chip>
          ))}
        </div>
      </div>

      <div style={{ overflowX: 'auto', paddingBottom: 4 }}>
        <div style={{ display: 'grid', gridTemplateColumns: movil ? '1fr' : 'repeat(3, minmax(320px, 1fr))', gap: 14, alignItems: 'start', minWidth: movil ? 'auto' : 980 }}>
          {perspectiva(izq, setIzq, der)}
          {perspectiva(der, setDer, izq)}

          <Columna titulo="Con qué se paga" nota={fdef.nota} icon="wallet"
            acciones={Object.entries(FUENTES_PLATA).map(([k, f]) => (
              <Chip key={k} active={k === fuente} onClick={() => setFuente(k)}>{f.label}</Chip>
            ))}
            pie={
              <div style={{ display: 'grid', gap: 9 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span className="tag" style={{ background: alcanza ? 'var(--olive-tint)' : 'var(--rust-tint)', color: alcanza ? 'var(--olive)' : 'var(--rust)', padding: '3px 9px', borderRadius: 999, fontSize: 11, fontWeight: 600 }}>{alcanza ? 'alcanza' : 'no alcanza'}</span>
                  <span style={{ marginLeft: 'auto', fontFamily: 'var(--mono)', fontSize: 12 }}>
                    {fuente === 'libre' ? clp(disponible) + ' este mes' : clp(cuota) + ' al mes'}
                  </span>
                </div>
                <div style={{ height: 5, borderRadius: 999, background: 'var(--line)', overflow: 'hidden' }}>
                  <div style={{ height: '100%', width: barPct + '%', background: alcanza ? 'var(--olive)' : 'var(--rust)' }} />
                </div>
                <p style={{ margin: 0, fontSize: 11.5, lineHeight: 1.5, color: 'var(--ink-4)' }}>
                  {disponible <= 0
                    ? 'El disponible del mes lo trae Finanzas, que todavía no está en la plataforma nueva. Por eso queda en blanco por ahora.'
                    : fuente === 'libre'
                      ? (falta > 0 ? 'Faltan ' + clp(falta) + ' para pagarlo de una vez. Juntándolo, son ' + meses + ' meses.' : 'Cabe en la plata libre de este mes, sin pedirle nada a nadie.')
                      : (alcanza ? 'La cuota entra en lo disponible del mes. Ojo con las otras cuotas que ya tienes.' : 'La cuota se pasa de lo disponible. Sube el plazo o baja el monto.')}
                </p>
                <button className="btn" onClick={llevarAFinanzas} style={{ justifyContent: 'center' }}>
                  Llevar a Finanzas <Icon name="chevronRight" size={14} />
                </button>
              </div>
            }>
            <HojaCalc key={idFin} hojaId={idFin} cols={fdef.cols} filas={fdef.filas} inicial={inicialDe(idFin, fdef.seed)}
              ayuda={fdef.ayuda} pesos={fdef.pesos} externos={externos} guardarCelda={guardarCelda} />
          </Columna>
        </div>
      </div>

      <div className="card" style={{ padding: '16px 18px', marginTop: 14 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
          <span style={{ color: 'var(--olive)', flexShrink: 0 }}><Icon name="plan" size={28} /></span>
          <p style={{ margin: 0, flex: 1, minWidth: 220, fontSize: 12, lineHeight: 1.55, color: 'var(--ink-4)' }}>
            Las celdas entienden fórmulas: <code style={{ fontFamily: 'var(--mono)' }}>=B2*C2</code>,{' '}
            <code style={{ fontFamily: 'var(--mono)' }}>=SUMA(D1:D6)</code>,{' '}
            <code style={{ fontFamily: 'var(--mono)' }}>=CUOTA(B1;B2;B3)</code>, y también{' '}
            <code style={{ fontFamily: 'var(--mono)' }}>PROM MIN MAX SI REDONDEA</code>.{' '}
            La palabra <code style={{ fontFamily: 'var(--mono)' }}>COSTO</code> trae el total de «La plata» a cualquier hoja.
          </p>
        </div>
      </div>

      {toast && (
        <div style={{ position: 'fixed', bottom: 20, left: '50%', transform: 'translateX(-50%)', background: 'var(--ink)', color: 'var(--paper)', padding: '11px 16px', borderRadius: 12, fontSize: 13, boxShadow: '0 8px 28px rgba(0,0,0,.2)', zIndex: 50, maxWidth: '90%' }}>{toast}</div>
      )}
    </div>
  );
}

window.AnalisisView = AnalisisView;
