export const STORY_WIDTH = 1080;
export const STORY_HEIGHT = 1920;
export const FEED_WIDTH = 1080;
export const FEED_HEIGHT = 1350;
export const STORY_COPY = 'Tried on with Aisthetix';
export const AISTHETIX_WORDMARK = 'aisthetix';
export const CREATED_WITH_COPY = 'created with';
export const AISTHETIX_WATERMARK_OPACITY = 0.72;

export type ShareFormat = 'story' | 'feed';
export type ShareChannel = 'instagram_stories' | 'instagram_feed' | 'whatsapp_status' | 'whatsapp_message';
export type ShareCapability = 'file_share' | 'url_share' | 'download_clipboard' | 'download_only' | 'unavailable';
export type ShareOutcome = 'share_sheet_closed' | 'cancelled' | 'fallback_ready' | 'failed';
export type SharePayloadMode = 'file_text' | 'file_only' | 'link_only' | 'none';

export interface ShareMetadata {
  productName: string;
  productUrl: string | null;
  merchantName?: string | null;
  merchantDomain?: string | null;
}

export interface ShareSheetResult {
  capability: ShareCapability;
  outcome: ShareOutcome;
  payloadMode: SharePayloadMode;
}

export interface Rect { x: number; y: number; width: number; height: number }

const FORMAT = {
  story: {
    width: STORY_WIDTH, height: STORY_HEIGHT,
    image: { x: 72, y: 120, width: 936, height: 1212 },
    card: { x: 48, y: 96, width: 984, height: 1260 },
    merchantY: 1490, domainY: 1560,
  },
  feed: {
    width: FEED_WIDTH, height: FEED_HEIGHT,
    image: { x: 72, y: 96, width: 936, height: 772 },
    card: { x: 48, y: 72, width: 984, height: 820 },
    merchantY: 1006, domainY: 1068,
  },
} as const;

/** Draws the quiet lowercase landing-page wordmark lockup. */
export function drawAisthetixMark(
  context: CanvasRenderingContext2D,
  right: number,
  centerY: number,
  scale = 1
): void {
  context.save();
  context.globalAlpha = AISTHETIX_WATERMARK_OPACITY;
  context.shadowColor = 'rgba(0, 0, 0, 0.45)';
  context.shadowBlur = 8 * scale;
  context.fillStyle = '#ffffff';
  context.textBaseline = 'middle';
  context.textAlign = 'right';
  context.font = `500 ${13 * scale}px "Helvetica Neue", Arial, sans-serif`;
  context.fillText(CREATED_WITH_COPY, right - (160 * scale), centerY, 80 * scale);
  context.textAlign = 'right';
  context.font = `600 ${38 * scale}px "Helvetica Neue", Arial, sans-serif`;
  context.fillText(AISTHETIX_WORDMARK, right, centerY, 190 * scale);
  context.restore();
}

export function containRect(sourceWidth: number, sourceHeight: number, bounds: Rect): Rect {
  if (sourceWidth <= 0 || sourceHeight <= 0) throw new Error('invalid image dimensions');
  const scale = Math.min(bounds.width / sourceWidth, bounds.height / sourceHeight);
  const width = sourceWidth * scale;
  const height = sourceHeight * scale;
  return { x: bounds.x + (bounds.width - width) / 2, y: bounds.y + (bounds.height - height) / 2, width, height };
}

export function readableMerchantDomain(metadata: ShareMetadata): string {
  const source = metadata.merchantDomain?.trim() || metadata.productUrl?.trim() || '';
  if (!source) return '';
  try {
    return new URL(/^https?:\/\//i.test(source) ? source : `https://${source}`).hostname.replace(/^www\./i, '');
  } catch {
    return source.replace(/^https?:\/\//i, '').split('/')[0].replace(/^www\./i, '');
  }
}

/** Merchant identity stays below the image; the quiet mark is overlaid inside the photo. */
export function drawShareComposition(
  context: CanvasRenderingContext2D,
  image: CanvasImageSource,
  sourceWidth: number,
  sourceHeight: number,
  metadata: ShareMetadata,
  format: ShareFormat
): Rect {
  const layout = FORMAT[format];
  const domain = readableMerchantDomain(metadata);
  const merchant = metadata.merchantName?.trim() || domain;
  context.fillStyle = '#0b1020';
  context.fillRect(0, 0, layout.width, layout.height);
  context.fillStyle = '#171f35';
  context.fillRect(layout.card.x, layout.card.y, layout.card.width, layout.card.height);
  const target = containRect(sourceWidth, sourceHeight, layout.image);
  context.drawImage(image, target.x, target.y, target.width, target.height);
  context.textAlign = 'center';
  context.textBaseline = 'middle';
  context.fillStyle = '#ffffff';
  context.font = '600 32px Arial, sans-serif';
  context.fillText(merchant, layout.width / 2, layout.merchantY, 900);
  context.font = '500 28px Arial, sans-serif';
  context.fillStyle = '#cbd5e1';
  context.fillText(domain, layout.width / 2, layout.domainY, 900);
  const watermarkScale = Math.max(0.55, Math.min(1, target.width / 936));
  drawAisthetixMark(
    context,
    target.x + target.width - (24 * watermarkScale),
    target.y + target.height - (38 * watermarkScale),
    watermarkScale
  );
  return target;
}

function loadImage(source: string): Promise<HTMLImageElement> {
  return new Promise((resolve, reject) => {
    const image = new Image();
    image.decoding = 'async';
    if (/^https?:/i.test(source)) image.crossOrigin = 'anonymous';
    image.onload = () => resolve(image);
    image.onerror = () => reject(new Error('share image could not be decoded'));
    image.src = source;
  });
}

/** Creates a separate PNG. The raw result is never an export fallback. */
export async function composeShareImage(source: string, metadata: ShareMetadata, format: ShareFormat): Promise<Blob> {
  const image = await loadImage(source);
  const layout = FORMAT[format];
  const canvas = document.createElement('canvas');
  canvas.width = layout.width;
  canvas.height = layout.height;
  const context = canvas.getContext('2d');
  if (!context) throw new Error('canvas unavailable');
  drawShareComposition(context, image, image.naturalWidth || image.width, image.naturalHeight || image.height, metadata, format);
  return new Promise((resolve, reject) => {
    try {
      canvas.toBlob((blob) => blob ? resolve(blob) : reject(new Error('share image export failed')), 'image/png');
    } catch {
      reject(new Error('share image export failed'));
    }
  });
}

export function shareFile(blob: Blob, format: ShareFormat): File {
  return new File([blob], `aisthetix-try-on-${format}.png`, { type: 'image/png' });
}

export function buildShareMessage(metadata: ShareMetadata): string {
  return [metadata.productName.trim(), metadata.productUrl?.trim(), STORY_COPY].filter(Boolean).join('\n');
}

function canShare(nav: Navigator, data: ShareData): boolean {
  try { return typeof nav.canShare === 'function' && nav.canShare(data); } catch { return false; }
}

/** Device class determines the UX; file capability is checked independently. */
export function isMobileShareDevice(nav: Navigator = navigator): boolean {
  const hint = (nav as Navigator & { userAgentData?: { mobile?: boolean } }).userAgentData?.mobile;
  if (typeof hint === 'boolean') return hint;
  return /Android|iPhone|iPad|iPod/i.test(nav.userAgent || '')
    || (/Macintosh/i.test(nav.userAgent || '') && nav.maxTouchPoints > 1);
}

export function detectSharePayloadMode(file: File, metadata: ShareMetadata, nav: Navigator = navigator): SharePayloadMode {
  // Validate the file by itself first: browsers can ignore unknown properties
  // and otherwise report true for a text payload with unsupported files.
  if (typeof nav.share !== 'function' || !canShare(nav, { files: [file] })) return 'none';
  const common = { title: metadata.productName || STORY_COPY, text: buildShareMessage(metadata) };
  return canShare(nav, { ...common, files: [file] }) ? 'file_text' : 'file_only';
}

export function detectShareCapability(file: File, nav: Navigator = navigator, metadata: ShareMetadata = { productName: '', productUrl: null }): ShareCapability {
  const mode = detectSharePayloadMode(file, metadata, nav);
  if (mode === 'file_text' || mode === 'file_only') return 'file_share';
  if (typeof document !== 'undefined') return typeof nav.clipboard?.writeText === 'function' ? 'download_clipboard' : 'download_only';
  return 'unavailable';
}

export async function openShareSheet(file: File, metadata: ShareMetadata, nav: Navigator = navigator): Promise<ShareSheetResult> {
  const payloadMode = detectSharePayloadMode(file, metadata, nav);
  if (payloadMode === 'none' || typeof nav.share !== 'function') {
    return { capability: detectShareCapability(file, nav, metadata), outcome: 'fallback_ready', payloadMode: 'none' };
  }
  const data: ShareData = payloadMode === 'file_text'
    ? { title: metadata.productName || STORY_COPY, text: buildShareMessage(metadata), files: [file] }
    : { files: [file] };
  try {
    await nav.share(data);
    return { capability: 'file_share', outcome: 'share_sheet_closed', payloadMode };
  } catch (error) {
    return { capability: 'file_share', outcome: error instanceof DOMException && error.name === 'AbortError' ? 'cancelled' : 'failed', payloadMode };
  }
}

export function downloadShareImage(blob: Blob, format: ShareFormat): void {
  const url = URL.createObjectURL(blob);
  const anchor = document.createElement('a');
  anchor.href = url;
  anchor.download = `aisthetix-try-on-${format}.png`;
  anchor.rel = 'noopener';
  document.body.appendChild(anchor);
  try { anchor.click(); } finally {
    anchor.remove();
    // WebKit and embedded browsers can consume the URL after this task ends.
    setTimeout(() => URL.revokeObjectURL(url), 30_000);
  }
}

export async function copyProductLink(productUrl: string, nav: Navigator = navigator): Promise<boolean> {
  let timer: ReturnType<typeof setTimeout> | undefined;
  try {
    if (!nav.clipboard?.writeText) return false;
    // Clipboard permission may stay pending after focus changes.
    // Keep the downloaded image and controls usable in that case.
    return await Promise.race([
      nav.clipboard.writeText(productUrl).then(() => true),
      new Promise<boolean>((resolve) => { timer = setTimeout(() => resolve(false), 2000); }),
    ]);
  } catch { return false; }
  finally { if (timer !== undefined) clearTimeout(timer); }
}
