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

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('meeting-studio').then(setToken);
  }, []);
  if (!token) return <div style={{ padding: 16, fontFamily: 'sans-serif' }}>loading…</div>;
  return (
    <MeetingProvider serviceUrl={SERVICE} token={token}>
      <App token={token} />
    </MeetingProvider>
  );
}

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