/* 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: 'tareas', label: 'Tareas', icon: 'check', pronto: true },
  { id: 'proyectos', label: 'Proyectos', icon: 'folder' },
  { id: 'analisis', label: 'Análisis', icon: 'chart' },
  { id: 'cuaderno', label: 'Cuaderno', icon: 'edit' },
  { id: 'bodega', label: 'Bodega', icon: 'cart', pronto: true },
  { id: 'plan', label: 'Plan', icon: 'calendar', pronto: true },
];

function Pronto({ titulo, detalle }) {
  return (
    <div className="card" style={{ padding: 40, textAlign: 'center', maxWidth: 480, margin: '48px auto' }}>
      <h2 style={{ fontFamily: "'Instrument Serif', serif", fontStyle: 'italic', fontSize: 22, margin: '0 0 8px' }}>{titulo}</h2>
      <p style={{ color: 'var(--ink-3)', fontSize: 13, margin: 0, lineHeight: 1.5 }}>{detalle}</p>
    </div>
  );
}

function Shell({ user }) {
  const [view, setView] = useState('proyectos');
  const logout = () => window.sb.auth.signOut();
  const initials = (user.email || '?').slice(0, 2).toUpperCase();
  const prontoLabels = { tareas: 'Tareas', bodega: 'Bodega', plan: 'Plan' };
  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">P</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 }}>Proyectos</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)} title={n.pronto ? 'Próximamente' : n.label}
              style={{ display: 'flex', alignItems: 'center', gap: 10, width: '100%', padding: '9px 12px', opacity: n.pronto ? 0.55 : 1 }}>
              <Icon name={n.icon} size={16} /> <span style={{ flex: 1, textAlign: 'left' }}>{n.label}</span>
              {n.pronto && <span style={{ fontSize: 9, color: 'var(--ink-4)', border: '1px solid var(--line)', borderRadius: 999, padding: '1px 6px' }}>pronto</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, flexShrink: 0 }}>{initials}</div>
            <span style={{ fontSize: 11, color: 'var(--ink-3)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }} title={user.email}>{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, overflowX: 'hidden', padding: '24px 26px 60px' }}>
        {view === 'proyectos' && <ProyectosView />}
        {view === 'analisis' && <AnalisisView />}
        {view === 'cuaderno' && <CuadernoView />}
        {(view === 'tareas' || view === 'bodega' || view === 'plan') && (
          <Pronto titulo={prontoLabels[view]} detalle="Esta sección existe en el diseño pero todavía no se construyó. El piloto se enfoca en Proyectos, Análisis y el Cuaderno." />
        )}
      </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 />);
