/* global React, ReactDOM, Nav, Footer, Hero, StatsBand, HowItWorks, WhyTrust, Counsellors,
   Testimonials, Pricing, CTA, FAQ, Wizard, RankPredictor, TweaksPanel, useTweaks, TweakSection,
          TweakRadio, TweakColor, TweakToggle, TweakSelect, Chatbot */

// ============================================================
// Theme handling — light/dark + accent color
// ============================================================

const ACCENT_PRESETS = {
  Terracotta: { primary: '#B8541A', active: '#973F0F', soft: '#F4E6D8',  softDark: '#3B2A1C' },
  Amber:      { primary: '#A67217', active: '#85580C', soft: '#F5E8CC',  softDark: '#3A2E14' },
  Sage:       { primary: '#5F8060', active: '#3F5F40', soft: '#E2EBDD',  softDark: '#1F2D20' },
  Clay:       { primary: '#A04F3B', active: '#7E3A28', soft: '#F1DDD3',  softDark: '#3A2620' },
  Indigo:     { primary: '#3A4D8F', active: '#283672', soft: '#DCE0EF',  softDark: '#1B2238' },
};

const TWEAK_DEFAULTS = {
  "accent": "Terracotta",
  "serifAccent": true,
  "ambientHero": true
};

const applyAccent = (preset) => {
  const root = document.documentElement;
  root.style.setProperty('--color-primary', preset.primary);
  root.style.setProperty('--color-primary-active', preset.active);
  if (root.getAttribute('data-theme') === 'dark') {
    root.style.setProperty('--color-primary-soft', preset.softDark);
  } else {
    root.style.setProperty('--color-primary-soft', preset.soft);
  }
};

// ============================================================
// Router — hash based
// ============================================================
const useRoute = () => {
  const [route, setRoute] = React.useState(() => window.location.hash.replace(/^#/, '') || '/');
  React.useEffect(() => {
    const onHash = () => {
      const hash = window.location.hash.replace(/^#/, '') || '/';
      // Only treat hashes that start with '/' as page routes (e.g. /counselling, /predictor).
      // Plain section anchors like #counsellors or #faq start without '/' — let the
      // browser scroll to them natively without resetting the route or jumping to top.
      if (hash.startsWith('/')) setRoute(hash);
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);
  return route;
};

// ============================================================
// Theme toggle
// ============================================================
const useTheme = () => {
  const [theme, setTheme] = React.useState(() => {
    try { return localStorage.getItem('ce_theme') || 'light'; } catch { return 'light'; }
  });
  React.useEffect(() => {
    document.documentElement.setAttribute('data-theme', theme);
    try { localStorage.setItem('ce_theme', theme); } catch {}
  }, [theme]);
  return [theme, () => setTheme(theme === 'dark' ? 'light' : 'dark')];
};

// ============================================================
// Home page composition
// ============================================================
const Home = () => (
  <>
    <Hero />
    <HowItWorks />
    <StatsBand />
    <Pricing />
    <WhyTrust />
    <Counsellors />
    <CTA />
    <FAQ />
  </>
);

// ============================================================
// Counselling page
// ============================================================
const CounsellingPage = () => (
  <Wizard />
);

// ============================================================
// Rank Predictor page
// ============================================================
const PredictorPage = () => (
  <RankPredictor />
);

// ============================================================
// App shell
// ============================================================
const App = () => {
  const route = useRoute();
  const [theme, toggleTheme] = useTheme();
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);

  React.useEffect(() => {
    const preset = ACCENT_PRESETS[tweaks.accent] || ACCENT_PRESETS.Terracotta;
    applyAccent(preset);
  }, [tweaks.accent, theme]);

  React.useEffect(() => {
    document.documentElement.style.setProperty('--ambient-display', tweaks.ambientHero ? 'block' : 'none');
  }, [tweaks.ambientHero]);

  React.useEffect(() => {
    window.scrollTo({ top: 0, behavior: 'auto' });
  }, [route]);

  const isForm      = route.startsWith('/counselling');
  const isPredictor = route.startsWith('/predictor');

  return (
    <div>
      <Nav route={route} theme={theme} onToggleTheme={toggleTheme} />
      <main>
        {isForm      ? <CounsellingPage /> :
         isPredictor ? <PredictorPage />   :
                       <Home />}
      </main>
      <Footer />

      <TweaksPanel title="Tweaks">
        <TweakSection label="Accent color">
          <TweakColor
            label="Theme accent"
            value={ACCENT_PRESETS[tweaks.accent]?.primary}
            options={Object.values(ACCENT_PRESETS).map((p) => p.primary)}
            onChange={(hex) => {
              const name = Object.entries(ACCENT_PRESETS).find(([, p]) => p.primary === hex)?.[0] || 'Terracotta';
              setTweak('accent', name);
            }}
          />
          <div className="caption" style={{ marginTop: 8, fontSize: 11 }}>
            Currently: <strong style={{ color: 'var(--color-ink)' }}>{tweaks.accent}</strong>
          </div>
        </TweakSection>

        <TweakSection label="Visuals">
          <TweakToggle
            label="Ambient hero glow"
            value={tweaks.ambientHero}
            onChange={(v) => setTweak('ambientHero', v)}
          />
        </TweakSection>

        <TweakSection label="Theme">
          <div style={{ fontFamily: 'var(--font-sans)', fontSize: 12, color: 'var(--color-body)', marginBottom: 8 }}>
            Toggle dark mode from the navbar.
          </div>
          <div style={{ fontFamily: 'var(--font-sans)', fontSize: 12, color: 'var(--color-ink)', fontWeight: 600 }}>
            Currently: {theme === 'dark' ? 'Dark' : 'Light'}
          </div>
        </TweakSection>
      </TweaksPanel>

      <Chatbot />
    </div>
  );
};

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