/* ── Router + mount ── */
const PUBLIC_PAGES = NAV.map(n => n.key).concat(['register', 'login']);
const KNOWN = PUBLIC_PAGES.concat(['admin', 'article']);

function pageFromHash() {
  const h = (location.hash || '').replace(/^#\/?/, '').split('?')[0];
  if (!h) return 'home';
  return KNOWN.includes(h) ? h : 'notfound';
}

function NotFound({ navigate }) {
  return (
    <div className="container" style={{ padding: '90px 20px', textAlign: 'center', minHeight: '60vh', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
      <div style={{ fontFamily: 'var(--font-d)', fontSize: 84, fontWeight: 900, color: 'var(--sage)', lineHeight: 1, letterSpacing: '-.03em' }}>404</div>
      <div className="hero-v10-arabic" style={{ fontSize: 22, margin: '14px 0 6px', color: 'var(--muted)' }}>لم نجد الصفحة</div>
      <h1 style={{ fontFamily: 'var(--font-d)', fontSize: 26, fontWeight: 800, color: 'var(--ink-deep)', margin: '0 0 10px' }}>Halaman Tidak Ditemukan</h1>
      <p style={{ color: 'var(--muted)', maxWidth: 440, margin: '0 auto 24px', lineHeight: 1.6 }}>Maaf, halaman yang Anda cari tidak ada atau telah dipindahkan.</p>
      <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', justifyContent: 'center' }}>
        <button className="btn-hero-primary" onClick={() => navigate('home')}>← Beranda</button>
        <button className="btn-hero-secondary" onClick={() => navigate('articles')}>Baca Artikel</button>
      </div>
    </div>
  );
}

function AdminHome({ user, navigate, onLogout }) {
  return (
    <div style={{ minHeight: '100vh', background: 'var(--bg)' }}>
      <div style={{ background: 'var(--brand-deep)', color: '#fff', padding: '16px 24px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <img src="logo.jpg" alt="" style={{ height: 34, borderRadius: 7 }} /><img src="logo-rq.png" alt="" style={{ height: 32, marginLeft: 7 }} />
          <strong>Dashboard MQA</strong>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <span style={{ fontSize: 13.5, opacity: .85 }}>{user.name} · {user.role}</span>
          <button onClick={onLogout} style={{ background: 'rgba(255,255,255,.12)', color: '#fff', border: 'none', borderRadius: 8, padding: '7px 14px', fontSize: 13, fontWeight: 700, cursor: 'pointer' }}>Keluar</button>
        </div>
      </div>
      <div className="container" style={{ padding: '40px 20px' }}>
        <div style={{ fontFamily: 'var(--font-d)', fontSize: 26, fontWeight: 900, color: 'var(--ink-deep)', marginBottom: 8 }}>Selamat datang, {user.name.split(' ')[0]} 👋</div>
        <p style={{ color: 'var(--muted)', marginBottom: 28 }}>Login berhasil melalui lapisan API (<strong>mode: {api.mode}</strong>). Modul dashboard lengkap akan di-port ke struktur no-build ini berikutnya.</p>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px,1fr))', gap: 16 }}>
          {['Artikel', 'Pendaftar', 'Program', 'Donasi', 'Toko Buku', 'Pengaturan'].map(m => (
            <div key={m} style={{ background: '#fff', borderRadius: 16, padding: '22px 20px', border: '1px solid var(--border-soft)', boxShadow: 'var(--shadow-warm-md)' }}>
              <div style={{ fontWeight: 800, color: 'var(--ink-deep)', marginBottom: 4 }}>{m}</div>
              <div style={{ fontSize: 12.5, color: 'var(--muted)' }}>Segera</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function App() {
  const [page, setPage] = useState(pageFromHash);
  const [user, setUser] = useState(null);
  const [activeArticle, setActiveArticle] = useState(null);
  const [authorView, setAuthorView] = useState(null);
  useFadeUp(page + ':' + (activeArticle ? activeArticle.id : ''));

  const openArticle = (a) => { setActiveArticle(a); setPage('article'); location.hash = '#/article?id=' + a.id; window.scrollTo(0, 0); if (window.SEO) SEO.article(normArticle(a)); };
  useEffect(() => { window.__openArticle = openArticle; }, []);

  // Saat refresh di #/article?id=… → pulihkan artikel yang sedang dibaca
  useEffect(() => {
    if (page === 'article' && !activeArticle) {
      const id = new URLSearchParams((location.hash.split('?')[1] || '')).get('id');
      if (id) {
        const local = ((window.MQA || {}).articles || []).find(x => String(x.id) === String(id));
        if (local) setActiveArticle(local);
        else api.get('articles.php?action=list').then(r => {
          const found = r.ok && r.articles && r.articles.find(x => String(x.id) === String(id));
          if (found) setActiveArticle(found);
        });
      }
    }
  }, [page]);

  const navigate = (p) => {
    setPage(p);
    const hash = '#/' + p;
    if (location.hash !== hash) location.hash = hash;
    window.scrollTo(0, 0);
  };

  useEffect(() => {
    const onHash = () => setPage(pageFromHash());
    window.addEventListener('hashchange', onHash);
    // cek sesi tersimpan
    api.get('auth.php?action=me').then(r => { if (r.ok) setUser(r.user); });
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  // Update SEO (judul + meta) tiap halaman berubah
  useEffect(() => {
    if (!window.SEO) return;
    if (page === 'article') { if (activeArticle) SEO.article(normArticle(activeArticle)); }
    else if (!['admin', 'login'].includes(page)) SEO.page(page);
  }, [page, activeArticle]);

  const onLogin = (u) => { setUser(u); navigate('admin'); };
  const onLogout = () => { api.post('auth.php?action=logout'); setUser(null); navigate('home'); };

  // Halaman admin (butuh login)
  if (page === 'admin') {
    if (!user) return <LoginPage navigate={navigate} onLogin={onLogin} />;
    return <Dashboard user={user} navigate={navigate} onLogout={onLogout} />;
  }
  if (page === 'login') {
    if (user) return <Dashboard user={user} navigate={navigate} onLogout={onLogout} />;
    return <LoginPage navigate={navigate} onLogin={onLogin} />;
  }

  let content;
  if (page === 'home') content = <HomePage navigate={navigate} openArticle={openArticle} />;
  else if (page === 'articles') content = <ArticlesPage navigate={navigate} openArticle={openArticle} />;
  else if (page === 'article') content = activeArticle ? <ArticleReader article={activeArticle} navigate={navigate} openArticle={openArticle} openAuthor={setAuthorView} /> : <ArticlesPage navigate={navigate} openArticle={openArticle} />;
  else if (page === 'programs') content = <ProgramsPage navigate={navigate} />;
  else if (page === 'teachers') content = <TeachersPage />;
  else if (page === 'gallery') content = <FasilitasPage />;
  else if (page === 'kegiatan') content = <KegiatanPage />;
  else if (page === 'about') content = <AboutPage navigate={navigate} />;
  else if (page === 'contact') content = <ContactPage />;
  else if (page === 'donasi') content = <DonasiPage navigate={navigate} />;
  else if (page === 'register') content = <RegisterPage navigate={navigate} />;
  else if (page === 'toko') content = <TokoPage navigate={navigate} />;
  else content = <NotFound navigate={navigate} />;

  return (
    <>
      <ReadingProgress />
      <Header navigate={navigate} page={page} user={user} />
      <div className="page-anim" key={page === 'article' && activeArticle ? 'article-' + activeArticle.id : page}>
        {content}
      </div>
      <Footer navigate={navigate} />
      <WAButton />
      {authorView && <AuthorProfile name={authorView} navigate={navigate} openArticle={openArticle} onClose={() => setAuthorView(null)} />}
      <BottomNav navigate={navigate} page={page} onSearch={() => navigate('articles')} />
    </>
  );
}

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