// amps-site.jsx — full AMPS site composition + Tweaks panel

const { useState: useStateS, useEffect: useEffectS } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "surnameMaxChars": 24,
  "showCatalogNumbers": true,
  "memberCap": 500
}/*EDITMODE-END*/;

function AMPSSite({ mobile = false, scale = 1, initialAuths = {}, tweaks = TWEAK_DEFAULTS }) {
  const [auths, setAuths] = useStateS(initialAuths);
  const [confirmed, setConfirmed] = useStateS(null);

  // expose state for the canvas-level reset
  useEffectS(() => {
    const handler = (e) => {
      if (!e.data) return;
      if (e.data.__amps_reset_auths) setAuths({});
      if (e.data.__amps_clear_confirmation) setConfirmed(null);
    };
    window.addEventListener('message', handler);
    return () => window.removeEventListener('message', handler);
  }, []);

  const onEnlist = () => {
    const root = document.querySelector(`[data-amps-root="${mobile ? 'mobile' : 'desktop'}"]`);
    const target = root?.querySelector('[data-amps-enrollment]');
    if (target) target.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  return (
    <div data-amps-root={mobile ? 'mobile' : 'desktop'} style={{
      background: T.void, color: T.discoveryWhite,
      fontFamily: T.fontBody, position: 'relative',
    }}>
      {confirmed ? (
        <Confirmation data={confirmed} onReset={() => setConfirmed(null)} mobile={mobile} />
      ) : (
        <>
          <NavBar onEnlist={onEnlist} mobile={mobile} />
          <SocietyNav current="index.html" />
          <Hero />
          <Transmission auths={auths} setAuths={setAuths} mobile={mobile} />
          <TheSociety mobile={mobile} />
          <Council mobile={mobile} />
          <NavigatorsCreed mobile={mobile} />
          <Enrollment auths={auths} setAuths={setAuths} mobile={mobile}
            surnameMaxChars={tweaks.surnameMaxChars}
            onConfirm={(d) => setConfirmed(d)} />
          <Footer />
        </>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Artboard wrapper — fixed-size scrollable viewport for site
// ─────────────────────────────────────────────────────────────
function SiteArtboard({ width, height, mobile, label, scale = 1 }) {
  return (
    <div style={{ position: 'relative' }}>
      {label && (
        <div style={{
          position: 'absolute', bottom: '100%', left: 0, paddingBottom: 12,
          fontSize: 12, fontFamily: '-apple-system, sans-serif',
          color: 'rgba(60,50,40,0.7)', letterSpacing: 0.2,
          fontWeight: 500, whiteSpace: 'nowrap',
        }}>
          {label} · <span style={{ opacity: 0.6 }}>{width}×{height}</span>
        </div>
      )}
      <div style={{
        width, height,
        background: T.void,
        boxShadow: '0 1px 3px rgba(0,0,0,0.12), 0 8px 32px rgba(0,0,0,0.10)',
        overflow: 'hidden',
        position: 'relative',
        border: '1px solid rgba(0,0,0,0.08)',
      }}>
        <div data-amps-scroll style={{
          width: '100%', height: '100%', overflowY: 'auto', overflowX: 'hidden',
          scrollBehavior: 'smooth',
        }}>
          <AMPSSite mobile={mobile} />
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Tweaks panel — host-toolbar driven
// ─────────────────────────────────────────────────────────────
function TweaksPanel() {
  const [open, setOpen] = useStateS(false);
  const [active, setActive] = useStateS(false);

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

  if (!active) return null;

  const resetAuths = () => {
    document.querySelectorAll('iframe, [data-amps-root]').forEach(() => {});
    window.postMessage({ __amps_reset_auths: true }, '*');
  };
  const presetAll = () => {
    window.postMessage({ __amps_set_auths: { spotify: true, youtube: true, amazon: true } }, '*');
  };

  return (
    <div style={{
      position: 'fixed', bottom: 24, right: 24, zIndex: 1000,
      background: '#15181E', color: '#E8E5DD',
      border: '1px solid #2A2D34',
      width: open ? 280 : 'auto',
      fontFamily: '-apple-system, BlinkMacSystemFont, sans-serif',
      boxShadow: '0 10px 40px rgba(0,0,0,0.4)',
      transition: 'width 0.2s',
    }}>
      <div onClick={() => setOpen(o => !o)} style={{
        padding: '10px 14px', cursor: 'pointer',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        borderBottom: open ? '1px solid #2A2D34' : 'none',
      }}>
        <span style={{ fontSize: 11, letterSpacing: '0.18em', fontWeight: 600, color: T.amber }}>✦  TWEAKS</span>
        <span style={{ fontSize: 12, opacity: 0.5 }}>{open ? '×' : '◐'}</span>
      </div>
      {open && (
        <div style={{ padding: 14, display: 'flex', flexDirection: 'column', gap: 10 }}>
          <button onClick={() => window.postMessage({ __amps_reset_auths: true }, '*')} style={tweakBtn}>
            ↺ Reset all platform auth
          </button>
          <button onClick={() => window.postMessage({ __amps_clear_confirmation: true }, '*')} style={tweakBtn}>
            ← Clear confirmation state
          </button>
          <div style={{ height: 1, background: '#2A2D34', margin: '4px 0' }} />
          <div style={{ fontSize: 10, opacity: 0.5, letterSpacing: '0.1em' }}>
            Platforms can also be toggled by clicking each card directly.
          </div>
        </div>
      )}
    </div>
  );
}

const tweakBtn = {
  padding: '8px 12px', background: 'transparent',
  border: '1px solid #2A2D34', borderRadius: 0,
  color: '#E8E5DD', fontSize: 11, letterSpacing: '0.06em',
  fontFamily: '-apple-system, sans-serif', cursor: 'pointer',
  textAlign: 'left',
};

// ─────────────────────────────────────────────────────────────
// Root render — design canvas
// ─────────────────────────────────────────────────────────────
function Root() {
  return (
    <>
      <DesignCanvas minScale={0.1} maxScale={3}>
        <DCSection
          title="AMPS Society of Navigators · Phase 1"
          subtitle="Single-page enlistment · World's Fair Era · Desktop 1280 + Mobile 375 · Scroll inside artboards · Pan with drag · Pinch/scroll-wheel to zoom"
          gap={120}
        >
          <SiteArtboard width={1280} height={920} mobile={false} label="Desktop · 1280 × 920" />
          <SiteArtboard width={375} height={812} mobile={true} label="Mobile · 375 × 812" />
        </DCSection>
      </DesignCanvas>
      <TweaksPanel />
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Root />);
