<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>MN Nearby Install</title>
    <style>
      body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; margin: 0; padding: 40px 16px; background: #111; color: #fafafa; }
      .card { max-width: 560px; margin: 0 auto; padding: 32px; background: rgba(255, 255, 255, 0.05); border-radius: 18px; box-shadow: 0 16px 30px rgba(0,0,0,0.25); }
      h1 { margin-top: 0; font-size: 1.8rem; }
      p { line-height: 1.5; }
      .platform-toggle { display: flex; gap: 12px; margin-top: 18px; padding: 6px; background: rgba(255, 255, 255, 0.04); border-radius: 14px; }
      .platform-button { flex: 1; border: none; border-radius: 10px; padding: 10px 0; background: transparent; color: inherit; font-size: 0.95rem; font-weight: 600; cursor: pointer; transition: background 0.2s ease, color 0.2s ease; }
      .platform-button.active { background: rgba(10, 132, 255, 0.25); color: #fff; box-shadow: inset 0 1px 0 rgba(255,255,255,0.15); }
      .platform-button:focus-visible { outline: 2px solid rgba(10,132,255,0.6); outline-offset: 2px; }
      .select-field { position: relative; margin-top: 16px; }
      .select-field::after { content: '\25BC'; position: absolute; right: 16px; top: 50%; transform: translateY(-50%); color: rgba(255, 255, 255, 0.55); pointer-events: none; font-size: 0.9rem; }
      select { width: 100%; padding: 14px 18px; border-radius: 12px; background: rgba(0, 0, 0, 0.4); color: #fafafa; border: 1px solid rgba(255, 255, 255, 0.2); font-size: 1rem; appearance: none; -webkit-appearance: none; -moz-appearance: none; box-shadow: inset 0 1px 3px rgba(0,0,0,0.3); transition: border-color 0.2s ease, box-shadow 0.2s ease, opacity 0.2s ease; color-scheme: dark; }
      select option { background: #1a1a1a; color: #fafafa; padding: 10px; }
      select:focus { outline: none; border-color: rgba(10, 132, 255, 0.8); box-shadow: 0 0 0 3px rgba(10, 132, 255, 0.25); }
      select:disabled { opacity: 0.4; cursor: not-allowed; }
      a.button { display: inline-block; margin-top: 20px; padding: 14px 22px; border-radius: 12px; background: #0a84ff; color: white; text-decoration: none; font-weight: 600; transition: opacity 0.2s ease, transform 0.2s ease; }
      a.button.disabled { opacity: 0.45; pointer-events: none; }
      a.button:not(.disabled):active { transform: translateY(1px); }
      .platform-section { margin: 24px 0; padding: 20px; background: rgba(255, 255, 255, 0.03); border-radius: 12px; border: 1px solid rgba(255, 255, 255, 0.1); }
      .platform-section h3 { margin: 0 0 12px 0; font-size: 1.3rem; }
      .build-info { margin: 8px 0 16px 0; font-size: 0.9rem; opacity: 0.8; font-family: 'SF Mono', Monaco, monospace; }
      .install-tip { margin-top: 16px; font-size: 0.85rem; opacity: 0.7; }
      code { background: rgba(255,255,255,0.12); padding: 2px 6px; border-radius: 6px; }
      footer { margin-top: 48px; font-size: 0.85rem; opacity: 0.6; text-align: center; }
      @media (max-width: 480px) {
        body { padding: 24px 12px; }
        .card { padding: 24px 20px; border-radius: 16px; }
        h1 { font-size: 1.6rem; }
        .platform-toggle { gap: 8px; padding: 5px; }
        .platform-button { font-size: 0.9rem; padding: 9px 0; }
        select { font-size: 1.05rem; padding: 16px 20px; }
        .select-field::after { right: 14px; }
      }
    </style>
  </head>
  <body>
    <div class="card">
      <h1>MN Nearby Install</h1>
      <p>Install the latest build for your platform:</p>
      
      <div id="ios-section" class="platform-section" style="display: none;">
        <h3><svg width="20" height="20" viewBox="0 0 24 24" fill="none" style="vertical-align: middle; margin-right: 8px;"><path d="M18.71 19.5c-.83 1.24-1.71 2.45-3.05 2.47-1.34.03-1.77-.79-3.29-.79-1.53 0-2 .77-3.27.82-1.31.05-2.3-1.32-3.14-2.53C4.25 17 2.94 12.45 4.7 9.39c.87-1.52 2.43-2.48 4.12-2.51 1.28-.02 2.5.87 3.29.87.78 0 2.26-1.07 3.81-.91.65.03 2.47.26 3.64 1.98-.09.06-2.17 1.28-2.15 3.81.03 3.02 2.65 4.03 2.68 4.04-.03.07-.42 1.44-1.38 2.83M13 3.5c.73-.83 1.94-1.46 2.94-1.5.13 1.17-.34 2.35-1.04 3.19-.69.85-1.83 1.51-2.95 1.42-.15-1.15.41-2.35 1.05-3.11z" fill="white"/></svg>iOS</h3>
        <div class="select-field">
          <select id="ios-build-select" onchange="onBuildChange('ios')">
            <option value="">Select a build...</option>
          </select>
        </div>
        <p id="ios-build-info" class="build-info"></p>
        <a id="ios-install-button" class="button disabled" href="" onclick="attemptInstall(event)" aria-disabled="true">
          Install on iOS
        </a>
        <p class="install-tip">If the install does not start, ensure the device UDID is registered and trust the MobileNexus profile under Settings -> General -> VPN &amp; Device Management.</p>
      </div>
      
      <div id="android-section" class="platform-section" style="display: none;">
        <h3><svg width="20" height="20" viewBox="0 0 24 24" fill="none" style="vertical-align: middle; margin-right: 8px;"><path d="M17.523 15.3414c-.5511 0-.9993-.4486-.9993-.9997s.4482-.9993.9993-.9993c.5511 0 .9993.4482.9993.9993.0001.5511-.4482.9997-.9993.9997m-11.046 0c-.5511 0-.9993-.4486-.9993-.9997s.4482-.9993.9993-.9993c.5511 0 .9993.4482.9993.9993 0 .5511-.4482.9997-.9993.9997m11.4045-6.02l1.9973-3.4592c.1125-.1948.0458-.4419-.1493-.5544-.1948-.1125-.4419-.0458-.5544.1493l-2.0223 3.5044c-1.2635-.5693-2.6742-.8638-4.1613-.8638s-2.8978.2945-4.1613.8638L6.7555 5.4617c-.1125-.1951-.3596-.2618-.5544-.1493-.1951.1125-.2618.3596-.1493.5544L8.051 9.3214C5.031 10.9556 3 14.1679 3 17.8877h18c0-3.7198-2.031-6.9321-5.0465-8.5663" fill="white"/></svg>Android</h3>
        <div class="select-field">
          <select id="android-build-select" onchange="onBuildChange('android')">
            <option value="">Select a build...</option>
          </select>
        </div>
        <p id="android-build-info" class="build-info"></p>
        <a id="android-install-button" class="button disabled" href="" onclick="attemptInstall(event)" aria-disabled="true">
          Download Android Build
        </a>
        <p class="install-tip">After downloading the build, open the APK and allow installs from your browser if prompted.</p>
      </div>
      
      <div id="loading-section">
        <p>Loading available builds...</p>
      </div>
    </div>
    <footer id="footer-text">Generated by GitHub Actions</footer>
    <script>
      const buildsEndpoint = '/builds.json?t=' + Date.now();
      const iosSection = document.getElementById('ios-section');
      const androidSection = document.getElementById('android-section');
      const loadingSection = document.getElementById('loading-section');
      const iosBuildInfo = document.getElementById('ios-build-info');
      const androidBuildInfo = document.getElementById('android-build-info');
      const iosInstallButton = document.getElementById('ios-install-button');
      const androidInstallButton = document.getElementById('android-install-button');
      const iosBuildSelect = document.getElementById('ios-build-select');
      const androidBuildSelect = document.getElementById('android-build-select');

      let allBuilds = [];

      function formatBuildInfo(build) {
        const workflowLabel = build.workflow === 'production' ? 'Production' : 'Internal';
        const dateLabel = build.published_at ? new Date(build.published_at).toLocaleDateString() : '';
        const shortSha = build.tag ? build.tag.split('-').pop() : 'unknown';
        return `${workflowLabel} • ${build.name.split('(')[1]?.replace(')', '') || shortSha} • ${dateLabel}`;
      }

      function formatSelectOption(build) {
        const date = build.published_at ? new Date(build.published_at).toLocaleDateString() : 'Unknown date';
        const shortSha = build.tag ? build.tag.split('-').pop() : 'unknown';
        return `${date} - ${shortSha}`;
      }

      function onBuildChange(platform) {
        const select = platform === 'ios' ? iosBuildSelect : androidBuildSelect;
        const selectedIndex = select.value;

        if (selectedIndex === '') {
          // No selection
          if (platform === 'ios') {
            iosBuildInfo.textContent = '';
            iosInstallButton.classList.add('disabled');
            iosInstallButton.setAttribute('aria-disabled', 'true');
          } else {
            androidBuildInfo.textContent = '';
            androidInstallButton.classList.add('disabled');
            androidInstallButton.setAttribute('aria-disabled', 'true');
          }
          return;
        }

        const builds = allBuilds.filter(b => b.platform === platform);
        const build = builds[parseInt(selectedIndex)];

        if (platform === 'ios') {
          setupIOSBuild(build);
        } else {
          setupAndroidBuild(build);
        }
      }

      function setupIOSBuild(build) {
        iosBuildInfo.textContent = formatBuildInfo(build);
        if (build.manifest_url && build.artifact_url) {
          const encodedManifest = encodeURIComponent(build.manifest_url);
          iosInstallButton.setAttribute('href', `itms-services://?action=download-manifest&url=${encodedManifest}`);
          iosInstallButton.setAttribute('data-manifest', build.manifest_url);
          iosInstallButton.setAttribute('data-platform', 'ios');
          iosInstallButton.classList.remove('disabled');
          iosInstallButton.removeAttribute('aria-disabled');
        } else {
          iosBuildInfo.textContent = 'iOS build not available';
          iosInstallButton.classList.add('disabled');
          iosInstallButton.setAttribute('aria-disabled', 'true');
        }
      }

      function setupAndroidBuild(build) {
        androidBuildInfo.textContent = formatBuildInfo(build);
        if (build.artifact_url) {
          androidInstallButton.setAttribute('href', build.artifact_url);
          androidInstallButton.setAttribute('data-platform', 'android');
          androidInstallButton.classList.remove('disabled');
          androidInstallButton.removeAttribute('aria-disabled');
        } else {
          androidBuildInfo.textContent = 'Android build not available';
          androidInstallButton.classList.add('disabled');
          androidInstallButton.setAttribute('aria-disabled', 'true');
        }
      }

      window.onBuildChange = onBuildChange;

      function attemptInstall(event) {
        const button = event.currentTarget;
        const platform = button.getAttribute('data-platform');
        const installHref = button.getAttribute('href');
        
        if (button.classList.contains('disabled') || !installHref) {
          event.preventDefault();
          alert('Build not available.');
          return;
        }
        
        // For Android, just proceed with download
        if (platform === 'android') {
          return; // Let browser handle the download
        }
        
        // iOS-specific manifest checking
        event.preventDefault();
        const manifestUrl = button.getAttribute('data-manifest');
        if (!manifestUrl) {
          alert('Manifest URL is missing.');
          return;
        }

        const showFailure = (message) => {
          alert('Unable to start install: ' + message + '\n\nPlease try again or contact support.');
        };

        fetch(manifestUrl + '?t=' + Date.now(), { method: 'GET', cache: 'no-store' })
          .then(async (response) => {
            if (!response.ok) {
              throw new Error(`Manifest returned HTTP ${response.status}`);
            }
            const manifestText = await response.text();
            const hasPlaceholders = /\{[a-z_]+\}/i.test(manifestText);
            if (hasPlaceholders) {
              throw new Error('Manifest still has unreplaced placeholders.');
            }
            window.location.href = installHref;
          })
          .catch((error) => {
            showFailure(error.message);
          });
      }

      window.attemptInstall = attemptInstall;

      // Load builds and setup UI
      fetch(buildsEndpoint)
        .then((response) => response.json())
        .then((builds) => {
          if (!Array.isArray(builds)) {
            throw new Error('Unexpected builds payload.');
          }

          allBuilds = builds;
          loadingSection.style.display = 'none';

          // Sort by published_at descending (most recent first)
          const iosBuilds = builds.filter(b => b.platform === 'ios')
            .sort((a, b) => new Date(b.published_at) - new Date(a.published_at));
          const androidBuilds = builds.filter(b => b.platform === 'android')
            .sort((a, b) => new Date(b.published_at) - new Date(a.published_at));

          // Populate iOS dropdown
          if (iosBuilds.length > 0) {
            iosBuilds.forEach((build, index) => {
              const option = document.createElement('option');
              option.value = index;
              option.textContent = formatSelectOption(build);
              iosBuildSelect.appendChild(option);
            });
            // Auto-select most recent
            iosBuildSelect.value = '0';
            allBuilds = iosBuilds.concat(androidBuilds); // Update allBuilds with sorted order
            setupIOSBuild(iosBuilds[0]);
            iosSection.style.display = 'block';
          }

          // Populate Android dropdown
          if (androidBuilds.length > 0) {
            androidBuilds.forEach((build, index) => {
              const option = document.createElement('option');
              option.value = index;
              option.textContent = formatSelectOption(build);
              androidBuildSelect.appendChild(option);
            });
            // Auto-select most recent
            androidBuildSelect.value = '0';
            allBuilds = iosBuilds.concat(androidBuilds); // Update allBuilds with sorted order
            setupAndroidBuild(androidBuilds[0]);
            androidSection.style.display = 'block';
          }

          if (iosBuilds.length === 0 && androidBuilds.length === 0) {
            loadingSection.innerHTML = '<p>No builds available</p>';
            loadingSection.style.display = 'block';
          }
        })
        .catch((error) => {
          console.error('Failed to fetch builds:', error);
          loadingSection.innerHTML = '<p>Failed to load builds</p>';
        });
    </script>
  </body>
</html>
