// Floating tweak panel for the cert preview.
// Drives the `tweaks` prop on <CertPreview>. All values are cqw (container query width).
// Persists to localStorage so refresh keeps your tuning.
//
// Exposes window.TweaksPanel(props) and window.useTweaks() hook factory.

(function () {
  const { useState, useEffect } = React;

  const LS_KEY = 'ugh-demo-cert-tweaks-v1';

  const SLIDER_GROUPS = [
    {
      title: 'Frame & Spacing',
      sliders: [
        ['contentInset',   'Frame → content inset',  1.5,  5,   0.1],
        ['outerBorder',    'Outer border width',     0.05, 0.6, 0.01],
        ['rowGap',         'Vertical row gap',       0.4,  4,   0.1],
        ['mainColGap',     'Main row column gap',    0.4,  4,   0.1],
        ['leftStackGap',   'Left stack gap',         0.4,  4,   0.1],
        ['bottomGap',      'Bottom row column gap',  0.4,  4,   0.1],
      ],
    },
    {
      title: 'Title & Date Bars',
      sliders: [
        ['titleSize',  'Title font size',  3,   8,    0.1],
        ['titlePadY',  'Title bar pad-y',  0.5, 4,    0.1],
        ['dateSize',   'Date font size',   0.8, 3,    0.05],
        ['datePadY',   'Date bar pad-y',   0.4, 3,    0.1],
      ],
    },
    {
      title: 'Achieved-By Tile',
      sliders: [
        ['achPadY',   'Tile pad-y',           0.5, 3,   0.1],
        ['achPadX',   'Tile pad-x',           0.5, 3,   0.1],
        ['nameSize',  'Golfer name size',     1,   4,   0.1],
        ['metaSize',  'Club/Hole/Dist size',  0.7, 2.5, 0.05],
      ],
    },
    {
      title: 'Hole Stats Tile',
      sliders: [
        ['statsPad',         'Tile pad',                  0.3, 2.5, 0.1],
        ['statsNumSize',     'Stat number size',          1,   4,   0.1],
        ['statsLabelSize',   'Stat label size',           0.4, 1.5, 0.05],
        ['statsNumOffsetY',  'Number Y offset (− = up)', -2,   2,   0.05],
      ],
    },
    {
      title: 'Witness Tile',
      sliders: [
        ['witPadY',       'Tile pad-y',  0.5, 3,   0.1],
        ['witPadX',       'Tile pad-x',  0.5, 3,   0.1],
        ['witLabelSize',  'Label size',  0.5, 2,   0.05],
        ['witNameSize',   'Name size',   0.8, 2.5, 0.05],
      ],
    },
    {
      title: 'Bottom Row & Columns',
      sliders: [
        ['bottomMinHeight', 'Bottom row min-height', 6,   18,  0.5],
        ['colLeftFr',       'Left column weight',    0.5, 2.5, 0.05],
        ['colPhotoFr',      'Photo column weight',   0.5, 2.5, 0.05],
        ['colHoleFr',       'Hole column weight',    0.5, 2.5, 0.05],
      ],
    },
  ];

  // Hook factory — call from your App() to get [tweaks, setTweaks] with LS persistence.
  function useTweaks() {
    const defaults = window.CertDefaultTweaks || {};
    const [tweaks, setTweaks] = useState(() => {
      try {
        const raw = localStorage.getItem(LS_KEY);
        if (raw) return { ...defaults, ...JSON.parse(raw) };
      } catch (e) { /* ignore */ }
      return defaults;
    });
    useEffect(() => {
      try { localStorage.setItem(LS_KEY, JSON.stringify(tweaks)); } catch (e) { /* ignore */ }
    }, [tweaks]);
    return [tweaks, setTweaks];
  }
  window.useTweaks = useTweaks;

  function TweaksPanel({ tweaks, setTweaks }) {
    const [open, setOpen] = useState(false);
    const [openGroup, setOpenGroup] = useState(0);

    const update = (key, val) =>
      setTweaks(t => ({ ...t, [key]: parseFloat(val) }));
    const resetAll = () => {
      if (confirm('Reset all tweaks to defaults?')) {
        setTweaks(window.CertDefaultTweaks || {});
      }
    };
    const copyJson = async () => {
      try {
        await navigator.clipboard.writeText(JSON.stringify(tweaks, null, 2));
        alert('Tweaks JSON copied to clipboard.');
      } catch (e) {
        alert('Copy failed — open DevTools, you can read tweaks at localStorage["' + LS_KEY + '"]');
      }
    };

    if (!open) {
      return (
        <button onClick={() => setOpen(true)} style={S.collapseBtn}
          title="Open cert tweak panel">
          ⚙ Tweaks
        </button>
      );
    }

    return (
      <div style={S.panel}>
        <div style={S.header}>
          <span style={S.headerTitle}>Cert Tweaks</span>
          <div style={{display:'flex', gap:6}}>
            <button onClick={copyJson} style={S.btn}>Copy</button>
            <button onClick={resetAll} style={S.btn}>Reset</button>
            <button onClick={() => setOpen(false)} style={S.btnClose}>×</button>
          </div>
        </div>
        <div style={S.body}>
          {SLIDER_GROUPS.map((g, gi) => {
            const isOpen = openGroup === gi;
            return (
              <div key={g.title} style={S.group}>
                <div style={S.groupHead}
                  onClick={() => setOpenGroup(isOpen ? -1 : gi)}>
                  <span>{g.title}</span>
                  <span style={S.caret}>{isOpen ? '▾' : '▸'}</span>
                </div>
                {isOpen && (
                  <div style={S.sliders}>
                    {g.sliders.map(([k, label, min, max, step]) => (
                      <div key={k} style={S.sliderRow}>
                        <div style={S.sliderLabel}>
                          <span>{label}</span>
                          <span style={S.sliderVal}>{Number(tweaks[k] ?? 0).toFixed(2)}</span>
                        </div>
                        <input type="range" min={min} max={max} step={step}
                          value={tweaks[k] ?? 0}
                          onChange={e => update(k, e.target.value)}
                          style={S.slider} />
                      </div>
                    ))}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      </div>
    );
  }

  // ── Styles ──────────────────────────────────────────────────
  const S = {
    collapseBtn: {
      position:'fixed', top:14, right:14, zIndex:9999,
      background:'#1F5240', color:'#F7EFDA',
      border:'1px solid #B8893E',
      padding:'10px 16px',
      fontFamily:'Inter, system-ui, sans-serif',
      fontSize:13, fontWeight:600, letterSpacing:0.5,
      borderRadius:4, cursor:'pointer',
      boxShadow:'0 4px 14px rgba(0,0,0,0.25)',
    },
    panel: {
      position:'fixed', top:14, right:14, zIndex:9999,
      width:320, maxHeight:'calc(100vh - 28px)',
      background:'#FAF4E4',
      border:'1px solid #B8893E',
      borderRadius:6,
      boxShadow:'0 8px 32px rgba(0,0,0,0.22)',
      fontFamily:'Inter, system-ui, sans-serif',
      color:'#1F2420',
      display:'flex', flexDirection:'column',
    },
    header: {
      padding:'10px 14px',
      borderBottom:'1px solid #B8893E55',
      display:'flex', alignItems:'center', justifyContent:'space-between',
      background:'#1F5240', color:'#F7EFDA',
      borderTopLeftRadius:5, borderTopRightRadius:5,
    },
    headerTitle: {
      fontSize:12, fontWeight:700, letterSpacing:1.5, textTransform:'uppercase',
    },
    btn: {
      background:'transparent', color:'#F7EFDA',
      border:'1px solid #B8893E', padding:'3px 9px',
      fontSize:11, fontWeight:600, letterSpacing:0.4,
      borderRadius:3, cursor:'pointer',
    },
    btnClose: {
      background:'transparent', color:'#F7EFDA',
      border:'none', padding:'2px 8px',
      fontSize:18, lineHeight:1, fontWeight:400,
      cursor:'pointer',
    },
    body: {
      overflowY:'auto', flex:1,
    },
    group: {
      borderBottom:'1px solid #B8893E22',
    },
    groupHead: {
      padding:'10px 14px',
      fontSize:11, fontWeight:600, letterSpacing:1.2, textTransform:'uppercase',
      color:'#1F5240',
      display:'flex', justifyContent:'space-between', alignItems:'center',
      cursor:'pointer', userSelect:'none',
    },
    caret: { color:'#B8893E', fontSize:14 },
    sliders: {
      padding:'4px 14px 14px',
      display:'flex', flexDirection:'column', gap:10,
    },
    sliderRow: { display:'flex', flexDirection:'column', gap:4 },
    sliderLabel: {
      display:'flex', justifyContent:'space-between', alignItems:'baseline',
      fontSize:11, color:'#4E544F',
    },
    sliderVal: {
      fontFamily:'ui-monospace, "SF Mono", Menlo, monospace',
      fontWeight:600, color:'#1F5240',
    },
    slider: { width:'100%', accentColor:'#B8893E' },
  };

  window.TweaksPanel = TweaksPanel;
})();
