// app.jsx — root + routing + tweaks

const { useState, useEffect } = React;

// ── Hash-based route serialization ───────────────────────────────────────────
// Routes serialize to URL hash so browser back/forward + refresh work.
// e.g. #pdp&productId=sildenafil&dose=100&qty=10&duration=3
function writeRouteToHash(route) {
  if (!route || route.name === 'landing') return '';
  const params = route.params || {};
  const parts = [route.name];
  for (const [k, v] of Object.entries(params)) {
    if (v == null || k === 'answers') continue; // don't serialize bulky answers
    parts.push(`${encodeURIComponent(k)}=${encodeURIComponent(v)}`);
  }
  return '#' + parts.join('&');
}
function readRouteFromHash() {
  const h = (location.hash || '').replace(/^#/, '');
  if (!h) return null;
  // Anchor links (#ed, #faq, etc) shouldn't be parsed as routes
  if (/^[a-z]+$/.test(h) && !['quiz', 'results', 'pdp', 'cart', 'confirm', 'landing'].includes(h)) return null;
  const [name, ...rest] = h.split('&');
  if (!name) return null;
  const validRoutes = ['landing', 'quiz', 'results', 'pdp', 'cart', 'confirm'];
  if (!validRoutes.includes(name)) return null;
  const params = {};
  for (const kv of rest) {
    const [k, v] = kv.split('=');
    if (!k) continue;
    const decoded = decodeURIComponent(v || '');
    // Coerce numeric-looking values
    const num = Number(decoded);
    params[decodeURIComponent(k)] = !Number.isNaN(num) && decoded !== '' && /^-?\d+(\.\d+)?$/.test(decoded) ? num : decoded;
  }
  return { name, params };
}

function App() {
  const [t, setTweak] = useTweaks(window.TWEAK_DEFAULTS);
  const [route, setRoute] = useState(() => readRouteFromHash() || { name: 'landing', params: {} });
  const [answers, setAnswers] = useState({});

  // Apply palette from tweaks
  useEffect(() => {
    document.body.setAttribute('data-palette', t.palette || 'cream');
  }, [t.palette]);

  // ── Browser history wiring ───────────────────────────────────────────
  // Push state on route change so browser back/forward work, and listen
  // for popstate to keep our React state in sync with the URL.
  useEffect(() => {
    const onPop = () => {
      const fromHash = readRouteFromHash();
      if (fromHash) setRoute(fromHash);
      else setRoute({ name: 'landing', params: {} });
    };
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);

  // Scroll to top on route change
  useEffect(() => {
    window.scrollTo({ top: 0, behavior: 'instant' });
  }, [route.name]);

  const go = (name, params = {}) => {
    if (params.answers) setAnswers(params.answers);
    const next = { name, params };
    setRoute(next);
    // Push to browser history (but only if we're actually changing route)
    const url = writeRouteToHash(next);
    if (url !== location.hash) {
      history.pushState(next, '', url || '#');
    }
  };

  let view;
  switch (route.name) {
    case 'landing':
      view = (
        <>
          <TrustRibbon />
          <TopNav go={go} current="landing" />
          <Landing go={go} />
          <SiteFooter />
        </>
      );
      break;
    case 'quiz':
      view = <Quiz go={go} />;
      break;
    case 'results':
      view = <Results go={go} answers={route.params.answers || answers} />;
      break;
    case 'pdp':
      view = <PDP go={go} productId={route.params.productId || 'sildenafil'} dose={route.params.dose} mode={route.params.mode} qty={route.params.qty} duration={route.params.duration} />;
      break;
    case 'cart':
      view = <Cart go={go} productId={route.params.productId} mode={route.params.mode} dose={route.params.dose} qty={route.params.qty} duration={route.params.duration} />;
      break;
    case 'confirm':
      view = <Confirm go={go} productId={route.params.productId} mode={route.params.mode} dose={route.params.dose} qty={route.params.qty} duration={route.params.duration} />;
      break;
    default:
      view = <Landing go={go} />;
  }

  const screenLabel = {
    landing: '01 Landing',
    quiz: '02 Quiz',
    results: '03 Results',
    pdp: '04 Product detail',
    cart: '05 Checkout',
    confirm: '06 Confirmation',
  }[route.name];

  return (
    <div data-screen-label={screenLabel}>
      {view}

      {/* Exit-intent modal — only on landing page, only once per session */}
      {route.name === 'landing' && (
        <ExitIntentModal onAccept={() => go('quiz')} />
      )}

      {/* Active discount badge — visible site-wide once applied */}
      <ActiveDiscountBanner />

      {/* Mobile sticky bottom CTA — landing only, hides during funnel */}
      {route.name === 'landing' && (
        <StickyMobileCTA go={go} />
      )}
      <TweaksPanel>
        <TweakSection label="Palette" />
        <TweakColor
          label="Theme"
          value={t.palette}
          options={[
            ['#f4ede0', '#0c2124', '#f3e396'],   // cream (default)
            ['#0c2124', '#f3e396', '#b4d8d8'],   // dark
            ['#f3ede0', '#0c2124', '#b4d8d8'],   // ocean (blue accent)
            ['#f7f0dc', '#f3e396', '#0c2124'],   // butter (yellow CTA)
          ]}
          onChange={(palette) => {
            const map = JSON.stringify(palette);
            const names = {
              [JSON.stringify(['#f4ede0', '#0c2124', '#f3e396'])]: 'cream',
              [JSON.stringify(['#0c2124', '#f3e396', '#b4d8d8'])]: 'dark',
              [JSON.stringify(['#f3ede0', '#0c2124', '#b4d8d8'])]: 'ocean',
              [JSON.stringify(['#f7f0dc', '#f3e396', '#0c2124'])]: 'butter',
            };
            setTweak('palette', names[map] || 'cream');
          }}
        />
        <div style={{ fontSize: 10.5, color: 'rgba(41,38,27,.55)', lineHeight: 1.5 }}>
          Cream is the brand default — Motivated-style editorial. Dark mirrors the favicon.
        </div>

        <TweakSection label="Jump to screen" />
        <div style={{ display: 'grid', gap: 6 }}>
          {[
            { id: 'landing', label: 'Landing page' },
            { id: 'quiz',    label: 'Quiz flow' },
            { id: 'results', label: 'Results page' },
            { id: 'pdp',     label: 'Product detail' },
            { id: 'cart',    label: 'Checkout' },
            { id: 'confirm', label: 'Confirmation' },
          ].map(s => (
            <button key={s.id} onClick={() => go(s.id,
                  s.id === 'pdp' ? { productId: 'sildenafil' }
                  : (s.id === 'cart' || s.id === 'confirm') ? { productId: 'sildenafil', dose: 100, qty: 10, duration: 3 }
                  : {}
                )}
                    style={{
                      all: 'unset', cursor: 'pointer',
                      padding: '7px 10px',
                      background: route.name === s.id ? 'rgba(0,0,0,.08)' : 'rgba(0,0,0,.03)',
                      border: '1px solid rgba(0,0,0,.06)',
                      borderRadius: 6,
                      fontSize: 11.5,
                      color: route.name === s.id ? '#29261b' : 'rgba(41,38,27,.7)',
                      fontWeight: route.name === s.id ? 600 : 400,
                    }}>
              {s.label}
            </button>
          ))}
        </div>
      </TweaksPanel>
    </div>
  );
}

// Mount + hide splash
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
requestAnimationFrame(() => {
  const sp = document.getElementById('__splash');
  if (sp) {
    sp.style.transition = 'opacity .4s ease';
    sp.style.opacity = '0';
    setTimeout(() => sp.remove(), 450);
  }
});
