/* ============ App root ============ */

const NAV = [
  { id: 'dashboard', label: 'Dashboard', icon: 'dashboard' },
  { id: 'clients',   label: 'Clients',   icon: 'people' },
  { id: 'signings',  label: 'Signings',  icon: 'calendar' },
  { id: 'mileage',   label: 'Mileage',   icon: 'car' },
  { id: 'reports',   label: 'Reports',   icon: 'chart' },
  { id: 'settings',  label: 'Settings',  icon: 'gear' },
];

function App() {
  const state = useStore();
  const saving = useSavingFlag();
  const [view, setView] = React.useState(() => location.hash.replace('#','') || 'dashboard');
  const [search, setSearch] = React.useState('');
  const searchRef = React.useRef(null);

  // Apply accent from settings
  React.useEffect(() => {
    document.body.dataset.accent = state.settings.accent || 'blue';
  }, [state.settings.accent]);

  // Persist view in hash
  React.useEffect(() => { location.hash = view; }, [view]);
  React.useEffect(() => {
    const h = () => setView(location.hash.replace('#','') || 'dashboard');
    window.addEventListener('hashchange', h);
    return () => window.removeEventListener('hashchange', h);
  }, []);

  // ⌘K / Ctrl-K to focus search
  React.useEffect(() => {
    const h = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
        e.preventDefault();
        searchRef.current?.focus();
      }
    };
    document.addEventListener('keydown', h);
    return () => document.removeEventListener('keydown', h);
  }, []);

  // Clear search when switching views
  React.useEffect(() => { setSearch(''); }, [view]);

  const counts = {
    clients:  state.clients.length,
    signings: state.signings.filter(s => s.date >= todayISO() && s.status === 'Scheduled').length,
    mileage:  state.mileage.length,
  };

  const title = NAV.find(n => n.id === view)?.label || 'Dashboard';

  const renderView = () => {
    switch (view) {
      case 'dashboard': return <Dashboard onNavigate={setView} />;
      case 'clients':   return <Clients   search={search} />;
      case 'signings':  return <Signings  search={search} />;
      case 'mileage':   return <Mileage   search={search} />;
      case 'reports':   return <Reports />;
      case 'settings':  return <Settings />;
      default: return null;
    }
  };

  const showSearch = ['clients','signings','mileage'].includes(view);

  // Quick "New" action by view
  const newAction = () => {
    if (view === 'clients')  Store.Clients.add({});
    if (view === 'signings') Store.Signings.add({});
    if (view === 'mileage')  Store.Mileage.add({});
  };
  const newLabel = { clients: 'New client', signings: 'New signing', mileage: 'Log trip' }[view];

  return (
    <ToastProvider>
      <div className="app">
        {/* Sidebar */}
        <aside className="sidebar">
          <div className="sidebar-brand">
            <div className="logo" aria-label="Middlesex Notary Co"></div>
            <div style={{ minWidth: 0 }}>
              <div className="brand-name" style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{state.settings.businessName || 'Middlesex Notary Co'}</div>
              <div className="brand-sub">{state.settings.notaryName || 'Notary practice'}</div>
            </div>
          </div>

          <div className="sidebar-section">Workspace</div>
          {NAV.slice(0, 5).map(n => (
            <div key={n.id} className={'nav-item' + (view === n.id ? ' active' : '')} onClick={() => setView(n.id)}>
              <span className="nav-icon"><Icon name={n.icon} size={18}/></span>
              <span className="nav-label">{n.label}</span>
              {counts[n.id] != null && <span className="nav-badge">{counts[n.id]}</span>}
            </div>
          ))}

          <div className="sidebar-section">System</div>
          {NAV.slice(5).map(n => (
            <div key={n.id} className={'nav-item' + (view === n.id ? ' active' : '')} onClick={() => setView(n.id)}>
              <span className="nav-icon"><Icon name={n.icon} size={18}/></span>
              <span className="nav-label">{n.label}</span>
            </div>
          ))}

          <div className="sidebar-spacer"></div>

          <div className="sidebar-footer">
            <span className={'save-dot' + (saving.saving ? ' saving' : '')}></span>
            <span>{saving.saving ? 'Saving…' : `Saved ${fmt.relativeTime(saving.savedAt)}`}</span>
          </div>
        </aside>

        {/* Main */}
        <main className="main">
          <div className="toolbar">
            <h1>{title}</h1>
            <div className="toolbar-spacer"></div>
            {showSearch && (
              <input ref={searchRef} className="search" placeholder="Search…  ⌘K" value={search} onChange={e => setSearch(e.target.value)} />
            )}
            {newLabel && (
              <Button variant="primary" icon="plus" onClick={newAction}>{newLabel}</Button>
            )}
          </div>
          <div className="content">
            {renderView()}
          </div>
        </main>
      </div>
    </ToastProvider>
  );
}

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