(function () {
  'use strict';

  function hasNativeFlag() {
    return /(?:source=app|native_app=1|capacitor=1|app_shell=1)/i.test(window.location.search || '');
  }

  function isNativeApp() {
    try {
      if (hasNativeFlag()) {
        sessionStorage.setItem('pyrk_native_app', '1');
        localStorage.setItem('pyrk_native_app', '1');
        return true;
      }
      if (window.Capacitor && typeof window.Capacitor.isNativePlatform === 'function') {
        return window.Capacitor.isNativePlatform();
      }
      if (window.Capacitor && window.Capacitor.platform) {
        return window.Capacitor.platform !== 'web';
      }
      if (sessionStorage.getItem('pyrk_native_app') === '1' || localStorage.getItem('pyrk_native_app') === '1') {
        return true;
      }
    } catch (e) {}
    return false;
  }

  function unlockScroll() {
    var html = document.documentElement;
    var body = document.body;
    if (!html || !body) return;

    html.classList.add('pyrk-native-scroll-root');
    body.classList.add('pyrk-native-scroll-root');

    html.style.overflowX = 'hidden';
    html.style.overflowY = 'scroll';
    html.style.height = '100%';
    html.style.minHeight = '100%';
    html.style.maxWidth = '100%';
    html.style.touchAction = 'pan-y';

    body.style.position = 'relative';
    body.style.display = 'block';
    body.style.overflowX = 'hidden';
    body.style.overflowY = 'visible';
    body.style.height = 'auto';
    body.style.minHeight = 'calc(100vh + 1px)';
    body.style.maxWidth = '100%';
    body.style.touchAction = 'pan-y';
    body.style.webkitOverflowScrolling = 'touch';

    var rootSelectors = [
      '#app', '#root', '.app-root', '.page-root', '.layout-root', '.mobile-root',
      '.client-root', '.admin-root', 'main', '.app', '.page', '.shell', '.dashboard',
      '.member-dashboard', '.content', '.container', '.app-shell', '.auth-shell',
      '.portal-shell', '.client-interface', '.client-dashboard', '.dashboard-page',
      '.dashboard-shell', '.member-page', '.member-home', '.member-app', '.native-app-page'
    ];

    document.querySelectorAll(rootSelectors.join(',')).forEach(function (el) {
      if (!el) return;
      var computed = window.getComputedStyle(el);
      if (computed.position === 'fixed') el.style.position = 'relative';
      el.style.width = '100%';
      el.style.maxWidth = '100%';
      el.style.minHeight = el === document.body ? 'calc(100vh + 1px)' : 'auto';
      el.style.height = 'auto';
      el.style.overflowX = 'hidden';
      el.style.overflowY = 'visible';
      el.style.webkitOverflowScrolling = 'touch';
    });
  }

  function scrollToMemberProfile() {
    location.href = 'mobile_profile.php';
  }


  function scrollToPhotoUpload() {
    var target = document.querySelector('[data-photo-upload-panel], #photoUploadPanel, #photoForm');
    if (target) {
      target.scrollIntoView({ behavior: 'smooth', block: 'start' });
      return;
    }
    if (!/walk\.php/i.test(location.pathname)) {
      location.href = 'index.php#walks';
    }
  }

  function fixViewportMeta() {
    var meta = document.querySelector('meta[name="viewport"]');
    if (!meta) {
      meta = document.createElement('meta');
      meta.name = 'viewport';
      document.head.appendChild(meta);
    }
    meta.setAttribute('content', 'width=device-width, initial-scale=1, maximum-scale=1, viewport-fit=cover');
  }

  function clampWideElements() {
    var width = window.innerWidth || document.documentElement.clientWidth || 0;
    if (!width) return;

    var selectors = [
      '.topbar', '.container', '.panel', '.card', '.stat', '.page-hero', '.client-hero-card',
      '.member-mobile-experience-pro', '.member-app-hero-card', '.walk-card', '.walk-card-list',
      '.nav-menu', '.nav-user', '.nav-dropdown', '.table-wrap', 'table', 'img', 'video', 'canvas', 'iframe'
    ];

    document.querySelectorAll(selectors.join(',')).forEach(function (el) {
      if (!el || el === document.documentElement || el === document.body) return;
      el.style.maxWidth = '100%';
      if (el.scrollWidth > width + 2 && !/^(TABLE)$/i.test(el.tagName)) {
        el.style.overflowX = 'hidden';
      }
    });
  }

  function markExternalLinks() {
    var links = document.querySelectorAll('a[href^="http"]');
    links.forEach(function (link) {
      try {
        var url = new URL(link.href);
        if (!/(^|\.)thepyrk\.com$/i.test(url.hostname)) {
          link.setAttribute('target', '_blank');
          link.setAttribute('rel', 'noopener');
        }
      } catch (e) {}
    });
  }

  function getHref(selector, fallback) {
    var el = document.querySelector(selector);
    return (el && el.getAttribute('href')) ? el.getAttribute('href') : fallback;
  }

  function addNativeDock() {
    if (document.querySelector('.pyrk-native-dock')) return;
    if (!document.querySelector('[data-pyrk-nav]')) return;
    if (/login-dev\.php|reset_password\.php|activate\.php/i.test(location.pathname)) return;

    var body = document.body;
    if (!body) return;

    var isAdmin = /\/admin\//i.test(location.pathname);
    var homeHref = isAdmin ? getHref('.brand.brand-managed', 'dashboard.php') : 'mobile_home.php';
    var logoutHref = getHref('.btn-logout', isAdmin ? '../login-dev.php?logout=1' : 'login-dev.php?logout=1');
    var qrHref = isAdmin ? 'attendance.php' : 'my_qr.php?source=app';
    var walksHref = isAdmin ? 'walks.php' : 'mobile_walks.php';
    var rewardsHref = 'mobile_rewards.php';
    var profileHref = 'mobile_profile.php';
    var profileLabel = 'Profile';
    var isWalkPage = /walk\.php/i.test(location.pathname);

    var dock = document.createElement('nav');
    dock.className = 'pyrk-native-dock' + (isWalkPage ? ' has-photos' : '');
    dock.setAttribute('aria-label', 'Mobile app actions');
    dock.innerHTML = '' +
      '<a href="' + homeHref + '"><span>⌂</span>Home</a>' +
      '<a href="' + walksHref + '"><span>🥾</span>Walks</a>' +
      '<a class="is-primary" href="' + qrHref + '"><span>▣</span>' + (isAdmin ? 'Scan' : 'QR') + '</a>' +
      (isWalkPage ? '<button type="button" data-pyrk-dock-photos><span>📸</span>Photos</button>' : '') +
      (isAdmin
        ? '<button type="button" data-pyrk-dock-admin-menu><span>☰</span>Menu</button><a class="is-danger" href="' + logoutHref + '"><span>⏻</span>Logout</a>'
        : '<a href="' + rewardsHref + '"><span>🎁</span>Rewards</a><a href="' + profileHref + '"><span>👤</span>' + profileLabel + '</a>');

    body.appendChild(dock);

    var photoBtn = dock.querySelector('[data-pyrk-dock-photos]');
    if (photoBtn) {
      photoBtn.addEventListener('click', function () {
        scrollToPhotoUpload();
      });
    }

    var profileBtn = dock.querySelector('[data-pyrk-dock-profile]');
    if (profileBtn) {
      profileBtn.addEventListener('click', function () {
        scrollToMemberProfile();
      });
    }

    var adminMenuBtn = dock.querySelector('[data-pyrk-dock-admin-menu]');
    if (adminMenuBtn) {
      adminMenuBtn.addEventListener('click', function () {
        var topbar = document.querySelector('[data-pyrk-nav]');
        if (!topbar) return;
        var open = topbar.classList.toggle('nav-open');
        var toggle = topbar.querySelector('[data-nav-toggle]');
        if (toggle) toggle.setAttribute('aria-expanded', open ? 'true' : 'false');
        if (open) {
          window.scrollTo({ top: 0, behavior: 'smooth' });
        }
      });
    }
  }

  function addPrizesToMobileMenu() {
    var root = document.querySelector('[data-pyrk-nav]');
    if (!root || root.dataset.nativePrizesReady === '1') return;
    root.dataset.nativePrizesReady = '1';
    if (/\/admin\//i.test(location.pathname)) return;
    var menu = root.querySelector('[data-nav-menu], .nav-menu');
    if (!menu) return;
    if (menu.querySelector('[data-native-prizes-link]')) return;
    var link = document.createElement('a');
    link.className = 'nav-link pyrk-native-prizes-link';
    link.setAttribute('data-native-prizes-link', '1');
    link.href = 'mobile_rewards.php';
    link.innerHTML = '<strong>🎁 Prizes</strong><small>Redeem points and view rewards</small>';
    var notifications = menu.querySelector('a[href$="notifications.php"]');
    if (notifications && notifications.nextSibling) {
      menu.insertBefore(link, notifications.nextSibling);
    } else {
      menu.appendChild(link);
    }
  }


  function rewriteMemberMenuLinks() {
    if (/\/admin\//i.test(location.pathname)) return;
    var root = document.querySelector('[data-pyrk-nav]');
    if (!root || root.dataset.nativeMemberRoutes === '1') return;
    root.dataset.nativeMemberRoutes = '1';

    var exact = {
      'index.php': 'mobile_home.php',
      'index.php#walks': 'mobile_walks.php',
      'index.php#badges': 'mobile_rewards.php',
      'index.php#rewards': 'mobile_rewards.php',
      'index.php#history': 'mobile_history.php'
    };
    root.querySelectorAll('a[href]').forEach(function (link) {
      var href = link.getAttribute('href') || '';
      if (exact[href]) link.setAttribute('href', exact[href]);
    });

    var menu = root.querySelector('[data-nav-menu], .nav-menu');
    if (menu && !menu.querySelector('[data-native-profile-link]')) {
      var profile = document.createElement('a');
      profile.className = 'nav-link';
      profile.setAttribute('data-native-profile-link', '1');
      profile.href = 'mobile_profile.php';
      profile.innerHTML = '<strong>👤 My profile</strong><small>View and edit my details</small>';
      menu.appendChild(profile);

      var activity = document.createElement('a');
      activity.className = 'nav-link';
      activity.setAttribute('data-native-activity-link', '1');
      activity.href = 'mobile_activity.php';
      activity.innerHTML = '<strong>⭐ Activity & points</strong><small>Points gained and used</small>';
      menu.appendChild(activity);
    }
  }

  function improveMenuClose() {
    var root = document.querySelector('[data-pyrk-nav]');
    if (!root || root.dataset.nativeMenuPolish === '1') return;
    root.dataset.nativeMenuPolish = '1';

    root.querySelectorAll('.nav-menu a').forEach(function (link) {
      link.addEventListener('click', function () {
        root.classList.remove('nav-open');
        var toggle = root.querySelector('[data-nav-toggle]');
        if (toggle) toggle.setAttribute('aria-expanded', 'false');
      });
    });
  }

  function init() {
    if (!isNativeApp()) return;
    document.documentElement.classList.add('pyrk-native-app');
    if (document.body) {
      document.body.classList.add('pyrk-native-app');
      if (!/\/admin\//i.test(location.pathname)) document.body.classList.add('pyrk-native-member');
    }
    fixViewportMeta();
    unlockScroll();
    clampWideElements();
    markExternalLinks();
    addNativeDock();
    addPrizesToMobileMenu();
    rewriteMemberMenuLinks();
    improveMenuClose();
    setTimeout(unlockScroll, 250);
    setTimeout(clampWideElements, 250);
    setTimeout(unlockScroll, 1000);
    setTimeout(clampWideElements, 1000);
    setTimeout(unlockScroll, 2000);
    setTimeout(clampWideElements, 2000);
  }

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

  window.addEventListener('load', function () {
    if (!isNativeApp()) return;
    unlockScroll();
    clampWideElements();
    markExternalLinks();
    addNativeDock();
    addPrizesToMobileMenu();
  });

  window.addEventListener('resize', function () {
    if (!isNativeApp()) return;
    setTimeout(function () {
      unlockScroll();
      clampWideElements();
    }, 100);
  });

  window.addEventListener('orientationchange', function () {
    if (!isNativeApp()) return;
    setTimeout(function () {
      unlockScroll();
      clampWideElements();
    }, 300);
  });

  try {
    var observer = new MutationObserver(function () {
      if (!isNativeApp()) return;
      unlockScroll();
      clampWideElements();
      addPrizesToMobileMenu();
      rewriteMemberMenuLinks();
      improveMenuClose();
    });
    observer.observe(document.documentElement, { childList: true, subtree: true });
  } catch (e) {}

  window.PyrkNativeApp = {
    isNativeApp: isNativeApp,
    fixScroll: unlockScroll,
    fixWidth: clampWideElements,
    profile: scrollToMemberProfile
  };
})();
