/* Tweaks panel — Ouka Tennis LP
   Lets you swap tone (Court / Pearl / Night), language, and a couple of micro options.
*/

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "tone": "court",
  "petals": true,
  "heroAlign": "split"
}/*EDITMODE-END*/;

const { useState, useEffect, useRef } = React;

function applyTone(tone) {
  document.documentElement.setAttribute('data-tone', tone);
}
function applyPetals(on) {
  document.querySelectorAll('.hero-ball').forEach(el => {
    el.style.animationPlayState = on ? 'running' : 'paused';
    el.style.opacity = on ? '' : '0.6';
  });
  document.querySelectorAll('.hero-insight, .hero-score').forEach(el => {
    el.style.animationPlayState = on ? 'running' : 'paused';
  });
  document.querySelectorAll('.petals, .section-petals').forEach(el => {
    el.style.display = on ? '' : 'none';
  });
}
function applyHeroAlign(mode) {
  const grid = document.querySelector('.hero-grid');
  if (!grid) return;
  if (mode === 'split') {
    grid.style.gridTemplateColumns = '';
    grid.style.textAlign = '';
  } else if (mode === 'center') {
    grid.style.gridTemplateColumns = '1fr';
    grid.style.textAlign = 'center';
    const copy = grid.querySelector('.hero-copy');
    if (copy) {
      copy.style.alignItems = 'center';
      copy.style.maxWidth = '720px';
      copy.style.margin = '0 auto';
    }
  }
}

const TONES = [
  {
    id: 'court',
    name: 'Court',
    sub: 'ネイビー × ライム',
    description: '既定。スコアボードと放送グラフィック寄り。',
    palette: ['#1C2430', '#B9DD36', '#F4F5F8']
  },
  {
    id: 'pearl',
    name: 'Pearl',
    sub: '和紙×桜',
    description: 'クレイコート風の暖かいオフホワイト。桜色をほのかに。',
    palette: ['#FAF6F0', '#C4E030', '#CC4A72']
  },
  {
    id: 'night',
    name: 'Night',
    sub: '黒×ネオンライム',
    description: '完全ダーク。ウェアラブル/ゲーミング寄り。',
    palette: ['#07090E', '#B9DD36', '#0F141C']
  }
];

function ToneCard({ tone, active, onSelect }) {
  return (
    <button
      onClick={() => onSelect(tone.id)}
      style={{
        textAlign: 'left',
        background: active ? 'rgba(185,221,54,0.12)' : 'transparent',
        border: '1px solid ' + (active ? '#B9DD36' : 'rgba(255,255,255,0.08)'),
        borderRadius: 12,
        padding: '12px 14px',
        cursor: 'pointer',
        display: 'flex',
        flexDirection: 'column',
        gap: 8,
        color: '#fff',
        fontFamily: 'inherit',
        transition: 'background 0.18s ease, border-color 0.18s ease',
      }}
    >
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div>
          <div style={{ fontFamily: "'Noto Sans JP','Plus Jakarta Sans',sans-serif", fontWeight: 900, fontSize: 14, letterSpacing: '-0.01em' }}>
            {tone.name}
          </div>
          <div style={{ fontFamily: "'Noto Sans JP','Plus Jakarta Sans',sans-serif", fontWeight: 500, fontSize: 11, color: 'rgba(255,255,255,0.55)', marginTop: 2 }}>
            {tone.sub}
          </div>
        </div>
        <div style={{ display: 'flex', gap: 4 }}>
          {tone.palette.map((c, i) => (
            <div key={i} style={{
              width: 18, height: 18, borderRadius: 5,
              background: c,
              border: '1px solid rgba(255,255,255,0.08)'
            }} />
          ))}
        </div>
      </div>
      <div style={{ fontFamily: "'Noto Sans JP','Plus Jakarta Sans',sans-serif", fontSize: 11, color: 'rgba(255,255,255,0.6)', lineHeight: 1.55 }}>
        {tone.description}
      </div>
    </button>
  );
}

function Toggle({ on, onChange }) {
  return (
    <button
      onClick={() => onChange(!on)}
      style={{
        width: 36, height: 20, borderRadius: 999,
        background: on ? '#B9DD36' : 'rgba(255,255,255,0.16)',
        border: 0, padding: 0, cursor: 'pointer',
        position: 'relative', transition: 'background 0.15s ease',
        flexShrink: 0,
      }}
    >
      <div style={{
        width: 16, height: 16, borderRadius: '50%',
        background: '#fff',
        position: 'absolute',
        top: 2,
        left: on ? 18 : 2,
        transition: 'left 0.18s cubic-bezier(0.2,0.7,0.2,1)',
        boxShadow: '0 1px 2px rgba(0,0,0,0.18)',
      }} />
    </button>
  );
}

function Row({ label, sub, children }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      gap: 16, padding: '12px 0',
      borderBottom: '1px solid rgba(255,255,255,0.06)',
    }}>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontFamily: "'Noto Sans JP','Plus Jakarta Sans',sans-serif", fontWeight: 700, fontSize: 13, color: '#fff' }}>
          {label}
        </div>
        {sub && <div style={{ fontFamily: "'Noto Sans JP','Plus Jakarta Sans',sans-serif", fontSize: 11, color: 'rgba(255,255,255,0.5)', marginTop: 2, lineHeight: 1.5 }}>
          {sub}
        </div>}
      </div>
      {children}
    </div>
  );
}

function Segmented({ value, options, onChange }) {
  return (
    <div style={{
      display: 'inline-flex',
      background: 'rgba(255,255,255,0.06)',
      borderRadius: 8,
      padding: 2,
      flexShrink: 0,
    }}>
      {options.map(o => (
        <button
          key={o.id}
          onClick={() => onChange(o.id)}
          style={{
            background: value === o.id ? '#B9DD36' : 'transparent',
            color: value === o.id ? '#151B26' : 'rgba(255,255,255,0.7)',
            border: 0,
            padding: '6px 12px',
            borderRadius: 6,
            fontFamily: "'Plus Jakarta Sans',sans-serif",
            fontWeight: 700,
            fontSize: 11,
            letterSpacing: '0.04em',
            cursor: 'pointer',
            transition: 'background 0.15s ease, color 0.15s ease',
          }}
        >
          {o.label}
        </button>
      ))}
    </div>
  );
}

function TweaksPanel() {
  const [open, setOpen] = useState(false);
  const [tone, setTone] = useState(TWEAK_DEFAULTS.tone);
  const [petals, setPetals] = useState(TWEAK_DEFAULTS.petals);
  const [heroAlign, setHeroAlign] = useState(TWEAK_DEFAULTS.heroAlign);
  const listenerReady = useRef(false);

  // Apply effects
  useEffect(() => { applyTone(tone); }, [tone]);
  useEffect(() => { applyPetals(petals); }, [petals]);
  useEffect(() => { applyHeroAlign(heroAlign); }, [heroAlign]);

  // Edit-mode protocol
  useEffect(() => {
    function onMsg(e) {
      if (!e.data || typeof e.data !== 'object') return;
      if (e.data.type === '__activate_edit_mode') setOpen(true);
      if (e.data.type === '__deactivate_edit_mode') setOpen(false);
    }
    window.addEventListener('message', onMsg);
    listenerReady.current = true;
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMsg);
  }, []);

  function persist(key, value) {
    const edits = { [key]: value };
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits }, '*');
  }
  function setT(t) { setTone(t); persist('tone', t); }
  function setP(v) { setPetals(v); persist('petals', v); }
  function setHA(v) { setHeroAlign(v); persist('heroAlign', v); }
  function close() {
    setOpen(false);
    window.parent.postMessage({ type: '__edit_mode_dismissed' }, '*');
  }

  if (!open) return null;

  return (
    <div
      style={{
        position: 'fixed',
        right: 20,
        bottom: 20,
        width: 340,
        maxHeight: 'calc(100vh - 40px)',
        overflowY: 'auto',
        background: 'rgba(15,20,28,0.96)',
        backdropFilter: 'blur(20px)',
        WebkitBackdropFilter: 'blur(20px)',
        border: '1px solid rgba(255,255,255,0.08)',
        borderRadius: 16,
        boxShadow: '0 32px 64px rgba(0,0,0,0.4)',
        zIndex: 9999,
        color: '#fff',
        fontFamily: "'Plus Jakarta Sans','Noto Sans JP',sans-serif",
      }}
    >
      <div style={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        padding: '16px 18px 14px',
        borderBottom: '1px solid rgba(255,255,255,0.08)',
      }}>
        <div>
          <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 10, letterSpacing: '0.14em', color: '#B9DD36', fontWeight: 700, textTransform: 'uppercase' }}>
            Tweaks
          </div>
          <div style={{ fontFamily: "'Noto Sans JP',sans-serif", fontWeight: 900, fontSize: 16, marginTop: 2 }}>
            トーンを切り替える
          </div>
        </div>
        <button onClick={close} style={{
          background: 'rgba(255,255,255,0.06)',
          border: 0,
          width: 28, height: 28,
          borderRadius: 6,
          color: '#fff',
          fontSize: 14,
          cursor: 'pointer',
        }}>×</button>
      </div>

      <div style={{ padding: '14px 18px 6px' }}>
        <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 10, letterSpacing: '0.12em', color: 'rgba(255,255,255,0.5)', fontWeight: 700, textTransform: 'uppercase', marginBottom: 10 }}>
          全体トーン
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {TONES.map(t => (
            <ToneCard key={t.id} tone={t} active={tone === t.id} onSelect={setT} />
          ))}
        </div>
      </div>

      <div style={{ padding: '14px 18px 18px' }}>
        <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 10, letterSpacing: '0.12em', color: 'rgba(255,255,255,0.5)', fontWeight: 700, textTransform: 'uppercase', marginBottom: 6 }}>
          コンテンツ
        </div>
        <Row label="ヒーロー配置" sub="左右分割 / 中央スタック">
          <Segmented value={heroAlign} options={[
            { id: 'split', label: 'SPLIT' },
            { id: 'center', label: 'CENTER' },
          ]} onChange={setHA} />
        </Row>
        <Row label="花びら・浮遊アニメ" sub="桜の花びらとボールの動き">
          <Toggle on={petals} onChange={setP} />
        </Row>
      </div>
    </div>
  );
}

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