---
/**
 * DownloadButton — client-side OS detection download component.
 *
 * Detects the user's OS from navigator.userAgentData.platform (modern)
 * with navigator.platform fallback for older browsers. Detects Linux
 * architecture (ARM64 vs x86_64). macOS is always treated as Apple
 * Silicon (arm64) — there is no Intel macOS build.
 *
 * Builds ALL download URLs deterministically from the unified release
 * asset names (`genesis_desktop_{os}_{arch}.{format}`) hosted under the
 * geo-split mirror base https://genesis.evox.group/dl/ — a Cloudflare
 * Worker proxy: requests from the worker's PROXY_COUNTRIES set
 * (CN/RU/IR/KP/CU/SY — GitHub state-blocked/restricted regions) are
 * streamed through the Cloudflare edge (15-min cache); all other users
 * are 302-redirected to the original GitHub
 * https://github.com/EMI-Group/genesis/releases/latest/download/<asset>
 * URL. There is still NO GitHub API call and NO runtime network request
 * from the browser — the component renders instantly with zero network
 * dependency.
 *
 * Renders a labeled platform picker and release fallback on the server.
 * Client-side detection selects a desktop target; mobile users choose one.
 * Package links are inserted with DOM APIs and keep accessible platform labels.
 *
 * Localization: the optional `copy` prop carries the `downloadButton`
 * section of the landing copy manifest (src/lib/landing-copy/index.json).
 * When omitted (e.g. MDX docs pages) the component falls back to the
 * canonical English strings from the manifest. The client script cannot
 * see the prop, so it mirrors the same English defaults and overrides
 * them at runtime from window.__LANDING_COPY__.downloadButton (published
 * by the LandingPage component before this module runs).
 */
interface Props {
  copy?: Record<string, any>;
}

const { copy } = Astro.props;

/**
 * Canonical English defaults — mirror of the `downloadButton` section of
 * src/lib/landing-copy/index.json. The client script below keeps a copy
 * of these in sync; both MUST match the manifest.
 */
const DEFAULT_COPY = {
  or: "or",
  viewReleases: "view all releases on GitHub",
  alsoAvailable: "Also available",
  chooseManually: "Not on this platform? Choose manually",
  choosePlatform: "Choose a platform",
  selectYourPlatform: "Select your platform below:",
  download: "Download",
  downloadFor: "Download for ",
  systemRequirements:
    "System requirements: 1 CPU core, 200MB memory, 100MB disk space",
  platforms: {
    macOS: "macOS (Apple Silicon)",
    linuxX64: "Linux (x86_64)",
    linuxArm64: "Linux (ARM64)",
    windows: "Windows (x86_64)",
  },
};

/** Merged copy: the prop wins per key, English defaults fill the rest. */
const c = {
  ...DEFAULT_COPY,
  ...(copy ?? {}),
  platforms: { ...DEFAULT_COPY.platforms, ...(copy?.platforms ?? {}) },
};
---

<div class="dl-card">
  <div class="dl-picker">
    <label for="download-platform-select">{c.choosePlatform}</label>
    <select id="download-platform-select" class="dl-card-select">
      <option value="">{c.selectYourPlatform}</option>
    </select>
  </div>
  <div id="download-recommended" aria-live="polite"></div>
  <div id="download-alternatives"></div>
  <p class="dl-card-req">{c.systemRequirements}</p>
  <a class="dl-card-link" href="https://github.com/EMI-Group/genesis/releases/latest" target="_blank" rel="noopener">{c.viewReleases}<span aria-hidden="true"> ↗</span></a>
</div>

<style is:global>
  .dl-card {
    --bg: var(--nb-card);
    --ink: var(--nb-foreground);
    --gray-2: var(--nb-muted-foreground);
    --hairline: var(--nb-border-strong);
    --accent: #c8383c;
    --accent-hover: #ab2f33;
    display: flex; flex-direction: column; gap: 20px; min-width: 0;
    color: var(--ink); text-align: start;
  }
  .home-demo .dl-card { --bg: var(--download-surface); --ink: inherit; --gray-2: var(--gray); --hairline: var(--download-border); }
  .dl-card .dl-picker { display: grid; gap: 8px; }
  .dl-card label { font-size: 13px; font-weight: 600; color: var(--gray-2); }
  .dl-card .dl-card-select {
    width: 100%; min-height: 48px; padding: 10px 14px; font: inherit;
    font-size: 15px; color: var(--ink); background: var(--bg);
    border: 1px solid var(--hairline); border-radius: 10px; cursor: pointer;
  }
  .dl-card .dl-card-select:focus-visible, .dl-card a:focus-visible { outline: 2px solid var(--accent); outline-offset: 4px; }
  .dl-card .dl-recommended { display: flex; flex-direction: column; gap: 12px; }
  .dl-card .dl-btn-primary {
    display: inline-flex; align-items: center; justify-content: center; gap: 10px;
    min-height: 50px; padding: 12px 20px; border-radius: 999px;
    background: var(--accent); color: #fff; font-size: 16px; font-weight: 600;
    line-height: 1.5; text-decoration: none; transition: background .2s;
  }
  .dl-card .dl-btn-primary:hover { background: var(--accent-hover); color: #fff; }
  .dl-card .dl-os-icon { width: 18px; height: 18px; flex: none; }
  .dl-card .dl-alts { display: flex; align-items: center; flex-wrap: wrap; gap: 8px 12px; }
  .dl-card .dl-alt-label { color: var(--gray-2); font-size: 13px; }
  .dl-card .dl-btn-alt { display: inline-flex; align-items: center; min-height: 36px; padding: 4px 12px; border: 1px solid var(--hairline); border-radius: 8px; color: var(--ink); font-size: 14px; text-decoration: none; }
  .dl-card .dl-btn-alt:hover { border-color: var(--accent); }
  .dl-card .dl-card-req { border-top: 1px solid var(--hairline); padding-top: 18px; font-size: 13px; line-height: 1.7; color: var(--gray-2); }
  .dl-card .dl-card-link { width: fit-content; color: var(--gray-2); font-size: 14px; text-decoration: underline; text-underline-offset: 4px; }
  .dl-card .dl-card-link:hover { color: var(--ink); }
  .dl-card .dl-empty { font-size: 15px; line-height: 1.6; color: var(--gray-2); }
</style>

<script>
  // -- OS detection & download URL configuration ---------------------------

  interface DownloadAsset {
    label: string;
    url: string;
  }

  interface PlatformConfig {
    name: string;
    icon: string;
    recommended: DownloadAsset;
    alternatives: DownloadAsset[];
  }

  // `navigator.userAgentData` is not yet in the standard Navigator typings.
  interface NavigatorWithUserAgentData extends Navigator {
    userAgentData?: { platform?: string };
  }

  // -- Localized copy ------------------------------------------------------
  //
  // The LandingPage component publishes the full copy manifest as
  // window.__LANDING_COPY__ from an inline script at the top of the page
  // (inline scripts run during parsing; this bundled module is deferred,
  // so the global is always set on the landing page). On docs pages there
  // is no global — fall back to the canonical English strings below.
  // These MUST stay in sync with DEFAULT_COPY in the frontmatter above
  // (src/lib/landing-copy/index.json → `downloadButton`).
  const DEFAULT_COPY = {
    or: "or",
    viewReleases: "view all releases on GitHub",
    alsoAvailable: "Also available",
    chooseManually: "Not on this platform? Choose manually",
    choosePlatform: "Choose a platform",
    selectYourPlatform: "Select your platform below:",
    download: "Download",
    downloadFor: "Download for ",
    systemRequirements:
      "System requirements: 1 CPU core, 200MB memory, 100MB disk space",
    platforms: {
      macOS: "macOS (Apple Silicon)",
      linuxX64: "Linux (x86_64)",
      linuxArm64: "Linux (ARM64)",
      windows: "Windows (x86_64)",
    },
  };

  const landingCopy: Record<string, any> =
    (window as any).__LANDING_COPY__?.downloadButton ?? {};
  const copy = {
    ...DEFAULT_COPY,
    ...landingCopy,
    platforms: {
      ...DEFAULT_COPY.platforms,
      ...(landingCopy.platforms ?? {}),
    },
  };

  const MIRROR_BASE = "https://genesis.evox.group/dl";

  /**
   * Build a download URL for a unified release asset name via the smart
   * geo-split mirror (CN/RU/IR/KP/CU/SY proxied via the CF edge, others
   * 302'd to GitHub). Artifact names are deterministic
   * (`genesis_desktop_{os}_{arch}.{format}`), so no GitHub API lookup is
   * needed.
   */
  function assetUrl(asset: string): string {
    return `${MIRROR_BASE}/${asset}`;
  }

  // Static platform metadata with deterministic direct asset URLs.
  // Names and button labels come from the localized copy
  // (`downloadFor` + platform name composes the primary button label).
  const PLATFORMS: Record<string, PlatformConfig> = {
    "macos-arm64": {
      name: copy.platforms.macOS,
      icon: "/icons/os-macos.svg",
      recommended: {
        label: copy.downloadFor + copy.platforms.macOS,
        url: assetUrl("genesis_desktop_darwin_arm64.dmg"),
      },
      alternatives: [
        {
          label: ".app.zip",
          url: assetUrl("genesis_desktop_darwin_arm64.app.zip"),
        },
      ],
    },
    "linux-x86_64": {
      name: copy.platforms.linuxX64,
      icon: "/icons/os-linux.svg",
      recommended: {
        label: copy.downloadFor + copy.platforms.linuxX64,
        url: assetUrl("genesis_desktop_linux_x64.AppImage"),
      },
      alternatives: [
        { label: ".deb", url: assetUrl("genesis_desktop_linux_x64.deb") },
        { label: ".rpm", url: assetUrl("genesis_desktop_linux_x64.rpm") },
        { label: ".tar.gz", url: assetUrl("genesis_desktop_linux_x64.tar.gz") },
      ],
    },
    "linux-arm64": {
      name: copy.platforms.linuxArm64,
      icon: "/icons/os-linux.svg",
      recommended: {
        label: copy.downloadFor + copy.platforms.linuxArm64,
        url: assetUrl("genesis_desktop_linux_arm64.deb"),
      },
      alternatives: [
        { label: ".rpm", url: assetUrl("genesis_desktop_linux_arm64.rpm") },
      ],
    },
    "windows-x86_64": {
      name: copy.platforms.windows,
      icon: "/icons/os-windows.svg",
      recommended: {
        label: copy.downloadFor + copy.platforms.windows,
        url: assetUrl("genesis_desktop_windows_x64.exe"),
      },
      alternatives: [
        { label: ".msi", url: assetUrl("genesis_desktop_windows_x64.msi") },
      ],
    },
  };

  // -- OS detection --------------------------------------------------------

  function detectPlatform(): string | null {
    // Modern API first (navigator.userAgentData), fallback for older browsers
    const nav = navigator as NavigatorWithUserAgentData;
    let osPlatform: string;
    if (nav.userAgentData?.platform) {
      osPlatform = nav.userAgentData.platform;
    } else {
      osPlatform = navigator.platform ?? "";
    }

    const ua = navigator.userAgent ?? "";

    // Touch devices choose a desktop target explicitly.
    if (/Android|iPhone|iPad|iPod/i.test(ua) || (/Mac/i.test(osPlatform) && navigator.maxTouchPoints > 1)) return null;

    // macOS has no Intel build — every Mac gets the Apple Silicon asset.
    if (/mac/i.test(osPlatform)) return "macos-arm64";
    if (/win/i.test(osPlatform)) return "windows-x86_64";
    if (/linux/i.test(osPlatform)) {
      if (/aarch64|arm64/i.test(ua)) return "linux-arm64";
      return "linux-x86_64";
    }
    return null;
  }

  // Keep the selected platform, package and accessible label in sync.
  const detectedId = detectPlatform();
  const recEl = document.getElementById("download-recommended");
  const altEl = document.getElementById("download-alternatives");
  const platformSelect = document.getElementById("download-platform-select") as HTMLSelectElement | null;

  function renderPlatform(id: string): void {
    const p = PLATFORMS[id];
    if (!recEl || !altEl) return;
    recEl.replaceChildren();
    altEl.replaceChildren();
    if (!p) {
      const hint = document.createElement("p");
      hint.className = "dl-empty";
      hint.textContent = copy.selectYourPlatform;
      recEl.append(hint);
      return;
    }
    const link = document.createElement("a");
    link.href = p.recommended.url;
    link.className = "dl-btn-primary";
    link.setAttribute("aria-label", p.recommended.label);
    const extension = p.recommended.url.slice(p.recommended.url.lastIndexOf("."));
    link.textContent = `${copy.download} ${extension}`;
    const row = document.createElement("div");
    row.className = "dl-recommended";
    row.append(link);
    recEl.append(row);
    if (p.alternatives.length) {
      const alts = document.createElement("div");
      alts.className = "dl-alts";
      const label = document.createElement("span");
      label.className = "dl-alt-label";
      label.textContent = copy.alsoAvailable;
      alts.append(label);
      for (const asset of p.alternatives) {
        const a = document.createElement("a");
        a.href = asset.url;
        a.className = "dl-btn-alt";
        a.textContent = asset.label;
        a.setAttribute("aria-label", `${copy.downloadFor}${p.name} (${asset.label})`);
        alts.append(a);
      }
      altEl.append(alts);
    }
  }

  if (platformSelect) {
    for (const [id, p] of Object.entries(PLATFORMS)) {
      const option = document.createElement("option");
      option.value = id;
      option.textContent = p.name;
      platformSelect.append(option);
    }
    platformSelect.value = detectedId ?? "";
    platformSelect.addEventListener("change", () => renderPlatform(platformSelect.value));
    renderPlatform(platformSelect.value);
  }
</script>