import { Injectable, inject, signal } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import { toPng } from 'html-to-image';

@Injectable({ providedIn: 'root' })
export class ScreenshotService {
  private document = inject(DOCUMENT);

  capturing = signal(false);
  lastError = signal('');

  async captureScreen(): Promise<string> {
    this.capturing.set(true);
    this.lastError.set('');

    // Hide ONLY feedback UI — keep other app dialogs/popups visible for the screenshot
    const hidden: HTMLElement[] = [];
    // Hide the feedback FAB button
    const fab = this.document.getElementById('feedback-fab');
    if (fab) { hidden.push(fab); fab.style.setProperty('display', 'none', 'important'); }
    // Hide only the feedback dialog mask (find mask that contains .feedback-modal-dialog)
    this.document.querySelectorAll('.p-dialog-mask').forEach((mask: Element) => {
      if (mask.querySelector('.feedback-modal-dialog')) {
        hidden.push(mask as HTMLElement);
        (mask as HTMLElement).style.setProperty('display', 'none', 'important');
      }
    });

    try {
      const dataUrl = await toPng(this.document.body, {
        quality: 0.95,
        pixelRatio: Math.min(window.devicePixelRatio || 1, 2),
        cacheBust: true,
        filter: (node: HTMLElement) => {
          const id = node.id || '';
          return !id.startsWith('feedback-inspector') && id !== 'feedback-fab';
        },
      });

      if (!dataUrl || dataUrl === 'data:,') {
        throw new Error('Empty screenshot captured');
      }

      this.capturing.set(false);
      return dataUrl;
    } catch (err: any) {
      this.lastError.set(err?.message || 'Screenshot capture failed');
      this.capturing.set(false);
      throw err;
    } finally {
      hidden.forEach((el) => el.style.removeProperty('display'));
    }
  }

  fileToDataUrl(file: File): Promise<string> {
    return new Promise((resolve, reject) => {
      if (!file.type.startsWith('image/')) {
        reject(new Error('Not an image file'));
        return;
      }
      const reader = new FileReader();
      reader.onload = () => resolve(reader.result as string);
      reader.onerror = () => reject(new Error('Failed to read file'));
      reader.readAsDataURL(file);
    });
  }
}
