/* YouVBiZ Dashboard – Shared Utilities */

/* ── Toast ── */
function showToast(msg, type='info') {
  const t = document.getElementById('toast');
  if (!t) return;
  t.textContent = msg;
  t.className = 'toast show toast-' + type;
  setTimeout(() => t.classList.remove('show'), 2600);
}

/* ── Confirm Delete ── */
function confirmDelete(msg, cb) {
  if (confirm(msg || 'Are you sure you want to delete this item?')) cb();
}

/* ── Indian States (sample for dropdowns) ── */
const STATES = [
  'Andhra Pradesh','Arunachal Pradesh','Assam','Bihar','Chhattisgarh','Goa','Gujarat',
  'Haryana','Himachal Pradesh','Jharkhand','Karnataka','Kerala','Madhya Pradesh',
  'Maharashtra','Manipur','Meghalaya','Mizoram','Nagaland','Odisha','Punjab',
  'Rajasthan','Sikkim','Tamil Nadu','Telangana','Tripura','Uttar Pradesh',
  'Uttarakhand','West Bengal','Delhi','Jammu & Kashmir'
];

const CITIES = {
  'Maharashtra': ['Mumbai','Pune','Nagpur','Nashik','Aurangabad','Thane','Solapur'],
  'Gujarat': ['Ahmedabad','Surat','Vadodara','Rajkot','Bhavnagar','Jamnagar'],
  'Delhi': ['New Delhi','Dwarka','Rohini','Noida','Gurgaon'],
  'Karnataka': ['Bangalore','Mysore','Hubli','Mangalore','Belgaum'],
  'Tamil Nadu': ['Chennai','Coimbatore','Madurai','Tiruchirappalli','Salem'],
  'Telangana': ['Hyderabad','Warangal','Nizamabad','Karimnagar'],
  'Uttar Pradesh': ['Lucknow','Kanpur','Agra','Varanasi','Allahabad','Meerut'],
  'West Bengal': ['Kolkata','Howrah','Durgapur','Asansol'],
  'Rajasthan': ['Jaipur','Jodhpur','Udaipur','Ajmer','Kota'],
  'Madhya Pradesh': ['Bhopal','Indore','Gwalior','Jabalpur'],
};

function populateStates(selectId, selectedVal) {
  const sel = document.getElementById(selectId);
  if (!sel) return;
  sel.innerHTML = '<option value="">Select State</option>';
  STATES.forEach(s => {
    const o = document.createElement('option');
    o.value = s; o.textContent = s;
    if (s === selectedVal) o.selected = true;
    sel.appendChild(o);
  });
}

function populateCities(stateVal, selectId, selectedVal) {
  const sel = document.getElementById(selectId);
  if (!sel) return;
  sel.innerHTML = '<option value="">Select City</option>';
  const cities = CITIES[stateVal] || [];
  cities.forEach(c => {
    const o = document.createElement('option');
    o.value = c; o.textContent = c;
    if (c === selectedVal) o.selected = true;
    sel.appendChild(o);
  });
}

/* ── Nav active state ── */
document.addEventListener('DOMContentLoaded', () => {
  const links = document.querySelectorAll('.bottom-nav .nav-item');
  const cur = location.pathname.split('/').pop();
  links.forEach(l => {
    if (l.getAttribute('href') === cur) l.classList.add('active');
    else l.classList.remove('active');
  });
});

/* ── Sample data store (localStorage) ── */
function getData(key) {
  try { return JSON.parse(localStorage.getItem('yvb_' + key) || 'null'); } catch { return null; }
}
function setData(key, val) {
  try { localStorage.setItem('yvb_' + key, JSON.stringify(val)); } catch {}
}
function getList(key) { return getData(key) || []; }
function saveList(key, arr) { setData(key, arr); }
function nextId(arr) { return arr.length ? Math.max(...arr.map(x => x.id || 0)) + 1 : 1; }
function formatDate(d) {
  const dt = d ? new Date(d) : new Date();
  return dt.toLocaleDateString('en-IN', {day:'2-digit', month:'short', year:'numeric'});
}

/* ── Role-based Navigation & Route Guard ── */
(function() {
  const role = localStorage.getItem('role');
  const path = window.location.pathname;
  const pageName = path.split('/').pop() || 'index.html';

  // 1. Strict Route Guarding
  function handleRedirection() {
    if (role && role !== 'undefined') {
      // Prevent logged-in users from hitting landing/login/register
      if (pageName === 'index.html' || (pageName === 'login.html' && !window.location.search.includes('role')) || pageName === 'register.html') {
        window.location.href = 'home.html';
        return true;
      }
    } else {
      // Prevent guest users from hitting private business pages
      const isPrivate = ['-dashboard', '-profile', '-settings', '-products', '-messages', '-enquiries', '-requirements', '-transactions', '-jobs', '-network', '-gallery', '-certificates'].some(term => pageName.includes(term));
      if (isPrivate) {
        window.location.href = 'index.html';
        return true;
      }
    }
    return false;
  }

  // 2. Navigation Syncing
  function syncNavigation() {
    if (!role || role === 'undefined') return;

    // A. Update Dashboard links (Topbar & Bottom-nav)
    document.querySelectorAll('#dashboardLink, #dashboardNavLink').forEach(el => {
      el.href = role + '-dashboard.html';
      el.style.display = 'flex';
    });

    // B. Map Bottom Nav Links to Role Context
    const navItems = document.querySelectorAll('.bottom-nav .nav-item');
    navItems.forEach(item => {
      let href = item.getAttribute('href');
      if (!href || href === '#') return;

      // Map role-specific pages
      if (['-products', '-messages', '-transactions', '-profile', '-enquiries', '-jobs'].some(t => href.includes(t))) {
         const base = href.split('-').pop(); // e.g. "products.html" from "manufacturer-products.html"
         item.href = role + '-' + base;
      } else if (href === 'login.html' || item.id === 'accountLink') {
         item.href = role + '-profile.html';
      }

      // C. Active Tab Highlighting (The "Nested Route" Feel)
      item.classList.remove('active');
      if (pageName === item.getAttribute('href')) {
        item.classList.add('active');
      }
      // Special case: Highlight Dashboard/Home tab if on dashboard
      if (pageName.includes('-dashboard') && (item.id === 'homeLink' || item.id === 'dashboardNavLink' || item.innerText.includes('Home'))) {
        item.classList.add('active');
      }
    });

    // D. Back-Button Intelligence (Always return to Dashboard)
    const backBtn = document.querySelector('.back-btn');
    if (backBtn) {
      if (pageName.includes('-') && !pageName.includes('-dashboard')) {
        // If on a sub-module (e.g. manufacturer-products), back goes to dashboard
        backBtn.href = role + '-dashboard.html';
      } else if (pageName === 'home.html' || pageName === 'Listing.html') {
        // From discovery pages, back button is hidden or goes to dashboard
        backBtn.href = role + '-dashboard.html';
      }
    }

    // E. Detail Page Context (e.g. show "Edit" on manufacturer_detail if owner)
    if (pageName === 'manufacturer_detail.html') {
      const editBtn = document.getElementById('editCompanyBtn');
      if (editBtn && role === 'manufacturer') editBtn.style.display = 'block';
    }
  }

  // Execute Guard immediately to prevent flickering
  if (!handleRedirection()) {
    document.addEventListener('DOMContentLoaded', syncNavigation);
  }

  // Global Helpers
  window.doLogout = function() {
    localStorage.removeItem('role');
    window.location.href = 'index.html';
  };

  window.showToast = function(msg) {
    let t = document.getElementById('toast');
    if (!t) {
      t = document.createElement('div');
      t.id = 'toast'; t.className = 'toast';
      document.body.appendChild(t);
    }
    t.textContent = msg; t.classList.add('show');
    setTimeout(() => t.classList.remove('show'), 2500);
  };
})();
