import { useEffect, useState } from 'react';
import Dashboard from './components/Dashboard';
import ReportView from './components/ReportView';
import WidgetConfigurator from './components/WidgetConfigurator';
import Settings from './components/Settings';
type View = '' | 'report' | 'widget' | 'settings';

function parseHash(): View {
  const hash = window.location.hash.replace('#/', '').replace('#', '') as View;
  return ['', 'report', 'widget', 'settings'].includes(hash) ? hash : '';
}

export default function App() {
  const [view, setView] = useState<View>(parseHash);

  useEffect(() => {
    const onHashChange = () => setView(parseHash());
    window.addEventListener('hashchange', onHashChange);
    return () => window.removeEventListener('hashchange', onHashChange);
  }, []);

  const navigate = (v: View) => {
    window.location.hash = v ? `/${v}` : '/';
    setView(v);
  };

  return (
    <div className="aai-app">
      {/* Sidebar nav */}
      <nav className="aai-nav" aria-label="accessmate navigation">
        <div className="aai-nav__brand">
          <span className="aai-nav__icon" aria-hidden="true">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="20" height="20" fill="currentColor"><circle cx="12" cy="3.5" r="2"/><path d="M17 7.5H7a1 1 0 0 0 0 2h3.5v3L8 17.5a1 1 0 0 0 1.8.9L12 14l2.2 4.4a1 1 0 0 0 1.8-.9L13.5 12.5v-3H17a1 1 0 0 0 0-2z"/></svg>
          </span>
          <span>AccessMate</span>
        </div>

        <ul className="aai-nav__links">
          <NavItem active={view === ''}        onClick={() => navigate('')}>Dashboard</NavItem>
          <NavItem active={view === 'report'}  onClick={() => navigate('report')}>Report</NavItem>
          <NavItem active={view === 'widget'}  onClick={() => navigate('widget')}>Widget</NavItem>
          <NavItem active={view === 'settings'}onClick={() => navigate('settings')}>Settings</NavItem>
        </ul>
      </nav>

      {/* Main content */}
      <main className="aai-main" id="main-content">
        {view === ''         && <Dashboard />}
        {view === 'report'   && <ReportView />}
        {view === 'widget'   && <WidgetConfigurator />}
        {view === 'settings' && <Settings />}
      </main>
    </div>
  );
}

function NavItem({
  active,
  onClick,
  children,
}: {
  active: boolean;
  onClick: () => void;
  children: React.ReactNode;
}) {
  return (
    <li>
      <button
        className={`aai-nav__link${active ? ' aai-nav__link--active' : ''}`}
        onClick={onClick}
        aria-current={active ? 'page' : undefined}
      >
        {children}
      </button>
    </li>
  );
}
