/**
 * CNPERP plan feature gating — hides navbar links and guards premium static pages.
 */
(function () {
  'use strict';

  const CACHE_KEY = 'cnperp_plan_features';
  const CACHE_TS = 'cnperp_plan_features_ts';
  const CACHE_MS = 5 * 60 * 1000;

  const STATIC_PATH_FEATURES = {
    '/static/manufacturing.html': 'manufacturing',
    '/static/job-cards.html': 'job_cards',
    '/static/job-sales-queue.html': 'job_cards',
    '/static/recipes.html': 'manufacturing',
    '/static/cogs.html': 'cogs',
    '/static/cogs-reports.html': 'cogs',
    '/static/serial-numbers.html': 'serial_numbers',
    '/static/traceability.html': 'traceability',
    '/static/procurement.html': 'procurement',
    '/static/landed-costs.html': 'landed_costs',
    '/static/budgeting.html': 'budgeting',
    '/static/accounting-codes-dimensional.html': 'dimensional',
    '/static/accounting-dimensions.html': 'dimensional',
    '/static/dimensional-reports.html': 'dimensional',
    '/static/billing.html': 'billing',
    '/static/branch-sales.html': 'branch_sales',
    '/static/inventory-allocation.html': 'inventory_allocation',
    '/static/uom-management.html': 'uom',
    '/static/business-intelligence.html': 'bi',
    '/static/asset-management.html': 'assets',
    '/static/asset.html': 'assets',
    '/static/management-reports.html': 'management_reports',
    '/static/period-reports.html': 'period_reports',
    '/static/invoice-designer.html': 'invoice_designer',
    '/static/invoice-customization.html': 'invoice_designer',
    '/static/excel-templates.html': 'excel_templates',
    '/static/logs-viewer.html': 'logs',
    '/static/backup-management.html': 'backup_mgmt',
  };

  const PLAN_LABELS = {
    standard: 'Standard',
    professional: 'Professional',
    enterprise: 'Enterprise',
  };

  function authHeaders() {
    const token = localStorage.getItem('token');
    return token ? { Authorization: 'Bearer ' + token } : {};
  }

  function normalizePath(href) {
    if (!href) return '';
    try {
      const u = new URL(href, window.location.origin);
      return u.pathname;
    } catch (_) {
      return href.split('?')[0];
    }
  }

  function featureForHref(href) {
    const path = normalizePath(href);
    if (STATIC_PATH_FEATURES[path]) return STATIC_PATH_FEATURES[path];
    for (const [p, fid] of Object.entries(STATIC_PATH_FEATURES)) {
      if (path.endsWith(p.replace('/static/', ''))) return fid;
    }
    return null;
  }

  function readCache() {
    try {
      const ts = parseInt(sessionStorage.getItem(CACHE_TS) || '0', 10);
      if (Date.now() - ts > CACHE_MS) return null;
      const raw = sessionStorage.getItem(CACHE_KEY);
      return raw ? JSON.parse(raw) : null;
    } catch (_) {
      return null;
    }
  }

  function writeCache(data) {
    try {
      sessionStorage.setItem(CACHE_KEY, JSON.stringify(data));
      sessionStorage.setItem(CACHE_TS, String(Date.now()));
    } catch (_) {}
  }

  async function fetchPlanFeatures(force) {
    if (!force) {
      const cached = readCache();
      if (cached) return cached;
    }
    const token = localStorage.getItem('token');
    if (!token) return { enforcement: false, features: [] };

    const res = await fetch('/api/v1/licensing/plan-features', { headers: authHeaders() });
    if (!res.ok) return { enforcement: false, features: [] };
    const data = await res.json();
    writeCache(data);
    return data;
  }

  function hasFeature(data, featureId) {
    if (!data || !data.enforcement) return true;
    if (!featureId) return true;
    return Array.isArray(data.features) && data.features.includes(featureId);
  }

  function applyNavbarFilter(data) {
    if (!data || !data.enforcement) return;

    const allowed = new Set(data.features || []);
    document.querySelectorAll('.cnperp-navbar a.dropdown-item[href], .cnperp-navbar a.nav-link[href]').forEach((link) => {
      const fid = featureForHref(link.getAttribute('href'));
      if (fid && !allowed.has(fid)) {
        const li = link.closest('li');
        if (li) li.style.display = 'none';
      }
    });

    document.querySelectorAll('.cnperp-navbar .nav-item.dropdown').forEach((dropdown) => {
      const visible = dropdown.querySelectorAll('.dropdown-menu li:not([style*="display: none"]) a.dropdown-item');
      let any = false;
      visible.forEach((a) => {
        if (a.closest('li') && a.closest('li').style.display !== 'none') any = true;
      });
      if (!any) dropdown.style.display = 'none';
    });
  }

  function guardCurrentPage(data) {
    if (!data || !data.enforcement) return;
    const path = window.location.pathname;
    const fid = STATIC_PATH_FEATURES[path];
    if (!fid || hasFeature(data, fid)) return;

    const required = (data.locked_features || []).find((x) => x.id === fid);
    const planLabel = required ? required.required_plan_label : 'a higher';
    const msg =
      'This module requires the ' + planLabel + ' plan. Your company is on ' +
      (data.plan_label || PLAN_LABELS[data.plan] || data.plan || 'Standard') +
      '. Contact CNP Solutions to upgrade.';
    alert(msg);
    window.location.replace('/static/index.html');
  }

  window.CNPERP = window.CNPERP || {};
  window.CNPERP.PlanFeatures = {
    fetch: fetchPlanFeatures,
    hasFeature,
    applyNavbarFilter,
    guardCurrentPage,
    clearCache: function () {
      sessionStorage.removeItem(CACHE_KEY);
      sessionStorage.removeItem(CACHE_TS);
    },
  };

  document.addEventListener('DOMContentLoaded', function () {
    if (!localStorage.getItem('token')) return;
    fetchPlanFeatures(false).then(function (data) {
      applyNavbarFilter(data);
      guardCurrentPage(data);
      if (data && data.plan_label) {
        document.documentElement.setAttribute('data-cnperp-plan', data.plan || 'standard');
      }
    }).catch(function () {});
  });
})();
