// App entry — mode toggle wires homeowner ↔ engineer + live flow modal host

const App = () => {
  const [mode, setMode] = React.useState(() => {
    if (typeof window !== 'undefined' && window.location.hash === '#engineer') return 'eng';
    return 'home';
  });

  React.useEffect(() => {
    const h = window.location.hash;
    if (h === '' || h === '#homeowner' || h === '#engineer') {
      window.location.hash = mode === 'eng' ? '#engineer' : '#homeowner';
    }
    document.body.classList.toggle('eng-mode', mode === 'eng');
    if (h === '' || h === '#homeowner' || h === '#engineer') {
      window.scrollTo({ top: 0, behavior: 'instant' });
    }
  }, [mode]);

  return (
    <>
      <ScrollProgress />
      <Header mode={mode} setMode={setMode} />
      {mode === 'home' ? <Homeowner /> : <Engineer />}
      <FlowHost />
    </>
  );
};

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

// Smooth in-page scroll for hash links — overrides default jump-cut.
document.addEventListener('click', (e) => {
  const a = e.target.closest('a[href^="#"]');
  if (!a) return;
  const href = a.getAttribute('href');
  if (href === '#' || href === '#homeowner' || href === '#engineer') return;
  if (href === '#top') {
    e.preventDefault();
    window.scrollTo({ top: 0, behavior: 'smooth' });
    return;
  }
  const target = document.querySelector(href);
  if (target) {
    e.preventDefault();
    target.scrollIntoView({ behavior: 'smooth', block: 'start' });
  }
});

// Toast helper preserved as fallback for any inert .btn the flows engine
// doesn't claim (e.g. unlabelled buttons added later).
window.showToast = (msg) => {
  document.querySelectorAll('.toast-feedback').forEach(t => t.remove());
  const t = document.createElement('div');
  t.className = 'toast-feedback';
  t.textContent = msg;
  document.body.appendChild(t);
  requestAnimationFrame(() => t.classList.add('in'));
  setTimeout(() => {
    t.classList.remove('in');
    setTimeout(() => t.remove(), 400);
  }, 3500);
};
