/* app.jsx — Root router (host- and path-based) */

const { useEffect: apUseEffect, useState: apUseState } = React;

// Domains in production. Anything else (localhost, vercel preview URLs) is treated as dev.
const LANDING_HOST = 'trinium.xyz';
const APP_HOST = 'app.trinium.xyz';

function isAppHost(host) {
  return host === APP_HOST || host.startsWith('app.');
}
function isLandingHost(host) {
  return host === LANDING_HOST || host === `www.${LANDING_HOST}`;
}

function currentRoute() {
  const host = window.location.hostname;
  const path = window.location.pathname;
  const hash = window.location.hash;
  // Production: app subdomain always renders the trading app.
  if (isAppHost(host)) return 'trade';
  // Production landing: only render landing (clicking start jumps to app subdomain).
  if (isLandingHost(host)) return 'landing';
  // Dev / preview: fall back to path, then hash.
  if (path.startsWith('/trade') || hash.startsWith('#/trade')) return 'trade';
  return 'landing';
}

function gotoTrade() {
  if (isLandingHost(window.location.hostname)) {
    window.location.href = `https://${APP_HOST}/trade`;
  } else if (isAppHost(window.location.hostname)) {
    window.location.href = '/trade';
  } else {
    window.location.hash = '#/trade/btc-5m-up-down';
  }
}

function gotoHome() {
  if (isAppHost(window.location.hostname)) {
    window.location.href = `https://${LANDING_HOST}/`;
  } else if (isLandingHost(window.location.hostname)) {
    window.location.href = '/';
  } else {
    window.location.hash = '#/';
  }
}

function App() {
  const [route, setRoute] = apUseState(currentRoute);

  apUseEffect(() => {
    const h = () => setRoute(currentRoute());
    window.addEventListener('hashchange', h);
    window.addEventListener('popstate', h);
    return () => {
      window.removeEventListener('hashchange', h);
      window.removeEventListener('popstate', h);
    };
  }, []);

  if (route === 'trade') {
    return (
      <div className="h-full w-full" data-screen-label="02 Trading App">
        <TradeApp onHome={gotoHome} />
      </div>
    );
  }
  return (
    <div className="h-full w-full" data-screen-label="01 Landing">
      <Landing onStart={gotoTrade} />
    </div>
  );
}

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