/* global React, ReactDOM, Navigation, Hero, Schedule, Commitments, Building, Visit, Legacy, Footer */
const { useState, useEffect } = React;

function TweaksPanel({ state, onChange, onClose }) {
  const Row = ({ label, children }) => (
    <div style={{ padding: '14px 16px', borderBottom: '1px solid #2a2a2a' }}>
      <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.14em', color: '#9a9a9a', marginBottom: 10, fontFamily: 'JetBrains Mono, monospace' }}>{label}</div>
      {children}
    </div>
  );
  const Seg = ({ value, options }) => (
    <div style={{ display: 'flex', gap: 4, background: '#1a1a1a', padding: 3, borderRadius: 8 }}>
      {options.map(o => (
        <button key={o.v} onClick={() => onChange({ ...state, [value]: o.v })}
          style={{
            flex: 1, padding: '8px 10px', fontSize: 11, borderRadius: 6,
            background: state[value] === o.v ? '#f4eee0' : 'transparent',
            color: state[value] === o.v ? '#0e0d0b' : '#c9bfaa',
            fontWeight: state[value] === o.v ? 600 : 400,
            transition: 'all 0.1s'
          }}>{o.l}</button>
      ))}
    </div>
  );
  const Toggle = ({ value }) => (
    <button onClick={() => onChange({ ...state, [value]: !state[value] })}
      style={{
        width: 42, height: 24, borderRadius: 999, position: 'relative',
        background: state[value] ? '#e89444' : '#333', transition: 'all 0.15s'
      }}>
      <span style={{
        position: 'absolute', top: 3, left: state[value] ? 21 : 3,
        width: 18, height: 18, borderRadius: 999, background: '#fff', transition: 'all 0.15s'
      }}/>
    </button>
  );

  return (
    <div style={{
      position: 'fixed', bottom: 24, right: 24, width: 320, zIndex: 100,
      background: '#0e0d0b', color: '#f4eee0', borderRadius: 14,
      boxShadow: '0 20px 60px rgba(0,0,0,0.4)', border: '1px solid #2a2a2a',
      fontFamily: 'Inter, sans-serif'
    }}>
      <div style={{ padding: '16px 18px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderBottom: '1px solid #2a2a2a' }}>
        <span style={{ fontSize: 13, fontWeight: 600, letterSpacing: '-0.01em' }}>Tweaks</span>
        <button onClick={onClose} style={{ fontSize: 18, color: '#9a9a9a', padding: 0, lineHeight: 1 }}>×</button>
      </div>
      <Row label="Direction">
        <Seg value="direction" options={[
          { v: 'reverent', l: 'Reverent' },
          { v: 'sacred',   l: 'Sacred' },
          { v: 'editorial',l: 'Editorial' },
        ]}/>
        <div style={{ fontSize: 11, color: '#7a7062', marginTop: 8, lineHeight: 1.4 }}>
          {state.direction === 'reverent'  && 'Warm cream, saffron, calm gravitas.'}
          {state.direction === 'sacred'    && 'Deep night palette, ember saffron.'}
          {state.direction === 'editorial' && 'Stark white, print-first hierarchy.'}
        </div>
      </Row>
      <Row label="Hero Treatment">
        <Seg value="heroStyle" options={[
          { v: 'lockup', l: 'Type lockup' },
          { v: 'quote',  l: 'Quote' },
          { v: 'photo',  l: 'Photo' },
        ]}/>
      </Row>
      <Row label="Gurmukhi first">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <span style={{ fontSize: 12, color: '#c9bfaa' }}>Show Gurmukhi on hukamnama</span>
          <Toggle value="showGurmukhi"/>
        </div>
      </Row>
      <Row label="Font pairing">
        <div style={{ fontSize: 12, color: '#c9bfaa', fontFamily: 'Fraunces, serif', fontSize: 16 }}>
          Fraunces <span style={{ color: '#7a7062' }}>&</span> <span style={{ fontFamily: 'Inter, sans-serif', fontSize: 12 }}>Inter</span>
        </div>
      </Row>
    </div>
  );
}

function App() {
  const [tweaks, setTweaks] = useState(() => {
    try { return JSON.parse(localStorage.getItem('gsid-tweaks')) || window.TWEAK_DEFAULTS; }
    catch { return window.TWEAK_DEFAULTS; }
  });
  const [tweaksOpen, setTweaksOpen] = useState(false);

  useEffect(() => {
    document.body.setAttribute('data-theme', tweaks.direction);
    localStorage.setItem('gsid-tweaks', JSON.stringify(tweaks));
  }, [tweaks]);

  // The TweaksPanel is driven by an outer edit harness via postMessage.
  // Only accept messages from the same origin (when iframed inside another
  // tab on gsid.co.uk) or, in the local-dev case, when there is no parent
  // origin at all. Reject anything else — otherwise any page that frames
  // the site can toggle the panel and read tweak state.
  useEffect(() => {
    const ALLOWED_ORIGINS = [
      window.location.origin,
      'https://www.gsid.co.uk',
      'https://gsid.co.uk',
    ];
    const isTrustedOrigin = (origin) =>
      origin === '' || // top-level / no parent
      ALLOWED_ORIGINS.includes(origin);

    const handler = (e) => {
      if (!isTrustedOrigin(e.origin)) return;
      if (!e.data || typeof e.data !== 'object') return;
      if (e.data.type === '__activate_edit_mode')   setTweaksOpen(true);
      if (e.data.type === '__deactivate_edit_mode') setTweaksOpen(false);
    };
    window.addEventListener('message', handler);
    // Announce ourselves only to the immediate parent's origin (or self if
    // top-level). `targetOrigin: '*'` would leak the announcement to any
    // intercepting frame.
    const parentOrigin = window.location.origin;
    try { window.parent.postMessage({ type: '__edit_mode_available' }, parentOrigin); } catch {}
    return () => window.removeEventListener('message', handler);
  }, []);

  const onChange = (next) => {
    setTweaks(next);
    try { window.parent.postMessage({ type: '__edit_mode_set_keys', edits: next }, window.location.origin); } catch {}
  };

  return (
    <div>
      <Navigation/>
      <Hero heroStyle={tweaks.heroStyle}/>
      <Legacy/>
      <Schedule/>
      <Commitments/>
      <Building/>
      <Visit/>
      <Footer/>
      {tweaksOpen && <TweaksPanel state={tweaks} onChange={onChange} onClose={() => setTweaksOpen(false)}/>}
    </div>
  );
}

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