/* ============================================================
   P&L App (Lite) · App shell (from the US demo's)
   ------------------------------------------------------------
   The narrow sidebar, icon above the label, like the demo. The square at the top shows the
   CLIENT's initials and their company name (brief 65: it should feel like their app).
   Jobs and Vehicles are paid-plan features: in the menu with a lock, they open a blurred
   sample (lock.jsx). On a phone the sidebar folds away behind a menu button.

   Order of checks when the page opens:
   1. Is someone logged in? No -> login screen. Nothing is loaded before this.
   2. Did they arrive from an invite / reset email? -> choose a password first.
   3. Load their company. Not linked to one yet -> "almost there".
   4. Not agreed to the terms yet -> the terms screen.
   5. The app.
   ============================================================ */
const NAV = [
  { id: 'dashboard', label: 'Dashboard', icon: 'home' },
  { id: 'pnl', label: 'Profit & Loss', icon: 'chart' },
  { id: 'incasari', label: 'Money In', icon: 'in' },
  { id: 'plati', label: 'Money Out', icon: 'out' },
  { id: 'jobs', label: 'Jobs', icon: 'folder', locked: true, trade: true },
  { id: 'vehicles', label: 'Vehicles', icon: 'car', locked: true, trade: true },
  { id: 'admin', label: 'Admin', icon: 'settings' },
];
function navItems() { return NAV.filter(n => !n.trade || showTrade()); }

function SidebarPanel({ active, setActive }) {
  const db = useDB();
  const rev = reviewCount();
  const name = companyName();
  return (
    <aside className="w-[92px] shrink-0 h-full flex flex-col items-center text-white overflow-y-auto" style={{ background: 'var(--sidebar)' }}>
      {/* the client's mark: their initials and company name */}
      <div className="pt-4 pb-3 px-1.5 text-center leading-none select-none w-full">
        <span className="inline-flex items-center justify-center w-[34px] h-[34px] rounded-[11px] font-800 text-[13px]" style={{ background: 'var(--lime)', color: 'var(--sidebar)' }}>{initialsOf(name)}</span>
        <div className="text-[9px] font-600 tracking-[0.12em] mt-1.5 leading-[1.3] uppercase break-words" style={{ color: 'rgba(255,255,255,0.55)' }} title={name}>{name}</div>
      </div>
      <div className="w-11 h-px mb-3 shrink-0" style={{ background: 'rgba(255,255,255,0.12)' }} />
      <nav className="flex flex-col items-center gap-2.5 pb-4">
        {navItems().map(n => {
          const on = active === n.id;
          return (
            <button key={n.id} onClick={() => setActive(n.id)} title={n.locked ? n.label + ' · paid plan' : n.label}
              className="group w-[80px] flex flex-col items-center gap-1 pt-1 pb-1.5 text-[11px] leading-tight text-center transition-colors"
              style={{ color: on ? '#fff' : n.locked ? 'rgba(255,255,255,0.5)' : 'rgba(255,255,255,0.72)', fontWeight: on ? 700 : 600 }}>
              <span className={'relative w-[50px] h-[30px] rounded-full flex items-center justify-center transition-colors ' + (on ? '' : 'group-hover:bg-[rgba(255,255,255,0.08)]')}
                style={on ? { background: 'var(--lime)', color: 'var(--sidebar)' } : undefined}>
                <Icon name={n.icon} size={19} />
                {n.locked && <span className="absolute -top-1 right-1 inline-flex items-center justify-center w-[15px] h-[15px] rounded-full" style={{ background: 'var(--sidebar)', color: 'var(--lime)' }}><Icon name="lock" size={10} strokeWidth={2} /></span>}
                {n.id === 'admin' && rev > 0 && (
                  <span className="absolute -top-1 right-0.5 min-w-[16px] h-[16px] px-1 rounded-full text-[10px] font-700 num inline-flex items-center justify-center" style={{ background: 'var(--neg)', color: '#fff' }}>{rev}</span>
                )}
              </span>
              {n.label}
            </button>
          );
        })}
      </nav>
    </aside>
  );
}

/* On a computer the sidebar is always there; on a phone it slides in from the menu button. */
function Sidebar({ active, setActive, open, onClose }) {
  return (
    <>
      <div className="hidden md:block w-[92px] shrink-0 h-screen sticky top-0"><SidebarPanel active={active} setActive={setActive} /></div>
      {open && (
        <div className="md:hidden fixed inset-0 z-50 fade-in" style={{ background: 'rgba(16,32,24,0.4)' }} onMouseDown={onClose}>
          <div className="h-full w-[92px] panel-in" onMouseDown={e => e.stopPropagation()}><SidebarPanel active={active} setActive={setActive} /></div>
        </div>
      )}
    </>
  );
}

/* The alerts bell: how many unpaid invoices / bills are overdue or due within ALERT_DAYS. A line opens the list already filtered. */
const BELL_SEEN_KEY = 'pnl-lite-due-alerts-seen-v1';   // per browser; if storage is blocked the bell still works, it just forgets on reload
function bellLoadSeen() { try { const v = JSON.parse(localStorage.getItem(BELL_SEEN_KEY) || '[]'); return Array.isArray(v) ? v : []; } catch (e) { return []; } }
function bellSaveSeen(ids) { try { localStorage.setItem(BELL_SEEN_KEY, JSON.stringify(ids)); } catch (e) { /* storage blocked: ignore */ } }

function AlertBell() {
  useDB();
  const [open, setOpen] = useState(false);
  const [seen, setSeen] = useState(bellLoadSeen);
  const weekly = weeklyLine(todayISO());
  const lines = (weekly ? [weekly] : []).concat(dueAlerts(todayISO()));
  const unseen = unseenCount(seen, todayISO());
  // opening the bell = everything in it is now seen (the number disappears)
  const toggle = () => { if (!open) { const ids = alertItemIds(todayISO()); setSeen(ids); bellSaveSeen(ids); } setOpen(o => !o); };
  const count = lines.filter(l => l.key !== 'week').reduce((s, l) => s + l.n, 0);
  return (
    <div className="relative">
      <button type="button" onClick={toggle} title={count ? `${count} ${plural(count, 'item')} need attention` : 'No alerts'}
        className="relative inline-flex items-center justify-center w-[38px] h-[38px] rounded-xl bg-surface border border-line hover:bg-[#F1FBD4] transition-colors text-ink">
        <Icon name="bell" size={19} />
        {unseen > 0 && <span className="absolute -top-0.5 -right-0.5 min-w-[18px] h-[18px] px-1 rounded-full text-[10.5px] font-700 num inline-flex items-center justify-center" style={{ background: 'var(--neg)', color: '#fff' }}>{unseen}</span>}
      </button>
      <Popover open={open} onClose={() => setOpen(false)} align="right" width={320}>
        <div className="text-[13px] font-700 text-ink mb-1.5">Alerts</div>
        {lines.length === 0 && <div className="text-[12.5px] text-muted py-1">Nothing due or overdue.</div>}
        {lines.map(l => (
          <button key={l.key} type="button" className="w-full flex items-start gap-2 text-left py-2 border-t border-line hover:bg-[#F6F8F3] rounded-md px-1 transition-colors"
            onClick={() => { setOpen(false); window.goToList && window.goToList(l.tab, l.tab, dueListState(l.kind, l.bucket, todayISO())); }}>
            <span className="w-2 h-2 rounded-full shrink-0 mt-[5px]" style={{ background: l.tone === 'neg' ? 'var(--neg)' : '#C98A12' }} />
            <span className="text-[12.5px] text-ink">{l.text}</span>
          </button>
        ))}
      </Popover>
    </div>
  );
}

/* Where the demo said "Connected to QuickBooks": the paid plan's QuickBooks link, locked. */
function QuickBooksBadge() {
  return (
    <button type="button" onClick={() => openPaid('quickbooks')} title="Part of the paid plan"
      className="hidden xl:inline-flex items-center gap-1.5 h-[30px] px-3 rounded-full text-[12px] font-700 whitespace-nowrap border border-line bg-surface text-muted hover:text-ink">
      <LockMark size={12} />Connect QuickBooks
    </button>
  );
}

/* The circle with the user's initial: who is signed in, the company, How it works and Sign out. */
function AccountMenu() {
  const email = currentUserEmail() || '';
  const [open, setOpen] = useState(false);
  const [guide, setGuide] = useState(false);
  const item = 'w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-left text-[13px] font-600 hover:bg-[#F6F8F3] transition-colors';
  return (
    <div className="relative">
      <button type="button" onClick={() => setOpen(o => !o)} title={'Signed in as ' + email}
              className="inline-flex items-center justify-center w-[38px] h-[38px] rounded-full font-800 text-[13px] shrink-0 hover:opacity-90"
              style={{ background: 'var(--sidebar)', color: 'var(--lime)' }}>{(email[0] || '?').toUpperCase()}</button>
      <Popover open={open} onClose={() => setOpen(false)} align="right" width={260}>
        <div className="px-1 pb-2.5 mb-1.5 border-b border-line">
          <div className="text-[11.5px] text-muted">Signed in as</div>
          <div className="text-[13px] font-700 text-ink break-all">{email}</div>
          <div className="text-[12px] text-muted mt-0.5">{companyName()}</div>
        </div>
        <button type="button" className={item + ' text-ink'} onClick={() => { setOpen(false); setGuide(true); }}><Icon name="sparkles" size={16} className="text-primary" />How it works</button>
        <button type="button" className={item + ' text-neg'} onClick={() => { setOpen(false); signOut(); }}><Icon name="arrowRight" size={16} />Sign out</button>
      </Popover>
      <Modal open={guide} onClose={() => setGuide(false)} width={1080} icon="sparkles" title="How it works" subtitle="The app in plain English"><HowItWorks /></Modal>
    </div>
  );
}

/* The top bar: the tab's name and the company on the left; QuickBooks (locked), the bell and the account circle on the right. */
function Topbar({ title, sub, right, onMenu }) {
  return (
    <header className="sticky top-0 z-30 bg-bg/90 backdrop-blur flex flex-wrap items-center px-3 sm:px-5 pt-3.5 pb-2.5 gap-x-4 gap-y-2">
      <button className="md:hidden -ml-0.5 p-1.5 rounded-lg text-ink hover:bg-[#E8EBE4]" onClick={onMenu} aria-label="Open the menu"><Icon name="menu" size={21} /></button>
      {/* at least 170px for the title: on a phone the buttons then drop to their own line instead of cutting the title */}
      <div className="min-w-[170px] flex-1">
        <h1 className="text-[19px] sm:text-[21px] font-800 text-ink leading-tight truncate">{title}</h1>
        <div className="text-[12.5px] text-muted truncate">{sub}</div>
      </div>
      <div className="ml-auto flex items-center gap-2 sm:gap-3">
        {right}
        <QuickBooksBadge />
        <AlertBell />
        <AccountMenu />
      </div>
    </header>
  );
}

function LoadingScreen({ error }) {
  return (
    <div className="min-h-screen flex flex-col items-center justify-center gap-4 text-center px-6">
      {error ? (
        <>
          <div className="font-display font-700 text-[17px] text-neg">Could not connect</div>
          <div className="text-[13.5px] text-muted max-w-sm">{error} Check the internet connection and reload the page.</div>
          <Button variant="outline" onClick={() => signOut()}>Log out</Button>
        </>
      ) : (
        <>
          <div className="font-display font-600 text-[15px] text-ink">Loading your numbers…</div>
          <div className="w-32 h-1 rounded-full overflow-hidden" style={{ background: 'var(--line)' }}>
            <div className="h-full w-1/2 rounded-full" style={{ background: 'var(--primary)', animation: 'fadeIn 0.6s ease-in-out infinite alternate' }} />
          </div>
        </>
      )}
    </div>
  );
}

function App() {
  const [active, setActiveRaw] = useState('dashboard');
  const [nonce, setNonce] = useState(0);   // bumped to re-open the SAME tab with a new filter (a click on a card or an alert)
  const [menuOpen, setMenuOpen] = useState(false);
  const setActive = id => { setActiveRaw(id); setMenuOpen(false); window.scrollTo(0, 0); };
  useEffect(() => {
    window.goToList = (tab, table, state) => { if (table && state) keepFilters(table, state); setActive(tab); setNonce(n => n + 1); };
  }, []);
  const [toast, setToast] = useState(null);
  const db = useDB();
  // 'invite' or 'recovery' when the page was opened from one of those emails (read in index.html)
  const [authFlow, setAuthFlow] = useState(window.AUTH_FLOW || null);

  // A failed save anywhere in the app shows up here, with the reason (see reportError in data.jsx).
  useEffect(() => {
    let t;
    const on = e => { setToast({ msg: e.detail.msg, tone: 'error' }); clearTimeout(t); t = setTimeout(() => setToast(null), 9000); };
    window.addEventListener('app-error', on);
    return () => { window.removeEventListener('app-error', on); clearTimeout(t); };
  }, []);

  // null = still checking for a stored session; false = signed out; object = signed in
  const [session, setSession] = useState(null);
  const [checked, setChecked] = useState(false);

  /* Is there already a session, and follow sign-in / sign-out. NOTHING touches the database until this says yes. */
  useEffect(() => {
    let alive = true;
    getSession().then(s => { if (alive) { setSession(s || false); setChecked(true); } });
    const off = onAuthChange((s, event) => {
      if (!alive) return;
      if (event === 'PASSWORD_RECOVERY') setAuthFlow('recovery');
      // token refreshes also arrive here: only react when the PERSON changes
      setSession(prev => (prev && s && prev.user.id === s.user.id) ? prev : (s || false));
      setChecked(true);
    });
    return () => { alive = false; off(); };
  }, []);

  /* The only place the load starts: after sign-in. */
  useEffect(() => { if (session) startSession(session); }, [session]);

  if (!checked) return <LoadingScreen />;
  if (!session) return <LoginScreen />;
  if (authFlow) return <SetPasswordScreen isInvite={authFlow === 'invite'} onDone={() => {
    setAuthFlow(null); window.AUTH_FLOW = null;
    history.replaceState(null, '', window.location.pathname);   // drop the email link's leftovers from the address bar
  }} />;
  if (!db._loaded) return <LoadingScreen />;
  if (db._error) return <LoadingScreen error={db._error} />;
  if (db._noCompany) return <NoCompanyScreen />;
  if (!db.membership.terms_accepted_at) return <TermsScreen />;

  const cur = NAV.find(n => n.id === active);
  const View = { dashboard: Dashboard, pnl: ProfitLoss, incasari: Incasari, plati: Plati, jobs: LockedJobs, vehicles: LockedVehicles, admin: Admin }[active];

  return (
    <div className="flex min-h-screen">
      <Sidebar active={active} setActive={setActive} open={menuOpen} onClose={() => setMenuOpen(false)} />
      <div className="flex-1 min-w-0 flex flex-col">
        <Topbar title={cur.label} onMenu={() => setMenuOpen(true)}
                sub={<>{companyName()}{active === 'dashboard' && <> · <DashPeriodLabel /></>}{cur.locked && ' · paid plan'}</>}
                right={active === 'dashboard' ? <DashPeriodButton /> : null} />
        <main className="flex-1 px-3 sm:px-5 pt-1.5 pb-5 max-w-[2200px] w-full mx-auto">
          <div key={active + ':' + nonce} className="fade-in"><View /></div>
        </main>
      </div>
      <RowsDrawer />
      <PaidCard />
      <Toast toast={toast} />
    </div>
  );
}

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