function showMessage(message, type = 'success') {
    // Remove any existing message
    const existingMessage = document.querySelector('.admin-message');
    if (existingMessage) {
        existingMessage.remove();
    }

    // Create new message element
    const messageDiv = document.createElement('div');
    messageDiv.className = `admin-message ${type}`;
    messageDiv.textContent = message;

    // Insert at the top of the main content
    const mainContent = document.querySelector('main') || document.body;
    mainContent.insertBefore(messageDiv, mainContent.firstChild);

    // Auto-hide after 3 seconds
    setTimeout(() => {
        if (messageDiv.parentNode) {
            messageDiv.remove();
        }
    }, 3000);
}

function showUserModal() {
    const modal = document.getElementById('user-modal');
    modal.classList.remove('hidden');
    const form = modal.querySelector('form');
    form.action.value = 'create_user';
    form.id.value = '';
    form.name.value = '';
    form.email.value = '';
    form.password.required = true;
    form.password.value = '';
    form.role.value = 'Normal User';
    form.status.value = 'Active';
    document.getElementById('user-modal-title').textContent = 'Create User';
}

function editUser(button) {
    const row = button.closest('tr');
    const user = JSON.parse(row.dataset.user);
    const modal = document.getElementById('user-modal');
    modal.classList.remove('hidden');
    const form = modal.querySelector('form');
    form.action.value = 'update_user';
    form.id.value = user.id;
    form.name.value = user.name;
    form.email.value = user.email;
    form.password.required = false;
    form.password.value = '';
    form.role.value = user.role;
    form.status.value = user.status;
    document.getElementById('user-modal-title').textContent = 'Edit User';
}

function deleteUser(id) {
    if (!confirm('Remove this user?')) return;
    deleteItem('delete_user', id, 'admin/users.php');
}

function showProjectModal() {
    const modal = document.getElementById('project-modal');
    modal.classList.remove('hidden');
    const form = modal.querySelector('form');
    form.action.value = 'create_project';
    form.id.value = '';
    form.reset();
    form.seo_title.value = '';
    form.seo_description.value = '';
    document.getElementById('project-modal-title').textContent = 'Add Portfolio Project';
}

function editProject(button) {
    const row = button.closest('tr');
    const project = JSON.parse(row.dataset.project);
    const modal = document.getElementById('project-modal');
    modal.classList.remove('hidden');
    const form = modal.querySelector('form');
    form.action.value = 'update_project';
    form.id.value = project.id;
    form.title.value = project.title;
    form.description.value = project.description;
    form.seo_title.value = project.seo_title || '';
    form.seo_description.value = project.seo_description || '';
    form.technologies.value = project.technologies;
    form.outcome.value = project.outcome;
    form.status.value = project.status;
    document.getElementById('project-modal-title').textContent = 'Edit Portfolio Project';
}

function showBlogModal() {
    const modal = document.getElementById('blog-modal');
    modal.classList.remove('hidden');
    const form = modal.querySelector('form');
    form.action.value = 'create_blog';
    form.id.value = '';
    form.reset();
    form.seo_title.value = '';
    form.seo_description.value = '';
    document.getElementById('blog-modal-title').textContent = 'Create Blog Post';
}

function editBlog(button) {
    const row = button.closest('tr');
    const post = JSON.parse(row.dataset.post);
    const modal = document.getElementById('blog-modal');
    modal.classList.remove('hidden');
    const form = modal.querySelector('form');
    form.action.value = 'update_blog';
    form.id.value = post.id;
    form.title.value = post.title;
    form.content.value = post.content;
    form.seo_title.value = post.seo_title || '';
    form.seo_description.value = post.seo_description || '';
    form.category_id.value = post.category_id;
    form.status.value = post.status;
    document.getElementById('blog-modal-title').textContent = 'Edit Blog Post';
}

function showBlogCategoryModal() {
    const modal = document.getElementById('blog-category-modal');
    modal.classList.remove('hidden');
    const form = modal.querySelector('form');
    form.action.value = 'create_blog_category';
    form.id.value = '';
    form.reset();
    form.seo_title.value = '';
    form.seo_description.value = '';
    document.getElementById('blog-category-modal-title').textContent = 'Add Blog Category';
}

function editBlogCategory(button) {
    const row = button.closest('tr');
    const category = JSON.parse(row.dataset.category);
    const modal = document.getElementById('blog-category-modal');
    modal.classList.remove('hidden');
    const form = modal.querySelector('form');
    form.action.value = 'update_blog_category';
    form.id.value = category.id;
    form.name.value = category.name;
    form.seo_title.value = category.seo_title || '';
    form.seo_description.value = category.seo_description || '';
    form.status.value = category.status;
    document.getElementById('blog-category-modal-title').textContent = 'Edit Blog Category';
}

function showPortfolioCategoryModal() {
    const modal = document.getElementById('portfolio-category-modal');
    modal.classList.remove('hidden');
    const form = modal.querySelector('form');
    form.action.value = 'create_portfolio_category';
    form.id.value = '';
    form.reset();
    form.seo_title.value = '';
    form.seo_description.value = '';
    document.getElementById('portfolio-category-modal-title').textContent = 'Add Portfolio Category';
}

function editPortfolioCategory(button) {
    const row = button.closest('tr');
    const category = JSON.parse(row.dataset.category);
    const modal = document.getElementById('portfolio-category-modal');
    modal.classList.remove('hidden');
    const form = modal.querySelector('form');
    form.action.value = 'update_portfolio_category';
    form.id.value = category.id;
    form.name.value = category.name;
    form.seo_title.value = category.seo_title || '';
    form.seo_description.value = category.seo_description || '';
    form.status.value = category.status;
    document.getElementById('portfolio-category-modal-title').textContent = 'Edit Portfolio Category';
}

function showCategoryModal() {
    const modal = document.getElementById('category-modal');
    modal.classList.remove('hidden');
    const form = modal.querySelector('form');
    form.action.value = 'create_shop_category';
    form.id.value = '';
    form.reset();
    form.seo_title.value = '';
    form.seo_description.value = '';
    document.getElementById('category-modal-title').textContent = 'Add Category';
}

function editCategory(button) {
    const row = button.closest('tr');
    const category = JSON.parse(row.dataset.category);
    const modal = document.getElementById('category-modal');
    modal.classList.remove('hidden');
    const form = modal.querySelector('form');
    form.action.value = 'update_shop_category';
    form.id.value = category.id;
    form.name.value = category.name;
    form.seo_title.value = category.seo_title || '';
    form.seo_description.value = category.seo_description || '';
    form.status.value = category.status;
    document.getElementById('category-modal-title').textContent = 'Edit Category';
}

function showServiceModal() {
    const modal = document.getElementById('service-modal');
    if (!modal) return;
    modal.classList.remove('hidden');
    const form = modal.querySelector('form');
    form.action.value = 'create_service';
    form.id.value = '';
    form.title.value = '';
    form.description.value = '';
    form.sort_order.value = '0';
    form.status.value = 'Published';
    form.thumbnail.value = '';
    const note = document.getElementById('service-thumbnail-note');
    if (note) {
        note.textContent = 'Upload a thumbnail to show in service cards.';
    }
    document.getElementById('service-modal-title').textContent = 'Add Service';
}

function editService(button) {
    const card = button.closest('.service-item');
    const service = JSON.parse(card.dataset.service);
    const modal = document.getElementById('service-modal');
    if (!modal) return;
    modal.classList.remove('hidden');
    const form = modal.querySelector('form');
    form.action.value = 'update_service';
    form.id.value = service.id;
    form.title.value = service.title;
    form.description.value = service.description || '';
    form.sort_order.value = service.sort_order || '0';
    form.status.value = service.status;
    form.thumbnail.value = '';
    const note = document.getElementById('service-thumbnail-note');
    if (note) {
        note.textContent = service.thumbnail ? 'Existing thumbnail available. Upload a new file to replace it.' : 'Upload a square image (150x150px recommended)';
    }
    document.getElementById('service-modal-title').textContent = 'Edit Service';
}

function showProductModal() {
    const modal = document.getElementById('product-modal');
    modal.classList.remove('hidden');
    const form = modal.querySelector('form');
    form.action.value = 'create_shop_product';
    form.id.value = '';
    form.name.value = '';
    form.description.value = '';
    form.specs.value = '';
    form.seo_title.value = '';
    form.seo_description.value = '';
    form.category_id.selectedIndex = 0;
    form.price.value = '';
    form.featured.checked = false;
    form.status.value = 'Published';
    document.getElementById('product-modal-title').textContent = 'Add Product';
}

function editProduct(button) {
    const row = button.closest('tr');
    const product = JSON.parse(row.dataset.product);
    const modal = document.getElementById('product-modal');
    modal.classList.remove('hidden');
    const form = modal.querySelector('form');
    form.action.value = 'update_shop_product';
    form.id.value = product.id;
    form.name.value = product.name;
    form.description.value = product.description;
    form.specs.value = product.specs || '';
    form.seo_title.value = product.seo_title || '';
    form.seo_description.value = product.seo_description || '';
    form.category_id.value = product.category_id;
    form.price.value = product.price;
    form.featured.checked = !!product.featured;
    form.status.value = product.status;
    document.getElementById('product-modal-title').textContent = 'Edit Product';
}

function toggleNewTeamMember() {
    const modal = document.getElementById('team-member-modal');
    if (!modal) return;
    modal.classList.toggle('hidden');
}

function toggleNewServiceRow() {
    const form = document.getElementById('new-service-row');
    if (!form) return;
    form.style.display = form.style.display === 'none' || form.style.display === '' ? 'grid' : 'none';
}

function deleteService(id) {
    if (!confirm('Delete this service?')) return;
    deleteItem('delete_service', id, 'admin/settings.php');
}

function deleteItem(action, id, redirect) {
    const csrfElement = document.querySelector('input[name=csrf]') || document.getElementById('csrf-token');
    const csrf = csrfElement ? csrfElement.value : '';
    const actionsUrl = new URL('actions.php', window.location.href).href;
    const normalizedRedirect = redirect.startsWith('admin/') ? redirect : 'admin/' + redirect;
    fetch(actionsUrl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest' },
        body: `csrf=${encodeURIComponent(csrf)}&action=${encodeURIComponent(action)}&id=${encodeURIComponent(id)}`
    }).then(r => r.json()).then(result => {
        if (result.status === 'success') {
            // Show success message and redirect
            showMessage(result.message || 'Item deleted successfully.', 'success');
            setTimeout(() => {
                window.location.href = normalizedRedirect;
            }, 1000);
        } else {
            showMessage(result.message || 'Action failed.', 'error');
        }
    }).catch(() => showMessage('Network error.', 'error'));
}

function updateStatus(action, id, value) {
    const csrfElement = document.querySelector('input[name=csrf]') || document.getElementById('csrf-token');
    const csrf = csrfElement ? csrfElement.value : '';
    fetch('actions.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest' },
        body: `csrf=${encodeURIComponent(csrf)}&action=${encodeURIComponent(action)}&id=${encodeURIComponent(id)}&status=${encodeURIComponent(value)}`
    }).then(r => r.json()).then(result => {
        if (result.status !== 'success') {
            alert(result.message || 'Unable to update status.');
        }
    });
}

window.addEventListener('submit', function (event) {
    const form = event.target;
    if (!form.classList.contains('ajax-form')) return;
    event.preventDefault();

    const data = new FormData(form);
    const actionsUrl = new URL('actions.php', window.location.href).href;
    fetch(actionsUrl, {
        method: 'POST',
        headers: { 'X-Requested-With': 'XMLHttpRequest' },
        body: data
    }).then(r => r.json()).then(result => {
        if (result.status === 'success') {
            showMessage(result.message || 'Saved successfully.', 'success');
            // Close modal if it's a modal form
            const modal = form.closest('.modal');
            if (modal) {
                modal.classList.add('hidden');
            }
            // Reload page after a short delay to show the message
            setTimeout(() => {
                window.location.reload();
            }, 1500);
        } else {
            showMessage(result.message || 'Unable to save.', 'error');
        }
    }).catch(() => showMessage('Network error. Please check your connection and try again.', 'error'));
});
