/* global React, ReactDOM, API, Login, Sidebar, Dashboard, Relations, TimeTracker, OutboundInvoices, InboundInvoices, BTWVAT, RecurringInvoices, Expenses */
const { useState, useEffect, useCallback, createContext, useContext } = React;

const AppCtx = createContext(null);
window.useApp = () => useContext(AppCtx);

function Toast({ toasts }) {
  return (
    <div className="toast-wrap">
      {toasts.map(t => (
        <div key={t.id} className={`toast ${t.type}`}>{t.msg}</div>
      ))}
    </div>
  );
}

function App() {
  const [session, setSession] = useState(undefined); // undefined=loading
  const [page, setPage]       = useState(window.location.hash.slice(1) || 'dashboard');
  const [toasts, setToasts]   = useState([]);

  useEffect(() => {
    const onHash = () => setPage(window.location.hash.slice(1) || 'dashboard');
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  useEffect(() => {
    API.get('/auth/session')
      .then(() => setSession(true))
      .catch(() => setSession(false));
  }, []);

  const navigate = useCallback((p) => {
    window.location.hash = p;
    setPage(p);
  }, []);

  const toast = useCallback((msg, type = 'success') => {
    const id = Date.now();
    setToasts(t => [...t, { id, msg, type }]);
    setTimeout(() => setToasts(t => t.filter(x => x.id !== id)), 3500);
  }, []);

  const logout = useCallback(async () => {
    await API.post('/auth/logout').catch(() => {});
    setSession(false);
  }, []);

  if (session === undefined) return (
    <div className="login-wrap">
      <div className="login-box">
        <div className="login-logo">Lake-Project</div>
        <div className="login-sub">Admin</div>
        <div className="text-muted text-mono" style={{fontSize:11}}>Connecting…</div>
      </div>
    </div>
  );

  if (!session) return <Login onLogin={() => setSession(true)} />;

  const pages = { dashboard: Dashboard, relations: Relations, time: TimeTracker, outbound: OutboundInvoices, inbound: InboundInvoices, btw: BTWVAT, recurring: RecurringInvoices, expenses: Expenses };
  const Page = pages[page] || Dashboard;

  return (
    <AppCtx.Provider value={{ navigate, toast, logout }}>
      <div className="admin-wrap">
        <Sidebar active={page} onNav={navigate} onLogout={logout} />
        <div className="admin-content">
          <Page />
        </div>
        <Toast toasts={toasts} />
      </div>
    </AppCtx.Provider>
  );
}

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