// tweaks-app.jsx — EPDS exploration tweaks
// Drives CSS levers from the panel:
//   • --font-label + --label-tracking  (secondary / technical label face)
//   • body[data-btnhover]               (primary-button hover effect)
//   • body[data-herobg] + --hero-img    (photographic hero backdrop)
// Also restores the panel after it's dismissed via an in-page launcher.

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "labelFont": "grotesk",
  "btnHover": "brighten",
  "cardHover": "glow",
  "heroBg": "pipes",
  "heroStyle": "glass",
  "heroLayout": "full"
}/*EDITMODE-END*/;

// Each label face pairs a font stack with the tracking that makes it read as a
// label — mono wants it tight, a humanist sans wants it wide.
const LABEL_FONTS = {
  mono:      { stack: '"IBM Plex Mono","SFMono-Regular",ui-monospace,monospace', track: '.04em' },
  grotesk:   { stack: '"Space Grotesk",ui-sans-serif,system-ui,sans-serif',      track: '.02em' },
  condensed: { stack: '"Saira Semi Condensed",ui-sans-serif,system-ui,sans-serif', track: '.05em' },
  archivo:   { stack: '"Archivo",ui-sans-serif,system-ui,sans-serif',            track: '.045em' },
  unified:   { stack: '"IBM Plex Sans","Helvetica Neue",Arial,sans-serif',       track: '.10em' },
};

// Hero backdrops — free, hotlinkable Unsplash CDN photos (industrial / ATEX).
const IMG = (id) => `https://images.unsplash.com/photo-${id}?auto=format&fit=crop&w=1920&q=70`;
const HERO_BGS = {
  none:  null,
  night: IMG('1566221857770-508d35ee6220'),  // refinery lit up at night
  smoke: IMG('1516937941344-00b4e0337589'),   // stacks & smoke, moody sky
  pipes: IMG('1678984239420-43cdc183bce6'),   // close pipework detail
};

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  // Track the panel's actual presence in the DOM (it renders nothing when
  // closed) so we can offer an always-available launcher to (re)open it.
  const [panelPresent, setPanelPresent] = React.useState(false);
  React.useEffect(() => {
    const id = setInterval(() => {
      setPanelPresent(!!document.querySelector('.twk-panel'));
    }, 200);
    return () => clearInterval(id);
  }, []);
  // Re-open the panel from inside the page (the ✕ only dismisses it). Works on
  // any device and on a fresh load — no prior activation required.
  const revive = () => window.postMessage({ type: '__activate_edit_mode' }, '*');

  React.useEffect(() => {
    const f = LABEL_FONTS[t.labelFont] || LABEL_FONTS.grotesk;
    const root = document.documentElement;
    root.style.setProperty('--font-label', f.stack);
    root.style.setProperty('--label-tracking', f.track);
  }, [t.labelFont]);

  React.useEffect(() => {
    const valid = ['glow', 'lift', 'brighten', 'sheen'];
    document.body.setAttribute('data-btnhover', valid.includes(t.btnHover) ? t.btnHover : 'brighten');
  }, [t.btnHover]);

  React.useEffect(() => {
    const valid = ['lift', 'subtle', 'glow', 'edge'];
    document.body.setAttribute('data-cardhover', valid.includes(t.cardHover) ? t.cardHover : 'lift');
  }, [t.cardHover]);

  React.useEffect(() => {
    const key = HERO_BGS[t.heroBg] !== undefined ? t.heroBg : 'night';
    document.body.setAttribute('data-herobg', key);
    const url = HERO_BGS[key];
    const img = document.querySelector('.hero-bg');
    if (img && url) img.src = url;
    // expose the URL for the "side" layout, which paints it into the visual column
    document.body.style.setProperty('--hero-img', url ? `url("${url}")` : 'none');
    const phImg = document.querySelector('.ph-photo');
    if (phImg && url) phImg.src = url;
  }, [t.heroBg]);

  React.useEffect(() => {
    const valid = ['full', 'side'];
    document.body.setAttribute('data-herolayout', valid.includes(t.heroLayout) ? t.heroLayout : 'full');
  }, [t.heroLayout]);

  React.useEffect(() => {
    const valid = ['glass', 'panel', 'scrim', 'minimal'];
    document.body.setAttribute('data-herostyle', valid.includes(t.heroStyle) ? t.heroStyle : 'glass');
  }, [t.heroStyle]);

  return (
    <>
      {!panelPresent && (
        <button type="button" onClick={revive} aria-label="Show tweaks"
          style={{
            position: 'fixed', right: 'calc(16px + env(safe-area-inset-right))',
            bottom: 'calc(16px + env(safe-area-inset-bottom))', zIndex: 2147483645,
            display: 'inline-flex', alignItems: 'center', gap: 7,
            height: 36, padding: '0 14px 0 12px', borderRadius: 999, cursor: 'pointer',
            border: '.5px solid rgba(255,255,255,.7)', color: '#fff',
            background: 'rgba(15,42,67,.94)', WebkitBackdropFilter: 'blur(8px)', backdropFilter: 'blur(8px)',
            font: '500 12.5px/1 "Space Grotesk",ui-sans-serif,system-ui,sans-serif',
            letterSpacing: '.02em', boxShadow: '0 6px 20px rgba(0,0,0,.32)',
          }}>
          <svg width="13" height="13" viewBox="0 0 16 16" fill="none" aria-hidden="true">
            <path d="M2 4h8M2 12h5M13 6V2M13 14v-4M3 8h11M9 6v4" stroke="#E98F17"
                  strokeWidth="1.5" strokeLinecap="round" />
          </svg>
          Tweaks
        </button>
      )}

      <TweaksPanel title="Tweaks">
        <TweakSection label="Hero background" />
        <TweakSelect
          label="Image"
          value={t.heroBg}
          options={[
            { value: 'night', label: 'Plant at night' },
            { value: 'smoke', label: 'Stacks & smoke' },
            { value: 'pipes', label: 'Pipework (close)' },
            { value: 'none',  label: 'None (white hero)' },
          ]}
          onChange={(v) => setTweak('heroBg', v)}
        />
        <TweakSelect
          label="Image layout"
          value={t.heroLayout}
          options={[
            { value: 'full', label: 'Full-bleed background' },
            { value: 'side', label: 'Right side only' },
          ]}
          onChange={(v) => setTweak('heroLayout', v)}
        />
        <TweakSelect
          label="Text treatment"
          value={t.heroStyle}
          options={[
            { value: 'glass',   label: 'Glass card (frosted)' },
            { value: 'panel',   label: 'Solid navy panel' },
            { value: 'scrim',   label: 'Light scrim' },
            { value: 'minimal', label: 'Photo-forward' },
          ]}
          onChange={(v) => setTweak('heroStyle', v)}
        />

        <TweakSection label="Secondary / label type" />
        <TweakSelect
          label="Label font"
          value={t.labelFont}
          options={[
            { value: 'grotesk',   label: 'Space Grotesk' },
            { value: 'condensed', label: 'Saira Semi Condensed' },
            { value: 'archivo',   label: 'Archivo' },
            { value: 'unified',   label: 'IBM Plex Sans (unified)' },
            { value: 'mono',      label: 'IBM Plex Mono (original)' },
          ]}
          onChange={(v) => setTweak('labelFont', v)}
        />

        <TweakSection label="Primary button hover" />
        <TweakSelect
          label="Hover effect"
          value={t.btnHover}
          options={[
            { value: 'glow',     label: 'Glow (orange halo)' },
            { value: 'lift',     label: 'Lift + shadow' },
            { value: 'brighten', label: 'Brighten' },
            { value: 'sheen',    label: 'Text shadow' },
          ]}
          onChange={(v) => setTweak('btnHover', v)}
        />

        <TweakSection label="Card hover" />
        <TweakSelect
          label="Promote on hover"
          value={t.cardHover}
          options={[
            { value: 'lift',   label: 'Lift + shadow' },
            { value: 'glow',   label: 'Accent glow ring' },
            { value: 'edge',   label: 'Accent top edge' },
            { value: 'subtle', label: 'Subtle (border only)' },
          ]}
          onChange={(v) => setTweak('cardHover', v)}
        />
      </TweaksPanel>
    </>
  );
}

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