// app.jsx — mount all sections, wire tweaks + nav progress + hero variant swap.

const { useState, useEffect } = React;

/* --- Hero title/dek variants (A/B/C) ------------------------------- */
function applyHeroVariant(variant){
  const el  = document.querySelector('.hero__title');
  const dek = document.querySelector('.hero__dek');
  if(!el || !dek) return;
  if(variant==='b'){
    el.innerHTML  = 'The Iran<br/><em>we forgot</em>';
    dek.textContent = "A century of opening and closing. The country once hosted US presidents, traded with Israel and ran a cosmopolitan middle class. The cycle may turn again.";
  } else if(variant==='c'){
    el.innerHTML  = 'An island<br/>of <em>stability</em>';
    dek.textContent = "Fourteen months before the Revolution, Iran was called an \u2018island of stability\u2019. The lesson for today's investor — consensus can miss the deepest currents.";
  } else {
    el.innerHTML  = 'Iran <em>before</em><br/>the Revolution';
    dek.textContent = "Iran has not always been as troubled as it is today. It was once seen as a champion of modernisation and a US ally. Today's conflicts are part of a longer-term cycle of openness and repression.";
  }
}

/* --- Scroll progress bar in nav ------------------------------------ */
function wireProgress(){
  const bar = document.getElementById('nav-progress');
  if(!bar) return;
  const onScroll = () => {
    const h = document.documentElement;
    const total = h.scrollHeight - h.clientHeight;
    const pct = total > 0 ? h.scrollTop / total : 0;
    bar.style.transform = `scaleX(${pct})`;
  };
  window.addEventListener('scroll', onScroll, {passive:true});
  onScroll();
}

/* --- Tweaks wiring ------------------------------------------------- */
function wireTweaks(setTweaks){
  window.addEventListener('message', (e)=>{
    const d = e.data || {};
    if(d.type === '__activate_edit_mode')   document.getElementById('tweaks-panel').classList.add('is-open');
    if(d.type === '__deactivate_edit_mode') document.getElementById('tweaks-panel').classList.remove('is-open');
  });
  if(window.parent !== window){
    window.parent.postMessage({type:'__edit_mode_available'}, '*');
  }

  document.getElementById('tweaks-close').onclick = () => {
    document.getElementById('tweaks-panel').classList.remove('is-open');
    if(window.parent !== window){
      window.parent.postMessage({type:'__deactivate_edit_mode'}, '*');
    }
  };

  // Accent swatches
  document.querySelectorAll('#twk-accent .twk-swatch').forEach(el => {
    el.onclick = () => {
      document.querySelectorAll('#twk-accent .twk-swatch').forEach(s => s.classList.remove('is-sel'));
      el.classList.add('is-sel');
      setTweaks(t => ({...t, accent: el.dataset.val}));
    };
  });

  const ov = document.getElementById('twk-overlay');
  ov.value = window.TWEAK_DEFAULTS.overlay;
  ov.oninput = (e)=> setTweaks(t => ({...t, overlay: parseFloat(e.target.value)}));

  const sc = document.getElementById('twk-scale');
  sc.value = window.TWEAK_DEFAULTS.scale;
  sc.oninput = (e)=> setTweaks(t => ({...t, scale: parseFloat(e.target.value)}));

  document.querySelectorAll('#twk-map button').forEach(b => {
    b.onclick = ()=>{
      document.querySelectorAll('#twk-map button').forEach(x => x.classList.remove('is-sel'));
      b.classList.add('is-sel');
      setTweaks(t => ({...t, mapStyle: b.dataset.val}));
    };
  });

  document.querySelectorAll('#twk-hero button').forEach(b => {
    b.onclick = ()=>{
      document.querySelectorAll('#twk-hero button').forEach(x => x.classList.remove('is-sel'));
      b.classList.add('is-sel');
      setTweaks(t => ({...t, heroVariant: b.dataset.val}));
    };
  });
}

/* --- Root shell ---------------------------------------------------- */
function AppShell(){
  const [tw, setTw] = useState(()=> Object.assign({}, window.TWEAK_DEFAULTS));
  const [hl, setHl] = useState(null);

  // CSS vars
  useEffect(()=>{
    const r = document.documentElement.style;
    r.setProperty('--accent-gold',   tw.accent);
    r.setProperty('--hero-overlay',  tw.overlay);
    r.setProperty('--headline-scale',tw.scale);
    applyHeroVariant(tw.heroVariant);
    if(window.parent !== window){
      window.parent.postMessage({type:'__edit_mode_set_keys', edits: tw}, '*');
    }
  }, [tw]);

  // Render each DOM slot via its own persistent root so we can swap props
  useEffect(()=>{
    if(!window._roots){
      window._roots = {
        q: ReactDOM.createRoot(document.getElementById('quiz-grid')),
        m: ReactDOM.createRoot(document.getElementById('map-shell')),
        t: ReactDOM.createRoot(document.getElementById('timeline-wrap')),
        a: ReactDOM.createRoot(document.getElementById('article-grid')),
        i: ReactDOM.createRoot(document.getElementById('impl-grid'))
      };
    }
    window._roots.q.render(<window.QuizSection />);
    window._roots.m.render(<window.GeographySection mapStyle={tw.mapStyle} />);
    window._roots.t.render(<window.TimelineSection onHighlight={setHl} />);
    window._roots.a.render(<window.ArticleSection highlight={hl} />);
    window._roots.i.render(<window.ImplicationsSection />);
  }, [tw, hl]);

  window._setTweaks = setTw;
  return null;
}

/* --- Boot ---------------------------------------------------------- */
(function boot(){
  window.mountBrand();
  wireProgress();

  const host = document.createElement('div');
  document.body.appendChild(host);
  ReactDOM.createRoot(host).render(<AppShell />);

  setTimeout(()=>{
    wireTweaks((updater)=>{
      if(typeof updater === 'function'){
        window._setTweaks(prev => updater(prev));
      } else {
        window._setTweaks(updater);
      }
    });
  }, 50);
})();
