/* global React, ReactDOM, PORTAL, Login, Home, Invoices, Documents, Company, Profile */
const { useState, useEffect, useCallback } = React;

const NAV = [
  { id: 'dashboard',  label: 'Dashboard', icon: 'M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2z' },
  { id: 'invoices',   label: 'Invoices',  icon: 'M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8zM14 2v6h6M16 13H8M16 17H8M10 9H8' },
  { id: 'documents',  label: 'Documents', icon: 'M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z' },
  { id: 'company',    label: 'Company',   icon: 'M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4' },
  { id: 'profile',    label: 'Profile',   icon: 'M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2M12 11a4 4 0 100-8 4 4 0 000 8z' },
];

function NavIcon({ d }) {
  return (
    <svg className="sidebar-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      <path d={d} />
    </svg>
  );
}

function App() {
  const [session, setSession] = useState(undefined);
  const [page, setPage]       = useState(null);
  const [invoiceId, setInvoiceId] = useState(null);

  useEffect(() => {
    PORTAL.get('/session')
      .then(s => { setSession(s); })
      .catch(() => setSession(null));

    // Check for deep link to invoice in hash or search param
    const hash = window.location.hash.slice(1);
    if (hash.startsWith('invoices/')) {
      setPage('invoices');
      setInvoiceId(hash.split('/')[1]);
    } else if (hash && hash !== 'login') {
      setPage(hash);
    }

    const urlEmail = new URLSearchParams(window.location.search).get('email');
    if (urlEmail) {
      // Pre-fill magic link email after redirect from invoice email
      history.replaceState(null,'','/');
    }
  }, []);

  const navigate = useCallback((p, id=null) => {
    window.location.hash = id ? `${p}/${id}` : p;
    setPage(p);
    setInvoiceId(id);
  }, []);

  async function logout() {
    await PORTAL.post('/auth/logout').catch(()=>{});
    setSession(null);
  }

  if (session === undefined) {
    return (
      <div className="login-wrap">
        <div style={{color:'var(--fg-subtle)',fontFamily:'var(--font-mono)',fontSize:12}}>Loading…</div>
      </div>
    );
  }

  if (!session) return <Login />;

  const activePage = page || 'dashboard';
  const PageComponents = { dashboard: Home, invoices: Invoices, documents: Documents, company: Company, profile: Profile };
  const Page = PageComponents[activePage] || Home;

  return (
    <div className="portal-wrap">
      <aside className="portal-sidebar">
        <div className="sidebar-logo">
          <span className="sidebar-logo-mark">Lake-Project</span>
          <span className="sidebar-logo-sub">Client portal</span>
          {session.company_name && <span className="sidebar-company">{session.company_name}</span>}
        </div>
        <nav className="sidebar-nav">
          {NAV.map(item => (
            <button
              key={item.id}
              className={`sidebar-link ${activePage===item.id?'is-active':''}`}
              onClick={()=>navigate(item.id)}
            >
              <NavIcon d={item.icon} />
              {item.label}
            </button>
          ))}
        </nav>
        <div className="sidebar-foot">
          <div className="sidebar-user">
            <span className="sidebar-email">{session.email}</span>
            <button className="sidebar-logout" onClick={logout}>Sign out</button>
          </div>
        </div>
      </aside>

      <main className="portal-main">
        {activePage === 'dashboard'  && <Home session={session} onNav={navigate} />}
        {activePage === 'invoices'   && <Invoices initialId={invoiceId} />}
        {activePage === 'documents'  && <Documents />}
        {activePage === 'company'    && <Company />}
        {activePage === 'profile'    && <Profile />}
      </main>
    </div>
  );
}

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