document.addEventListener("DOMContentLoaded", () => {
// Check if the user is an admin
const isAdmin = localStorage.getItem("adminAuth") === "true";
if (!isAdmin) return;
let isPreviewMode = false;
// Create Admin Toolbar
const toolbar = document.createElement("div");
toolbar.id = "admin-cms-toolbar";
renderToolbar();
document.body.appendChild(toolbar);
function renderToolbar() {
toolbar.innerHTML = `
${isPreviewMode ? 'visibility_off' : 'edit'}
${isPreviewMode ? 'Preview Mode' : 'Edit Mode'}
${!isPreviewMode ? '
' : ''}
forum
`;
// Re-bind listeners after re-render
document.getElementById("cms-preview-btn").addEventListener("click", togglePreview);
const saveBtn = document.getElementById("cms-save-btn");
if(saveBtn) saveBtn.addEventListener("click", savePageContent);
document.getElementById("cms-logout-btn").addEventListener("click", logoutAdmin);
}
function togglePreview() {
isPreviewMode = !isPreviewMode;
applyMode();
renderToolbar();
}
function logoutAdmin() {
localStorage.removeItem("adminAuth");
window.location.reload();
}
// Track original page path to key localstorage edits
const pageId = window.location.pathname.split("/").pop() || "index.html";
// Load any previously saved content using the backend API
fetch(`api/cms.php?page=${pageId}`)
.then(res => res.json())
.then(data => {
if (data.status === 'success' && data.content) {
// Found saved DB content for this page.
// In a real sophisticated SPA, we'd map nodes dynamically.
// For this HTML setup, replacing the innerHTML inside a controlled block is standard.
// document.body.innerHTML = data.content;
console.log("DB Content mapped for page:", pageId);
}
}).catch(err => console.log("CMS Load fallback to local DOM defaults.", err));
const textSelectors = "h1, h2, h3, h4, h5, h6, p, span.font-serif, p.text-on-surface-variant, div.font-serif";
const imgSelectors = "img:not(.no-edit)";
function applyMode() {
const textElements = document.querySelectorAll(textSelectors);
const imgElements = document.querySelectorAll(imgSelectors);
// Inject Admin Link if not present
injectAdminLink();
textElements.forEach(el => {
if(el.closest('nav') || el.closest('footer') || el.closest('.material-symbols-outlined') || el.closest('button') || el.id === "admin-cms-toolbar") return;
if (isPreviewMode) {
el.removeAttribute("contenteditable");
el.style.border = "none";
el.style.cursor = "inherit";
} else {
el.setAttribute("contenteditable", "true");
el.style.outline = "none";
setupTextListeners(el);
}
});
imgElements.forEach(img => {
if(img.closest('nav') || img.closest('.material-symbols-outlined') || img.closest('button')) return;
if (isPreviewMode) {
img.style.cursor = "inherit";
img.style.border = "none";
} else {
img.style.cursor = "pointer";
setupImgListeners(img);
}
});
}
function injectAdminLink() {
// Find existing nav bar
const navContainer = document.querySelector('nav .hidden, header nav.hidden, div.md\\:flex');
if (navContainer && !document.getElementById('cms-admin-link')) {
const adminLink = document.createElement("a");
adminLink.id = "cms-admin-link";
adminLink.href = "login.html";
adminLink.className = "text-[#884b41] font-bold font-sans tracking-wide uppercase text-xs hover:opacity-70 transition-all duration-300";
adminLink.style.marginLeft = "20px";
adminLink.textContent = "Admin Dash";
navContainer.appendChild(adminLink);
}
}
function setupTextListeners(el) {
el.addEventListener("mouseenter", () => {
if (isPreviewMode) return;
el.style.border = "1px dashed #884b41";
el.style.cursor = "text";
});
el.addEventListener("mouseleave", () => {
el.style.border = "none";
});
}
function setupImgListeners(img) {
img.addEventListener("mouseenter", () => {
if (isPreviewMode) return;
img.style.opacity = "0.8";
img.style.border = "2px dashed #884b41";
});
img.addEventListener("mouseleave", () => {
img.style.opacity = "1";
img.style.border = "none";
});
img.addEventListener("click", handleImgClick);
}
function handleImgClick(e) {
if (isPreviewMode) return;
const img = e.target;
e.preventDefault();
const currentSrc = img.src;
const newUrl = prompt("Enter new Image URL:", currentSrc);
if (newUrl && newUrl !== currentSrc) {
img.src = newUrl;
img.style.transform = "scale(0.98)";
setTimeout(() => img.style.transform = "scale(1)", 150);
}
}
function savePageContent() {
// Clean up before saving
isPreviewMode = true;
applyMode();
// Remove toolbar from the HTML to be saved
const toolbarRef = document.getElementById("admin-cms-toolbar");
if(toolbarRef) toolbarRef.remove();
// Save via unified backend API
const pageContent = document.body.innerHTML;
fetch('api/cms.php', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ page: pageId, content: pageContent })
})
.then(res => res.json())
.then(data => {
if(data.status === 'success') {
alert("Page edits saved successfully to Database!");
window.location.reload();
} else {
alert("Failed to save: " + data.message);
}
})
.catch(err => {
console.error(err);
alert("Database Error: Make sure api/config.php has correct credentials.");
});
}
// Initial Apply
applyMode();
});