/* app.jsx — shell: nav, accessibility bar, routing, tweaks */
window.addEventListener('error', (e) => {
  document.body.innerHTML += `<div style="position:fixed;top:0;left:0;z-index:9999;background:#900;color:#fff;padding:20px;font-size:16px;"><b>Runtime Error:</b> ${e.message}<br/>${e.filename}:${e.lineno}<br/><pre>${e.error?.stack}</pre></div>`;
});
window.addEventListener('unhandledrejection', (e) => {
  document.body.innerHTML += `<div style="position:fixed;top:100px;left:0;z-index:9999;background:#900;color:#fff;padding:20px;font-size:16px;"><b>Promise Error:</b> ${e.reason?.message || e.reason}<br/><pre>${e.reason?.stack}</pre></div>`;
});
const { useState: appState, useEffect: appEffect, useRef: appRef } = React;

const ACCENTS = [
  { lime: '#8FBF2E', sl: '#5F8417', sd: '#BCEA72' },
  { lime: '#54A85E', sl: '#357A41', sd: '#86D690' },
  { lime: '#34A8A0', sl: '#1F7A74', sd: '#6FD8D0' },
  { lime: '#E0A92E', sl: '#9A6E12', sd: '#F2CC6B' },
];

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "dark": false,
  "nav": "sidebar",
  "lessonLayout": "guided",
  "accent": "#8FBF2E",
  "textSize": 1,
  "highContrast": false,
  "reduceMotion": false,
  "roundness": 12
}/*EDITMODE-END*/;

const PROFILE_VERSIONS = {
  staff:     { label: 'Staff',   ver: '2.1' },
  editor:    { label: 'Staff',   ver: '2.1' },
  edlearner: { label: 'Learner', ver: '1.0' },
  client:    { label: 'Learner', ver: '1.0' },
  learner:   { label: 'Learner', ver: '1.0' },
};
const ROLE_DISPLAY = {
  staff:     'Course Staff',
  editor:    'Content Editor',
  edlearner: 'Learner',
  client:    'Learner',
  learner:   'Learner',
};

const NAV_GROUPS = [
  {
    title: 'Learning',
    items: [
      { id: 'dashboard', label: 'Dashboard', icon: 'home' },
      { id: 'curriculum', label: 'Curriculum', icon: 'grid' },
      { id: 'live', label: 'Live sessions', icon: 'calendar' },
    ]
  },
  {
    title: 'Connect',
    items: [
      { id: 'community', label: 'Community', icon: 'users' },
    ]
  },
];

function Brand() {
  return (
    <div className="brand-chip" style={{ background: 'transparent', padding: '16px 0 10px', justifyContent: 'flex-start', overflow: 'hidden' }}>
      <img src="assets/Logo-white-03.png?v=1" alt="Edstutia" style={{ width: 220, height: 50, objectFit: 'cover', objectPosition: 'left center', imageRendering: 'high-quality', transform: 'scale(1.35)', transformOrigin: 'left center' }} />
    </div>
  );
}

function A11yBar({ t, setTweak }) {
  const tip = (label) => ({ title: label, 'aria-label': label });
  return (
    <div className="a11y-bar">
      <button className="icon-btn" {...tip('Smaller text')} onClick={() => setTweak('textSize', Math.max(0.85, +(t.textSize - 0.1).toFixed(2)))}>
        <span style={{ fontFamily: 'var(--font-head)', fontWeight: 800, fontSize: 14 }}>A−</span>
      </button>
      <button className="icon-btn" {...tip('Larger text')} onClick={() => setTweak('textSize', Math.min(1.4, +(t.textSize + 0.1).toFixed(2)))}>
        <span style={{ fontFamily: 'var(--font-head)', fontWeight: 800, fontSize: 19 }}>A+</span>
      </button>
      <button className={'icon-btn' + (t.highContrast ? ' on' : '')} {...tip('High contrast')} onClick={() => setTweak('highContrast', !t.highContrast)}><Icon name="contrast" size={20} /></button>
      <button className={'icon-btn' + (t.reduceMotion ? ' on' : '')} {...tip('Reduce motion')} onClick={() => setTweak('reduceMotion', !t.reduceMotion)}><Icon name="motion" size={20} /></button>
      <button className="icon-btn" {...tip(t.dark ? 'Light mode' : 'Dark mode')} onClick={() => setTweak('dark', !t.dark)}><Icon name={t.dark ? 'sun' : 'moon'} size={20} /></button>
    </div>
  );
}

function ProfileMenu({ open, onClose, onLogout, go }) {
  if (!open) return null;
  return (
    <React.Fragment>
      <div className="profile-menu-overlay" onClick={onClose}></div>
      <div className="profile-menu">
        <div className="profile-menu-header">
          <strong>{window.EDSTUTIA.learner.name}</strong>
          <div className="row gap-8" style={{ alignItems: 'center', flexWrap: 'wrap' }}>
            <span>{ROLE_DISPLAY[window.EDSTUTIA.learner.role] || window.EDSTUTIA.learner.role}</span>
            {(() => { const pv = PROFILE_VERSIONS[window.EDSTUTIA.learner.role]; return pv ? <span style={{ fontSize: 10, fontWeight: 700, padding: '2px 6px', borderRadius: 5, background: 'var(--lime-soft)', color: 'var(--lime-strong)', fontFamily: 'var(--font-head)' }}>{pv.label} v{pv.ver}</span> : null; })()}
          </div>
        </div>
        <button className="profile-menu-item" onClick={() => { onClose(); go({ name: 'settings' }); }}>
          <Icon name="settings" size={18} /> Settings
        </button>
        <button className="profile-menu-item" onClick={() => { onClose(); go({ name: 'support' }); }}>
          <Icon name="info" size={18} /> Help & Support
        </button>
        <div className="profile-menu-divider"></div>
        <button className="profile-menu-item danger" onClick={onLogout}>
          <Icon name="logout" size={18} /> Log Out
        </button>
      </div>
    </React.Fragment>
  );
}

function App() {
  const [t, setT] = usePersist('settings', TWEAK_DEFAULTS);
  const setTweak = (k, v) => setT(p => ({ ...p, [k]: v }));
  
  const [route, setRoute] = usePersist('route', { name: 'dashboard' });
  const [sidebarOpen, setSidebarOpen] = appState(true);
  const [profileMenuOpen, setProfileMenuOpen] = appState(false);
  const [searchQuery, setSearchQuery] = appState('');
  const [searchFocus, setSearchFocus] = appState(false);
  const searchRef = appRef(null);

  const searchResults = React.useMemo(() => {
    const q = searchQuery.toLowerCase().trim();
    if (!q || q.length < 2) return [];
    const results = [];
    (window.EDSTUTIA?.modules || []).forEach(m => {
      (m.lessons || []).forEach(l => {
        if (l.title.toLowerCase().includes(q) || (l.summary || '').toLowerCase().includes(q) || m.title.toLowerCase().includes(q)) {
          results.push({ type: 'lesson', id: l.id, label: l.title, sub: m.title, icon: 'book' });
        }
      });
      if (m.title.toLowerCase().includes(q)) {
        results.push({ type: 'module', id: m.id, label: m.title, sub: (m.lessons?.length || 0) + ' lessons', icon: 'grid' });
      }
    });
    return results.slice(0, 8);
  }, [searchQuery]);
  
  const go = (r) => { setRoute(r); window.scrollTo({ top: 0 }); };
  
  const handleLogout = async () => {
    if (!window.supabaseClient) return;
    await window.supabaseClient.auth.signOut();
    window.location.reload();
  };

  // apply theme + a11y settings to <html>
  appEffect(() => {
    const r = document.documentElement;
    r.dataset.theme = t.dark ? 'dark' : 'light';
    r.dataset.contrast = t.highContrast ? 'high' : 'normal';
    r.dataset.motion = t.reduceMotion ? 'reduced' : 'full';
    r.style.setProperty('--scale', t.textSize);
    r.style.setProperty('--radius', t.roundness + 'px');
    r.style.setProperty('--radius-sm', (t.roundness * 0.66) + 'px');
    r.style.setProperty('--radius-lg', (t.roundness * 1.45) + 'px');
    const a = ACCENTS.find(x => x.lime === t.accent) || ACCENTS[0];
    r.style.setProperty('--lime', a.lime);
    r.style.setProperty('--lime-strong', t.dark ? a.sd : a.sl);
    r.style.setProperty('--lime-soft', `color-mix(in srgb, ${a.lime} ${t.dark ? 16 : 16}%, var(--surface))`);
    r.style.setProperty('--ring', `color-mix(in srgb, ${a.lime} 42%, transparent)`);
  }, [t]);

  const topnav = t.nav === 'top';

  const Screen = () => {
    switch (route.name) {
      case 'curriculum': return <Curriculum go={go} focus={route.focus} />;
      case 'live': return <LiveSessions go={go} />;
      case 'community': return <Community go={go} />;
      case 'lesson': return <LessonPage id={route.id} go={go} layout={t.lessonLayout} />;
      case 'admin': return <Admin go={go} />;
      case 'settings': return <SettingsPage t={t} setTweak={setTweak} />;
      case 'support': return <SupportPage />;
      default: return <Dashboard go={go} />;
    }
  };

  const NavItems = ({ onPick }) => {
    const isEditor = ['editor', 'staff'].includes(window.EDSTUTIA.learner.role);
    
    const groups = JSON.parse(JSON.stringify(NAV_GROUPS));
    if (isEditor) {
      const connectGroup = groups.find(g => g.title === 'Connect');
      if (connectGroup) connectGroup.items.push({ id: 'admin', label: 'Admin', icon: 'shield' });
    }
    
    return (
      <div className="nav-groups stack" style={{ gap: 24 }}>
        {groups.map((g, i) => (
          <div key={i} className="nav-group">
            <div className="nav-group-title">{g.title}</div>
            <div className="col gap-6">
              {g.items.map(n => {
                const active = route.name === n.id || (n.id === 'curriculum' && route.name === 'lesson');
                return (
                  <button key={n.id} className={'nav-item' + (active ? ' active' : '')}
                    onClick={() => { go({ name: n.id }); onPick && onPick(); }}>
                    <div className="nav-item-indicator"></div>
                    <div className="nav-ic-wrap"><Icon name={n.icon} size={20} /></div>
                    <span className="nav-label-text">{n.label}</span>
                  </button>
                );
              })}
            </div>
          </div>
        ))}
      </div>
    );
  };

  // Editor is full-page — render outside shell
  if (route.name === 'editor') {
    return <LessonEditor lessonId={route.id} go={go} />;
  }

  return (
    <React.Fragment>
      <a href="#main" className="skip">Skip to content</a>
      <div className={'app' + (topnav ? ' topnav' : '') + (!sidebarOpen ? ' sidebar-closed' : '')}>
        {!topnav && (
          <div className="sidebar-toggle-wrapper">
            <button className="sidebar-toggle-btn" onClick={() => setSidebarOpen(!sidebarOpen)} title="Toggle sidebar">
              <Icon name={sidebarOpen ? "chevron-left" : "chevron-right"} size={16} />
            </button>
          </div>
        )}
        {!topnav && (
          <aside className="sidebar">
            <div style={{ marginBottom: 14 }}>
              <Brand />
            </div>

            <NavItems />
            <div className="sidebar-foot" style={{ position: 'relative' }}>
              <ProfileMenu open={profileMenuOpen} onClose={() => setProfileMenuOpen(false)} onLogout={handleLogout} go={go} />
              <div className="card" style={{ padding: 14, background: 'var(--surface-2)', boxShadow: 'none', cursor: 'pointer' }} onClick={() => setProfileMenuOpen(!profileMenuOpen)}>
                <div className="row gap-10">
                  <div className="avatar">{window.EDSTUTIA.learner.avatar}</div>
                  <div className="col" style={{ minWidth: 0 }}>
                    <strong style={{ fontFamily: 'var(--font-head)', fontSize: 15, lineHeight: 1.1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{window.EDSTUTIA.learner.name}</strong>
                    <div className="row gap-6" style={{ alignItems: 'center' }}>
                      <span className="muted" style={{ fontSize: 12.5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{ROLE_DISPLAY[window.EDSTUTIA.learner.role] || window.EDSTUTIA.learner.role}</span>
                      {(() => { const pv = PROFILE_VERSIONS[window.EDSTUTIA.learner.role]; return pv ? <span style={{ fontSize: 9.5, fontWeight: 700, padding: '1px 5px', borderRadius: 4, background: 'var(--lime-soft)', color: 'var(--lime-strong)', flexShrink: 0, fontFamily: 'var(--font-head)' }}>{pv.label} v{pv.ver}</span> : null; })()}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </aside>
        )}

        <div className="content">
          {topnav ? (
            <div className="topnav-bar">
              <Brand />
              <div className="topnav-links"><NavItems /></div>
              <div className="row gap-16" style={{ marginLeft: 'auto', position: 'relative' }}>
                <A11yBar t={t} setTweak={setTweak} />
                <div className="avatar" title={window.EDSTUTIA.learner.name} style={{ cursor: 'pointer' }} onClick={() => setProfileMenuOpen(!profileMenuOpen)}>{window.EDSTUTIA.learner.avatar}</div>
                <div className="topnav-menu-wrapper">
                  <ProfileMenu open={profileMenuOpen} onClose={() => setProfileMenuOpen(false)} onLogout={handleLogout} go={go} />
                </div>
              </div>
            </div>
          ) : (
            <div className="topbar">
              <div className="search" style={{ position: 'relative' }} ref={searchRef}>
                <Icon name="search" size={18} />
                <input
                  placeholder="Search lessons, modules…"
                  value={searchQuery}
                  onChange={e => setSearchQuery(e.target.value)}
                  onFocus={() => setSearchFocus(true)}
                  onBlur={() => setTimeout(() => setSearchFocus(false), 150)}
                  onKeyDown={e => { if (e.key === 'Escape') { setSearchQuery(''); setSearchFocus(false); e.target.blur(); } }}
                />
                {searchFocus && searchResults.length > 0 && (
                  <div className="search-dropdown">
                    {searchResults.map((r, i) => (
                      <div key={i} className="search-result-item"
                        onMouseDown={() => { setSearchQuery(''); setSearchFocus(false); go(r.type === 'lesson' ? { name: 'lesson', id: r.id } : { name: 'curriculum', focus: r.id }); }}>
                        <div style={{ width: 34, height: 34, borderRadius: 10, background: 'var(--lime-soft)', color: 'var(--lime-strong)', display: 'grid', placeItems: 'center', flex: 'none' }}>
                          <Icon name={r.icon} size={17} />
                        </div>
                        <div className="col" style={{ minWidth: 0 }}>
                          <strong style={{ fontSize: 14.5, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{r.label}</strong>
                          <span className="muted" style={{ fontSize: 12.5 }}>{r.sub}</span>
                        </div>
                        <span className="pill" style={{ fontSize: 10, marginLeft: 'auto', flex: 'none' }}>{r.type}</span>
                      </div>
                    ))}
                  </div>
                )}
                {searchFocus && searchQuery.length >= 2 && searchResults.length === 0 && (
                  <div className="search-dropdown" style={{ padding: 16, color: 'var(--text-muted)', fontSize: 14, textAlign: 'center' }}>
                    No results for "{searchQuery}"
                  </div>
                )}
              </div>
              <div className="row gap-16" style={{ marginLeft: 'auto' }}>
                <A11yBar t={t} setTweak={setTweak} />
              </div>
            </div>
          )}
          <main id="main"><Screen /></main>
        </div>
      </div>
    </React.Fragment>
  );
}

function LoginScreen({ onLogin }) {
  const [email, setEmail] = appState('');
  const [password, setPassword] = appState('');
  const [loading, setLoading] = appState(false);
  const [errorMsg, setErrorMsg] = appState('');
  const [isSignUp, setIsSignUp] = appState(false);
  const [fullName, setFullName] = appState('');
  
  const handleLogin = async (e) => {
    e.preventDefault();
    if (!window.supabaseClient) { setErrorMsg("Supabase not connected. Check keys."); return; }
    setLoading(true);
    setErrorMsg('');
    
    let result;
    if (isSignUp) {
      result = await window.supabaseClient.auth.signUp({ 
        email, 
        password,
        options: { data: { full_name: fullName } }
      });
    } else {
      result = await window.supabaseClient.auth.signInWithPassword({ email, password });
    }
    
    setLoading(false);
    if (result.error) setErrorMsg(result.error.message);
    else if (onLogin && result.data.session) onLogin(result.data.session);
    else if (isSignUp && !result.data.session) setErrorMsg("Registration successful! Check your email to confirm.");
  };
  
  return (
    <div className="login-split enter">
      <div className="login-hero">
        <img src="assets/login_hero.png?v=2" alt="Immersive abstract background" className="hero-bg" />
        <div className="login-hero-overlay"></div>
        <div className="login-hero-content">
          <h2>Welcome to the Next Era of Learning</h2>
          <p>Edstutia LMS blends immersive technology with human connection to create unparalleled educational experiences.</p>
        </div>
      </div>
      <div className="login-panel-wrap">
        <div className="login-panel">
          <div style={{ overflow: 'hidden', marginBottom: 16 }}>
            <img src="assets/Logo-white-03.png?v=1" alt="Edstutia" style={{ width: 340, height: 100, objectFit: 'cover', objectPosition: 'left center', transform: 'scale(1.35)', transformOrigin: 'left center' }} />
          </div>
          <h1 style={{ fontSize: 32, marginBottom: 32, marginTop: 24 }}>{isSignUp ? 'Sign Up' : 'Sign In'}</h1>
          
          {errorMsg && <div style={{ padding: 12, background: 'var(--lime-soft)', color: 'var(--lime-strong)', borderRadius: 8, fontWeight: 600, marginBottom: 20 }}>{errorMsg}</div>}
          
          <form onSubmit={handleLogin}>
            {isSignUp && (
              <div className="login-form-group">
                <label>Full Name</label>
                <input type="text" placeholder="Jane Doe" value={fullName} onChange={e => setFullName(e.target.value)} required={isSignUp} className="login-input" />
              </div>
            )}
            <div className="login-form-group">
              <label>Email Address</label>
              <input type="email" placeholder="name@example.com" value={email} onChange={e => setEmail(e.target.value)} required className="login-input" />
            </div>
            <div className="login-form-group">
              <label>Password</label>
              <input type="password" placeholder="••••••••" value={password} onChange={e => setPassword(e.target.value)} required className="login-input" />
            </div>
            
            <button type="submit" className="btn btn-primary login-btn" disabled={loading}>
              {loading ? (isSignUp ? 'Creating account...' : 'Authenticating...') : (isSignUp ? 'Sign Up' : 'Sign In')}
            </button>
          </form>
          
          <div style={{ marginTop: 24, textAlign: 'center', fontSize: 14 }}>
            <span className="muted">{isSignUp ? 'Already have an account?' : "Don't have an account?"}</span>{' '}
            <a href="#" onClick={(e) => { e.preventDefault(); setIsSignUp(!isSignUp); setErrorMsg(''); }} style={{ fontWeight: 700, textDecoration: 'none' }}>
              {isSignUp ? 'Sign In' : 'Sign Up'}
            </a>
          </div>
        </div>
      </div>
    </div>
  );
}

function Root() {
  const [session, setSession] = appState(null);
  // sessionChecked: do we know whether a session exists yet?
  // profileLoaded: has setupProfile finished writing globals?
  const [sessionChecked, setSessionChecked] = appState(false);
  const [profileLoaded, setProfileLoaded] = appState(false);
  // Guard against duplicate setupProfile calls (getSession + onAuthStateChange both fire)
  const loadingForRef = appRef(null);

  appEffect(() => {
    if (!window.supabaseClient) { setSessionChecked(true); return; }

    window.supabaseClient.auth.getSession().then(({ data: { session } }) => {
      setSessionChecked(true);
      if (session) { setSession(session); setupProfile(session.user); }
    });

    const { data: { subscription } } = window.supabaseClient.auth.onAuthStateChange((_event, newSession) => {
      if (!newSession) {
        setSession(null);
        setProfileLoaded(false);
        setSessionChecked(true);
      } else {
        setSession(newSession);
        setupProfile(newSession.user);
      }
    });
    return () => subscription.unsubscribe();
  }, []);

  const setupProfile = async (user) => {
    // Deduplicate: if already loading profile for this uid, skip
    if (loadingForRef.current === user.id) return;

    // Snapshot static content_blocks NOW (sync, before any await overwrites window.EDSTUTIA.modules)
    const _staticBlocks = {};
    ((window.EDSTUTIA && window.EDSTUTIA.modules) || []).forEach(m =>
      (m.lessons || []).forEach(l => {
        if (l.title && l.content_blocks && l.content_blocks.length)
          _staticBlocks[l.title] = l.content_blocks;
      })
    );
    loadingForRef.current = user.id;
    setProfileLoaded(false);

    const uid = user.id;
    window.ME_UUID = uid;
    try {
      const { data: profile } = await window.supabaseClient.from('profiles').select('*').eq('id', uid).single();
      if (profile) {
        window.EDSTUTIA.learner.name = profile.name || 'New User';
        window.EDSTUTIA.learner.first = profile.first_name || 'User';
        window.EDSTUTIA.learner.role = profile.role || 'learner';
        window.EDSTUTIA.learner.avatar = profile.avatar || (profile.name ? profile.name.charAt(0) : 'U');

        const isEditorRole = ['staff', 'editor'].includes(profile.role);

        if (!isEditorRole) {
          // EDLEARNER: Supabase is single source of truth — published lessons only, sequential lock
          const [{ data: mods, error: modsErr }, { data: prog }] = await Promise.all([
            window.supabaseClient.from('modules').select('*, lessons(*)').order('num', { ascending: true }),
            window.supabaseClient.from('lesson_progress').select('*').eq('user_id', uid),
          ]);

          if (modsErr) console.error('[Edstutia] EdLearner modules fetch failed:', modsErr);

          const doneIds = new Set((prog || []).filter(x => x.status === 'completed').map(x => x.lesson_id));
          window.EDSTUTIA._completedIds = doneIds;

          if (mods && mods.length) {
            const processed = mods.map(m => {
              const publishedLessons = [...(m.lessons || [])]
                .filter(l => l.status === 'published')
                .sort((a, b) => (a.position ?? 9999) - (b.position ?? 9999) || new Date(a.created_at) - new Date(b.created_at))
                .map((l, i, arr) => {
                  const staticCb = _staticBlocks[l.title];
                  let cb = l.content_blocks;
                  if (staticCb && staticCb.length) {
                    const sbTypes = new Set((l.content_blocks || []).map(b => b.type));
                    const missingType = staticCb.some(b => !sbTypes.has(b.type));
                    if (missingType) cb = staticCb;
                  }
                  const base = (cb && cb !== l.content_blocks) ? { ...l, content_blocks: cb } : l;
                  if (doneIds.has(l.id)) return { ...base, status: 'completed' };
                  if (i === 0) return base;
                  return doneIds.has(arr[i - 1].id) ? base : { ...base, status: 'locked' };
                });
              return { ...m, lessons: publishedLessons };
            }).filter(m => m.lessons.length > 0);
            window.EDSTUTIA.modules = processed;
            console.log('[Edstutia] EdLearner modules loaded:', processed.length, 'modules,', processed.reduce((a, m) => a + m.lessons.length, 0), 'lessons');
          } else {
            console.warn('[Edstutia] No published modules found in Supabase for this edlearner.');
            window.EDSTUTIA.modules = [];
          }
        } else {
          // EDITOR: hydrate lesson progress onto existing modules (Curriculum does the full fetch)
          const { data: prog } = await window.supabaseClient.from('lesson_progress').select('*').eq('user_id', uid);
          if (prog) {
            window.EDSTUTIA._completedIds = new Set(prog.filter(x => x.status === 'completed').map(x => x.lesson_id));
            window.EDSTUTIA.modules.forEach(m => {
              m.lessons.forEach(l => {
                const p = prog.find(x => x.lesson_id === l.id);
                if (p) { l.status = p.status; l.progress = p.progress; }
              });
            });
          }
        }

        loadingForRef.current = null;
        setProfileLoaded(true);
      } else {
        // Auto-create a stub profile for new accounts
        const fullName = user.user_metadata?.full_name || 'New User';
        const firstName = fullName.split(' ')[0] || 'New';
        const initials = fullName.split(' ').map(n => n?.[0] || '').join('').substring(0, 2).toUpperCase() || 'NU';

        let userRole = 'edlearner';
        if (user.email) {
          const { data: authAdmin } = await window.supabaseClient.from('authorized_admins').select('email').eq('email', user.email).maybeSingle();
          if (authAdmin) userRole = 'staff';
        }

        const { error: insertError } = await window.supabaseClient.from('profiles').insert({
          id: uid, name: fullName, first_name: firstName, role: userRole, avatar: initials
        });

        if (insertError) {
          console.error("Profile creation error:", insertError);
          window.EDSTUTIA.learner.name = fullName;
          window.EDSTUTIA.learner.first = firstName;
          window.EDSTUTIA.learner.role = userRole;
          window.EDSTUTIA.learner.avatar = initials;
          loadingForRef.current = null;
          setProfileLoaded(true);
          return;
        }
        loadingForRef.current = null; // allow the recursive call through
        setupProfile(user);
      }
    } catch (err) {
      console.error("Error setting up profile:", err);
      loadingForRef.current = null;
      setProfileLoaded(true); // show app even on error rather than hanging forever
    }
  };

  // Show loading until we know session status AND (if logged in) profile is ready
  if (!sessionChecked || (session && !profileLoaded)) {
    return <div className="page" style={{ padding: 40, color: 'var(--text-muted)' }}>Loading...</div>;
  }
  if (!session) return <LoginScreen onLogin={(s) => { setSession(s); }} />;
  return <App />;
}

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