/* Finanzas (Fase 2, mínimo): login + «Disponible del mes».
   Fijás el ingreso disponible del mes; ese número es el que Proyectos usa en la
   3ª columna de Análisis. El gastado sale de transactions (0 hasta que haya). */
const { useState, useEffect } = React;

window.fmtCLP = (n) => '$' + (Math.round(Number(n) || 0)).toLocaleString('es-CL');

function Login() {
  const [email, setEmail] = useState('');
  const [sent, setSent] = useState(false);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');
  const enviar = async (e) => {
    e.preventDefault();
    if (!email || busy) return;
    setBusy(true); setErr('');
    try {
      const { error } = await window.sb.auth.signInWithOtp({ email, options: { emailRedirectTo: window.location.origin } });
      if (error) throw error; setSent(true);
    } catch (ex) { setErr(ex.message || 'No se pudo enviar'); } finally { setBusy(false); }
  };
  return (
    <div style={{ minHeight: '100vh', display: 'grid', placeItems: 'center', background: 'var(--paper)' }}>
      <div className="card" style={{ maxWidth: 380, width: '90%', padding: 28, textAlign: 'center' }}>
        <div className="brand-mark" style={{ margin: '0 auto 14px' }}>F</div>
        <h1 style={{ fontFamily: "'Instrument Serif', serif", fontStyle: 'italic', fontSize: 26, margin: '0 0 6px' }}>Finanzas</h1>
        <p style={{ color: 'var(--ink-3)', fontSize: 13, margin: '0 0 20px' }}>Entrá con tu correo y te mandamos un enlace.</p>
        {sent ? (
          <div className="tag" style={{ display: 'inline-flex', padding: '10px 14px' }}><Icon name="check" size={14} /> Revisá tu correo: te enviamos el enlace a {email}.</div>
        ) : (
          <form onSubmit={enviar}>
            <input type="email" required value={email} onChange={(e) => setEmail(e.target.value)} placeholder="tu@correo.cl" autoFocus
              style={{ width: '100%', padding: '11px 13px', borderRadius: 12, border: '1px solid var(--line)', background: 'var(--card-elev)', color: 'var(--ink)', fontSize: 14, marginBottom: 12 }} />
            <button className="btn olive" type="submit" disabled={busy} style={{ width: '100%', justifyContent: 'center' }}>{busy ? 'Enviando…' : 'Enviarme el enlace'}</button>
            {err && <p style={{ color: 'var(--rust)', fontSize: 12, marginTop: 10 }}>{err}</p>}
          </form>
        )}
      </div>
    </div>
  );
}

function Disponible() {
  const [mes, setMes] = useState(() => new Date().toISOString().slice(0, 7));
  const [data, setData] = useState(null);
  const [ingreso, setIngreso] = useState('');
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');
  const [ok, setOk] = useState('');

  const cargar = async (m) => {
    setErr('');
    try {
      const d = await window.api('/api/finanzas/app-data?mes=' + m);
      setData(d); setIngreso(d.ingreso ? String(d.ingreso) : '');
    } catch (e) { setErr(e.message); }
  };
  useEffect(() => { cargar(mes); }, [mes]);

  const guardar = async (e) => {
    e.preventDefault();
    if (busy) return; setBusy(true); setOk('');
    try {
      const d = await window.api('/api/finanzas/budget/disponible', { method: 'PUT', body: JSON.stringify({ mes, ingreso: Number(ingreso) || 0 }) });
      setData(d); setOk('Guardado. Este es el disponible que Proyectos usa en Análisis.');
      setTimeout(() => setOk(''), 4000);
    } catch (ex) { setErr(ex.message); } finally { setBusy(false); }
  };

  return (
    <div style={{ maxWidth: 560 }}>
      <h1 style={{ fontFamily: "'Instrument Serif', serif", fontStyle: 'italic', fontSize: 26, margin: '0 0 4px' }}>Disponible del mes</h1>
      <p style={{ color: 'var(--ink-4)', fontSize: 13, margin: '0 0 20px' }}>Fijá el ingreso disponible del mes. Es el número que Proyectos usa para saber si un proyecto “alcanza”.</p>

      <div className="card" style={{ padding: 20, display: 'grid', gap: 16 }}>
        <label style={{ display: 'flex', flexDirection: 'column', gap: 4, fontSize: 12, color: 'var(--ink-3)' }}>
          Mes
          <input type="month" value={mes} onChange={(e) => setMes(e.target.value)}
            style={{ padding: '9px 11px', borderRadius: 10, border: '1px solid var(--line)', background: 'var(--card-elev)', color: 'var(--ink)', fontSize: 14, maxWidth: 200 }} />
        </label>
        <form onSubmit={guardar} style={{ display: 'grid', gap: 12 }}>
          <label style={{ display: 'flex', flexDirection: 'column', gap: 4, fontSize: 12, color: 'var(--ink-3)' }}>
            Ingreso disponible (CLP)
            <input inputMode="numeric" value={ingreso} onChange={(e) => setIngreso(e.target.value.replace(/[^\d]/g, ''))} placeholder="Ej: 850000"
              style={{ padding: '11px 13px', borderRadius: 10, border: '1px solid var(--line)', background: 'var(--card-elev)', color: 'var(--ink)', fontSize: 16, fontFamily: 'var(--mono)' }} />
          </label>
          <button className="btn olive" type="submit" disabled={busy} style={{ justifySelf: 'start' }}><Icon name="check" size={14} /> {busy ? 'Guardando…' : 'Guardar'}</button>
        </form>

        {data && (
          <div style={{ borderTop: '1px solid var(--line)', paddingTop: 14, display: 'grid', gap: 6 }}>
            <Fila label="Ingreso del mes" valor={window.fmtCLP(data.ingreso)} />
            <Fila label="Gastado" valor={'− ' + window.fmtCLP(data.gastado)} />
            <Fila label="Disponible" valor={window.fmtCLP(data.disponible)} fuerte />
          </div>
        )}
        {err && <p style={{ color: 'var(--rust)', fontSize: 12, margin: 0 }}>{err}</p>}
        {ok && <p style={{ color: 'var(--olive)', fontSize: 12, margin: 0 }}>{ok}</p>}
      </div>
      <p style={{ color: 'var(--ink-4)', fontSize: 12, marginTop: 14 }}>El “gastado” saldrá de tus movimientos cuando se porte la ingesta de cartolas. Por ahora arranca en 0.</p>
    </div>
  );
}

function Fila({ label, valor, fuerte }) {
  return (
    <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
      <span style={{ fontSize: fuerte ? 14 : 12.5, color: fuerte ? 'var(--ink)' : 'var(--ink-4)', fontWeight: fuerte ? 600 : 400 }}>{label}</span>
      <span style={{ marginLeft: 'auto', fontFamily: 'var(--mono)', fontSize: fuerte ? 18 : 13, fontWeight: fuerte ? 600 : 400 }}>{valor}</span>
    </div>
  );
}

function Creditos() {
  const [propuestos, setPropuestos] = useState([]);
  const [cuotas, setCuotas] = useState([]);
  const [busy, setBusy] = useState('');
  const [err, setErr] = useState('');

  const cargar = async () => {
    setErr('');
    try {
      const [p, c] = await Promise.all([
        window.api('/api/finanzas/propuestos'),
        window.api('/api/finanzas/cuotas'),
      ]);
      setPropuestos(p || []); setCuotas(c || []);
    } catch (e) { setErr(e.message); }
  };
  useEffect(() => { cargar(); }, []);

  const tomar = async (plan) => {
    setBusy(plan.id);
    try { await window.api('/api/finanzas/cuotas/tomar', { method: 'POST', body: JSON.stringify({ plan_id: plan.id }) }); await cargar(); }
    catch (e) { setErr(e.message); } finally { setBusy(''); }
  };

  return (
    <div style={{ maxWidth: 620 }}>
      <h1 style={{ fontFamily: "'Instrument Serif', serif", fontStyle: 'italic', fontSize: 26, margin: '0 0 4px' }}>Créditos</h1>
      <p style={{ color: 'var(--ink-4)', fontSize: 13, margin: '0 0 20px' }}>Los escenarios que “llevaste a Finanzas” desde Proyectos llegan como propuestos. Cuando el banco te lo apruebe, marcá “Ya lo tomé” y se vuelve una cuota real.</p>

      <section style={{ marginBottom: 22 }}>
        <h3 style={{ fontSize: 13, textTransform: 'uppercase', letterSpacing: '.05em', color: 'var(--ink-3)', margin: '0 0 10px' }}>Propuestos</h3>
        {propuestos.length === 0 ? (
          <p style={{ color: 'var(--ink-4)', fontSize: 13 }}>Nada propuesto. Desde Proyectos → Análisis, botón “Llevar a Finanzas”.</p>
        ) : (
          <div style={{ display: 'grid', gap: 8 }}>
            {propuestos.map((p) => (
              <div key={p.id} className="card" style={{ padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
                <div style={{ flex: 1, minWidth: 160 }}>
                  <strong style={{ fontSize: 14, textTransform: 'capitalize' }}>{p.fuente}</strong>
                  <span style={{ color: 'var(--ink-4)', fontSize: 12 }}> · {p.proyecto_nombre || 'Proyecto'}</span>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2, fontFamily: 'var(--mono)' }}>
                    {window.fmtCLP(p.monto)}{p.cuotas ? ` · ${p.cuotas}× ${window.fmtCLP(p.cuota)}` : ''}
                  </div>
                </div>
                <button className="btn olive" disabled={busy === p.id} onClick={() => tomar(p)}><Icon name="check" size={14} /> {busy === p.id ? 'Tomando…' : 'Ya lo tomé'}</button>
              </div>
            ))}
          </div>
        )}
      </section>

      <section>
        <h3 style={{ fontSize: 13, textTransform: 'uppercase', letterSpacing: '.05em', color: 'var(--ink-3)', margin: '0 0 10px' }}>Cuotas reales</h3>
        {cuotas.length === 0 ? (
          <p style={{ color: 'var(--ink-4)', fontSize: 13 }}>Sin cuotas todavía.</p>
        ) : (
          <div style={{ display: 'grid', gap: 8 }}>
            {cuotas.map((c) => (
              <div key={c.id} className="card" style={{ padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 10 }}>
                <Icon name="bank" size={15} />
                <div style={{ flex: 1 }}>
                  <strong style={{ fontSize: 14 }}>{c.descripcion}</strong>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)', fontFamily: 'var(--mono)' }}>{c.cuotas_totales ? `${c.cuotas_totales}× ` : ''}{window.fmtCLP(c.cuota)} · total {window.fmtCLP(c.monto)}</div>
                </div>
                <span className="tag" style={{ fontSize: 11, padding: '3px 9px', borderRadius: 999, background: 'var(--olive-tint)', color: 'var(--olive)' }}>{c.estado}</span>
              </div>
            ))}
          </div>
        )}
      </section>
      {err && <p style={{ color: 'var(--rust)', fontSize: 12, marginTop: 14 }}>{err}</p>}
    </div>
  );
}

const NAV = [
  { id: 'disponible', label: 'Disponible', icon: 'bank' },
  { id: 'creditos', label: 'Créditos', icon: 'chart' },
];

function Shell({ user }) {
  const [view, setView] = useState('disponible');
  const logout = () => window.sb.auth.signOut();
  return (
    <div style={{ display: 'flex', minHeight: '100vh', background: 'var(--paper)', color: 'var(--ink)' }}>
      <aside style={{ width: 232, flexShrink: 0, borderRight: '1px solid var(--line)', background: 'var(--card)', display: 'flex', flexDirection: 'column', padding: '16px 12px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '4px 8px 18px' }}>
          <div className="brand-mark">F</div>
          <div style={{ display: 'flex', flexDirection: 'column', lineHeight: 1.15 }}>
            <span style={{ fontSize: 9, letterSpacing: '.14em', color: 'var(--ink-4)', textTransform: 'uppercase' }}>Simplificando</span>
            <span style={{ fontFamily: "'Instrument Serif', serif", fontStyle: 'italic', fontSize: 18 }}>Finanzas</span>
          </div>
        </div>
        <nav style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          {NAV.map((n) => (
            <button key={n.id} className={'nav-item ' + (view === n.id ? 'active' : '')} onClick={() => setView(n.id)}
              style={{ display: 'flex', alignItems: 'center', gap: 10, width: '100%', padding: '9px 12px' }}>
              <Icon name={n.icon} size={16} /> <span>{n.label}</span>
            </button>
          ))}
        </nav>
        <div style={{ marginTop: 'auto', display: 'flex', flexDirection: 'column', gap: 8, paddingTop: 12 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '8px 10px', borderRadius: 12, background: 'var(--paper-2)' }}>
            <div style={{ width: 30, height: 30, borderRadius: '50%', background: 'var(--olive)', color: '#fff', display: 'grid', placeItems: 'center', fontSize: 11, fontWeight: 600 }}>{(user.email || '?').slice(0, 2).toUpperCase()}</div>
            <span style={{ fontSize: 11, color: 'var(--ink-3)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{user.email}</span>
          </div>
          <button className="btn" onClick={logout} style={{ justifyContent: 'center' }}><Icon name="logout" size={14} /> Cerrar sesión</button>
        </div>
      </aside>
      <main style={{ flex: 1, minWidth: 0, padding: '24px 26px 60px' }}>
        {view === 'disponible' && <Disponible />}
        {view === 'creditos' && <Creditos />}
      </main>
    </div>
  );
}

function App() {
  const session = window.useSession();
  if (session === null) return <div style={{ minHeight: '100vh', display: 'grid', placeItems: 'center', background: 'var(--paper)', color: 'var(--ink-3)' }}>Cargando…</div>;
  if (!session) return <Login />;
  return <Shell user={session.user} />;
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
