// Trove — App shell: top nav + routing
window.TOOLS_URL = 'https://tools.trove.education';
function TopNav({ onHome, onLibrary, onWiki, onTools, onCalendar, theme, onToggleTheme, presale }) {
  const { w } = window.useViewport();
  const compact = w <= 900;
  const [menuOpen, setMenuOpen] = React.useState(false);
  React.useEffect(() => { if (!compact) setMenuOpen(false); }, [compact]);

  const navItems = presale
    ? [
        { label: 'Tools', href: window.TOOLS_URL, external: true },
        { label: 'Wiki', onClick: onWiki },
        { label: 'Calendar', onClick: onCalendar },
      ]
    : [
        { label: 'Library', onClick: onLibrary },
        { label: 'Wiki', onClick: onWiki },
        { label: 'Tools', href: window.TOOLS_URL, external: true },
        { label: 'Calendar', onClick: onCalendar },
        { label: 'Curriculum', onClick: null },
        { label: 'Pricing', onClick: null },
        { label: 'For schools', onClick: null },
      ];
  const go = (fn) => { setMenuOpen(false); if (fn) fn(); };

  const themeToggle = (
    <button
      onClick={onToggleTheme}
      className="btn btn-sm"
      aria-label={theme === 'dark' ? 'Switch to light mode' : 'Switch to dark mode'}
      title={theme === 'dark' ? 'Switch to light mode' : 'Switch to dark mode'}
      style={{ padding: 8, color: 'var(--fg-muted)' }}>
      {theme === 'dark' ? (
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="12" cy="12" r="4"/><path d="M12 3v2M12 19v2M3 12h2M19 12h2M5.6 5.6l1.4 1.4M17 17l1.4 1.4M5.6 18.4 7 17M17 7l1.4-1.4"/>
        </svg>
      ) : (
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
          <path d="M20 14.5A8 8 0 0 1 9.5 4 8 8 0 1 0 20 14.5z"/>
        </svg>
      )}
    </button>
  );

  const actions = (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 7,
      padding: '7px 14px', borderRadius: 999,
      background: 'color-mix(in oklab, var(--accent) 16%, var(--bg))',
      color: 'var(--gold-deep)', fontSize: 13, fontWeight: 600, whiteSpace: 'nowrap',
    }}>
      <Icon.Sparkle width="14" height="14" />Library coming soon
    </span>
  );

  return (
    <header className="chrome-dark" style={{
      position: 'sticky', top: 0, zIndex: 50,
      borderBottom: '1px solid rgba(212,175,55,.2)',
    }}>
      <div style={{
        maxWidth: 1280, margin: '0 auto', padding: compact ? '14px 18px' : '16px 48px',
        display: 'flex', alignItems: 'center', gap: compact ? 14 : 28,
      }}>
        <button onClick={() => go(onHome)} style={{ display: 'inline-flex', alignItems: 'center', gap: 10, background: 'transparent', border: 0, cursor: 'pointer', padding: 0 }}>
          <img
            src="assets/trove-logo-dark.png"
            alt="Trove"
            style={{ height: compact ? 34 : 46, width: 'auto', display: 'block' }}
          />
        </button>

        {!compact && (
          <nav style={{ display: 'flex', gap: 4, marginLeft: 12 }}>
            {navItems.map(item => item.href ? (
              <a key={item.label} href={item.href} style={{ ...navLinkStyle, textDecoration: 'none' }}>
                {item.label}
              </a>
            ) : (
              <button key={item.label} onClick={item.onClick || undefined} style={navLinkStyle}>{item.label}</button>
            ))}
          </nav>
        )}

        <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 8 }}>
          {themeToggle}
          {!compact && actions}
          {compact && (
            <button
              onClick={() => setMenuOpen(o => !o)}
              aria-label={menuOpen ? 'Close menu' : 'Open menu'}
              aria-expanded={menuOpen}
              className="btn btn-sm"
              style={{ padding: 9, color: 'var(--fg)' }}>
              {menuOpen
                ? <Icon.X width="20" height="20" />
                : <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><path d="M3 6h18M3 12h18M3 18h18"/></svg>}
            </button>
          )}
        </div>
      </div>

      {compact && menuOpen && (
        <div className="fade-in" style={{
          borderTop: '1px solid var(--border)', background: 'var(--bg)',
          padding: '10px 18px 18px', display: 'flex', flexDirection: 'column', gap: 2,
          maxHeight: 'calc(100vh - 60px)', overflowY: 'auto',
        }}>
          {navItems.map(item => item.href ? (
            <a key={item.label} href={item.href} onClick={() => setMenuOpen(false)}
              style={{ ...navLinkStyle, width: '100%', justifyContent: 'space-between', padding: '13px 10px', fontSize: 16, borderRadius: 10, textDecoration: 'none' }}>
              {item.label}<Icon.ChevronRight width="16" height="16" style={{ opacity: .5 }} />
            </a>
          ) : (
            <button key={item.label} onClick={() => go(item.onClick)}
              style={{ ...navLinkStyle, width: '100%', justifyContent: 'space-between', padding: '13px 10px', fontSize: 16, borderRadius: 10 }}>
              {item.label}<Icon.ChevronRight width="16" height="16" style={{ opacity: .5 }} />
            </button>
          ))}
          <div style={{ height: 1, background: 'var(--border)', margin: '10px 0' }} />
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10, alignItems: 'center' }}>
            {actions}
          </div>
        </div>
      )}
    </header>
  );
}

const navLinkStyle = {
  background: 'transparent', border: 0, padding: '8px 12px', borderRadius: 8,
  color: 'var(--fg-muted)', fontSize: 14.5, fontWeight: 600, cursor: 'pointer',
  display: 'inline-flex', alignItems: 'center', gap: 4,
};
function Footer({ theme, presale, onNavigate }) {
  const { isMobile } = window.useViewport();
  const cols = [
    { h: 'Trove', items: [['About', 'about'], ['Contact', 'contact']] },
    { h: 'Legal', items: [['Privacy', 'privacy'], ['Cookies', 'cookies'], ['Terms', 'terms']] },
  ];
  return (
    <footer className="chrome-dark" style={{ borderTop: '1px solid rgba(212,175,55,.2)', padding: isMobile ? '32px 20px 28px' : '40px 48px 32px' }}>
      <div style={{ maxWidth: 1184, margin: '0 auto', display: 'grid', gridTemplateColumns: isMobile ? '1fr 1fr' : '2fr 1fr 1fr', gap: isMobile ? 28 : 40 }}>
        <div style={{ gridColumn: isMobile ? '1 / -1' : 'auto' }}>
          <img
            src="assets/trove-logo-dark.png"
            alt="Trove"
            style={{ height: 28, width: 'auto', display: 'block' }}
          />
          <p style={{ color: 'var(--fg-muted)', fontSize: 13.5, marginTop: 12, maxWidth: 320, lineHeight: 1.55 }}>
            Premium primary teaching resources, made by teachers, for teachers. UK curriculum-aligned, classroom-ready.
          </p>
        </div>
        {cols.map(col => (
          <div key={col.h}>
            <div className="t-micro" style={{ color: 'var(--fg-muted)', marginBottom: 12 }}>{col.h}</div>
            <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
              {col.items.map(([label, route]) => (
                <li key={route}>
                  <button onClick={() => onNavigate(route)}
                    style={{ background: 'none', border: 0, padding: 0, cursor: 'pointer', fontSize: 13.5, color: 'var(--fg)', textAlign: 'left' }}
                    onMouseEnter={(e) => e.currentTarget.style.color = 'var(--gold-deep)'}
                    onMouseLeave={(e) => e.currentTarget.style.color = 'var(--fg)'}>
                    {label}
                  </button>
                </li>
              ))}
            </ul>
          </div>
        ))}
      </div>
      <div style={{ maxWidth: 1184, margin: '32px auto 0', paddingTop: 20, borderTop: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', gap: 10, flexWrap: 'wrap', fontSize: 12.5, color: 'var(--fg-subtle)' }}>
        <span>© {new Date().getFullYear()} Trove</span>
        <span>trove.education</span>
      </div>
    </footer>
  );
}

function App() {
  // Soft launch: sign-in, purchase and pricing are not part of this build.
  const presale = true;
  const variant = 1;
  const [theme, setThemeState] = React.useState(() => {
    try { return localStorage.getItem('trove-theme') === 'dark' ? 'dark' : 'light'; } catch (e) { return 'light'; }
  });
  function setTheme(next) {
    setThemeState(next);
    try { localStorage.setItem('trove-theme', next); } catch (e) { /* private browsing */ }
  }

  // Trigger a re-render when Supabase data lands.
  const [, forceUpdate] = React.useReducer(x => x + 1, 0);
  React.useEffect(() => {
    function onUpdated() { forceUpdate(); }
    window.addEventListener('trove:resources-updated', onUpdated);
    // The Supabase fetch can resolve before React mounts, in which case the
    // one update event fired with no listener attached. Catch that case too.
    if (window.RESOURCES_SOURCE) forceUpdate();
    return () => window.removeEventListener('trove:resources-updated', onUpdated);
  }, []);

  const [route, setRoute] = React.useState({ name: 'home' });
  const [popup, setPopup] = React.useState(null);

  React.useEffect(() => {
    document.documentElement.dataset.theme = theme;
    document.documentElement.dataset.accent = 'warm';
  }, [theme]);

  function goLibrary(query, chip) {
    setRoute({ name: 'library', query: query || '', chip: chip || null });
    window.scrollTo({ top: 0 });
  }
  function goHome() { setRoute({ name: 'home' }); window.scrollTo({ top: 0 }); }
  function goWiki() { setRoute({ name: 'wiki' }); window.scrollTo({ top: 0 }); }
  function goWikiArticle(slug) { setRoute({ name: 'wiki-article', slug }); window.scrollTo({ top: 0 }); }
  function goTools() { window.location.href = window.TOOLS_URL; }
  function goCalendar(eventId) { setRoute({ name: 'calendar', eventId: typeof eventId === 'string' ? eventId : null }); window.scrollTo({ top: 0 }); }
  function goPage(name) { setRoute({ name }); window.scrollTo({ top: 0 }); }
  function openResource(r) { setPopup(r); }
  function closePopup() { setPopup(null); }

  return (
    <div data-screen-label={({home:'Home',library:'Library',wiki:'Wiki','wiki-article':'Wiki article',calendar:'School Calendar',curriculum:'Curriculum',about:'About',contact:'Contact',privacy:'Privacy',cookies:'Cookies',terms:'Terms'})[route.name] || 'Trove'} style={{ minHeight: '100vh', background: 'var(--bg)', color: 'var(--fg)' }}>
      <TopNav onHome={goHome} onLibrary={() => goLibrary('')} onWiki={goWiki} onTools={goTools} onCalendar={goCalendar} theme={theme} onToggleTheme={() => setTheme(theme === 'dark' ? 'light' : 'dark')} presale={presale} />
      {route.name === 'home' && (
        <HomeScreen
          variant={variant}
          presale={presale}
          onSearch={(q, chip) => goLibrary(q, chip)}
          onOpenLibrary={() => goLibrary('')}
          onOpenResource={openResource}
          onOpenWiki={goWiki}
          onOpenTools={goTools}
          onOpenCalendar={goCalendar}
          onOpenArticle={goWikiArticle}
          onNavigate={goPage}
        />
      )}
      {route.name === 'library' && (
        <LibraryScreen
          initialQuery={route.query}
          initialChip={route.chip}
          presale={presale}
          onOpenResource={openResource}
          onBackHome={goHome}
        />
      )}
      {route.name === 'wiki' && (
        <WikiIndex onOpenArticle={goWikiArticle} onOpenLibrary={() => goLibrary('')} />
      )}
      {route.name === 'wiki-article' && (
        <WikiArticle slug={route.slug} onOpenArticle={goWikiArticle} onOpenWiki={goWiki} onOpenResource={openResource} />
      )}
      {route.name === 'calendar' && (
        <CalendarScreen onOpenArticle={goWikiArticle} onOpenWiki={goWiki} initialEventId={route.eventId} />
      )}
      {['about', 'contact', 'privacy', 'cookies', 'terms'].includes(route.name) && (
        <InfoPage page={route.name} onNavigate={goPage} onOpenWiki={goWiki} onOpenTools={goTools} presale={presale} />
      )}
      <Footer theme={theme} presale={presale} onNavigate={goPage} />

      {popup && (
        <ResourcePopup
          resource={popup}
          onClose={closePopup}
          presale={presale}
        />
      )}
    </div>
  );
}

window.App = App;
