// Vellum — per-template tweaks bundle.
// Each template <link rel="stylesheet"> + <script> includes this and calls
// VellumTweaks.mount({ ...config }) once React is available.

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

  function applyVar(name, value) {
    document.documentElement.style.setProperty(name, value);
  }

  function applyPersona(personaKey) {
    const p = (window.VELLUM_PERSONAS || {})[personaKey];
    if (!p) return;
    document.querySelectorAll("[data-bind]").forEach((el) => {
      const key = el.getAttribute("data-bind");
      if (p[key] == null) return;
      if (el.tagName === "IMG") {
        const parent = el.parentElement;
        const ph = parent && parent.querySelector(".placeholder");
        if (p.photo) {
          el.src = p.photo;
          el.style.opacity = "1";
          if (ph) ph.style.display = "none";
        } else {
          el.style.opacity = "0";
          el.removeAttribute("src");
          if (ph) ph.style.display = "";
        }
      } else if (key === "stats") {
        // Render a list of stats into existing slots
        const slots = el.querySelectorAll("[data-stat-slot]");
        p.stats.forEach((s, i) => {
          const slot = slots[i];
          if (!slot) return;
          const n = slot.querySelector("[data-stat-n]");
          const l = slot.querySelector("[data-stat-label]");
          if (n) n.textContent = s.n;
          if (l) l.textContent = s.label;
        });
      } else {
        el.textContent = p[key];
      }
    });
    // Persona-conditional blocks: show those whose data-persona matches; hide others
    document.querySelectorAll("[data-persona-only]").forEach((el) => {
      const allowed = el.getAttribute("data-persona-only").split(",");
      el.style.display = allowed.includes(personaKey) ? "" : "none";
    });
    document.body.setAttribute("data-active-persona", personaKey);
  }

  function applyFontPair(pairKey, pairs) {
    const pair = pairs.find((p) => p.key === pairKey) || pairs[0];
    applyVar("--font-display", pair.display);
    applyVar("--font-body", pair.body);
    if (pair.mono) applyVar("--font-mono", pair.mono);
  }

  function applyMode(mode) {
    document.documentElement.setAttribute("data-mode", mode);
  }

  function applyAccent(value) {
    applyVar("--accent", value);
  }

  function applyLabels(show) {
    document.documentElement.setAttribute(
      "data-show-labels",
      show ? "true" : "false"
    );
  }

  window.VellumTweaks = {
    apply({ defaults, fontPairs }) {
      applyAccent(defaults.accent);
      applyFontPair(defaults.fontPair, fontPairs);
      applyMode(defaults.mode);
      applyLabels(defaults.showLabels);
      // Persona applied after DOM ready to be safe
      if (document.readyState === "loading") {
        document.addEventListener("DOMContentLoaded", () =>
          applyPersona(defaults.persona)
        );
      } else {
        applyPersona(defaults.persona);
      }
    },

    Panel({ defaults, accents, fontPairs, modes = ["light", "dark"], onClose, title = "Tweaks" }) {
      const t = useTweaks(defaults);

      useEffect(() => applyAccent(t.accent), [t.accent]);
      useEffect(() => applyFontPair(t.fontPair, fontPairs), [t.fontPair]);
      useEffect(() => applyMode(t.mode), [t.mode]);
      useEffect(() => applyLabels(t.showLabels), [t.showLabels]);
      useEffect(() => applyPersona(t.persona), [t.persona]);

      const personaOptions = Object.keys(window.VELLUM_PERSONAS || {}).map(
        (k) => ({
          value: k,
          label: window.VELLUM_PERSONAS[k].name
        })
      );

      return (
        <TweaksPanel onClose={onClose} title={title}>
          <TweakSection title="Identity">
            <TweakSelect
              label="Persona"
              value={t.persona}
              options={personaOptions}
              onChange={(v) => t.set("persona", v)}
            />
            <TweakToggle
              label="Industry labels"
              value={t.showLabels}
              onChange={(v) => t.set("showLabels", v)}
            />
          </TweakSection>

          <TweakSection title="Surface">
            {modes.length > 1 && (
              <TweakRadio
                label="Mode"
                value={t.mode}
                options={modes.map((m) => ({ value: m, label: m }))}
                onChange={(v) => t.set("mode", v)}
              />
            )}
            <TweakColor
              label="Accent"
              value={t.accent}
              options={accents}
              onChange={(v) => t.set("accent", v)}
            />
          </TweakSection>

          <TweakSection title="Typography">
            <TweakSelect
              label="Type pairing"
              value={t.fontPair}
              options={fontPairs.map((p) => ({
                value: p.key,
                label: p.label
              }))}
              onChange={(v) => t.set("fontPair", v)}
            />
          </TweakSection>
        </TweaksPanel>
      );
    },

    mount(config) {
      // Pre-apply defaults so first paint is right
      this.apply(config);
      const container = document.createElement("div");
      document.body.appendChild(container);
      const root = ReactDOM.createRoot(container);

      function render() {
        root.render(
          <window.VellumTweaks.Panel
            {...config}
            onClose={() => {
              root.render(null);
              window.parent.postMessage(
                { type: "__edit_mode_dismissed" },
                "*"
              );
              listen();
            }}
          />
        );
      }

      function listen() {
        const handler = (e) => {
          if (!e.data || typeof e.data !== "object") return;
          if (e.data.type === "__activate_edit_mode") {
            window.removeEventListener("message", handler);
            render();
          }
        };
        window.addEventListener("message", handler);
        window.parent.postMessage({ type: "__edit_mode_available" }, "*");
      }

      listen();
    }
  };
})();
