"use client";

import type { ComponentPropsWithoutRef, MouseEvent as ReactMouseEvent, ReactNode } from "react";
import { downloadPath, DOWNLOAD_FRAME_NAME, type DownloadOs } from "@/lib/downloads";

type DownloadButtonProps = Omit<ComponentPropsWithoutRef<"a">, "href"> & {
  os?: DownloadOs;
  children: ReactNode;
};

function triggerBackgroundDownload(url: string) {
  const existing = document.querySelector<HTMLIFrameElement>(
    `iframe[name="${DOWNLOAD_FRAME_NAME}"]`,
  );
  const frame = existing instanceof HTMLIFrameElement ? existing : document.createElement("iframe");

  if (!existing) {
    frame.id = DOWNLOAD_FRAME_NAME;
    frame.name = DOWNLOAD_FRAME_NAME;
    frame.style.display = "none";
    frame.setAttribute("aria-hidden", "true");
    document.body.appendChild(frame);
  }

  frame.src = url;
}

/** Shared CTA that hits `/api/download` (503 until env installer URLs are set). */
export function DownloadButton({
  os = "windows",
  children,
  onClick,
  target,
  ...rest
}: DownloadButtonProps) {
  const href = downloadPath(os);

  function handleClick(event: ReactMouseEvent<HTMLAnchorElement>) {
    onClick?.(event);
    if (event.defaultPrevented) return;

    const isPrimaryClick = event.button === 0;
    const hasModifier = event.metaKey || event.ctrlKey || event.shiftKey || event.altKey;

    if (!isPrimaryClick || hasModifier) return;

    event.preventDefault();
    triggerBackgroundDownload(href);
  }

  return (
    <a href={href} target={target ?? DOWNLOAD_FRAME_NAME} onClick={handleClick} {...rest}>
      {children}
    </a>
  );
}
