/* Root app: hash-based router + Tweaks + edit-mode wiring. */
/* useState/useEffect reused from Primitives.jsx */
const useST = React.useState;
const useEF = React.useEffect;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "light",
  "heroLayout": "split",
  "heroCopy": "agent",
  "accent": "pink"
}/*EDITMODE-END*/;

const TWEAK_SCHEMA_VERSION = 2;

function parseHash() {
  const h = (location.hash || '#').replace(/^#/, '');
  return h || '';
}

function loadTweaks() {
  try {
    const raw = JSON.parse(localStorage.getItem('sb_tweaks') || '{}');
    // v2 migration: prior builds defaulted accent to "terracotta" (orange).
    // Brick Rose is now the canonical brand color; drop that legacy pin so the default kicks in.
    if ((raw.__v || 0) < 2) {
      if (raw.accent === 'terracotta') delete raw.accent;
      raw.__v = TWEAK_SCHEMA_VERSION;
    }
    return { ...TWEAK_DEFAULTS, ...raw, __v: TWEAK_SCHEMA_VERSION };
  } catch {
    return { ...TWEAK_DEFAULTS, __v: TWEAK_SCHEMA_VERSION };
  }
}

function App() {
  const [route, setRoute] = useST(parseHash());
  const [tweaks, setTweaks] = useST(loadTweaks);
  const [tweaksVisible, setTweaksVisible] = useST(false);

  useEF(() => {
    const onHash = () => {
      setRoute(parseHash());
      // scrollIntoView is forbidden — use plain scroll
      window.scrollTo({ top: 0, behavior: 'instant' });
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  useEF(() => {
    localStorage.setItem('sb_tweaks', JSON.stringify(tweaks));
    document.documentElement.classList.toggle('theme-dark', tweaks.theme === 'dark');
    document.documentElement.classList.toggle('dark', tweaks.theme === 'dark');
    // Accent override — reset to default terracotta (hsl 14 62% 45%) unless overridden
    const accents = {
      pink:       { light: '340 55% 50%', dark: '340 60% 60%' },
      terracotta: { light: '14 62% 45%',  dark: '14 55% 58%'  },
      blue:       { light: '229 92% 54%', dark: '229 92% 64%' },
      ink:        { light: '222 20% 20%', dark: '210 20% 85%' },
    };
    const a = accents[tweaks.accent] || accents.pink;
    document.documentElement.style.setProperty('--sb-primary', tweaks.theme === 'dark' ? a.dark : a.light);
  }, [tweaks]);

  // Edit-mode (Tweaks toolbar toggle) — host protocol
  useEF(() => {
    const onMsg = (e) => {
      if (!e.data || typeof e.data !== 'object') return;
      if (e.data.type === '__activate_edit_mode') setTweaksVisible(true);
      if (e.data.type === '__deactivate_edit_mode') setTweaksVisible(false);
    };
    window.addEventListener('message', onMsg);
    try { window.parent.postMessage({ type: '__edit_mode_available' }, '*'); } catch {}
    return () => window.removeEventListener('message', onMsg);
  }, []);

  const updateTweaks = (patch) => {
    setTweaks(t => ({ ...t, ...patch }));
    try { window.parent.postMessage({ type: '__edit_mode_set_keys', edits: patch }, '*'); } catch {}
  };

  window.__nav = (to) => { location.hash = '#' + to; };

  const page = (() => {
    switch (route) {
      case '': return <HomePage tweaks={tweaks} />;
      case 'product': return <ProductPage />;
      case 'modules': return <ModulesPage />;
      case 'workforce': return <WorkforcePage />;
      case 'pricing': return <PricingPage />;
      case 'security': return <SecurityPage />;
      case 'customers': return <CustomersPage />;
      case 'about': return <AboutPage />;
      case 'changelog': return <ChangelogPage />;
      case 'contact': return <ContactPage />;
      default: return <HomePage tweaks={tweaks} />;
    }
  })();

  return (
    <div data-screen-label={route ? route : 'home'}>
      <AnnouncementBar />
      <TopNav route={route} theme={tweaks.theme} onToggleTheme={() => updateTweaks({ theme: tweaks.theme === 'dark' ? 'light' : 'dark' })} />
      <main>{page}</main>
      <Footer />
      <TweaksPanel visible={tweaksVisible} onClose={() => setTweaksVisible(false)} state={tweaks} setState={updateTweaks} />
    </div>
  );
}

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