// Shared per-screen runtime. Reads `#stage[data-screen][data-dark]` and renders
// the matching component for the active variant (P / A / B). Falls back to P
// when the requested variant doesn't exist for this screen.

(function () {
  const PHONE_W = 390;
  const PHONE_H = 844;

  function Phone({ children, dark }) {
    return (
      <IOSDevice width={PHONE_W} height={PHONE_H}>
        <div style={{ width: '100%', height: '100%', position: 'relative', overflow: 'hidden', background: dark ? '#1F1C18' : '#F4EFE8' }}>
          <IOSStatusBar dark={dark} />
          <div style={{ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, paddingTop: 50 }}>
            {children}
          </div>
        </div>
      </IOSDevice>
    );
  }

  function FallbackNote({ variant }) {
    return (
      <div style={{
        marginTop: 14,
        padding: '10px 14px',
        background: 'rgba(45,42,38,0.04)',
        border: '1px solid var(--line)',
        borderRadius: 10,
        color: 'var(--ink-2)',
        fontSize: 12,
        lineHeight: 1.55,
        maxWidth: 422,
        textAlign: 'center',
      }}>
        Variant <b>{variant}</b> hasn't been built for this screen — showing <b>Pebble Refined</b> instead.
      </div>
    );
  }

  let root = null;

  function pickComponent(screenKey, variant) {
    const name = variant + '_' + screenKey;
    return { Comp: window[name] || window['P_' + screenKey], fellBack: !window[name] && variant !== 'P' };
  }

  function render(variant) {
    const stage = document.getElementById('stage');
    if (!stage) return;
    const screenKey = stage.dataset.screen;
    const dark = stage.dataset.dark === 'true';
    if (!root) root = ReactDOM.createRoot(stage);

    const { Comp, fellBack } = pickComponent(screenKey, variant);
    if (!Comp) {
      root.render(<div style={{padding: 24, color: 'var(--clay-dk)'}}>No component found for {screenKey}.</div>);
      return;
    }
    root.render(
      <>
        <Phone dark={dark}><Comp /></Phone>
        {fellBack && <FallbackNote variant={variant} />}
      </>
    );
  }

  // Expose to wishlist.js so the variant toggle re-renders.
  window.WL_RENDER = render;

  // Initial render once the runtime has loaded. Prefer the persisted variant
  // (read via WL.getVariant); default to 'P' if WL hasn't initialised yet.
  function bootstrap() {
    const v = (window.WL && typeof window.WL.getVariant === 'function') ? window.WL.getVariant() : 'P';
    render(v);
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', bootstrap);
  } else {
    bootstrap();
  }
})();
