/* ── APP ROUTER ─────────────────────────────────────────────────────────── */

const { useState, useEffect } = React;

/* ── Login Screen ── */
function LoginScreen({ onLogin }) {
  const [pwd, setPwd]   = useState('');
  const [err, setErr]   = useState('');
  const [loading, setLoading] = useState(false);

  async function attempt(e) {
    e.preventDefault();
    setLoading(true);
    // Pequeno delay para suavizar UX (visualizacao do estado "Verificando...")
    await new Promise(r => setTimeout(r, 300));
    try {
      const ok = await Store.checkPassword(pwd);
      if (ok) {
        sessionStorage.setItem('mb_auth', '1');
        onLogin();
      } else {
        setErr('Senha incorreta. Tente novamente.');
        setLoading(false);
      }
    } catch (ex) {
      setErr('Erro ao verificar a senha. Tente novamente.');
      setLoading(false);
    }
  }

  return (
    <div className="login-root">
      <form className="login-card" onSubmit={attempt}>
        <img src={(window.__resources && window.__resources.logo) || "platform/logo.png"} alt="Mirabaud 1819" style={{ width: 64, height: 'auto', display: 'block', margin: '0 auto 20px' }}
             onError={e => { if (e.target.src.indexOf('blob:') === -1) e.target.src = 'logo.png'; }} />
        <div className="login-logo" style={{ textAlign: 'center' }}>Mirabaud</div>
        <div className="login-sub" style={{ textAlign: 'center' }}>Family Office</div>
        <div className="login-divider" style={{ margin: '0 auto 40px' }} />

        <div style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: '1.1rem', color: 'var(--heading)', marginBottom: 24 }}>
          Verificação de Carteiras
        </div>

        <div className="login-field">
          <label>Senha de acesso</label>
          <input
            type="password"
            value={pwd}
            onChange={e => { setPwd(e.target.value); setErr(''); }}
            className={err ? 'error' : ''}
            placeholder="••••••••••"
            autoFocus
          />
          {err && <div className="login-error">{err}</div>}
        </div>

        <button className="login-btn" type="submit" disabled={loading}>
          {loading ? 'Verificando…' : 'Entrar'}
        </button>

        <div className="login-year">© {new Date().getFullYear()} Mirabaud Family Office · Plataforma interna</div>
      </form>
    </div>
  );
}

/* ── Main App ── */
function App() {
  const [authed, setAuthed] = useState(() => sessionStorage.getItem('mb_auth') === '1');
  const [view,   setView]   = useState('dashboard');
  const [months, setMonths] = useState(() => Store.getMonths());
  const [activeMonthKey, setActiveMonthKey] = useState(() => {
    const ms = Store.getMonths();
    return ms[0]?.key || '';
  });
  const [selectedCarteira, setSelectedCarteira] = useState(null);

  function refreshMonths() {
    const ms = Store.getMonths();
    setMonths(ms);
    if (ms.length && !activeMonthKey) setActiveMonthKey(ms[0].key);
  }

  function handleMonthChange(key) {
    setActiveMonthKey(key);
    setSelectedCarteira(null);
    setView('dashboard');
  }

  function handleMonthAdded(key) {
    refreshMonths();
    setActiveMonthKey(key);
    setView('dashboard');
  }

  function handleSelectCarteira(nome) {
    setSelectedCarteira(nome);
    setView('carteira');
  }

  function logout() {
    sessionStorage.removeItem('mb_auth');
    setAuthed(false);
  }

  if (!authed) return <LoginScreen onLogin={() => setAuthed(true)} />;

  const currentMonth = months.find(m => m.key === activeMonthKey) || months[0] || null;

  /* ── topbar config per view ── */
  const topbarMap = {
    dashboard:   { title: 'Dashboard',         sub: currentMonth ? `${currentMonth.label} · ${currentMonth.totals?.total} carteiras` : '' },
    carteira:    { title: selectedCarteira || 'Carteira', sub: currentMonth?.label },
    comparative: { title: 'Comparativo Mensal', sub: '' },
    findings:    { title: 'Achados & Exceções',  sub: currentMonth?.label },
    receitas:    { title: 'Receitas & ROA',      sub: 'Jan/2025 → Jan/2026 · 99 clientes' },
    import:      { title: 'Importar PDFs',       sub: 'SmartBrain · Books mensais' },
    users:       { title: 'Usuários',            sub: '' },
  };
  const tb = topbarMap[view] || { title: '', sub: '' };

  return (
    <Shell
      view={view} setView={v => { setView(v); if (v !== 'carteira') setSelectedCarteira(null); }}
      currentMonth={currentMonth} months={months}
      onMonthChange={handleMonthChange}
      user={Store.getUsers()[0]}
      onLogout={logout}
      topbarTitle={tb.title}
      topbarSub={tb.sub}
    >
      {view === 'dashboard' && (
        <DashboardView
          month={currentMonth}
          months={months}
          activeMonthKey={activeMonthKey}
          onMonthSelect={handleMonthChange}
          onSelectCarteira={handleSelectCarteira}
          onMonthChange={() => refreshMonths()}
        />
      )}
      {view === 'carteira' && selectedCarteira && (
        <CarteiraView
          month={currentMonth}
          nome={selectedCarteira}
          allMonths={months}
          onBack={() => setView('dashboard')}
        />
      )}
      {view === 'comparative' && (
        <ComparativeView months={months} onSelectCarteira={handleSelectCarteira} />
      )}
      {view === 'findings' && (
        <FindingsView month={currentMonth} allMonths={months} onSelectCarteira={handleSelectCarteira} />
      )}
      {view === 'receitas' && (
        <ReceitasView />
      )}
      {view === 'import' && (
        <ImportView onMonthAdded={handleMonthAdded} />
      )}
      {view === 'users' && (
        <UsersView />
      )}
    </Shell>
  );
}

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