export function triggerFileDownload(htmlContent: string, filename: string): void {
  const blob = new Blob([htmlContent], { type: 'text/html' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  setTimeout(() => URL.revokeObjectURL(url), 1000);
}

export function downloadHtmlAsFile(htmlContent: string, filename: string): void {
  triggerFileDownload(htmlContent, filename);
}

export function printHtmlInIframe(htmlContent: string, timeoutMs = 30000): Promise<void> {
  const blob = new Blob([htmlContent], { type: 'text/html' });
  const url = URL.createObjectURL(blob);

  const iframe = document.createElement('iframe');
  iframe.style.position = 'fixed';
  iframe.style.left = '-10000px';
  iframe.style.top = '-10000px';
  iframe.style.width = '1px';
  iframe.style.height = '1px';
  iframe.style.border = 'none';
  document.body.appendChild(iframe);

  return new Promise((resolve, reject) => {
    const cleanup = () => {
      if (iframe.parentNode) document.body.removeChild(iframe);
      URL.revokeObjectURL(url);
    };

    const timer = setTimeout(() => {
      cleanup();
      reject(new Error('Print timed out'));
    }, timeoutMs);

    iframe.onload = () => {
      clearTimeout(timer);
      try {
        iframe.contentWindow?.print();
      } catch {
        // ignore
      }
      setTimeout(() => {
        cleanup();
        resolve();
      }, 5000);
    };

    iframe.onerror = () => {
      clearTimeout(timer);
      cleanup();
      reject(new Error('Failed to load print document'));
    };

    iframe.src = url;
  });
}