// OGS LP — エントリーポイント。LPを通常のスクロールページとして描画し、
// ビューポート幅に合わせてスケールする（デザイン幅 1280px）。

const DESIGN_WIDTH = 1280;

function useTweaks() {
  const [tweaks, setTweaks] = React.useState(() => {
    try {
      const el = document.getElementById('tweak-defaults');
      const m = el.textContent.match(/\/\*EDITMODE-BEGIN\*\/([\s\S]*?)\/\*EDITMODE-END\*\//);
      return m ? JSON.parse(m[1]) : {};
    } catch { return {}; }
  });
  const persist = React.useCallback((patch) => {
    setTweaks((prev) => {
      const next = { ...prev, ...patch };
      try { window.parent.postMessage({ type: '__edit_mode_set_keys', edits: patch }, '*'); } catch {}
      return next;
    });
  }, []);
  return [tweaks, persist];
}

// Red swatches — same lightness/chroma, hue varies.
const RED_SWATCHES = [
  { n: '緋', h: 20 },
  { n: '赤', h: 25 },
  { n: '信号赤', h: 29 },
  { n: '朱', h: 38 },
];

function TweaksPanel({ visible, tweaks, onChange }) {
  if (!visible) return null;
  const row = { display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 14 };
  const label = { fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', color: '#777' };
  const inputStyle = { width: '100%', padding: '6px 8px', border: '1px solid #ddd', borderRadius: 6, fontFamily: 'inherit', fontSize: 13 };
  const seg = (options, key, def) => (
    <div style={{ display: 'flex', gap: 4 }}>
      {options.map(([v, l]) => (
        <button key={v} onClick={() => onChange({ [key]: v })}
          style={{ flex: 1, padding: '6px 4px', fontSize: 12, cursor: 'pointer', borderRadius: 5, fontFamily: 'inherit',
            border: (tweaks[key] ?? def) === v ? '1.5px solid #222' : '1px solid #ccc',
            background: (tweaks[key] ?? def) === v ? '#f2f0eb' : '#fff', color: '#222' }}>{l}</button>
      ))}
    </div>
  );
  return (
    <div style={{
      position: 'fixed', bottom: 20, right: 20, zIndex: 9999,
      width: 252, background: '#fff', border: '1px solid rgba(0,0,0,0.12)',
      borderRadius: 10, padding: 16, boxShadow: '0 8px 32px rgba(0,0,0,0.15)',
      fontFamily: 'system-ui, sans-serif', fontSize: 13, color: '#222',
    }}>
      <div style={{ fontSize: 12, fontWeight: 600, letterSpacing: '0.05em', textTransform: 'uppercase', marginBottom: 12, paddingBottom: 10, borderBottom: '1px solid #eee' }}>Tweaks</div>

      <div style={row}>
        <div style={label}>赤の色</div>
        <div style={{ display: 'flex', gap: 4 }}>
          {RED_SWATCHES.map((p) => (
            <button key={p.h} onClick={() => onChange({ redHue: p.h })} title={p.n}
              style={{ flex: 1, height: 22, cursor: 'pointer', padding: 0, borderRadius: 3,
                border: (tweaks.redHue ?? 29) === p.h ? '2px solid #222' : '1px solid #ccc',
                background: `oklch(0.56 0.22 ${p.h})` }}></button>
          ))}
        </div>
      </div>

      <div style={row}>
        <div style={label}>赤の量</div>
        {seg([['standard', '標準'], ['min', '控えめ']], 'redAmount', 'standard')}
      </div>

      <div style={row}>
        <div style={label}>ヒーローコピー</div>
        <select value={tweaks.heroCopy ?? 'subete'} onChange={(e) => onChange({ heroCopy: e.target.value })} style={inputStyle}>
          <option value="subete">グッズ販売に必要なこと、すべて。</option>
          <option value="urakata">600公演の、裏方。</option>
          <option value="soba">公演の、そばに。</option>
        </select>
      </div>

      <div style={row}>
        <div style={label}>ラインナップ段組</div>
        {seg([['tiered', 'ティア組'], ['flat', 'フラット']], 'lineup', 'tiered')}
      </div>

      <div style={row}>
        <div style={label}>クロージング帯</div>
        {seg([['red', '赤'], ['ink', '墨']], 'contactBand', 'red')}
      </div>

      <div style={row}>
        <div style={label}>マーキー周期（{tweaks.marqueeSec ?? 80}秒）</div>
        <input type="range" min="20" max="200" step="5" value={tweaks.marqueeSec ?? 80}
          onChange={(e) => onChange({ marqueeSec: +e.target.value })}></input>
      </div>
    </div>
  );
}

function TweaksStyleInjector({ tweaks }) {
  React.useEffect(() => {
    const hue = tweaks.redHue ?? 29;
    let s = document.getElementById('tweak-overrides');
    if (!s) { s = document.createElement('style'); s.id = 'tweak-overrides'; document.head.appendChild(s); }
    s.textContent = `
      .vc-root { --red: oklch(0.56 0.22 ${hue}) !important; }
    `;
  }, [tweaks]);
  return null;
}

function App() {
  const [tweakVisible, setTweakVisible] = React.useState(false);
  const [tweaks, setTweaks] = useTweaks();
  const [vw, setVw] = React.useState(window.innerWidth);

  React.useEffect(() => {
    const onMsg = (e) => {
      const d = e.data || {};
      if (d.type === '__activate_edit_mode') setTweakVisible(true);
      if (d.type === '__deactivate_edit_mode') setTweakVisible(false);
    };
    const onResize = () => setVw(window.innerWidth);
    window.addEventListener('message', onMsg);
    window.addEventListener('resize', onResize);
    try { window.parent.postMessage({ type: '__edit_mode_available' }, '*'); } catch {}
    return () => { window.removeEventListener('message', onMsg); window.removeEventListener('resize', onResize); };
  }, []);

  // Below MOBILE_BP the design reflows to a native 1-column layout (zoom 1);
  // above it, the 1280px desktop design is scaled to fit the viewport width.
  const MOBILE_BP = 800;
  const isMobile = vw <= MOBILE_BP;
  const zoom = isMobile ? 1 : Math.min(vw / DESIGN_WIDTH, 1.5);

  return (
    <>
      <TweaksStyleInjector tweaks={tweaks}></TweaksStyleInjector>
      <div style={{ zoom: zoom }}>
        <OGSLandingPage
          heroCopy={tweaks.heroCopy ?? 'subete'}
          lineup={tweaks.lineup ?? 'tiered'}
          marqueeSec={tweaks.marqueeSec ?? 80}
          redAmount={tweaks.redAmount ?? 'standard'}
          contactBand={tweaks.contactBand ?? 'red'}>
        </OGSLandingPage>
      </div>
      <TweaksPanel visible={tweakVisible} tweaks={tweaks} onChange={setTweaks}></TweaksPanel>
    </>
  );
}

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