const { useState: useState4, useEffect: useEffect4 } = React;

/* =========================================================
   TWEAKS PANEL (variant switch, persisted)
   ========================================================= */
window.TweaksPanel = function TweaksPanel({ variant, setVariant, accent, setAccent }) {
  const [open, setOpen] = useState4(false);

  useEffect4(() => {
    const handler = (e) => {
      if (e.data?.type === '__activate_edit_mode') setOpen(true);
      if (e.data?.type === '__deactivate_edit_mode') setOpen(false);
    };
    window.addEventListener('message', handler);
    window.parent.postMessage({type:'__edit_mode_available'}, '*');
    return () => window.removeEventListener('message', handler);
  }, []);

  const commit = (edits) => {
    window.parent.postMessage({type:'__edit_mode_set_keys', edits}, '*');
  };

  if (!open) return null;
  return (
    <div className="tweaks open">
      <h4>Дизайн</h4>
      <div className="tweaks__row">
        <label>Напрямок стилю</label>
        <div className="tweaks__options">
          {[
            ['corporate', 'Corporate'],
            ['warm', 'Warm'],
            ['bold', 'Bold'],
          ].map(([v, l]) => (
            <button key={v} className={`tweaks__opt ${variant===v?'on':''}`} onClick={()=>{ setVariant(v); commit({variant: v}); }}>{l}</button>
          ))}
        </div>
      </div>
      <div className="tweaks__row">
        <label>Hero-заголовок</label>
        <div className="tweaks__options">
          {[
            ['serif', 'Editorial'],
            ['sans',  'Sans'],
          ].map(([v, l]) => (
            <button key={v} className={`tweaks__opt ${accent===v?'on':''}`} onClick={()=>{ setAccent(v); commit({accent: v}); }}>{l}</button>
          ))}
        </div>
      </div>
      <div style={{fontSize:11, color:'var(--ink-3)', marginTop:8, lineHeight:1.4}}>
        3 напрямки: <b>Corporate</b> — синій + editorial, <b>Warm</b> — теплі тони amber, <b>Bold</b> — чорний + жовтий акцент.
      </div>
    </div>
  );
};

/* =========================================================
   COOKIE BANNER + STICKY MESSENGERS
   ========================================================= */
window.CookieBanner = function CookieBanner() {
  const [show, setShow] = useState4(true);
  if (!show) return null;
  return (
    <div className="cookies">
      <div>Ми використовуємо cookies для покращення роботи сайту. Продовжуючи, ви погоджуєтесь з Політикою конфіденційності.</div>
      <div className="cookies__actions">
        <button className="btn btn--primary btn--sm" onClick={()=>setShow(false)}>Прийняти</button>
        <button className="btn btn--outline btn--sm" onClick={()=>setShow(false)}>Налаштувати</button>
      </div>
    </div>
  );
};

window.StickyMessengers = function StickyMessengers() {
  return (
    <div className="sticky-msgs">
      <a href="#" className="msg-float msg-float--tg" title="Telegram"><Icon name="chat" size={22}/></a>
      <a href="#" className="msg-float msg-float--wa" title="WhatsApp"><Icon name="mail" size={22}/></a>
    </div>
  );
};

/* =========================================================
   ROOT APP
   ========================================================= */
function App() {
  const TWEAKS = /*EDITMODE-BEGIN*/{
    "variant": "corporate",
    "accent": "serif"
  }/*EDITMODE-END*/;

  const [variant, setVariant] = useState4(TWEAKS.variant);
  const [accent, setAccent] = useState4(TWEAKS.accent);
  const [lang, setLang] = useState4(() => {
    try { return localStorage.getItem('mosty_lang') || 'UA'; } catch(e) { return 'UA'; }
  });

  useEffect4(() => {
    document.documentElement.setAttribute('data-variant', variant);
    document.documentElement.setAttribute('data-accent', accent);
  }, [variant, accent]);

  // Set data-lang SYNCHRONOUSLY before render so t() reads correct value
  if (typeof document !== 'undefined') {
    document.documentElement.setAttribute('data-lang', lang);
  }

  useEffect4(() => {
    document.documentElement.setAttribute('data-lang', lang);
    document.documentElement.setAttribute('lang', lang === 'RU' ? 'ru' : 'uk');
    try { localStorage.setItem('mosty_lang', lang); } catch(e) {}
    if (window.I18N && window.I18N[lang]) {
      document.title = window.I18N[lang].title;
      const desc = document.querySelector('meta[name="description"]');
      if (desc) desc.setAttribute('content', window.I18N[lang].description);
      const kw = document.querySelector('meta[name="keywords"]');
      if (kw) kw.setAttribute('content', window.I18N[lang].keywords);
    }
  }, [lang]);

  return (
    <div key={lang} style={{display:'contents'}}>
      <Topbar lang={lang} setLang={setLang}/>
      <Hero/>
      <LogosStrip/>
      <Benefits/>
      <UrgentJobs/>
      <Countries/>
      <Categories/>
      <Steps/>
      <Calculator/>
      <Stats/>
      <Testimonials/>
      <Community/>
      <FaqSection/>
      <FinalCTA/>
      <Footer/>
      <StickyMessengers/>
      <CookieBanner/>
      <TweaksPanel variant={variant} setVariant={setVariant} accent={accent} setAccent={setAccent}/>
    </div>
  );
}

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