// app.jsx — Responsive entry point + admin-hantering + databootstrap

function useIsMobile() {
  const [isMobile, setIsMobile] = React.useState(window.innerWidth < 768);
  React.useEffect(() => {
    const handler = () => setIsMobile(window.innerWidth < 768);
    window.addEventListener('resize', handler);
    return () => window.removeEventListener('resize', handler);
  }, []);
  return isMobile;
}

// Enkel laddningsskärm medan data hämtas från /api
function LoadingSplash() {
  const T = SITE_TOKENS;
  return (
    <div style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 22, background: T.cream }}>
      <Wordmark size={40}/>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, color: T.muted, fontSize: 14 }}>
        <span style={{ width: 16, height: 16, borderRadius: '50%', border: `2.5px solid ${T.line}`, borderTopColor: T.forest, display: 'inline-block', animation: 'sint-spin 0.8s linear infinite' }}/>
        Laddar…
      </div>
      <style>{`@keyframes sint-spin { to { transform: rotate(360deg); } }`}</style>
    </div>
  );
}

// Fångar renderingsfel så att hela sidan inte blir vit
class ErrorBoundary extends React.Component {
  constructor(props) { super(props); this.state = { error: null }; }
  static getDerivedStateFromError(error) { return { error }; }
  componentDidCatch(error, info) { console.error('Render-fel:', error, info); }
  render() {
    if (this.state.error) {
      const T = SITE_TOKENS;
      return (
        <div style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 16, padding: 24, textAlign: 'center', background: T.cream, color: T.ink }}>
          <Wordmark size={40}/>
          <p style={{ maxWidth: 380, color: T.ink2, lineHeight: 1.5 }}>Något gick fel när sidan skulle visas. Försök ladda om.</p>
          <button className="btn btn-primary" onClick={() => window.location.reload()}>Ladda om sidan</button>
        </div>
      );
    }
    return this.props.children;
  }
}

function App() {
  const isMobile = useIsMobile();
  const [ready, setReady] = React.useState(false);

  // Admin-session (lever kvar tills fliken stängs) — kräver giltig token
  const [adminSession,   setAdminSession]   = React.useState(
    () => (API.isAuthed() ? sessionStorage.getItem('sint_admin') : null)
  );
  const [adminRole,      setAdminRole]      = React.useState(
    () => (API.isAuthed() ? (sessionStorage.getItem('sint_role') || 'admin') : null)
  );
  const [showAdminLogin, setShowAdminLogin] = React.useState(false);
  const [showPolicy,     setShowPolicy]     = React.useState(false);

  React.useEffect(() => {
    const handler = () => setShowPolicy(true);
    window.addEventListener('sint-open-policy', handler);
    return () => window.removeEventListener('sint-open-policy', handler);
  }, []);

  // ── Hämta data från servern vid start (med fallback till hårdkodade värden) ──
  React.useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const [events, board, settings, stadgar, stats, companies] = await Promise.all([
          API.get('events').catch(() => null),
          API.get('board').catch(() => null),
          API.get('settings').catch(() => null),
          API.get('stadgar').catch(() => null),
          API.get('stats').catch(() => null),
          API.get('companies').catch(() => null),
        ]);
        applyServerData({
          events,
          board,
          settings,
          stadgarUrl: stadgar && stadgar.url,
          stats,
          companies,
        });
      } catch (e) {
        // Behåll fallback-data
      }
      if (!cancelled) setReady(true);
    })();
    return () => { cancelled = true; };
  }, []);

  // Lyssna på "openAdmin"-eventet som navbaren/footern skickar
  React.useEffect(() => {
    const handler = () => {
      if (adminSession) return; // redan inloggad — dashboard visas redan
      setShowAdminLogin(true);
    };
    window.addEventListener('openAdmin', handler);
    return () => window.removeEventListener('openAdmin', handler);
  }, [adminSession]);

  // Sessionen har gått ut (401 från API) → logga ut och visa inloggning
  React.useEffect(() => {
    const handler = () => {
      setAdminSession(null);
      setAdminRole(null);
      setShowAdminLogin(true);
    };
    window.addEventListener('sint-session-expired', handler);
    return () => window.removeEventListener('sint-session-expired', handler);
  }, []);

  const handleLogin = (email, role) => {
    setAdminSession(email);
    setAdminRole(role || 'admin');
    setShowAdminLogin(false);
  };

  const handleLogout = () => {
    setAdminSession(null);
    setAdminRole(null);
    sessionStorage.removeItem('sint_admin');
    API.clearToken();
  };

  if (!ready) {
    return (
      <>
        <SiteStyles/>
        <LoadingSplash/>
      </>
    );
  }

  return (
    <>
      <SiteStyles/>
      <ErrorBoundary>
        {isMobile ? <MobileSite/> : <DesktopSite/>}
      </ErrorBoundary>

      {/* Integritetspolicy & cookies */}
      {showPolicy && <PolicyModal onClose={() => setShowPolicy(false)}/>}

      {/* Admin login-popup */}
      {showAdminLogin && !adminSession && (
        <AdminLoginModal
          onLogin={handleLogin}
          onClose={() => setShowAdminLogin(false)}
        />
      )}

      {/* Admin-dashboard (helskärm) */}
      {adminSession && (
        <AdminDashboard
          adminEmail={adminSession}
          adminRole={adminRole}
          onLogout={handleLogout}
        />
      )}
    </>
  );
}

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