/**
 * Ragreen - Shared app nav
 * Include after jQuery: injects the top nav into #appNav and checks
 * session state via /api/auth/me.php to show the right links.
 * Responsive: a hamburger toggle appears under 860px (see style.css) and
 * shows/hides the link list, which is otherwise always visible on desktop.
 */

/**
 * Ragreen - Shared app nav
 * Include after jQuery: injects the top nav into #appNav and checks
 * session state via /api/auth/me.php to show the right links.
 * Responsive: a hamburger toggle appears under 860px (see style.css) and
 * shows/hides the link list, which is otherwise always visible on desktop.
 *
 * Access control: pass options to guard a page.
 *   renderNav('cart', { requireAuth: true })                     - must be logged in
 *   renderNav('admin', { requireAuth: true, requireRole: 'admin' }) - must be logged in AND that role
 * Reuses the /api/auth/me.php call this function already makes, rather
 * than firing a second request just to check access.
 */

function renderNav(activePage, options = {}) {
  const $nav = $('#appNav');
  if (!$nav.length) return;

  $nav.html(`
    <div class="brand-mark" style="cursor:pointer;" id="navHome"><img src="assets/img/logo-ragreen-transparent.png" alt="Ragreen"></div>
    <button class="nav-toggle" id="navToggle" aria-label="Menu" aria-expanded="false">☰</button>
    <div class="app-nav-links" id="navLinksArea"></div>
  `);

  $('#navHome').on('click', () => window.location.href = 'marketplace.html');

  $('#navToggle').on('click', function () {
    const isOpen = $('#navLinksArea').toggleClass('open').hasClass('open');
    $(this).attr('aria-expanded', isOpen).text(isOpen ? '✕' : '☰');
  });

  $.get(`${API_BASE}/auth/me.php`)
    .done(function (res) {
      const accountType = res.data.user.account_type;

      if (options.requireRole && accountType !== options.requireRole) {
        window.location.replace('marketplace.html');
        return;
      }

      const links = [
        { key: 'marketplace', label: 'Marketplace', href: 'marketplace.html' },
        { key: 'vendors', label: 'Vendors', href: 'vendors.html' },
        { key: 'my-listings', label: 'My Listings', href: 'my-listings.html' },
        { key: 'pantry', label: 'My Pantry', href: 'pantry.html' },
        { key: 'order-history', label: 'Orders', href: 'order-history.html' },
        { key: 'requests', label: 'Requests', href: 'requests.html' },
        { key: 'loyalty', label: 'Rewards', href: 'loyalty.html' },
        { key: 'sell', label: 'Sell an item', href: 'product-form.html' },
        { key: 'sales-history', label: 'My Sales', href: 'sales-history.html' },
      ];
      if (accountType === 'personal') {
        links.push({ key: 'profile', label: 'Profile', href: 'profile.html' });
      }
      if (accountType === 'business') {
        links.push({ key: 'business-dashboard', label: 'Dashboard', href: 'business-dashboard.html' });
      }
      if (accountType === 'admin') {
        links.push({ key: 'profile', label: 'My Profile', href: 'profile.html' });
        links.push({ key: 'admin', label: 'Admin', href: 'admin.html' });
      }

      const linkHtml = links.map(l =>
        `<a href="${l.href}" class="${l.key === activePage ? 'active' : ''}">${l.label}</a>`
      ).join('');

      $('#navLinksArea').html(`
        ${linkHtml}
        <a href="my-reports.html" id="navReports" title="My reports">🚩</a>
        <a href="notifications.html" id="navBell">🔔<span id="navBellBadge" class="bell-badge" style="display:none;"></span></a>
        <a href="cart.html" id="navCart">Cart<span id="navCartBadge" style="display:none;"></span></a>
        <a href="#" id="navLogout">Log out</a>
      `);
      $('#navLogout').on('click', function (e) {
        e.preventDefault();
        $.post(`${API_BASE}/auth/logout.php`).always(() => window.location.href = 'login.html');
      });
      updateCartBadge();
      updateBellBadge();
    })
    .fail(function () {
      if (options.requireAuth) {
        const returnTo = encodeURIComponent(window.location.pathname.split('/').pop() + window.location.search);
        window.location.replace(`login.html?redirect=${returnTo}`);
        return;
      }
      $('#navLinksArea').html(`
        <a href="marketplace.html" class="${activePage === 'marketplace' ? 'active' : ''}">Marketplace</a>
        <a href="vendors.html" class="${activePage === 'vendors' ? 'active' : ''}">Vendors</a>
        <a href="login.html" class="btn-nav">Log in</a>
      `);
    });
}

function updateCartBadge() {
  $.get(`${API_BASE}/cart/list.php`).done(function (res) {
    const count = res.data.summary.item_count;
    const $badge = $('#navCartBadge');
    if (count > 0) {
      $badge.text(` (${count})`).show();
    } else {
      $badge.hide();
    }
  });
}

function updateBellBadge() {
  $.get(`${API_BASE}/notifications/unread_count.php`).done(function (res) {
    const count = res.data.unread_count;
    const $badge = $('#navBellBadge');
    if (count > 0) {
      $badge.text(count).show();
    } else {
      $badge.hide();
    }
  });
}
