/* App shell: hash router, navbar, footer, toasts, scroll-reveal */
const { useState: uS, useEffect: uE, useCallback: uC } = React;

/* ---- routing helpers (global) ---- */
window.navigate = (path) => {window.location.hash = '#' + path;window.scrollTo({ top: 0, behavior: 'auto' });};
window.scrollToId = (id) => {
  if (window.location.hash && window.location.hash !== '#/' && !window.location.hash.startsWith('#/?')) {
    window.location.hash = '#/';
    setTimeout(() => {const el = document.getElementById(id);if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 80, behavior: 'smooth' });}, 60);
  } else {
    const el = document.getElementById(id);if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 80, behavior: 'smooth' });
  }
};
window.flashCond = () => {
  const run = () => {
    const el = document.getElementById('dieu-kien-qua');
    if (!el) return;
    window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 90, behavior: 'smooth' });
    el.classList.remove('flash');
    void el.offsetWidth;
    el.classList.add('flash');
  };
  if (window.location.hash && window.location.hash !== '#/' && !window.location.hash.startsWith('#/?')) {
    window.location.hash = '#/';
    setTimeout(run, 80);
  } else { run(); }
};

function parseHash() {
  const raw = (window.location.hash || '#/').replace(/^#/, '');
  const [path, qs] = raw.split('?');
  return { path: path || '/', query: new URLSearchParams(qs || '') };
}

function Navbar() {
  const links = [
  ['Giới thiệu', 'gioi-thieu'], ['Agenda', 'agenda'], ['Diễn giả', 'dien-gia'], ['Quyền lợi', 'qua-tang']];

  return (
    <div className="nav">
      <div className="wrap">
        <button className="brand" onClick={() => window.navigate('/')} aria-label="VietCanThi — trang chủ webinar">
          <img src="brand-assets/logo-rays-navy.svg" alt="VietCanThi" />
        </button>
        <div className="links">
          {links.map(([t, id]) => <a key={id} onClick={() => window.scrollToId(id)}>{t}</a>)}
          <a onClick={() => window.navigate('/trai-nghiem-phan-mem')}>Trải nghiệm phần mềm</a>
          <span className="sep" />
          <a className="btn btn-accent" onClick={() => window.scrollToId('dang-ky')}>Đăng ký tham dự</a>
        </div>
      </div>
    </div>);

}

function Footer() {
  const C = window.VTC.CONTACT;
  return (
    <footer className="site">
      <div className="wrap">
        <div className="cols">
          <div>
            <div className="logo"><img src="brand-assets/logo-rays-white.svg" alt="VietCanThi" /></div>
            <p>Hệ thống chăm sóc cận thị cho người Việt</p>
          </div>
          <div>
            <h5>Sự kiện</h5>
            <a onClick={() => window.scrollToId('agenda')}>Agenda</a>
            <a onClick={() => window.scrollToId('dang-ky')}>Đăng ký tham dự</a>
            <a onClick={() => window.navigate('/khao-sat')}>Khảo sát cuối webinar</a>
            <a onClick={() => window.navigate('/bang-kiem-phong-kham')}>Bảng kiểm phòng khám</a>
          </div>
          <div>
            <h5>Liên hệ</h5>
            <a><span style={{ display: 'inline-flex', gap: 8, alignItems: 'center' }}><Icon name="mail" /> {C.email}</span></a>
            <a><span style={{ display: 'inline-flex', gap: 8, alignItems: 'center' }}><Icon name="phone" /> {C.hotline} <span className="placeholder">TODO</span></span></a>
            <a><span style={{ display: 'inline-flex', gap: 8, alignItems: 'center' }}><Icon name="pin" /> {C.website}</span></a>
          </div>
          <div>
            <h5>Phần mềm</h5>
            <a onClick={() => window.navigate('/trai-nghiem-phan-mem')}>Đăng ký dùng thử</a>
            <a onClick={() => window.navigate('/trai-nghiem-phan-mem')}>Tính năng</a>
          </div>
        </div>
        <div className="disc">
          <span>© 2026 VietCanThi</span>
          <span>vietcanthi.com</span>
        </div>
      </div>
    </footer>);

}

/* ---- toasts ---- */
function ToastHost() {
  const [items, setItems] = uS([]);
  uE(() => {
    window.toast = (t) => {
      const id = Date.now() + Math.random();
      setItems((p) => [...p, { ...t, id }]);
      setTimeout(() => setItems((p) => p.filter((x) => x.id !== id)), 4200);
    };
  }, []);
  return (
    <div className="toasts">
      {items.map((t) =>
      <div key={t.id} className={'toast ' + (t.kind || '')}>{t.title}{t.sub && <small>{t.sub}</small>}</div>
      )}
    </div>);

}

/* ---- scroll reveal ---- */
function useReveal(dep) {
  uE(() => {
    const els = document.querySelectorAll('.reveal:not(.in)');
    if (!('IntersectionObserver' in window)) {els.forEach((e) => e.classList.add('in'));return;}
    const io = new IntersectionObserver((ents) => ents.forEach((en) => {if (en.isIntersecting) {en.target.classList.add('in');io.unobserve(en.target);}}), { threshold: 0.12 });
    els.forEach((e) => io.observe(e));
    return () => io.disconnect();
  }, [dep]);
}

function App() {
  const [route, setRoute] = uS(parseHash());
  uE(() => {
    const on = () => setRoute(parseHash());
    window.addEventListener('hashchange', on);
    return () => window.removeEventListener('hashchange', on);
  }, []);
  useReveal(route.path);

  const { path, query } = route;
  const isForm = path !== '/';

  let page;
  if (path === '/khao-sat') page = <SurveyPage />;else
  if (path === '/bang-kiem-phong-kham') page = <ClinicPage />;else
  if (path === '/trai-nghiem-phan-mem') page = <TrialPage />;else
  if (path === '/cam-on') page = <ThankYou query={query} />;else
  page = <Landing />;

  return (
    <>
      <Navbar />
      {page}
      <Footer />
      <ToastHost />
    </>);

}

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