// app.jsx — functional D&D Energy CRM entry.
// Hash router + auth gate. Session is an httpOnly cookie managed by the server;
// the browser just asks /api/auth/me whether it's valid.

const IDLE_MS = 15 * 60 * 1000; // local heartbeat — server is authoritative

function getRoute() {
  const h = window.location.hash.replace(/^#\/?/, '');
  // Strip query string — "order?id=18186" → "order"
  return h.split('?')[0] || 'dashboard';
}
function setRoute(r) { window.location.hash = '#/' + r; }

function renderScreen(route) {
  switch (route) {
    case 'dashboard':   return <Dashboard/>;
    case 'orders':      return <OrdersList/>;
    case 'order':       return <OrderDetail/>;
    case 'products':    return <Products/>;
    case 'ai':          return <AiAssistant/>;
    case 'pricing':     return <IndividualPricing/>;
    case 'b2b':         return <B2BApprovals/>;
    case 'datasheets':  return <Datasheets/>;
    case 'gallery':     return <Realizations/>;
    case 'calendar':    return <CalendarLeave/>;
    case 'servis':      return <TechnicianServis/>;
    // Sidebar "CRM Používatelia" (admin) → internal team.
    // Sidebar "Zákazníci" (work) → WooCommerce customers list, detail under /customer?id=…
    case 'users':       return <UsersPermissions/>;
    case 'customers':   return <UsersList/>;
    case 'customer':    return <UserDetail/>;
    case 'user':        return <UserDetail/>;   // legacy alias
    case 'modules':     return <ModuleManager/>;
    case 'settings':    return <Settings2FA/>;
    case 'launcher':    return <AppLauncher/>;
    case 'integrations':return <IntegrationsScreen/>;
    default:            return <NotFound route={route}/>;
  }
}

function NotFound({ route }) {
  return (
    <AppShell active="dashboard" crumbs={['Domov', '404']}>
      <div className="page-head">
        <div>
          <h1>Stránka nenájdená</h1>
          <p>Route <code>#/{route}</code> neexistuje.</p>
        </div>
        <div className="page-head-actions">
          <a href="#/dashboard" className="btn btn-primary">Na prehľad</a>
        </div>
      </div>
    </AppShell>
  );
}

function BootSplash() {
  return (
    <div style={{
      position:'fixed', inset:0, display:'flex', alignItems:'center', justifyContent:'center',
      background:'linear-gradient(135deg,#0e2744,#133258 60%,#23507f)', color:'#e6eef7', fontFamily:'Georama, system-ui'
    }}>
      <div style={{textAlign:'center'}}>
        <div className="sb-logo-mark" style={{width:56, height:56, margin:'0 auto 14px'}}/>
        <div style={{fontWeight:700, fontSize:18}}>D&amp;D Energy CRM</div>
        <div style={{fontSize:11, color:'#a6c0df', marginTop:4, letterSpacing:'0.18em', textTransform:'uppercase'}}>Overujem reláciu…</div>
      </div>
    </div>
  );
}

function App() {
  const [booting, setBooting] = React.useState(true);
  const [session, setSession] = React.useState(null);
  const [pending2FA, setPending2FA] = React.useState(null);
  const [route, setRouteState] = React.useState(getRoute());

  React.useEffect(() => {
    const onHash = () => setRouteState(getRoute());
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  // On mount: check session via the server
  React.useEffect(() => {
    let alive = true;
    (async () => {
      const me = await API.me();
      if (!alive) return;
      if (me) setSession(me);
      setBooting(false);
    })();
    return () => { alive = false; };
  }, []);

  // Periodic revalidation — catches server-side logout / session expiry / perm changes
  React.useEffect(() => {
    if (!session) return;
    const id = setInterval(async () => {
      const me = await API.me();
      if (!me) setSession(null); else setSession(me);
    }, 60_000);
    return () => clearInterval(id);
  }, [session]);

  // Cross-tab logout
  React.useEffect(() => {
    const onVis = () => {
      if (document.visibilityState === 'visible') {
        API.me().then(me => {
          if (!me && session) setSession(null);
          else if (me) setSession(me);
        });
      }
    };
    document.addEventListener('visibilitychange', onVis);
    return () => document.removeEventListener('visibilitychange', onVis);
  }, [session]);

  // Live refresh when admin toggles a module — Sidebar rebuilds from new session.modules.
  React.useEffect(() => {
    const onChange = async () => {
      const me = await API.me();
      if (me) setSession(me);
    };
    window.addEventListener('dd-modules-changed', onChange);
    window.addEventListener('dd-session-changed', onChange);
    return () => {
      window.removeEventListener('dd-modules-changed', onChange);
      window.removeEventListener('dd-session-changed', onChange);
    };
  }, []);

  async function handleLoggedIn(_user) {
    // After login, re-fetch /me so we also get effective permissions + modules.
    const me = await API.me();
    if (me) setSession(me);
    const target = sessionStorage.getItem('dd_post_login') || 'dashboard';
    sessionStorage.removeItem('dd_post_login');
    setRoute(target);
  }
  function handleNeed2FA(ctx) {
    setPending2FA(ctx);
    setRoute('2fa');
  }
  function handle2FAVerified(user) {
    setPending2FA(null);
    handleLoggedIn(user);
  }
  async function handleLogout() {
    try { await API.logout(); } catch {}
    setSession(null);
    setPending2FA(null);
    setRoute('login');
  }

  if (booting) return <BootSplash/>;

  if (!session) {
    if (route === '2fa' && pending2FA) {
      return <TwoFactorScreen
        onVerified={handle2FAVerified}
        onBack={() => { setPending2FA(null); setRoute('login'); }}
        pendingUser={pending2FA}/>;
    }
    if (route && route !== 'login' && route !== '2fa') {
      try { sessionStorage.setItem('dd_post_login', route); } catch {}
    }
    return <LoginScreen onLoggedIn={handleLoggedIn} onNeed2FA={handleNeed2FA}/>;
  }

  return <AppRootShell session={session} route={route} onLogout={handleLogout}/>;
}

function AppRootShell({ session, route, onLogout }) {
  // Expose session globally so individual screens can read permissions / current user
  // without having to wire props through AppShell.
  window.currentSession = session;
  window.hasPerm = (p) => {
    const perms = session && session.permissions;
    if (!perms) return false;
    if (perms['*'] === true) return true;
    return perms[p] === true;
  };

  React.useEffect(() => {
    const root = document.getElementById('root');
    if (!root) return;
    const handler = (e) => {
      const a = e.target.closest('.sidebar a');
      const logoutBtn = e.target.closest('.sb-user svg');
      if (a) {
        e.preventDefault();
        const label = (a.querySelector('span')?.textContent || '').trim();
        const map = {
          'Prehľad': 'dashboard',
          'Objednávky': 'orders',
          'Produkty': 'products',
          'Individ. ceny': 'pricing',
          'B2B schvaľ.': 'b2b',
          'Datasheety': 'datasheets',
          'Realizácie': 'gallery',
          'AI asistent': 'ai',
          'Kalendár & dovolenky': 'calendar',
          'Zákazníci': 'customers',
          'CRM Používatelia': 'users',
          'Používatelia': 'users',
          'Moduly': 'modules',
          'Integrácie': 'integrations',
          'Nastavenia': 'settings',
        };
        const target = map[label];
        if (target) setRoute(target);
      } else if (logoutBtn && logoutBtn.closest('.sb-user')) {
        e.preventDefault();
        if (confirm('Naozaj sa chcete odhlásiť?')) onLogout();
      }
    };
    root.addEventListener('click', handler);
    return () => root.removeEventListener('click', handler);
  }, [onLogout]);

  // Inject current user into the sidebar on every render
  React.useEffect(() => {
    const u = session.user || session;
    const name = document.querySelector('.sb-user-name');
    const role = document.querySelector('.sb-user-role');
    const av   = document.querySelector('.sb-avatar');
    if (name) name.textContent = u.name;
    if (role) role.textContent = u.role === 'admin' ? 'Administrátor' : (u.role || 'Používateľ');
    if (av)   av.textContent = (u.name || '?').split(/\s+/).map(p => p[0]).join('').slice(0, 2).toUpperCase();
  });

  return renderScreen(route);
}

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