/* global React, ReactDOM */

// TWEAKS defaults
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "cyan",
  "theme": "dark",
  "density": "default"
}/*EDITMODE-END*/;

const ACCENT_MAP = {
  cyan: { v: '#3FA4C9', name: 'Cyan' },
  orange: { v: '#E89B3C', name: 'Orange' },
  navy: { v: '#1B3360', name: 'Navy' },
  green: { v: '#6FB85A', name: 'Green' },
  sky: { v: '#7FB9DC', name: 'Sky' },
};

function App() {
  const hash = useHashRoute();
  const [theme, setThemeState] = useState(TWEAK_DEFAULTS.theme);
  const [accent, setAccent] = useState(TWEAK_DEFAULTS.accent);
  const [mobileOpen, setMobileOpen] = useState(false);
  const [tweaksOpen, setTweaksOpen] = useState(false);
  const [editModeActive, setEditModeActive] = useState(false);

  // apply theme to document
  useEffect(() => { document.documentElement.setAttribute('data-theme', theme); }, [theme]);
  // apply accent via CSS var
  useEffect(() => {
    const c = ACCENT_MAP[accent]?.v || ACCENT_MAP.cyan.v;
    document.documentElement.style.setProperty('--accent', c);
  }, [accent]);

  const setTheme = (t) => {
    setThemeState(t);
    window.parent?.postMessage({type:'__edit_mode_set_keys', edits:{theme:t}}, '*');
  };
  const pickAccent = (a) => {
    setAccent(a);
    window.parent?.postMessage({type:'__edit_mode_set_keys', edits:{accent:a}}, '*');
  };

  // close mobile menu on route change
  useEffect(() => { setMobileOpen(false); }, [hash]);

  // Tweaks protocol — listener first, then announce
  useEffect(() => {
    const handle = (ev) => {
      if (ev.data?.type === '__activate_edit_mode') { setEditModeActive(true); setTweaksOpen(true); }
      if (ev.data?.type === '__deactivate_edit_mode') { setEditModeActive(false); setTweaksOpen(false); }
    };
    window.addEventListener('message', handle);
    window.parent?.postMessage({type:'__edit_mode_available'}, '*');
    return () => window.removeEventListener('message', handle);
  }, []);

  const Page = pickPage(hash);

  return (
    <>
      <Nav route={hash} theme={theme} setTheme={setTheme} mobileOpen={mobileOpen} setMobileOpen={setMobileOpen} />
      <main data-screen-label={labelFromHash(hash)}>
        <Page />
      </main>
      <Footer/>
      {editModeActive && (
        <div className={`tweaks-panel ${tweaksOpen?'open':''}`}>
          <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:8}}>
            <h5 style={{margin:0}}>Tweaks</h5>
            <button onClick={() => setTweaksOpen(!tweaksOpen)} style={{fontSize:16,color:'var(--fg-muted)'}}>{tweaksOpen?'−':'+'}</button>
          </div>
          <div className="tweaks-row">
            <span>Theme</span>
            <div style={{display:'flex',gap:6}}>
              <button className={`btn ${theme==='dark'?'btn-primary':'btn-ghost'}`} style={{padding:'6px 10px',fontSize:12}} onClick={() => setTheme('dark')}>Dark</button>
              <button className={`btn ${theme==='light'?'btn-primary':'btn-ghost'}`} style={{padding:'6px 10px',fontSize:12}} onClick={() => setTheme('light')}>Light</button>
            </div>
          </div>
          <div className="tweaks-row">
            <span>Akzent</span>
            <div className="swatch-row">
              {Object.entries(ACCENT_MAP).map(([k, v]) => (
                <button key={k} className={`swatch ${accent===k?'active':''}`} style={{background:v.v}} onClick={() => pickAccent(k)} title={v.name}/>
              ))}
            </div>
          </div>
        </div>
      )}
    </>
  );
}

function pickPage(hash) {
  const p = hash.replace('#','');
  if (p === '/' || p === '') return HomePage;
  if (p.startsWith('/ueber-uns')) return AboutPage;
  if (p.startsWith('/geschichte')) return HistoryPage;
  if (p.startsWith('/dienstleistung')) return DienstleistungPage;
  if (p.startsWith('/produkte')) return ProduktePage;
  if (p.startsWith('/beratung')) return BeratungPage;
  if (p.startsWith('/rechenzentrum')) return RechenzentrumPage;
  if (p.startsWith('/loesungen/ungana-cloud')) return UnganaCloudPage;
  if (p.startsWith('/loesungen/ungana-exchange')) return UnganaExchangePage;
  if (p.startsWith('/loesungen')) return LoesungenPage;
  if (p.startsWith('/blog/')) {
    const slug = p.replace('/blog/', '');
    return () => <BlogDetailPage slug={slug} />;
  }
  if (p.startsWith('/blog')) return BlogPage;
  if (p.startsWith('/jobs')) return JobsPage;
  if (p.startsWith('/kontakt')) return KontaktPage;
  if (p.startsWith('/anfahrt')) return AnfahrtPage;
  if (p.startsWith('/fernwartung')) return FernwartungPage;
  if (p.startsWith('/impressum')) return ImpressumPage;
  if (p.startsWith('/datenschutz')) return DatenschutzPage;
  return HomePage;
}

function labelFromHash(hash) {
  const p = hash.replace('#','');
  if (p === '/' || p === '') return 'Start';
  return p.replace(/^\//,'').replace(/\//g,' · ');
}

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