// Default data with categories, products, and image URLs (quantities set to 0)
const defaultData = [
  {
    category: 'Meat',
    image: 'https://betterme.world/articles/wp-content/uploads/2023/09/shutterstock_2242365477-scaled.jpg',
    products: [
      { id: 1, name: 'Sheep (per sheep)', price: 3000.00, quantity: 0 },
      { id: 2, name: 'Cow (per cow)', price: 8500.00, quantity: 0 },
      { id: 3, name: 'Chicken (5kg)', price: 220.00, quantity: 0 },
    ],
  },
  {
    category: 'Starch',
    image: 'https://badgut.org/wp-content/uploads/Image-Content-resistant-starch.png',
    products: [
      { id: 4, name: 'Bread (per loaf)', price: 20.00, quantity: 0 },
      { id: 5, name: 'Samp (Ummgqusho) (10kg)', price: 150.00, quantity: 0 },
      { id: 6, name: 'Beans (10kg)', price: 350.00, quantity: 0 },
      { id: 7, name: 'Rice (10kg)', price: 175.00, quantity: 0 },
      { id: 8, name: 'Mealie Meal (10kg)', price: 140.00, quantity: 0 },
    ],
  },
  {
    category: 'Vegetables',
    image: 'https://www.healthshots.com/healthshots/en/uploads/2024/05/15135824/vegetables-for-breakfast-1-1.jpg',
    products: [
      { id: 9, name: 'Cabbage (8 kg)', price: 200.00, quantity: 0 },
      { id: 10, name: 'Potatoes (10kg)', price: 45.00, quantity: 0 },
      { id: 11, name: 'Onion (10kg)', price: 175.00, quantity: 0 },
      { id: 12, name: 'Carrots (10kg)', price: 85.00, quantity: 0 },
    ],
  },
  {
    category: 'Fruit',
    image: 'https://www.euroschoolindia.com/blogs/wp-content/uploads/2023/04/ways-to-eat-more-fruit.jpg',
    products: [
      { id: 13, name: 'Apples (per box)', price: 225.00, quantity: 0 },
      { id: 14, name: 'Banana (per box)', price: 150.00, quantity: 0 },
    ],
  },
  {
    category: 'Refreshments',
    image: 'https://images.unsplash.com/photo-1513553404607-9881becc302b',
    products: [
      { id: 15, name: 'Coffee (750g)', price: 120.00, quantity: 0 },
      { id: 16, name: 'Teabag (100\'s)', price: 50.00, quantity: 0 },
      { id: 17, name: 'Milk (6x1L)', price: 125.00, quantity: 0 },
      { id: 18, name: 'Sugar (10kg)', price: 260.00, quantity: 0 },
      { id: 19, name: 'Bottled Water (24 of 300ml)', price: 125.00, quantity: 0 },
      { id: 20, name: 'Juice (25 of 300ml)', price: 200.00, quantity: 0 },
      { id: 21, name: 'Carbonated Drink (6 of 2L)', price: 140.00, quantity: 0 },
    ],
  },
  {
    category: 'Implements',
    image: 'https://blog.etundra.com/wp-content/Media/2013/04/iStock_000011120058XSmall.jpg',
    products: [
      { id: 22, name: 'Tent (per item)', price: 1000.00, quantity: 0 },
      { id: 23, name: 'Tables (per item)', price: 150.00, quantity: 0 },
      { id: 24, name: 'Chairs (per item)', price: 15.00, quantity: 0 },
      { id: 25, name: 'Mobile Fridge (per item)', price: 2000.00, quantity: 0 },
      { id: 26, name: 'Mobile Toilet (per item)', price: 1000.00, quantity: 0 },
      { id: 27, name: 'Gas Stove/Burner (per item)', price: 500.00, quantity: 0 },
      { id: 28, name: 'Industrial Pots (per item)', price: 100.00, quantity: 0 },
      { id: 29, name: 'Plates (per item)', price: 10.00, quantity: 0 },
      { id: 30, name: 'Takeaway plate (75 pcs)', price: 100.00, quantity: 0 },
      { id: 31, name: 'Spoons (10 pkt)', price: 20.00, quantity: 0 },
      { id: 32, name: 'Coffee Mugs (12 pack)', price: 200.00, quantity: 0 },
      { id: 33, name: 'Funeral Program (per item)', price: 15.00, quantity: 0 },
    ],
  },
  {
    category: 'Corpse',
    image: 'https://texascriminaldefensegroup.com/wp-content/uploads/2024/03/Texas-Law-on-Abuse-of-a-Corpse.png',
    products: [
      { id: 34, name: 'Municipal Grave fees (per item)', price: 1500.00, quantity: 0 },
      { id: 35, name: 'Coffin (per item)', price: 10000.00, quantity: 0 },
      { id: 36, name: 'Coffin Stand (per day)', price: 650.00, quantity: 0 },
      { id: 37, name: 'Grave digging (per item)', price: 1200.00, quantity: 0 },
      { id: 38, name: 'Grave filling/building (per item)', price: 500.00, quantity: 0 },
      { id: 39, name: 'Tombstone (per item)', price: 3500.00, quantity: 0 },
      { id: 40, name: 'Hearse (per day)', price: 2500.00, quantity: 0 },
      { id: 41, name: 'Wreath/Flowers (per item)', price: 150.00, quantity: 0 },
      { id: 42, name: 'Suits/Dresses (per item)', price: 1000.00, quantity: 0 },
      { id: 43, name: 'Blanket (per item)', price: 250.00, quantity: 0 },
      { id: 44, name: 'Body Travel (per item)', price: 6500.00, quantity: 0 },
    ],
  },
  {
    category: 'Event Execution',
    image: 'https://eventguys.b-cdn.net/wp-content/uploads/2023/08/Event-guys.jpeg',
    products: [
      { id: 45, name: 'Slaughters (per day)', price: 100.00, quantity: 0 },
      { id: 46, name: 'Cookers (per day)', price: 2000.00, quantity: 0 },
      { id: 47, name: 'Barbecue (per day)', price: 2000.00, quantity: 0 },
      { id: 48, name: 'Bus/Taxi (per day)', price: 650.00, quantity: 0 },
      { id: 49, name: 'Videographer (per day)', price: 2500.00, quantity: 0 },
      { id: 50, name: 'Pastor (per day)', price: 3000.00, quantity: 0 },
      { id: 51, name: 'Church Quire (per day)', price: 3000.00, quantity: 0 },
    ],
  },
];

// State
let currentData = null;
let currentView = 'signup'; // Start with signup view
let currentUser = null; // Track the signed-up user

// DOM elements
let signupContainer;
let signupView;
let loginView;
let checkoutContainer;
let checkoutView;
let homepageView;
let categoriesView;
let categoryView;
let productView;
let headerTitle;
let navButtons;
let homeBtn;
let categoriesBtn;
let checkoutBtn;
let saveBtn;
let resetBtn;
let logoutBtn;
let planEventBtn;
let backBtn;
let categoryTitle;
let productList;
let totalCost;
let categoryTotal;
let checkoutTotal;
let toast;
let toastMessage;
let signupBtn;
let loginBtn;
let usernameInput;
let passwordInput;
let confirmPasswordInput;
let loginUsernameInput;
let loginPasswordInput;
let toggleLoginBtn;
let toggleSignupBtn;
let cardNumberInput;
let expiryDateInput;
let cvvInput;
let cardholderNameInput;
let finalizePurchaseBtn;
let cancelCheckoutBtn;
let cardNumberError;
let expiryDateError;
let cvvError;
let cardholderNameError;
let newProductNameInput;
let newProductPriceInput;
let newProductQuantityInput;
let addProductBtn;
let newProductError;

// Initialize when DOM is ready
function initialize() {
  // Initialize DOM elements
  signupContainer = document.getElementById('signup-container');
  signupView = document.getElementById('signup-view');
  loginView = document.getElementById('login-view');
  checkoutContainer = document.getElementById('checkout-container');
  checkoutView = document.getElementById('checkout-view');
  homepageView = document.getElementById('homepage-view');
  categoriesView = document.getElementById('categories-view');
  categoryView = document.getElementById('category-view');
  productView = document.getElementById('product-view');
  headerTitle = document.getElementById('header-title');
  navButtons = document.getElementById('nav-buttons');
  homeBtn = document.getElementById('home-btn');
  categoriesBtn = document.getElementById('categories-btn');
  checkoutBtn = document.getElementById('checkout-btn');
  saveBtn = document.getElementById('save-btn');
  resetBtn = document.getElementById('reset-btn');
  logoutBtn = document.getElementById('logout-btn');
  planEventBtn = document.getElementById('plan-event-btn');
  backBtn = document.getElementById('back-btn');
  categoryTitle = document.getElementById('category-title');
  productList = document.getElementById('product-list');
  totalCost = document.getElementById('total-cost');
  categoryTotal = document.getElementById('category-total');
  checkoutTotal = document.getElementById('checkout-total');
  toast = document.getElementById('toast');
  toastMessage = document.getElementById('toast-message');
  signupBtn = document.getElementById('signup-btn');
  loginBtn = document.getElementById('login-btn');
  usernameInput = document.getElementById('username');
  passwordInput = document.getElementById('password');
  confirmPasswordInput = document.getElementById('confirm-password');
  loginUsernameInput = document.getElementById('login-username');
  loginPasswordInput = document.getElementById('login-password');
  toggleLoginBtn = document.getElementById('toggle-login-btn');
  toggleSignupBtn = document.getElementById('toggle-signup-btn');
  cardNumberInput = document.getElementById('card-number');
  expiryDateInput = document.getElementById('expiry-date');
  cvvInput = document.getElementById('cvv');
  cardholderNameInput = document.getElementById('cardholder-name');
  finalizePurchaseBtn = document.getElementById('finalize-purchase-btn');
  cancelCheckoutBtn = document.getElementById('cancel-checkout-btn');
  cardNumberError = document.getElementById('card-number-error');
  expiryDateError = document.getElementById('expiry-date-error');
  cvvError = document.getElementById('cvv-error');
  cardholderNameError = document.getElementById('cardholder-name-error');
  newProductNameInput = document.getElementById('new-product-name');
  newProductPriceInput = document.getElementById('new-product-price');
  newProductQuantityInput = document.getElementById('new-product-quantity');
  addProductBtn = document.getElementById('add-product-btn');
  newProductError = document.getElementById('new-product-error');

  // Load data after DOM elements are initialized
  currentData = loadData();

  // Toast Notification Function
  function showToast(message, isError = false) {
    toastMessage.textContent = message;
    toast.classList.remove('hidden');
    toast.classList.add('show');
    toast.setAttribute('role', 'alert');
    if (isError) {
      toast.classList.add('error');
    } else {
      toast.classList.remove('error');
    }
    toast.focus();
    setTimeout(() => {
      toast.classList.remove('show');
      toast.classList.add('hidden');
    }, 3000);
  }

  // Save and Load Data Functions
  function saveData() {
    try {
      if (currentUser) {
        localStorage.setItem(`simpliPlanData_${currentUser}`, JSON.stringify(currentData));
        showToast('Budget saved successfully!');
      } else {
        showToast('No user signed in.', true);
      }
    } catch (e) {
      showToast('Failed to save budget: Storage limit exceeded.', true);
    }
  }

  function loadData() {
    if (currentUser) {
      const savedData = localStorage.getItem(`simpliPlanData_${currentUser}`);
      return savedData ? JSON.parse(savedData) : JSON.parse(JSON.stringify(defaultData));
    }
    return JSON.parse(JSON.stringify(defaultData));
  }

  function resetData() {
    if (currentUser) {
      localStorage.removeItem(`simpliPlanData_${currentUser}`);
    }
    currentData = JSON.parse(JSON.stringify(defaultData));
    showToast('Budget reset to default!');
    if (currentView === 'categories') {
      if (!productView.classList.contains('hidden')) {
        showProducts(categoryTitle.textContent);
      } else {
        renderCategories();
      }
    }
    updateTotal();
  }

  // Sign-Up Functionality
  function handleSignUp() {
    const username = usernameInput.value.trim();
    const password = passwordInput.value.trim();
    const confirmPassword = confirmPasswordInput.value.trim();

    // Validation
    if (!username || !password || !confirmPassword) {
      showToast('Please fill in all fields.', true);
      return;
    }
    if (username.length < 3) {
      showToast('Username must be at least 3 characters long.', true);
      return;
    }
    if (password.length < 6) {
      showToast('Password must be at least 6 characters long.', true);
      return;
    }
    if (password !== confirmPassword) {
      showToast('Passwords do not match.', true);
      return;
    }

    // Check if username exists
    const users = JSON.parse(localStorage.getItem('simpliPlanUsers') || '{}');
    if (users[username]) {
      showToast('Username already exists. Please choose another.', true);
      return;
    }

    // Save new user
    users[username] = password; // Store plain text password (not secure; use hashing in production)
    localStorage.setItem('simpliPlanUsers', JSON.stringify(users));
    localStorage.setItem('isLoggedIn', 'true');
    localStorage.setItem('currentUser', username);
    currentUser = username;
    currentData = loadData(); // Load user-specific data
    showToast('Sign-up successful! Welcome to SimpliPlan.');
    showHomepage();
  }

  // Login Functionality
  function handleLogin() {
    const username = loginUsernameInput.value.trim();
    const password = loginPasswordInput.value.trim();

    // Validation
    if (!username || !password) {
      showToast('Please fill in both username and password.', true);
      return;
    }

    // Check credentials
    const users = JSON.parse(localStorage.getItem('simpliPlanUsers') || '{}');
    if (users[username] && users[username] === password) {
      localStorage.setItem('isLoggedIn', 'true');
      localStorage.setItem('currentUser', username);
      currentUser = username;
      currentData = loadData();
      showToast('Login successful! Welcome back.');
      showHomepage();
    } else {
      showToast('Invalid username or password.', true);
    }
  }

  // Logout Functionality
  function handleLogout() {
    localStorage.removeItem('isLoggedIn');
    localStorage.removeItem('currentUser');
    currentUser = null;
    showToast('Logged out successfully!');
    showSignUp();
  }

  // Checkout Functionality
  function validateCardDetails() {
    let isValid = true;
    // Reset error states
    cardNumberInput.classList.remove('input-error');
    expiryDateInput.classList.remove('input-error');
    cvvInput.classList.remove('input-error');
    cardholderNameInput.classList.remove('input-error');
    cardNumberError.style.display = 'none';
    expiryDateError.style.display = 'none';
    cvvError.style.display = 'none';
    cardholderNameError.style.display = 'none';

    // Card Number (16 digits, numbers only)
    const cardNumber = cardNumberInput.value.replace(/\s/g, '');
    if (!/^\d{16}$/.test(cardNumber)) {
      cardNumberInput.classList.add('input-error');
      cardNumberError.style.display = 'block';
      isValid = false;
    }

    // Expiry Date (MM/YY, valid date)
    const expiry = expiryDateInput.value;
    if (!/^(0[1-9]|1[0-2])\/\d{2}$/.test(expiry)) {
      expiryDateInput.classList.add('input-error');
      expiryDateError.style.display = 'block';
      isValid = false;
    } else {
      const [month, year] = expiry.split('/');
      const currentYear = new Date().getFullYear() % 100;
      const currentMonth = new Date().getMonth() + 1;
      if (parseInt(year) < currentYear || (parseInt(year) === currentYear && parseInt(month) < currentMonth)) {
        expiryDateInput.classList.add('input-error');
        expiryDateError.textContent = 'Card has expired.';
        expiryDateError.style.display = 'block';
        isValid = false;
      }
    }

    // CVV (3 digits)
    const cvv = cvvInput.value;
    if (!/^\d{3}$/.test(cvv)) {
      cvvInput.classList.add('input-error');
      cvvError.style.display = 'block';
      isValid = false;
    }

    // Cardholder Name (non-empty)
    const cardholderName = cardholderNameInput.value.trim();
    if (!cardholderName) {
      cardholderNameInput.classList.add('input-error');
      cardholderNameError.style.display = 'block';
      isValid = false;
    }

    return isValid;
  }

  function handleFinalizePurchase() {
    const total = updateTotal();
    if (total === 0) {
      showToast('Your cart is empty. Please add items before checking out.', true);
      return;
    }

    if (validateCardDetails()) {
      // Simulate payment processing
      showToast('Purchase finalized successfully! Thank you for your order.');
      resetData(); // Clear cart after purchase
      showHomepage(); // Return to homepage
    } else {
      showToast('Please correct the errors in the form.', true);
    }
  }

  // Calculate total for a category
  function calculateCategoryTotal(category) {
    const categoryData = currentData.find((cat) => cat.category === category);
    let total = 0;
    categoryData.products.forEach((product) => {
      total += product.price * product.quantity;
    });
    return total.toFixed(2);
  }

  // Update category total in product view
  function updateCategoryTotal(category) {
    const total = calculateCategoryTotal(category);
    categoryTotal.textContent = total;
  }

  // Update overall total cost
  function updateTotal() {
    let total = 0;
    currentData.forEach((cat) => {
      cat.products.forEach((product) => {
        total += product.price * product.quantity;
      });
    });
    totalCost.textContent = total.toFixed(2);
    checkoutTotal.textContent = total.toFixed(2);
    return total;
  }

  // Render categories as tiles with images and totals
  function renderCategories() {
    categoryView.innerHTML = '';
    currentData.forEach((cat) => {
      const total = calculateCategoryTotal(cat.category);
      const tile = document.createElement('div');
      tile.className = 'category-tile';
      tile.innerHTML = `
        <img src="${cat.image}" alt="${cat.category}" loading="lazy" onerror="this.src='https://via.placeholder.com/150';">
        <div class="text-container">
          <h2>${cat.category}</h2>
          <p>Total: R${total}</p>
        </div>
      `;
      tile.addEventListener('click', () => showProducts(cat.category));
      tile.addEventListener('keydown', (e) => {
        if (e.key === 'Enter' || e.key === ' ') {
          showProducts(cat.category);
        }
      });
      tile.setAttribute('tabindex', '0');
      tile.setAttribute('role', 'button');
      categoryView.appendChild(tile);
    });
  }

  // Show products for a selected category
  function showProducts(category) {
    const categoryData = currentData.find((cat) => cat.category === category);
    categoryTitle.textContent = category;
    productView.setAttribute('data-category', category);
    productList.innerHTML = '';
    categoryData.products.forEach((product) => {
      const row = document.createElement('tr');
      row.innerHTML = `
        <td class="border p-2">${product.name}</td>
        <td class="border p-2">
          <input type="number" value="${product.price.toFixed(2)}" min="0.01" step="0.01" class="price-input" data-id="${product.id}" aria-label="Price for ${product.name}">
        </td>
        <td class="border p-2">
          <input type="number" value="${product.quantity}" min="0" step="1" class="quantity-input" data-id="${product.id}" aria-label="Quantity for ${product.name}">
        </td>
        <td class="border p-2 text-right">${(product.price * product.quantity).toFixed(2)}</td>
      `;
      productList.appendChild(row);
    });
    categoryView.classList.add('hidden');
    productView.classList.remove('hidden');
    updateCategoryTotal(category);
    updateTotal();
    // Reset new product form
    newProductNameInput.value = '';
    newProductPriceInput.value = '';
    newProductQuantityInput.value = '0';
    newProductNameInput.classList.remove('input-error');
    newProductPriceInput.classList.remove('input-error');
    newProductError.style.display = 'none';
  }

  // Handle quantity and price input changes
  productList.addEventListener('input', (e) => {
    if (e.target.classList.contains('quantity-input')) {
      const id = parseInt(e.target.dataset.id);
      const category = currentData.find((cat) => cat.category === categoryTitle.textContent);
      const product = category.products.find((p) => p.id === id);
      let value = parseInt(e.target.value) || 0;
      if (value < 0) {
        value = 0;
        e.target.value = 0;
      }
      product.quantity = value;
      const row = e.target.closest('tr');
      row.cells[3].textContent = (product.price * product.quantity).toFixed(2);
      updateCategoryTotal(categoryTitle.textContent);
      updateTotal();
      renderCategories();
    } else if (e.target.classList.contains('price-input')) {
      const id = parseInt(e.target.dataset.id);
      const category = currentData.find((cat) => cat.category === categoryTitle.textContent);
      const product = category.products.find((p) => p.id === id);
      let value = parseFloat(e.target.value) || 0;
      if (value <= 0) {
        value = product.price; // Revert to original price
        e.target.value = product.price.toFixed(2);
        showToast('Price must be greater than 0.', true);
        return;
      }
      product.price = parseFloat(value.toFixed(2));
      const row = e.target.closest('tr');
      row.cells[3].textContent = (product.price * product.quantity).toFixed(2);
      updateCategoryTotal(categoryTitle.textContent);
      updateTotal();
      renderCategories();
    }
  });

  // Handle new product addition
  function handleAddProduct() {
    const name = newProductNameInput.value.trim();
    const price = parseFloat(newProductPriceInput.value);
    const quantity = parseInt(newProductQuantityInput.value) || 0;

    // Reset error states
    newProductNameInput.classList.remove('input-error');
    newProductPriceInput.classList.remove('input-error');
    newProductError.style.display = 'none';

    // Validation
    let isValid = true;
    if (!name) {
      newProductNameInput.classList.add('input-error');
      newProductError.textContent = 'Please enter a product name.';
      newProductError.style.display = 'block';
      isValid = false;
    }
    const category = currentData.find((cat) => cat.category === categoryTitle.textContent);
    if (category.products.some((p) => p.name.toLowerCase() === name.toLowerCase())) {
      newProductNameInput.classList.add('input-error');
      newProductError.textContent = 'Product name already exists in this category.';
      newProductError.style.display = 'block';
      isValid = false;
    }
    if (isNaN(price) || price <= 0) {
      newProductPriceInput.classList.add('input-error');
      newProductError.textContent = 'Please enter a valid price greater than 0.';
      newProductError.style.display = 'block';
      isValid = false;
    }
    if (quantity < 0) {
      newProductQuantityInput.value = '0';
      newProductError.textContent = 'Quantity cannot be negative.';
      newProductError.style.display = 'block';
      isValid = false;
    }

    if (!isValid) {
      showToast('Please correct the errors in the form.', true);
      return;
    }

    // Find the highest product ID
    const maxId = Math.max(...currentData.flatMap((cat) => cat.products.map((p) => p.id)), 0);
    const newProduct = {
      id: maxId + 1,
      name,
      price: parseFloat(price.toFixed(2)),
      quantity,
    };

    // Add to currentData
    category.products.push(newProduct);
    showToast('Product added successfully!');
    showProducts(categoryTitle.textContent); // Refresh product list
  }

  // View toggling functions
  function showSignUp() {
    currentView = 'signup';
    signupContainer.classList.remove('hidden');
    signupView.classList.remove('hidden');
    loginView.classList.add('hidden');
    checkoutContainer.classList.add('hidden');
    homepageView.classList.add('hidden');
    categoriesView.classList.add('hidden');
    navButtons.classList.add('hidden');
    headerTitle.textContent = 'SimpliPlan - Sign Up';
  }

  function showLogin() {
    currentView = 'login';
    signupContainer.classList.remove('hidden');
    signupView.classList.add('hidden');
    loginView.classList.remove('hidden');
    checkoutContainer.classList.add('hidden');
    homepageView.classList.add('hidden');
    categoriesView.classList.add('hidden');
    navButtons.classList.add('hidden');
    headerTitle.textContent = 'SimpliPlan - Log In';
  }

  function showCheckout() {
    if (localStorage.getItem('isLoggedIn') !== 'true' || !currentUser) {
      showSignUp();
      return;
    }
    currentView = 'checkout';
    signupContainer.classList.add('hidden');
    checkoutContainer.classList.remove('hidden');
    homepageView.classList.add('hidden');
    categoriesView.classList.add('hidden');
    navButtons.classList.remove('hidden');
    homeBtn.classList.remove('active');
    categoriesBtn.classList.remove('active');
    checkoutBtn.classList.add('active');
    headerTitle.textContent = 'SimpliPlan - Checkout';
    updateTotal();
    // Clear form and errors
    cardNumberInput.value = '';
    expiryDateInput.value = '';
    cvvInput.value = '';
    cardholderNameInput.value = '';
    cardNumberInput.classList.remove('input-error');
    expiryDateInput.classList.remove('input-error');
    cvvInput.classList.remove('input-error');
    cardholderNameInput.classList.remove('input-error');
    cardNumberError.style.display = 'none';
    expiryDateError.style.display = 'none';
    cvvError.style.display = 'none';
    cardholderNameError.style.display = 'none';
  }

  function showHomepage() {
    if (localStorage.getItem('isLoggedIn') !== 'true' || !currentUser) {
      showSignUp();
      return;
    }
    currentView = 'homepage';
    signupContainer.classList.add('hidden');
    checkoutContainer.classList.add('hidden');
    homepageView.classList.remove('hidden');
    categoriesView.classList.add('hidden');
    navButtons.classList.remove('hidden');
    homeBtn.classList.add('active');
    categoriesBtn.classList.remove('active');
    checkoutBtn.classList.remove('active');
    headerTitle.textContent = 'SimpliPlan';
  }

  function showCategories() {
    if (localStorage.getItem('isLoggedIn') !== 'true' || !currentUser) {
      showSignUp();
      return;
    }
    currentView = 'categories';
    signupContainer.classList.add('hidden');
    checkoutContainer.classList.add('hidden');
    homepageView.classList.add('hidden');
    categoriesView.classList.remove('hidden');
    categoryView.classList.remove('hidden');
    productView.classList.add('hidden');
    navButtons.classList.remove('hidden');
    homeBtn.classList.remove('active');
    categoriesBtn.classList.add('active');
    checkoutBtn.classList.remove('active');
    headerTitle.textContent = 'SimpliPlan - Categories';
    renderCategories();
  }

  // Event listeners
  signupBtn.addEventListener('click', handleSignUp);
  loginBtn.addEventListener('click', handleLogin);
  toggleLoginBtn.addEventListener('click', showLogin);
  toggleSignupBtn.addEventListener('click', showSignUp);
  homeBtn.addEventListener('click', showHomepage);
  categoriesBtn.addEventListener('click', showCategories);
  checkoutBtn.addEventListener('click', showCheckout);
  planEventBtn.addEventListener('click', showCategories);
  saveBtn.addEventListener('click', saveData);
  resetBtn.addEventListener('click', () => {
    if (confirm('Are you sure you want to reset your budget? This cannot be undone.')) {
      resetData();
    }
  });
  logoutBtn.addEventListener('click', handleLogout);
  backBtn.addEventListener('click', () => {
    productView.classList.add('hidden');
    categoryView.classList.remove('hidden');
  });
  finalizePurchaseBtn.addEventListener('click', handleFinalizePurchase);
  cancelCheckoutBtn.addEventListener('click', showHomepage);
  addProductBtn.addEventListener('click', handleAddProduct);

  // Initial render
  currentUser = localStorage.getItem('currentUser');
  if (localStorage.getItem('isLoggedIn') === 'true' && currentUser) {
    currentData = loadData();
    showHomepage();
  } else {
    showSignUp();
  }
  updateTotal();
}

// Run initialization when DOM is ready
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', initialize);
} else {
  initialize();
}