import { inject, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { LoggerService } from './logger.service';

@Injectable({ providedIn: 'root' })
export class FastIconService {
  private loaded = false;
  private http = inject(HttpClient);
  private logger = inject(LoggerService);

  loadSprite(): Promise<void> {
    if (this.loaded) return Promise.resolve();

    return new Promise((resolve) => {
      this.http
        .get('assets/iconlibrary.html', { responseType: 'text' })
        .subscribe({
          next: (svgContent) => {
            // Create a temporary container
            const parser = new DOMParser();
            const doc = parser.parseFromString(svgContent, 'image/svg+xml');

            // Get the SVG element
            const svg = doc.querySelector('svg');

            if (!svg) {
              console.error('No SVG element found in sprite');
              resolve();
              return;
            }

            // Create wrapper div
            const div = document.createElement('div');
            div.style.display = 'none';
            div.setAttribute('aria-hidden', 'true');
            div.id = 'svg-sprite-container';

            // Append the SVG to the div
            div.appendChild(svg);

            // Insert at the beginning of body
            document.body.insertBefore(div, document.body.firstChild);

            const symbolCount = svg.querySelectorAll('symbol').length;
            this.logger.log(`✓ Icons loaded: ${symbolCount}`);

            this.loaded = true;
            resolve();
          },
          error: (err) => {
            console.error('Failed to load icon sprite:', err);
            resolve();
          },
        });
    });
  }
}
