/* Raíz: puerta de login (Supabase Auth, magic link) + shell + vistas. */
const { useState, useEffect } = React;

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

// Login con enlace por correo (magic link).
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' }}>P</div>
        <h1 style={{ fontFamily: 'var(--serif, Instrument Serif), serif', fontStyle: 'italic', fontSize: 26, margin: '0 0 6px' }}>Proyectos</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: 'var(--c-radius-md, 12px)',
                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>
  );
}

const NAV = [
  { id: 'proyectos', label: 'Proyectos', icon: 'folder' },
];

function Shell({ user }) {
  const [view, setView] = useState('proyectos');
  const logout = () => window.sb.auth.signOut();
  return (
    <div style={{ minHeight: '100vh', background: 'var(--paper)', color: 'var(--ink)' }}>
      <header style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '12px 20px',
        borderBottom: '1px solid var(--line)', background: 'var(--card)' }}>
        <div className="brand-mark">P</div>
        <nav style={{ display: 'flex', gap: 4, flex: 1 }}>
          {NAV.map(n => (
            <button key={n.id} className={'nav-item ' + (view === n.id ? 'active' : '')}
              style={{ display: 'inline-flex', alignItems: 'center', gap: 7, width: 'auto', padding: '7px 12px' }}
              onClick={() => setView(n.id)}>
              <Icon name={n.icon} size={16} /> <span>{n.label}</span>
            </button>
          ))}
        </nav>
        <span style={{ fontSize: 12, color: 'var(--ink-3)' }}>{user.email}</span>
        <button className="btn" onClick={logout} title="Cerrar sesión" style={{ padding: '6px 10px' }}>
          <Icon name="logout" size={14} />
        </button>
      </header>
      <main style={{ maxWidth: 1280, margin: '0 auto', padding: '22px 20px 60px' }}>
        {view === 'proyectos' && <ProyectosView />}
      </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 />);
