/* ============================================================
   SNAFU T CO — Tweaks
   Applies design direction to <html> + mirrors to localStorage
   so the choice follows the user across pages.
   ============================================================ */

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "olive",
  "headfont": "classic",
  "texture": true,
  "copy": "edgy",
  "brand": "SNAFU T CO"
}/*EDITMODE-END*/;

const LS_KEY = 'cf_tweaks_v2';

// merge persisted values so the direction carries across page loads
function initialTweaks() {
  let saved = {};
  try { saved = JSON.parse(localStorage.getItem(LS_KEY) || '{}'); } catch (e) {}
  return { ...TWEAK_DEFAULTS, ...saved };
}

const THEME_SWATCHES = {
  olive:    ['#58622f', '#c7b27a', '#15170f'],
  coyote:   ['#6e4b2c', '#8a9a5b', '#17140f'],
  blackops: ['#1d1d1f', '#ff6a1a', '#0d0d0e'],
  patriot:  ['#1b2748', '#c0263a', '#eef1f7'],
};
const THEME_LABELS = {
  olive: 'Olive Drab', coyote: 'Coyote / Ranger',
  blackops: 'Black Ops', patriot: 'Patriotic',
};

function applyTweaks(t) {
  const r = document.documentElement;
  r.setAttribute('data-theme', t.theme);
  r.setAttribute('data-headfont', t.headfont);
  r.setAttribute('data-texture', t.texture ? 'on' : 'off');
  r.setAttribute('data-copy', t.copy);
  document.querySelectorAll('[data-brand]').forEach((el) => {
    // keep any <small> tagline child intact
    const small = el.querySelector('small');
    el.childNodes.forEach((n) => { if (n.nodeType === 3) n.textContent = ''; });
    el.insertBefore(document.createTextNode(t.brand), el.firstChild);
    if (small) el.appendChild(small);
  });
  try { localStorage.setItem(LS_KEY, JSON.stringify(t)); } catch (e) {}
}

// apply immediately on load (before React mounts) to avoid a flash
applyTweaks(initialTweaks());

function ThemePicker({ value, onChange }) {
  return (
    <div className="twk-row">
      <div className="twk-lbl"><span>Color direction</span>
        <span className="twk-val">{THEME_LABELS[value]}</span></div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 7, marginTop: 2 }}>
        {Object.keys(THEME_SWATCHES).map((k) => {
          const sw = THEME_SWATCHES[k];
          const on = k === value;
          return (
            <button key={k} type="button" onClick={() => onChange(k)}
              style={{
                display: 'flex', alignItems: 'center', gap: 7, padding: '6px 8px',
                border: on ? '1.5px solid rgba(0,0,0,.85)' : '.5px solid rgba(0,0,0,.14)',
                borderRadius: 7, background: 'rgba(255,255,255,.55)', cursor: 'pointer',
                font: '500 10.5px/1 ui-sans-serif,system-ui,sans-serif', color: '#29261b',
                textAlign: 'left',
              }}>
              <span style={{ display: 'flex', borderRadius: 4, overflow: 'hidden', boxShadow: '0 0 0 .5px rgba(0,0,0,.15)', flexShrink: 0 }}>
                {sw.map((c, i) => <i key={i} style={{ width: 11, height: 18, background: c }} />)}
              </span>
              <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{THEME_LABELS[k]}</span>
            </button>
          );
        })}
      </div>
    </div>
  );
}

function App() {
  const [t, setTweak] = useTweaks(initialTweaks());
  React.useEffect(() => { applyTweaks(t); }, [t]);
  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Direction" />
      <ThemePicker value={t.theme} onChange={(v) => setTweak('theme', v)} />
      <TweakSection label="Style" />
      <TweakRadio label="Headline type" value={t.headfont}
        options={[{ value: 'classic', label: 'Classic' }, { value: 'stencil', label: 'Stencil' }]}
        onChange={(v) => setTweak('headfont', v)} />
      <TweakToggle label="Worn texture" value={t.texture}
        onChange={(v) => setTweak('texture', v)} />
      <TweakSection label="Voice" />
      <TweakRadio label="Copy tone" value={t.copy}
        options={[{ value: 'edgy', label: 'Edgy' }, { value: 'tame', label: 'Clean' }]}
        onChange={(v) => setTweak('copy', v)} />
      <TweakText label="Brand name" value={t.brand}
        onChange={(v) => setTweak('brand', v)} />
    </TweaksPanel>
  );
}

(function mount() {
  let root = document.getElementById('tweak-root');
  if (!root) { root = document.createElement('div'); root.id = 'tweak-root'; document.body.appendChild(root); }
  ReactDOM.createRoot(root).render(<App />);
})();
