(function () {
  'use strict';

  var ua = navigator.userAgent || '';
  var isAndroid = /Android/i.test(ua);
  var isApp = /POSMobileApp/i.test(ua) || /; wv\)|\bwv\b/i.test(ua) || window.Capacitor;

  if (!isAndroid || !isApp) {
    return;
  }

  var rootUrl = window.POS_NATIVE_BASE_URL || window.base_url || (window.location.origin + '/');
  var appName = window.POS_NATIVE_APP_NAME || 'POS Mobile';
  var path = window.location.pathname.replace(/\/+$/, '');
  var isLogin = /\/adm(\/index)?$|\/login|\/dashboard$|\/app\.poskasirpercetakan\/?$/.test(path) && !document.getElementById('wrapper');

  function url(route) {
    return String(rootUrl).replace(/\/?$/, '/') + route.replace(/^\/+/, '');
  }

  function icon(name) {
    return '<i class="' + name + '" aria-hidden="true"></i>';
  }

  function pageLabel() {
    var title = document.title || appName;
    title = title.split('|')[0].trim();
    if (!title || title.length > 28) {
      title = appName;
    }
    return title;
  }

  function navLink(route, label, iconClass, activeMatch) {
    var active = activeMatch.test(window.location.pathname) ? ' is-active' : '';
    return '<a class="pos-native-bottom-nav__item' + active + '" href="' + url(route) + '">' + icon(iconClass) + '<span>' + label + '</span></a>';
  }

  function navButton(action, label, iconClass) {
    return '<button class="pos-native-bottom-nav__item" type="button" data-pos-native-action="' + action + '">' + icon(iconClass) + '<span>' + label + '</span></button>';
  }

  function cleanText(value) {
    return String(value || '').replace(/\s+/g, ' ').trim();
  }

  function buildProfileItems() {
    var items = [];
    var seen = {};
    var originalItems = document.querySelectorAll('.dropdown-menu[aria-labelledby="userDropdown"] a[href]');

    Array.prototype.forEach.call(originalItems, function (item) {
      var href = item.getAttribute('href') || '';
      var label = cleanText(item.textContent);
      if (!href || href === '#' || !label || seen[href + label]) {
        return;
      }
      seen[href + label] = true;
      items.push({
        href: href,
        label: label,
        icon: /logout/i.test(label) ? 'fa fa-sign-out fas fa-sign-out-alt' : (/setting/i.test(label) ? 'fa fa-cog fas fa-cog' : 'fa fa-user fas fa-user')
      });
    });

    var hasProfile = items.some(function (item) { return /profile|profil/i.test(item.label); });
    var hasSettings = items.some(function (item) { return /setting/i.test(item.label); });
    var hasLogout = items.some(function (item) { return /logout|keluar/i.test(item.label); });
    var logoutItem = null;

    items = items.filter(function (item) {
      if (/logout|keluar/i.test(item.label)) {
        logoutItem = item;
        return false;
      }
      return true;
    });

    if (!hasProfile) {
      items.unshift({ href: url('main/info'), label: 'Profile', icon: 'fa fa-user fas fa-user' });
    }

    if (!hasSettings) {
      items.push({ href: url('main/info'), label: 'Settings', icon: 'fa fa-cog fas fa-cog' });
    }

    if (logoutItem) {
      items.push(logoutItem);
    } else if (!hasLogout) {
      items.push({ href: url('main/logout'), label: 'Logout', icon: 'fa fa-sign-out fas fa-sign-out-alt' });
    }

    if (!items.length) {
      items.push({ href: url('main/info'), label: 'Settings', icon: 'fa fa-cog fas fa-cog' });
      items.push({ href: url('main/logout'), label: 'Logout', icon: 'fa fa-sign-out fas fa-sign-out-alt' });
    }

    return items;
  }

  function buildProfileMenu() {
    var items = buildProfileItems();
    return '<div class="pos-native-profile-menu" id="posNativeProfileMenu" aria-hidden="true">' +
      items.map(function (item) {
        return '<a href="' + item.href + '">' + icon(item.icon) + '<span>' + item.label + '</span></a>';
      }).join('') +
    '</div>';
  }

  function collectSidebarLinks() {
    var links = [];
    var seen = {};
    var selectors = [
      '#accordionSidebar a[href]',
      '#sidebar a[href]',
      '.sidebar a[href]',
      '.openPopup[data-href]'
    ];

    Array.prototype.forEach.call(document.querySelectorAll(selectors.join(',')), function (item) {
      var href = item.getAttribute('data-href') || item.getAttribute('href') || '';
      var label = cleanText(item.textContent);

      if (!href || href === '#' || /^javascript:/i.test(href) || !label || /panel admin/i.test(label)) {
        return;
      }

      var key = href + '|' + label;
      if (seen[key]) {
        return;
      }

      seen[key] = true;
      links.push({
        href: href,
        label: label,
        icon: item.querySelector('i') ? item.querySelector('i').className : 'fa fa-circle-o fas fa-circle'
      });
    });

    if (!links.length) {
      links = [
        { href: url('home'), label: 'Dashboard', icon: 'fa fa-home fas fa-home' },
        { href: url('penjualan/order'), label: 'Data Transaksi', icon: 'fa fa-shopping-cart fas fa-shopping-cart' },
        { href: url('transaksi'), label: 'Laporan Transaksi', icon: 'fa fa-bar-chart fas fa-chart-column' },
        { href: url('laporan/operator'), label: 'Job List', icon: 'fa fa-tasks fas fa-list-check' }
      ];
    }

    return links;
  }

  function buildDrawer() {
    var links = collectSidebarLinks();
    return '<div class="pos-native-drawer-backdrop" id="posNativeDrawerBackdrop" aria-hidden="true">' +
      '<aside class="pos-native-drawer" role="dialog" aria-label="Menu aplikasi">' +
        '<div class="pos-native-drawer__header">' +
          '<div><strong>Opsi Menu</strong><span>Semua halaman POS</span></div>' +
          '<button class="pos-native-drawer__close" type="button" data-pos-native-action="close-menu" aria-label="Tutup">' + icon('fa fa-times fas fa-times') + '</button>' +
        '</div>' +
        '<div class="pos-native-drawer__links">' +
          links.map(function (item) {
            return '<a href="' + item.href + '">' + icon(item.icon) + '<span>' + item.label + '</span></a>';
          }).join('') +
        '</div>' +
      '</aside>' +
    '</div>';
  }

  function toggleDrawer(show) {
    var drawer = document.getElementById('posNativeDrawerBackdrop');
    if (!drawer) {
      return;
    }
    drawer.classList.toggle('is-open', !!show);
    drawer.setAttribute('aria-hidden', show ? 'false' : 'true');
  }

  function toggleProfileMenu(show) {
    var menu = document.getElementById('posNativeProfileMenu');
    if (!menu) {
      return;
    }
    menu.classList.toggle('is-open', !!show);
    menu.setAttribute('aria-hidden', show ? 'false' : 'true');
  }

  function buildShell() {
    if (document.getElementById('posNativeAppbar')) {
      return;
    }

    document.body.classList.add('pos-mobile-app-shell');

    var shell = document.createElement('div');
    shell.className = 'pos-native-shell';
    shell.innerHTML =
      '<div class="pos-native-appbar" id="posNativeAppbar">' +
        '<button class="pos-native-icon-btn" type="button" data-pos-native-action="back" aria-label="Kembali">' + icon('fa fa-arrow-left fas fa-arrow-left') + '</button>' +
        '<div class="pos-native-appbar__title">' + pageLabel() + '<span class="pos-native-appbar__subtitle">' + appName + '</span></div>' +
        '<button class="pos-native-icon-btn" type="button" data-pos-native-action="refresh" aria-label="Refresh">' + icon('fa fa-refresh fas fa-sync-alt') + '</button>' +
        '<button class="pos-native-icon-btn" type="button" data-pos-native-action="profile" aria-label="Profil">' + icon('fa fa-user fas fa-user-circle') + '</button>' +
        buildProfileMenu() +
      '</div>';

    if (!isLogin) {
      shell.innerHTML +=
        '<nav class="pos-native-bottom-nav" aria-label="Navigasi aplikasi">' +
          navLink('home', 'Dashboard', 'fa fa-home fas fa-home', /\/home(\/|$)|\/dashboard(\/|$)/i) +
          navLink('penjualan/order', 'Transaksi', 'fa fa-shopping-cart fas fa-receipt', /\/penjualan\/order|\/penjualan\/trx/i) +
          navLink('transaksi', 'Laporan', 'fa fa-bar-chart fas fa-chart-column', /\/transaksi(\/|$)/i) +
          navLink('laporan/operator', 'Job List', 'fa fa-tasks fas fa-list-check', /\/laporan\/operator|\/operator/i) +
          navButton('open-menu', 'Opsi', 'fa fa-bars fas fa-bars') +
        '</nav>' +
        buildDrawer();
    }

    document.body.appendChild(shell);

    document.body.addEventListener('click', function (event) {
      var actionButton = event.target.closest('[data-pos-native-action]');
      var profileMenu = event.target.closest('#posNativeProfileMenu');

      if (!actionButton && !profileMenu) {
        toggleProfileMenu(false);
      }

      if (!actionButton) {
        if (event.target.id === 'posNativeDrawerBackdrop') {
          toggleDrawer(false);
        }
        return;
      }

      var action = actionButton.getAttribute('data-pos-native-action');

      if (action === 'back') {
        if (window.history.length > 1) {
          window.history.back();
        } else {
          window.location.href = url('home');
        }
      } else if (action === 'refresh') {
        window.location.reload();
      } else if (action === 'profile') {
        var menu = document.getElementById('posNativeProfileMenu');
        toggleProfileMenu(!menu.classList.contains('is-open'));
      } else if (action === 'open-menu') {
        toggleProfileMenu(false);
        toggleDrawer(true);
      } else if (action === 'close-menu') {
        toggleDrawer(false);
      }
    });
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', buildShell);
  } else {
    buildShell();
  }
})();
