const MOBILE_OVERLAY_ID = 'asm-html-report-overlay';

export type HtmlReportHandle = {
  write: (html: string) => void;
  close: () => void;
};

const isMobileViewport = (): boolean =>
  typeof window !== 'undefined' && window.matchMedia('(max-width: 1023px)').matches;

export function toAbsoluteSiteUrl(url: string): string {
  if (!url) return url;
  if (/^https?:\/\//i.test(url)) return url;
  const origin = window.location.origin;
  return url.startsWith('/') ? `${origin}${url}` : `${origin}/${url}`;
}

function injectBaseTag(html: string): string {
  const baseHref = `${window.location.origin}/`;
  if (/<base[\s>]/i.test(html)) return html;
  if (/<head[^>]*>/i.test(html)) {
    return html.replace(/<head[^>]*>/i, match => `${match}<base href="${baseHref}">`);
  }
  return `<head><base href="${baseHref}"></head>${html}`;
}

function normalizeHtml(html: string): string {
  const trimmed = html.trim();
  if (/^<!DOCTYPE/i.test(trimmed) || /^<html/i.test(trimmed)) {
    return injectBaseTag(trimmed);
  }
  return injectBaseTag(`<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>${trimmed}</body></html>`);
}

export function showReportBlockedMessage(): void {
  window.alert('Please allow popups for this site to view the report.');
}

function removeMobileOverlay(): void {
  document.getElementById(MOBILE_OVERLAY_ID)?.remove();
}

function openMobileOverlay(initialHtml?: string): HtmlReportHandle | null {
  document.body.style.overflow = '';
  removeMobileOverlay();

  const overlay = document.createElement('div');
  overlay.id = MOBILE_OVERLAY_ID;
  overlay.style.cssText =
    'position:fixed;inset:0;z-index:2147483646;background:#fff;display:flex;flex-direction:column;height:100dvh;width:100vw;';

  const toolbar = document.createElement('div');
  toolbar.style.cssText =
    'display:flex;gap:8px;padding:8px 12px;border-bottom:1px solid #e5e7eb;background:#f9fafb;flex-shrink:0;';

  const printBtn = document.createElement('button');
  printBtn.type = 'button';
  printBtn.textContent = 'Print';
  printBtn.style.cssText =
    'min-height:44px;padding:0 16px;border-radius:8px;border:1px solid #d1d5db;background:#fff;font-size:14px;font-weight:600;';

  const closeBtn = document.createElement('button');
  closeBtn.type = 'button';
  closeBtn.textContent = 'Close';
  closeBtn.style.cssText =
    'min-height:44px;padding:0 16px;border-radius:8px;border:1px solid #d1d5db;background:#fff;font-size:14px;font-weight:600;margin-left:auto;';

  const iframe = document.createElement('iframe');
  iframe.title = 'Report';
  iframe.style.cssText = 'flex:1;width:100%;border:0;background:#fff;';

  let blobUrl: string | null = null;

  const setIframeHtml = (html: string) => {
    if (blobUrl) {
      URL.revokeObjectURL(blobUrl);
      blobUrl = null;
    }
    const normalized = normalizeHtml(html);
    const blob = new Blob([normalized], { type: 'text/html;charset=utf-8' });
    blobUrl = URL.createObjectURL(blob);
    iframe.src = blobUrl;
  };

  const close = () => {
    if (blobUrl) URL.revokeObjectURL(blobUrl);
    removeMobileOverlay();
  };

  printBtn.addEventListener('click', () => {
    try {
      iframe.contentWindow?.focus();
      iframe.contentWindow?.print();
    } catch {
      window.alert('Unable to print this report on this device.');
    }
  });
  closeBtn.addEventListener('click', close);

  toolbar.appendChild(printBtn);
  toolbar.appendChild(closeBtn);
  overlay.appendChild(toolbar);
  overlay.appendChild(iframe);
  document.body.appendChild(overlay);

  if (initialHtml) {
    setIframeHtml(initialHtml);
  }

  return {
    write: setIframeHtml,
    close,
  };
}

function openDesktopReport(initialHtml?: string): HtmlReportHandle | null {
  const win = window.open('', '_blank');
  if (!win) return null;

  if (initialHtml) {
    win.document.open();
    win.document.write(normalizeHtml(initialHtml));
    win.document.close();
  }

  return {
    write: (html: string) => {
      win.document.open();
      win.document.write(normalizeHtml(html));
      win.document.close();
    },
    close: () => win.close(),
  };
}

export function openHtmlReport(initialHtml?: string): HtmlReportHandle | null {
  if (isMobileViewport()) {
    return openMobileOverlay(initialHtml);
  }
  return openDesktopReport(initialHtml);
}
