// Tiploy Landing — root app with Tweaks panel

const DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "green",
  "hero": "stageA",
  "heroDevice": "pax",
  "headline": "channel"
}/*EDITMODE-END*/;

function useLocalState(key, initial) {
  const [v, setV] = React.useState(() => {
    try {
      const s = localStorage.getItem(key);
      return s ? JSON.parse(s) : initial;
    } catch { return initial; }
  });
  React.useEffect(() => {
    try { localStorage.setItem(key, JSON.stringify(v)); } catch {}
  }, [key, v]);
  return [v, setV];
}

function TweaksPanel({ state, setState, visible }) {
  if (!visible) return null;
  const update = (k, val) => {
    setState(s => ({ ...s, [k]: val }));
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [k]: val } }, '*');
  };
  const row = (label, children) => (
    <div style={{ marginBottom: 14 }}>
      <p style={{ margin: '0 0 6px', fontSize: 11, color: tpTokens.muted, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.08em' }}>{label}</p>
      {children}
    </div>
  );
  const segBtn = (active, onClick, children) => (
    <button onClick={onClick} style={{
      flex: 1, padding: '7px 8px', fontFamily: 'inherit', fontSize: 12, fontWeight: 700,
      background: active ? tpTokens.ink : '#fff', color: active ? '#fff' : tpTokens.ink,
      border: `1px solid ${active ? tpTokens.ink : tpTokens.line}`, cursor: 'pointer',
      borderRadius: 6,
    }}>{children}</button>
  );
  return (
    <div style={{
      position: 'fixed', bottom: 20, right: 20, zIndex: 100,
      width: 280, background: '#fff', borderRadius: 14,
      border: `1px solid ${tpTokens.line}`, boxShadow: '0 24px 60px rgba(29,41,57,.18)',
      padding: 18, fontFamily: 'var(--font-body)',
    }}>
      <p style={{ margin: '0 0 14px', fontSize: 14, fontWeight: 800, color: tpTokens.ink, letterSpacing: '-0.01em' }}>Tweaks</p>
      {row('Brand accent',
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 6 }}>
          {Object.entries(ACCENT_THEMES).map(([k, th]) => (
            <button key={k} onClick={() => update('accent', k)} title={th.label} style={{
              aspectRatio: '1', borderRadius: 8, border: `2px solid ${state.accent === k ? tpTokens.ink : tpTokens.line}`, background: th.accent, cursor: 'pointer',
            }}/>
          ))}
        </div>
      )}
      {row('Hero device',
        <div style={{ display: 'flex', gap: 6 }}>
          {segBtn(state.heroDevice === 'pax',       () => update('heroDevice', 'pax'), 'PAX + phones')}
          {segBtn(state.heroDevice === 'dashboard', () => update('heroDevice', 'dashboard'), 'Dashboard')}
        </div>
      )}
      {row('Headline',
        <div style={{ display: 'grid', gap: 6 }}>
          {[['channel', 'Channel (ISO-first)'], ['compliance', 'Compliance-led'], ['product', 'Product-led']].map(([k, l]) =>
            <button key={k} onClick={() => update('headline', k)} style={{
              textAlign: 'left', padding: '8px 10px', fontFamily: 'inherit', fontSize: 12.5, fontWeight: 600,
              background: state.headline === k ? tpTokens.bgDeep : '#fff', color: tpTokens.ink,
              border: `1px solid ${state.headline === k ? tpTokens.lineStrong : tpTokens.line}`,
              borderRadius: 6, cursor: 'pointer',
            }}>{l}</button>
          )}
        </div>
      )}
    </div>
  );
}

function App() {
  const [state, setState] = useLocalState('tiploy_tweaks', DEFAULTS);
  const [editMode, setEditMode] = React.useState(false);

  React.useEffect(() => {
    const onMsg = (e) => {
      if (!e.data || typeof e.data !== 'object') return;
      if (e.data.type === '__activate_edit_mode') setEditMode(true);
      if (e.data.type === '__deactivate_edit_mode') setEditMode(false);
    };
    window.addEventListener('message', onMsg);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMsg);
  }, []);

  const theme = { ...ACCENT_THEMES[state.accent] || ACCENT_THEMES.green, name: state.accent };

  return (
    <TpThemeCtx.Provider value={theme}>
      <div id="top" style={{ background: tpTokens.bg, color: tpTokens.ink, fontFamily: 'var(--font-body)' }}>
        <TpTopbar/>
        <HeroStageA headlineKey={state.headline} device={state.heroDevice}/>
        <HowItWorks/>
        <TipActSection/>
        <FeatureGrid/>
        <PartnersSection/>
        <DeviceShowcase/>
        <IntegrationsBand/>
        <PricingSection/>
        <FaqSection/>
        <FinalCtaSection/>
        <TpFooter/>
        <TweaksPanel state={state} setState={setState} visible={editMode}/>
      </div>
    </TpThemeCtx.Provider>
  );
}

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