document.addEventListener("DOMContentLoaded", () => { const form = document.getElementById("aibui-settings-form"); const toast = document.getElementById("aibui-settings-toast"); function showToast(message, isError = false) { if (!toast) return; toast.textContent = message; toast.style.display = "block"; toast.style.background = isError ? "#b00020" : "#23272f"; toast.style.color = "#fff"; toast.style.padding = "10px 14px"; toast.style.borderRadius = "8px"; setTimeout(() => { toast.style.display = "none"; }, 4000); } async function getJwtToken() { const res = await fetch(aiBuilderVars.ajaxurl, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: `action=aibui_get_token&nonce=${aiBuilderVars.nonce}`, }); const data = await res.json(); if (data.success && data.data.token) return data.data.token; throw new Error("Missing token"); } async function loadSettings() { try { const jwt = await getJwtToken(); const res = await fetch(window.config.apiUrl + "/settings", { method: "GET", headers: { Authorization: `Bearer ${jwt}` }, }); if (!res.ok) throw new Error("Failed to load settings"); const data = await res.json(); // Expect shape: { primaryColor, secondaryColor, siteName, siteDescription, nativeFont } const { primaryColor = "#2f80ed", secondaryColor = "#00b87c", siteName = "", siteDescription = "", // nativeFont = "system-ui", } = data || {}; document.getElementById("primaryColor").value = primaryColor; console.log("a"); document.getElementById("secondaryColor").value = secondaryColor; console.log("b"); document.getElementById("siteName").value = siteName; console.log("d"); document.getElementById("siteDescription").value = siteDescription; console.log("e"); // document.getElementById("nativeFont").value = nativeFont; console.log("f"); } catch (e) { // Silent load error; user can still save console.warn("AI Builder Settings: load failed", e); } } form?.addEventListener("submit", async (e) => { e.preventDefault(); try { const jwt = await getJwtToken(); const body = { primaryColor: document.getElementById("primaryColor").value, secondaryColor: document.getElementById("secondaryColor").value, siteName: document.getElementById("siteName").value.trim(), siteDescription: document .getElementById("siteDescription") .value.trim(), // nativeFont: document.getElementById("nativeFont").value, }; const res = await fetch(window.config.apiUrl + "/settings", { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${jwt}`, }, body: JSON.stringify(body), }); if (!res.ok) throw new Error("Save failed"); showToast("Settings saved"); } catch (err) { showToast("Error saving settings", true); } }); loadSettings(); });