import { createRoot } from 'react-dom/client';
import { CommunityProvider } from '@insignia/iios-community-web';
import { App, SERVICE } from './App';
import { useEffect, useState } from 'react';

const APP_ID = 'portal-demo';

async function devToken(userId: string): Promise<string> {
  const r = await fetch(`${SERVICE}/v1/dev/token`, {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({ appId: APP_ID, userId, name: userId }),
  });
  if (!r.ok) throw new Error(`devToken ${r.status} (service running with IIOS_DEV_TOKENS=1?)`);
  return ((await r.json()) as { token: string }).token;
}

function Root() {
  const [token, setToken] = useState<string | null>(null);
  useEffect(() => {
    void devToken('route-admin').then(setToken);
  }, []);
  if (!token) return <div style={{ padding: 16, fontFamily: 'sans-serif' }}>loading…</div>;
  return (
    <CommunityProvider serviceUrl={SERVICE} token={token}>
      <App token={token} />
    </CommunityProvider>
  );
}

const el = document.getElementById('root');
if (el) createRoot(el).render(<Root />);
