// asiz-app.jsx — the main site app, rendering all pages

// Listen for in-form cross-page requests (legal links from consent checkboxes)
(() => {
  window.addEventListener('asiz-goto', (e) => {
    const route = e.detail;
    window.__asiz_setRoute && window.__asiz_setRoute(route);
  });
})();

// Map between SPA route names and real URL paths. Only legal pages have real URLs;
// other internal routes stay at `/` to preserve current behavior.
const PATH_FOR_ROUTE = {
  terms: '/terms',
  privacy: '/privacy',
  sellers: '/sellers',
  agents: '/agents',
  about: '/about',
  how: '/how-it-works',
  compare: '/compare',
  faq: '/faq',
  contact: '/contact',
  subToVsCash: '/sub-to-vs-cash-offer',
  subToVsShortSale: '/sub-to-vs-short-sale',
};
const ROUTE_FOR_PATH = {
  '/terms': 'terms',
  '/privacy': 'privacy',
  '/sellers': 'sellers',
  '/agents': 'agents',
  '/about': 'about',
  '/how-it-works': 'how',
  '/compare': 'compare',
  '/faq': 'faq',
  '/contact': 'contact',
  '/sub-to-vs-cash-offer': 'subToVsCash',
  '/sub-to-vs-short-sale': 'subToVsShortSale',
};
const routeFromLocation = () => ROUTE_FOR_PATH[window.location.pathname] || 'home';

function AsizSite({ palette, heroVariant, formStyle, motionScale, fontPair, showMiniBar, logoVariant }) {
  const [route, setRouteRaw] = React.useState(routeFromLocation);

  const setRoute = React.useCallback((next) => {
    setRouteRaw(next);
    const targetPath = PATH_FOR_ROUTE[next] || '/';
    if (window.location.pathname !== targetPath) {
      window.history.pushState({ route: next }, '', targetPath);
    }
  }, []);

  React.useEffect(() => { window.__asiz_setRoute = setRoute; }, [setRoute]);

  // Sync state when the user uses the browser back/forward buttons.
  React.useEffect(() => {
    const onPop = () => setRouteRaw(routeFromLocation());
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);
  const [miniVisible, setMiniVisible] = React.useState(false);
  const scrollRef = React.useRef(null);

  // Reset scroll on route change
  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = 0;
  }, [route]);

  // Show mini-bar after scrolling past the hero on home page
  React.useEffect(() => {
    if (!showMiniBar || route !== 'home') {
      setMiniVisible(false);
      return;
    }
    const el = scrollRef.current;
    if (!el) return;
    const onScroll = () => {
      setMiniVisible(el.scrollTop > 500 && el.scrollTop < el.scrollHeight - el.clientHeight - 800);
    };
    el.addEventListener('scroll', onScroll);
    onScroll();
    return () => el.removeEventListener('scroll', onScroll);
  }, [showMiniBar, route]);

  const page = (() => {
    switch (route) {
      case 'about': return <AboutPage setRoute={setRoute} formStyle={formStyle} />;
      case 'how': return <HowPage setRoute={setRoute} formStyle={formStyle} />;
      case 'compare': return <ComparePage setRoute={setRoute} formStyle={formStyle} />;
      case 'faq': return <FAQPage setRoute={setRoute} formStyle={formStyle} />;
      case 'contact': return <ContactPage setRoute={setRoute} formStyle={formStyle} />;
      case 'sellers': return <SellersPage setRoute={setRoute} formStyle={formStyle} />;
      case 'agents': return <AgentsPage setRoute={setRoute} formStyle={formStyle} />;
      case 'terms': return <TermsPage setRoute={setRoute} />;
      case 'privacy': return <PrivacyPage setRoute={setRoute} />;
      case 'subToVsCash': return <SubToVsCashOfferPage setRoute={setRoute} formStyle={formStyle} />;
      case 'subToVsShortSale': return <SubToVsShortSalePage setRoute={setRoute} formStyle={formStyle} />;
      default:
        return <HomePage setRoute={setRoute} heroVariant={heroVariant} formStyle={formStyle} />;
    }
  })();

  // Palette -> CSS variables
  const pal = PALETTES[palette] || PALETTES.warm;
  const fp = FONT_PAIRS[fontPair] || FONT_PAIRS.editorial;

  const rootStyle = {
    '--bg': pal.bg,
    '--bg-2': pal.bg2,
    '--ink': pal.ink,
    '--ink-soft': pal.inkSoft,
    '--line': pal.line,
    '--accent': pal.accent,
    '--accent-ink': pal.accentInk,
    '--sage': pal.sage,
    '--warn': pal.warn,
    '--font-display': fp.display,
    '--font-body': fp.body,
    '--font-mono': fp.mono,
    '--motion-scale': String(motionScale),
    height: '100%',
    display: 'flex',
    flexDirection: 'column',
  };

  return (
    <div
      className="asiz-root"
      data-motion={motionScale === 0 ? '0' : '1'}
      style={rootStyle}
    >
      <Nav route={route} setRoute={setRoute} logoVariant={logoVariant} />
      <div
        ref={scrollRef}
        className="asiz-shell"
        style={{ flex: 1, overflowY: 'auto', overflowX: 'hidden' }}
      >
        {page}
        <Footer setRoute={setRoute} logoVariant={logoVariant} />
        {showMiniBar && <MiniBar visible={miniVisible} onExpand={() => setRoute('contact')} />}
      </div>
    </div>
  );
}

// ─── Palette & font lookup ────────────────────────────────────

const PALETTES = {
  warm: {
    bg: '#F5F1EA', bg2: '#EAE3D6', ink: '#1A1512', inkSoft: 'rgba(26,21,18,0.62)',
    line: 'rgba(26,21,18,0.12)', accent: '#C65D3A', accentInk: '#FFFFFF',
    sage: '#3E5C4A', warn: '#B8906A',
  },
  dusk: {
    bg: '#0E1116', bg2: '#1A1F26', ink: '#E8E4DC', inkSoft: 'rgba(232,228,220,0.62)',
    line: 'rgba(232,228,220,0.14)', accent: '#D4A574', accentInk: '#0E1116',
    sage: '#4A6B5C', warn: '#B8906A',
  },
  sage: {
    bg: '#FAFAF7', bg2: '#EEEBE2', ink: '#2B3A2E', inkSoft: 'rgba(43,58,46,0.62)',
    line: 'rgba(43,58,46,0.14)', accent: '#B8906A', accentInk: '#FAFAF7',
    sage: '#8B9B7A', warn: '#C65D3A',
  },
  electric: {
    bg: '#FFFFFF', bg2: '#F2F0ED', ink: '#111111', inkSoft: 'rgba(17,17,17,0.62)',
    line: 'rgba(17,17,17,0.12)', accent: '#0033FF', accentInk: '#FFFFFF',
    sage: '#2B3A2E', warn: '#FF5C2B',
  },
};

const FONT_PAIRS = {
  editorial: {
    display: "'Fraunces', 'Playfair Display', Georgia, serif",
    body: "'Inter', system-ui, sans-serif",
    mono: "'JetBrains Mono', ui-monospace, monospace",
  },
  modern: {
    display: "'Instrument Serif', Georgia, serif",
    body: "'Geist', 'Inter', system-ui, sans-serif",
    mono: "'Geist Mono', ui-monospace, monospace",
  },
  swiss: {
    display: "'Söhne', 'Helvetica Neue', Helvetica, sans-serif",
    body: "'Söhne', 'Helvetica Neue', Helvetica, sans-serif",
    mono: "'JetBrains Mono', ui-monospace, monospace",
  },
  grotesk: {
    display: "'Space Grotesk', 'Inter', sans-serif",
    body: "'Inter', system-ui, sans-serif",
    mono: "'Space Mono', ui-monospace, monospace",
  },
};

Object.assign(window, { AsizSite, PALETTES, FONT_PAIRS });
