/* ============================================================
   COURSEDY — App root & router
   ============================================================ */
const { useState: useS, useEffect: useE } = React;

// One-shot localStorage migration: curio_* -> coursedy_*
try {
  ['route', 'last_course'].forEach(k => {
    const oldKey = 'curio_' + k;
    const newKey = 'coursedy_' + k;
    if (!localStorage.getItem(newKey) && localStorage.getItem(oldKey)) {
      localStorage.setItem(newKey, localStorage.getItem(oldKey));
      localStorage.removeItem(oldKey);
    }
  });
} catch {}

function parseLocation() {
  const path = window.location.pathname.replace(/\/+$/, '') || '/';
  const search = new URLSearchParams(window.location.search);
  // Static mappings
  const map = {
    '/landing': { view: 'landing', params: {} },
    '/signin':  { view: 'signin',  params: {} },
    '/signup':  { view: 'signup',  params: {} },
    '/onboarding': { view: 'onboarding', params: {} },
    '/library': { view: 'library', params: {} },
    '/create':  { view: 'creator', params: {} },
    '/admin':   { view: 'admin',   params: {} },
    '/upgrade': { view: 'upgrade', params: {} },
    '/Coursedy.html': { view: 'landing', params: {} },  // bare-html fallback
    '/':        { view: 'landing', params: {} },
  };
  if (map[path]) return map[path];
  // Dynamic: /edit/:courseId
  let m = path.match(/^\/edit\/([A-Za-z0-9_-]{6,})$/);
  if (m) return { view: 'creator', params: { editId: m[1] } };
  // Dynamic: /lesson/:lessonId?course=...
  m = path.match(/^\/lesson\/([A-Za-z0-9_-]{6,})$/);
  if (m) return { view: 'lesson', params: { id: m[1], courseId: search.get('course') || undefined } };
  // Dynamic: /quiz/:moduleId?course=...
  m = path.match(/^\/quiz\/([A-Za-z0-9_-]{6,})$/);
  if (m) return { view: 'quiz', params: { id: m[1], courseId: search.get('course') || undefined } };
  // Dynamic: /preview/:courseId
  m = path.match(/^\/preview\/([A-Za-z0-9_-]{6,})$/);
  if (m) return { view: 'preview', params: { id: m[1] } };
  return { view: 'library', params: {} };
}

function viewToUrl(view, params = {}) {
  switch (view) {
    case 'landing':     return '/landing';
    case 'signin':      return '/signin';
    case 'signup':      return '/signup';
    case 'onboarding':  return '/onboarding';
    case 'library':     return '/library';
    case 'admin':       return '/admin';
    case 'upgrade':     return '/upgrade';
    case 'creator':     return params.editId ? `/edit/${params.editId}` : '/create';
    case 'lesson': {
      const q = params.courseId ? `?course=${encodeURIComponent(params.courseId)}` : '';
      return `/lesson/${params.id}${q}`;
    }
    case 'quiz': {
      const q = params.courseId ? `?course=${encodeURIComponent(params.courseId)}` : '';
      return `/quiz/${params.id}${q}`;
    }
    case 'preview':     return `/preview/${params.id}`;
    default:            return '/library';
  }
}

// App chrome shared by library / creator / admin
function AppShell({ go, view, children, wide, user }) {
  const isSuperAdmin = !!(user && user.isSuperAdmin);
  const nav = [
    { id: 'library', label: 'My library', icon: 'Library' },
    { id: 'creator', label: 'Create course', icon: 'Plus', accent: true },
    ...(isSuperAdmin ? [{ id: 'admin', label: 'Admin', icon: 'Shield' }] : []),
  ];
  const onSignOut = async () => {
    try { await window.API.logout(); } catch {}
    window.__user = null;
    go('landing');
  };
  return (
    <div className="app-shell">
      <aside className="sidebar">
        <div style={{ padding: '6px 8px 18px' }}>
          <Logo onClick={() => go('landing')} />
        </div>
        <nav style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          {nav.map(n => {
            const Icon = ICON_BY_NAME(n.icon);
            const active = view === n.id;
            if (n.accent) return (
              <button key={n.id} className="btn btn-ai" style={{ height: 40, margin: '8px 2px', justifyContent: 'flex-start', paddingLeft: 12 }} onClick={() => go(n.id)}>
                <Plus size={17} /> {n.label}
              </button>
            );
            return (
              <div key={n.id} className={`nav-item ${active ? 'active' : ''}`} onClick={() => go(n.id)}>
                <Icon /> {n.label}
              </div>
            );
          })}
        </nav>
        <div className="grow" />
        <div className="card" style={{ padding: 13, background: 'var(--brand-tint)', border: 'none' }}>
          <div className="row" style={{ gap: 8 }}><span className="badge badge-brand" style={{ background:'var(--brand)', color:'#fff' }}>FREE</span><b style={{ fontSize: 13 }}>2 / 3 courses left</b></div>
          <Progress value={66} height={5} />
          <Btn variant="brand" size="sm" block style={{ marginTop: 11 }} onClick={() => go('upgrade')}>Upgrade to Pro</Btn>
        </div>
        <div className="nav-item" style={{ marginTop: 8 }} onClick={onSignOut}><Logout /> Sign out</div>
      </aside>
      <main style={{ minWidth: 0 }}>{children}</main>
    </div>
  );
}

function App() {
  const [route, setRoute] = useS(() => parseLocation());
  const [user, setUser] = useS(() => window.__user || null);
  const go = (view, params = {}) => {
    // Graceful fallbacks for removed views.
    if (view === 'browser') { view = 'library'; params = {}; }
    if (view === 'course') { view = 'creator'; params = params && params.id ? { editId: params.id } : {}; }
    const url = viewToUrl(view, params);
    const r = { view, params };
    if (url !== window.location.pathname + window.location.search) {
      window.history.pushState(r, '', url);
    }
    setRoute(r);
    const sc = document.querySelector('[data-app-scroll], [data-landing-scroll]');
    if (sc) sc.scrollTop = 0;
    window.scrollTo(0, 0);
  };
  const { view, params } = route;

  useE(() => {
    const onPop = () => setRoute(parseLocation());
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);

  useE(() => { window.__go = go; }, [route]);

  // Fire-and-forget visit tracking. De-duped per session via window.__lastVisitPath.
  useE(() => {
    try {
      const path = window.location.pathname + window.location.search;
      if (window.__lastVisitPath === path) return;
      window.__lastVisitPath = path;
      if (window.API && typeof window.API.trackVisit === 'function') {
        window.API.trackVisit(path);
      }
    } catch {}
  }, [route]);

  // Bootstrap: fetch the current user from the API on mount
  useE(() => {
    let cancelled = false;
    window.API.me().then(d => {
      if (cancelled) return;
      const u = d?.user || null;
      window.__user = u;
      setUser(u);
      const protectedViews = ['library', 'creator', 'admin', 'lesson', 'quiz', 'preview', 'upgrade'];
      if (!u && protectedViews.includes(route.view)) {
        go('signin');
      }
    });
    return () => { cancelled = true; };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Standalone (no app chrome)
  if (view === 'landing') return <Landing go={go} />;
  if (view === 'signup' || view === 'signin') return <Auth go={go} mode={view} />;
  if (view === 'onboarding') return <Onboarding go={go} />;
  if (view === 'creator') return <Creator go={go} params={params} user={user} />;
  if (view === 'lesson') return <LessonPage go={go} params={params} user={user} />;
  if (view === 'quiz') return <QuizPage go={go} params={params} user={user} />;
  if (view === 'preview') return <PreviewPage go={go} params={params} user={user} />;
  if (view === 'upgrade') return <UpgradePage go={go} params={params} user={user} setUser={setUser} />;

  // App-chrome views
  let content;
  if (view === 'library') content = <Browser go={go} params={params} view="library" user={user} />;
  else if (view === 'admin') content = <Admin go={go} user={user} />;
  else content = <Browser go={go} params={params} view="library" user={user} />;

  return <AppShell go={go} view={view} user={user}>{content}</AppShell>;
}

Object.assign(window, { AppShell });
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
