/**
 * shareContent — builds a canonical deep-link URL and shares it.
 *
 * Strategy:
 *  1. navigator.share()  — native share sheet on mobile/PWA
 *  2. navigator.clipboard.writeText() — copy to clipboard on desktop
 *  3. prompt() fallback  — for browsers with no clipboard API (very rare)
 *
 * Returns: "shared" | "copied" | "fallback"
 */

export type ShareResult = "shared" | "copied" | "fallback";

export interface ShareOptions {
  title: string;
  /** Relative path that will be combined with window.location.origin */
  path: string;
  text?: string;
}

export async function shareContent(opts: ShareOptions): Promise<ShareResult> {
  if (typeof window === "undefined") return "fallback";

  const url = `${window.location.origin}${opts.path}`;

  // Native share sheet (mobile, PWA)
  if (typeof navigator.share === "function") {
    try {
      await navigator.share({ title: opts.title, text: opts.text ?? opts.title, url });
      return "shared";
    } catch {
      // User dismissed or share failed — fall through to clipboard
    }
  }

  // Clipboard API
  if (typeof navigator.clipboard?.writeText === "function") {
    try {
      await navigator.clipboard.writeText(url);
      return "copied";
    } catch {
      // Clipboard write blocked — fall through
    }
  }

  // Last resort: prompt so the user can manually copy
  window.prompt("Copy this link:", url);
  return "fallback";
}

/** Build the correct deep-link path for a given content type and ID. */
export function contentSharePath(contentType: number, id: string | number): string {
  switch (contentType) {
    case 1: return `/video/${id}`;
    case 2:
    case 4:
    case 6: return `/content/${contentType}/${id}`;
    case 3: return `/reel/${id}`;
    default: return `/video/${id}`;
  }
}
