// Main Application
class BadeCanteenApp {
  constructor() {
    this.currentView = 'menu';
    this.currentCategory = 'all';
    this.menuItems = [];
    this.orders = [];
    this.init();
  }

  async init() {
    this.setupEventListeners();
    await this.loadMenu();
    this.renderMenu();

    // Check URL parameters for view
    const params = new URLSearchParams(window.location.search);
    const view = params.get('view');
    if (view) {
      this.switchView(view);
    }
  }

  setupEventListeners() {
    // Mobile bottom navigation
    const navItems = document.querySelectorAll('.mobile-nav-item');
    navItems.forEach(item => {
      item.addEventListener('click', (e) => {
        e.preventDefault();
        const view = e.currentTarget.dataset.view;
        this.switchView(view);
      });
    });

    // Mobile category pills
    const categoryPills = document.querySelectorAll('.mobile-category-pill');
    categoryPills.forEach(pill => {
      pill.addEventListener('click', (e) => {
        const category = e.currentTarget.dataset.category;
        this.filterByCategory(category);
      });
    });
  }

  switchView(view) {
    this.currentView = view;

    // Update nav tabs
    document.querySelectorAll('.nav-tab').forEach(tab => {
      if (tab.dataset.view === view) {
        tab.classList.add('active');
      } else {
        tab.classList.remove('active');
      }
    });

    // Hide all views
    document.querySelectorAll('.view-content').forEach(v => {
      v.classList.add('hidden');
    });

    // Show selected view
    const viewElement = document.getElementById(`${view}View`);
    if (viewElement) {
      viewElement.classList.remove('hidden');
    }

    // Load data for the view
    if (view === 'orders') {
      this.loadOrders();
    } else if (view === 'profile') {
      this.loadProfile();
    }

    // Update URL
    const url = new URL(window.location);
    url.searchParams.set('view', view);
    window.history.pushState({}, '', url);
  }

  filterByCategory(category) {
    this.currentCategory = category;

    // Update category buttons
    document.querySelectorAll('.category-btn').forEach(btn => {
      if (btn.dataset.category === category) {
        btn.classList.add('active');
      } else {
        btn.classList.remove('active');
      }
    });

    this.renderMenu();
  }

  async loadMenu() {
    try {
      const response = await fetch('/api/menu?available=true');
      const data = await response.json();

      if (data.success) {
        this.menuItems = data.items;
      }
    } catch (error) {
      console.error('Error loading menu:', error);
      this.showToast('Failed to load menu', 'error');
    }
  }

  renderMenu() {
    const grid = document.getElementById('foodGrid');
    if (!grid) return;

    let filteredItems = this.menuItems;

    // Filter by category
    if (this.currentCategory !== 'all') {
      filteredItems = this.menuItems.filter(item => item.category === this.currentCategory);
    }

    // Filter by time-based availability (optional enhancement)
    filteredItems = this.filterByTimeOfDay(filteredItems);

    if (filteredItems.length === 0) {
      grid.innerHTML = `
        <div style="grid-column: 1 / -1; text-align: center; padding: 3rem;">
          <div style="font-size: 4rem; margin-bottom: 1rem;">🍽️</div>
          <h3>No items available</h3>
          <p style="color: var(--gray-500);">Check back later or try a different category</p>
        </div>
      `;
      return;
    }

    grid.innerHTML = filteredItems.map(item => this.createFoodCard(item)).join('');
  }

  filterByTimeOfDay(items) {
    const now = new Date();
    const hour = now.getHours();

    // Define time windows
    const isBreakfastTime = hour >= 6 && hour < 11;
    const isLunchTime = hour >= 11 && hour < 16;
    const isSnacksTime = hour >= 16 && hour < 21;

    // For demo purposes, show all items
    // In production, you'd filter based on time
    return items;

    /* Uncomment for time-based filtering:
    return items.filter(item => {
      if (item.category === 'breakfast' && !isBreakfastTime) return false;
      if (item.category === 'lunch' && !isLunchTime) return false;
      if (item.category === 'snacks' && !isSnacksTime) return false;
      return true;
    });
    */
  }

  createFoodCard(item) {
    const isAvailable = item.availability === 'available';
    const badgeClass = `badge-${item.availability.replace('_', '-')}`;
    const badgeText = item.availability.replace('_', ' ').toUpperCase();

    return `
      <div class="food-card" data-id="${item.id}">
        <img src="${item.image_url || '/images/placeholder.png'}" 
             alt="${item.name}" 
             class="food-card-image"
             onerror="this.src='/images/placeholder.png'">
        <span class="food-card-badge ${badgeClass}">${badgeText}</span>
        
        <div class="food-card-content">
          <div class="food-card-header">
            <h3 class="food-card-title">${item.name}</h3>
            <span class="food-card-price">₹${item.price}</span>
          </div>
          
          ${item.description ? `<p class="food-card-description">${item.description}</p>` : ''}
          
          <div class="food-card-meta">
            <span>⏱️ ${item.prep_time || 15} min</span>
            <span>🏷️ ${this.formatCategory(item.category)}</span>
          </div>
          
          <div class="food-card-footer">
            ${isAvailable ? `
              <button class="btn btn-primary btn-block" onclick="app.addToCart('${item.id}')">
                Add to Cart
              </button>
            ` : `
              <button class="btn btn-secondary btn-block" disabled>
                Not Available
              </button>
            `}
          </div>
        </div>
      </div>
    `;
  }

  formatCategory(category) {
    const categories = {
      breakfast: 'Breakfast',
      lunch: 'Lunch',
      snacks: 'Snacks',
      beverages: 'Beverages'
    };
    return categories[category] || category;
  }

  addToCart(itemId) {
    const item = this.menuItems.find(i => i.id === itemId);
    if (item && window.cart) {
      window.cart.addItem(item);
    }
  }

  async loadOrders() {
    const container = document.getElementById('ordersList');
    if (!container) return;

    container.innerHTML = '<div class="text-center"><div class="spinner"></div></div>';

    try {
      const response = await fetch('/api/orders/my-orders', {
        headers: window.auth.getAuthHeaders()
      });

      const data = await response.json();

      if (data.success) {
        this.orders = data.orders;
        this.renderOrders();
      } else {
        throw new Error(data.error);
      }
    } catch (error) {
      console.error('Error loading orders:', error);
      container.innerHTML = `
        <div class="text-center" style="padding: 2rem;">
          <p style="color: var(--error);">Failed to load orders</p>
        </div>
      `;
    }
  }

  renderOrders() {
    const container = document.getElementById('ordersList');
    if (!container) return;

    if (this.orders.length === 0) {
      container.innerHTML = `
        <div class="text-center" style="padding: 3rem;">
          <div style="font-size: 4rem; margin-bottom: 1rem;">📦</div>
          <h3>No orders yet</h3>
          <p style="color: var(--gray-500);">Start ordering from the menu!</p>
          <button class="btn btn-primary mt-lg" onclick="app.switchView('menu')">Browse Menu</button>
        </div>
      `;
      return;
    }

    container.innerHTML = this.orders.map(order => this.createOrderCard(order)).join('');
  }

  createOrderCard(order) {
    const statusColors = {
      ordered: 'var(--info)',
      preparing: 'var(--warning)',
      ready: 'var(--success)',
      completed: 'var(--gray-500)',
      cancelled: 'var(--error)'
    };

    const statusIcons = {
      ordered: '📝',
      preparing: '👨‍🍳',
      ready: '✅',
      completed: '✔️',
      cancelled: '❌'
    };

    const itemCount = order.order_items?.length || 0;
    const firstItems = order.order_items?.slice(0, 2) || [];

    return `
      <div class="order-card" style="background: var(--white); border-radius: var(--radius-xl); padding: var(--spacing-lg); margin-bottom: var(--spacing-lg); box-shadow: var(--shadow-md); cursor: pointer;" onclick="app.viewOrderDetails('${order.id}')">
        <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: var(--spacing-md);">
          <div>
            <h3 style="margin: 0 0 0.5rem 0;">${order.order_number}</h3>
            <p style="color: var(--gray-500); font-size: 0.875rem; margin: 0;">
              ${new Date(order.created_at).toLocaleString()}
            </p>
          </div>
          <div style="text-align: right;">
            <div style="display: inline-block; padding: 0.5rem 1rem; border-radius: var(--radius-full); background: ${statusColors[order.status]}20; color: ${statusColors[order.status]}; font-weight: 700; font-size: 0.875rem; margin-bottom: 0.5rem;">
              ${statusIcons[order.status]} ${order.status.toUpperCase()}
            </div>
            <p style="font-size: 1.25rem; font-weight: 700; color: var(--primary-orange); margin: 0;">
              ₹${parseFloat(order.total).toFixed(2)}
            </p>
          </div>
        </div>
        
        <div style="border-top: 1px solid var(--gray-200); padding-top: var(--spacing-md);">
          <p style="color: var(--gray-600); font-size: 0.875rem; margin: 0;">
            ${firstItems.map(item => `${item.food_items?.name} × ${item.quantity}`).join(', ')}
            ${itemCount > 2 ? ` and ${itemCount - 2} more` : ''}
          </p>
          ${order.estimated_time ? `
            <p style="color: var(--gray-500); font-size: 0.875rem; margin: 0.5rem 0 0 0;">
              ⏱️ Estimated time: ${order.estimated_time} minutes
            </p>
          ` : ''}
        </div>
      </div>
    `;
  }

  async viewOrderDetails(orderId) {
    try {
      const response = await fetch(`/api/orders/${orderId}`, {
        headers: window.auth.getAuthHeaders()
      });

      const data = await response.json();

      if (data.success) {
        this.showOrderModal(data.order);
      } else {
        throw new Error(data.error);
      }
    } catch (error) {
      console.error('Error loading order details:', error);
      this.showToast('Failed to load order details', 'error');
    }
  }

  showOrderModal(order) {
    const modal = document.getElementById('orderModal');
    const detailsContainer = document.getElementById('orderDetails');

    if (!modal || !detailsContainer) return;

    const statusColors = {
      ordered: 'var(--info)',
      preparing: 'var(--warning)',
      ready: 'var(--success)',
      completed: 'var(--gray-500)',
      cancelled: 'var(--error)'
    };

    detailsContainer.innerHTML = `
      <div style="margin-bottom: var(--spacing-lg);">
        <h2 style="margin: 0 0 0.5rem 0;">${order.order_number}</h2>
        <p style="color: var(--gray-500); margin: 0;">
          ${new Date(order.created_at).toLocaleString()}
        </p>
      </div>

      <div style="display: inline-block; padding: 0.75rem 1.5rem; border-radius: var(--radius-full); background: ${statusColors[order.status]}20; color: ${statusColors[order.status]}; font-weight: 700; margin-bottom: var(--spacing-lg);">
        ${order.status.toUpperCase()}
      </div>

      <h4>Order Items</h4>
      <div style="background: var(--gray-50); border-radius: var(--radius-md); padding: var(--spacing-md); margin-bottom: var(--spacing-lg);">
        ${order.order_items.map(item => `
          <div style="display: flex; justify-content: space-between; padding: 0.5rem 0;">
            <span>${item.food_items?.name} × ${item.quantity}</span>
            <span style="font-weight: 700;">₹${(parseFloat(item.price) * item.quantity).toFixed(2)}</span>
          </div>
        `).join('')}
        <div style="border-top: 2px solid var(--gray-300); margin-top: var(--spacing-md); padding-top: var(--spacing-md);">
          <div style="display: flex; justify-content: space-between; font-size: 1.25rem; font-weight: 700;">
            <span>Total:</span>
            <span style="color: var(--primary-orange);">₹${parseFloat(order.total).toFixed(2)}</span>
          </div>
        </div>
      </div>

      <div style="display: grid; grid-template-columns: 1fr 1fr; gap: var(--spacing-md); margin-bottom: var(--spacing-lg);">
        <div>
          <p style="color: var(--gray-500); font-size: 0.875rem; margin: 0 0 0.25rem 0;">Payment Method</p>
          <p style="font-weight: 600; margin: 0;">${order.payment_method?.toUpperCase() || 'N/A'}</p>
        </div>
        ${order.estimated_time ? `
          <div>
            <p style="color: var(--gray-500); font-size: 0.875rem; margin: 0 0 0.25rem 0;">Estimated Time</p>
            <p style="font-weight: 600; margin: 0;">${order.estimated_time} minutes</p>
          </div>
        ` : ''}
      </div>

      ${order.status === 'ready' ? `
        <div style="background: var(--success); color: var(--white); padding: var(--spacing-lg); border-radius: var(--radius-md); text-align: center;">
          <h3 style="margin: 0 0 0.5rem 0;">🎉 Your order is ready!</h3>
          <p style="margin: 0;">Please collect from the counter</p>
        </div>
      ` : ''}
    `;

    modal.classList.add('active');

    // Setup close button
    const closeBtn = document.getElementById('closeOrderBtn');
    if (closeBtn) {
      closeBtn.onclick = () => modal.classList.remove('active');
    }

    // Close on background click
    modal.onclick = (e) => {
      if (e.target === modal) {
        modal.classList.remove('active');
      }
    };
  }

  loadProfile() {
    const container = document.getElementById('profileContent');
    if (!container || !window.auth.user) return;

    container.innerHTML = `
      <div style="background: var(--white); border-radius: var(--radius-xl); padding: var(--spacing-xl); box-shadow: var(--shadow-md);">
        <div style="text-align: center; margin-bottom: var(--spacing-xl);">
          <div style="width: 100px; height: 100px; border-radius: var(--radius-full); background: linear-gradient(135deg, var(--primary-orange) 0%, var(--primary-orange-dark) 100%); color: var(--white); display: flex; align-items: center; justify-content: center; font-size: 3rem; margin: 0 auto var(--spacing-md);">
            👤
          </div>
          <h2 style="margin: 0 0 0.5rem 0;">${window.auth.user.name}</h2>
          <p style="color: var(--gray-500); margin: 0;">Student ID: ${window.auth.user.student_id}</p>
        </div>

        <div style="border-top: 1px solid var(--gray-200); padding-top: var(--spacing-lg);">
          <h3 style="margin: 0 0 var(--spacing-md) 0;">Account Information</h3>
          
          <div style="margin-bottom: var(--spacing-md);">
            <p style="color: var(--gray-500); font-size: 0.875rem; margin: 0 0 0.25rem 0;">Email</p>
            <p style="font-weight: 600; margin: 0;">${window.auth.user.email || 'Not provided'}</p>
          </div>

          <div style="margin-bottom: var(--spacing-md);">
            <p style="color: var(--gray-500); font-size: 0.875rem; margin: 0 0 0.25rem 0;">Mobile</p>
            <p style="font-weight: 600; margin: 0;">${window.auth.user.mobile || 'Not provided'}</p>
          </div>

          <div style="margin-bottom: var(--spacing-md);">
            <p style="color: var(--gray-500); font-size: 0.875rem; margin: 0 0 0.25rem 0;">Role</p>
            <p style="font-weight: 600; margin: 0;">${window.auth.user.role || 'Student'}</p>
          </div>
        </div>

        <div style="border-top: 1px solid var(--gray-200); padding-top: var(--spacing-lg); margin-top: var(--spacing-lg);">
          <h3 style="margin: 0 0 var(--spacing-md) 0;">Notifications</h3>
          <div style="display: flex; justify-content: space-between; align-items: center; padding: var(--spacing-md); background: var(--gray-50); border-radius: var(--radius-md);">
            <span>Push Notifications</span>
            <span style="color: var(--success); font-weight: 700;">
              ${window.notifications?.permission === 'granted' ? '✓ Enabled' : '✗ Disabled'}
            </span>
          </div>
        </div>
      </div>
    `;
  }

  showToast(message, type = 'info') {
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.textContent = message;

    const container = document.getElementById('toastContainer');
    if (container) {
      container.appendChild(toast);
      setTimeout(() => toast.remove(), 3000);
    }
  }
}

// Initialize app when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
  window.app = new BadeCanteenApp();
});
