/* global React, ReactDOM, TweaksPanel, TweakSection, TweakSlider, TweakToggle, TweakRadio, useTweaks */

const TWEAK_DEFAULTS = (() => {
  try {
    const raw = document.getElementById("tweak-defaults").textContent;
    const json = raw.replace(/\/\*EDITMODE-(BEGIN|END)\*\//g, "");
    return JSON.parse(json);
  } catch (e) {
    return { palette: "cream", speed: 1, grain: true, boldness: "high" };
  }
})();
const LEGACY_TWEAKS_ENABLED = new URLSearchParams(window.location.search).get("legacyTweaks") === "1";

function isPreviewMode() {
  const params = new URLSearchParams(window.location.search);
  return Boolean(
    params.get("previewKey") &&
      (params.has("editorPreview") || params.has("payloadEditor") || params.has("payloadPreview")),
  );
}

function acceptsPreviewMessage(data) {
  if (data?.type !== "lpv-theme-content-preview") return false;
  if (!isPreviewMode()) return false;
  const previewKey = new URLSearchParams(window.location.search).get("previewKey");
  return typeof data.previewKey === "string" && data.previewKey === previewKey;
}

const PALETTES = {
  cream:  { bg: "#f4efe6", ink: "#1a1a1a", accent: "#c8472e", paper: "#ebe4d6", muted: "#8a8275" },
  noir:   { bg: "#0e0e0e", ink: "#f4efe6", accent: "#e8c547", paper: "#1a1a1a", muted: "#8a8275" },
  vert:   { bg: "#e8e2d5", ink: "#1f2e26", accent: "#8b3a3a", paper: "#d4cdb8", muted: "#7a7565" },
  brique: { bg: "#fafafa", ink: "#0a0a0a", accent: "#ff4500", paper: "#f0eee9", muted: "#9b9b9b" },
};

function applyPalette(name) {
  const p = PALETTES[name] || PALETTES.cream;
  const r = document.documentElement.style;
  r.setProperty("--bg", p.bg);
  r.setProperty("--ink", p.ink);
  r.setProperty("--accent", p.accent);
  r.setProperty("--paper", p.paper);
  r.setProperty("--muted", p.muted);
}

function applySpeed(s) {
  document.documentElement.style.setProperty("--speed", String(s));
  // Re-trigger hero animation? Keep simple — speed affects future runs.
  // Marquee duration:
  document.querySelectorAll(".marquee__track").forEach(el => {
    el.style.animationDuration = (32 / s) + "s";
  });
}

function applyGrain(on) {
  document.body.classList.toggle("no-grain", !on);
}

function applyBoldness(level) {
  const r = document.documentElement.style;
  if (level === "low") r.setProperty("--bold-mult", "0.78");
  else if (level === "medium") r.setProperty("--bold-mult", "0.92");
  else r.setProperty("--bold-mult", "1");
}

function applyFontPair(font) {
  if (!font || typeof font !== "object") return;
  const r = document.documentElement.style;
  Object.entries(font).forEach(([name, value]) => {
    if (typeof value === "string" && name.startsWith("--")) {
      r.setProperty(name, value);
    }
  });
}

// Inject support styles
const supportStyle = document.createElement("style");
supportStyle.textContent = `
  body.no-grain::before { opacity: 0 !important; }
  .hero__title { font-size: calc(clamp(64px, 14vw, 220px) * var(--bold-mult, 1)) !important; }
  .section__title { font-size: calc(clamp(48px, 8vw, 130px) * var(--bold-mult, 1)) !important; }
  .newsletter__title { font-size: calc(clamp(48px, 9vw, 150px) * var(--bold-mult, 1)) !important; }
  .footer__giant { font-size: calc(clamp(100px, 22vw, 360px) * var(--bold-mult, 1)) !important; }
`;
if (LEGACY_TWEAKS_ENABLED) document.head.appendChild(supportStyle);

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

  React.useEffect(() => { if (LEGACY_TWEAKS_ENABLED) applyPalette(t.palette); }, [t.palette]);
  React.useEffect(() => { if (LEGACY_TWEAKS_ENABLED) applySpeed(t.speed); }, [t.speed]);
  React.useEffect(() => { if (LEGACY_TWEAKS_ENABLED) applyGrain(t.grain); }, [t.grain]);
  React.useEffect(() => { if (LEGACY_TWEAKS_ENABLED) applyBoldness(t.boldness); }, [t.boldness]);

  React.useEffect(() => {
    function applyDesign(design) {
      if (typeof design?.palette === "string") {
        setTweak("palette", design.palette);
        applyPalette(design.palette);
      }
      applyFontPair(design?.font);
    }

    function onMessage(event) {
      if (!acceptsPreviewMessage(event?.data)) return;
      applyDesign(event.data.design || event.data.content?._design);
    }

    function onDesign(event) {
      applyDesign(event.detail);
    }

    window.addEventListener("message", onMessage);
    window.addEventListener("lpv-theme-design-preview", onDesign);
    return () => {
      window.removeEventListener("message", onMessage);
      window.removeEventListener("lpv-theme-design-preview", onDesign);
    };
  }, [setTweak]);

  return (
    LEGACY_TWEAKS_ENABLED ? <TweaksPanel title="Tweaks">
      <TweakSection label="Palette" />
      <TweakRadio
        label="Couleur"
        value={t.palette}
        onChange={v => setTweak("palette", v)}
        options={[
          { value: "cream",  label: "Crème" },
          { value: "noir",   label: "Noir" },
          { value: "vert",   label: "Forêt" },
          { value: "brique", label: "Brique" },
        ]}
      />

      <TweakSection label="Typographie" />
      <TweakRadio
        label="Échelle"
        value={t.boldness}
        onChange={v => setTweak("boldness", v)}
        options={[
          { value: "low",    label: "Sobre" },
          { value: "medium", label: "Moyen" },
          { value: "high",   label: "Bold" },
        ]}
      />

      <TweakSection label="Mouvement" />
      <TweakSlider
        label="Vitesse"
        value={t.speed}
        onChange={v => setTweak("speed", v)}
        min={0.4} max={2} step={0.1}
        unit="×"
      />

      <TweakSection label="Texture" />
      <TweakToggle
        label="Grain papier"
        value={t.grain}
        onChange={v => setTweak("grain", v)}
      />
    </TweaksPanel> : null
  );
}

ReactDOM.createRoot(document.getElementById("tweaks-root")).render(<TweaksApp />);
