// Theorema Tech — Tweaks app
// Exposes: theme variant, logo variant, accent override.

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "paper",
  "logo": "wordmark",
  "type": "geist",
  "showQED": true
}/*EDITMODE-END*/;

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

  // Apply on every change
  React.useEffect(() => {
    document.documentElement.setAttribute("data-theme", t.theme);
    localStorage.setItem("tt_theme", t.theme);
  }, [t.theme]);

  React.useEffect(() => {
    document.documentElement.setAttribute("data-logo", t.logo);
    localStorage.setItem("tt_logo", t.logo);
    document.querySelectorAll("[data-logo-variant]").forEach((el) => {
      el.style.display = el.dataset.logoVariant === t.logo ? "" : "none";
    });
  }, [t.logo]);

  React.useEffect(() => {
    const root = document.documentElement;
    if (t.type === "geist") {
      root.style.setProperty("--font-sans", `"Geist", "Helvetica Neue", Helvetica, Arial, sans-serif`);
    } else if (t.type === "space") {
      root.style.setProperty("--font-sans", `"Space Grotesk", "Helvetica Neue", sans-serif`);
      ensureFont("https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&display=swap");
    } else if (t.type === "neueh") {
      root.style.setProperty("--font-sans", `"Inter Tight", "Helvetica Neue", sans-serif`);
      ensureFont("https://fonts.googleapis.com/css2?family=Inter+Tight:wght@400;500;600;700&display=swap");
    }
  }, [t.type]);

  React.useEffect(() => {
    document.querySelectorAll(".qed").forEach((el) => {
      el.style.display = t.showQED ? "" : "none";
    });
  }, [t.showQED]);

  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Тема" />
      <TweakRadio
        label="Палітра"
        value={t.theme}
        options={["paper", "terminal", "blueprint"]}
        onChange={(v) => setTweak("theme", v)}
      />

      <TweakSection label="Логотип" />
      <TweakRadio
        label="Варіант"
        value={t.logo}
        options={["wordmark", "monogram", "infinity"]}
        onChange={(v) => setTweak("logo", v)}
      />

      <TweakSection label="Типографіка" />
      <TweakRadio
        label="Шрифт"
        value={t.type}
        options={["geist", "space", "neueh"]}
        onChange={(v) => setTweak("type", v)}
      />

      <TweakSection label="Деталі" />
      <TweakToggle
        label="Знаки ∎ (Q.E.D.)"
        value={t.showQED}
        onChange={(v) => setTweak("showQED", v)}
      />
    </TweaksPanel>
  );
}

function ensureFont(url) {
  if (document.querySelector(`link[href="${url}"]`)) return;
  const l = document.createElement("link");
  l.rel = "stylesheet";
  l.href = url;
  document.head.appendChild(l);
}

// Mount
const __twkRoot = document.createElement("div");
document.body.appendChild(__twkRoot);
ReactDOM.createRoot(__twkRoot).render(<TweaksApp />);
