// ===== WebAnchor — Tweaks: switchable site colour patterns =====
// A palette re-themes the WHOLE page: the gradient (hero text + buttons),
// links, eyebrows, highlights, focus rings, ambient page glow — plus the
// accent dots. Each palette is a complementary triad [primary, secondary, tertiary].

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": ["#1C6CE0", "#0EA5B5", "#2BC2B8"],
  "theme": "Abyss",
  "rays": true,
  "floor": true,
  "bubbles": true,
  "particles": false,
  "fish": true
}/*EDITMODE-END*/;

const PALETTES = [
  ['#1C6CE0', '#0EA5B5', '#2BC2B8'], // Deep Sea  — ocean blue · teal · aqua
  ['#0E7FD0', '#13B0A6', '#41D1C4'], // Lagoon    — bright tropical shallows
  ['#3A5BD9', '#1C8FB8', '#2FB6D9'], // High Tide — indigo · marine · sky
  ['#1668C9', '#13A89A', '#F0795A'], // Coral Reef— blue · teal · coral pop
];

const STORE_KEY = 'wa-palette-v2';

// ── tiny hex helpers ──────────────────────────────────────────────
function hexToRgb(h) {
  const n = parseInt(h.replace('#', ''), 16);
  return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}
function rgbToHex(r, g, b) {
  const c = (x) => Math.max(0, Math.min(255, Math.round(x))).toString(16).padStart(2, '0');
  return '#' + c(r) + c(g) + c(b);
}
function darken(hex, amt) {
  const [r, g, b] = hexToRgb(hex);
  return rgbToHex(r * (1 - amt), g * (1 - amt), b * (1 - amt));
}
function mix(h1, h2, t) {
  const a = hexToRgb(h1), b = hexToRgb(h2);
  return rgbToHex(a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t);
}

function readStored() {
  try {
    const v = JSON.parse(localStorage.getItem(STORE_KEY));
    if (Array.isArray(v) && v.length === 3 && v.every((c) => typeof c === 'string')) return v;
  } catch (e) {}
  return null;
}

function applyPalette(p) {
  const [a, b, c] = p;
  const s = document.documentElement.style;
  // accent dots
  s.setProperty('--dot-1', a); s.setProperty('--dot-2', b); s.setProperty('--dot-3', c);
  // core accents (drive links, eyebrows, highlights, tints, ambient glow)
  s.setProperty('--violet', a);
  s.setProperty('--cyan', b);
  s.setProperty('--pink', c);
  s.setProperty('--violet-deep', darken(a, 0.18));
  s.setProperty('--cyan-deep', darken(b, 0.18));
  s.setProperty('--pink-deep', darken(c, 0.18));
  // gradients (hero headline + primary buttons + CTA borders)
  s.setProperty('--grad', `linear-gradient(135deg, ${a} 0%, ${mix(a, b, 0.55)} 100%)`);
  s.setProperty('--grad-tri', `linear-gradient(120deg, ${a} 0%, ${c} 52%, ${b} 100%)`);
  s.setProperty('--grad-soft', `linear-gradient(135deg, ${a}, ${mix(a, b, 0.5)})`);
}

// Apply immediately on load — before React mounts — preferring the locally
// saved choice so it survives a host-triggered reload.
const INITIAL = readStored() || TWEAK_DEFAULTS.palette;
applyPalette(INITIAL);

// ── Ocean theme + water effects ──────────────────────────────────
// theme: 'Reef' (light) | 'Abyss' (dark, the live default). Effects are
// independent toggles. Reef styling is kept in ocean.css but there is no
// in-page switch to it — Abyss is the shipped look.
const FX_KEY = 'wa-ocean-v2';
const FX_KEYS = ['rays', 'floor', 'bubbles', 'particles'];
function readFx() {
  try {
    const v = JSON.parse(localStorage.getItem(FX_KEY));
    if (v && typeof v === 'object') return v;
  } catch (e) {}
  return null;
}
function applyOcean(s) {
  const r = document.documentElement;
  r.setAttribute('data-theme', (s.theme || 'Abyss').toLowerCase());
  FX_KEYS.forEach((k) => r.classList.toggle('fx-' + k, !!s[k]));
}
const INITIAL_FX = { ...TWEAK_DEFAULTS, ...(readFx() || {}) };
applyOcean(INITIAL_FX);

function TweaksApp() {
  const [t, setTweak] = useTweaks({
    ...TWEAK_DEFAULTS, palette: INITIAL,
    theme: INITIAL_FX.theme,
    rays: INITIAL_FX.rays,
    floor: INITIAL_FX.floor, bubbles: INITIAL_FX.bubbles, particles: INITIAL_FX.particles,
  });
  React.useEffect(() => {
    const p = t.palette || TWEAK_DEFAULTS.palette;
    applyPalette(p);
    try { localStorage.setItem(STORE_KEY, JSON.stringify(p)); } catch (e) {}
  }, [t.palette]);

  React.useEffect(() => {
    const s = { theme: t.theme, rays: t.rays, floor: t.floor, bubbles: t.bubbles, particles: t.particles };
    applyOcean(s);
    try { localStorage.setItem(FX_KEY, JSON.stringify(s)); } catch (e) {}
  }, [t.theme, t.rays, t.floor, t.bubbles, t.particles]);

  React.useEffect(() => {
    const on = t.fish !== false;
    try { localStorage.setItem('wa-fish', on ? '1' : '0'); } catch (e) {}
    window.dispatchEvent(new CustomEvent('wa-fish-toggle', { detail: { on } }));
  }, [t.fish]);

  return (
    <TweaksPanel>
      <TweakSection label="Water effects" />
      <TweakToggle label="Light shafts" value={t.rays !== false} onChange={(v) => setTweak('rays', v)} />
      <TweakToggle label="Seabed glow" value={t.floor !== false} onChange={(v) => setTweak('floor', v)} />
      <TweakToggle label="Rising bubbles" value={t.bubbles !== false} onChange={(v) => setTweak('bubbles', v)} />
      <TweakToggle label="Drifting current" value={!!t.particles} onChange={(v) => setTweak('particles', v)} />
      <TweakSection label="Site colour" />
      <TweakColor
        label="Colour pattern"
        value={t.palette}
        options={PALETTES}
        onChange={(v) => setTweak('palette', v)}
      />
      <TweakSection label="Background" />
      <TweakToggle
        label="Swimming fish"
        value={t.fish !== false}
        onChange={(v) => setTweak('fish', v)}
      />
    </TweaksPanel>
  );
}

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