// 1. Strict TypeScript Interface for Complete Image SEO Data
interface ImageSEOData {
  contentUrl: string;
  alt: string;             // 🟢 Alt Text
  title: string;           // Title Attribute
  caption: string;         // Caption Text
  description: string;     // Description
  category: string;        // Category / Type
  width: number;           // DYNAMIC naturalWidth
  height: number;          // DYNAMIC naturalHeight
  focalPoint: string;      // DYNAMIC focal point
  creditText: string;      // STATIC: "Images by Bsetec Pvt.Ltd"
  licenseUrl: string;      // STATIC: License Page URL
}

class ImageSEOManager {
  private images: NodeListOf<HTMLImageElement>;
  private static readonly CREDIT_TEXT = 'Images by Bsetec Pvt.Ltd';
  private static readonly LICENSE_URL = 'https://bsetectrainingcenter.in/terms';

  constructor(selector: string = 'img[data-caption], img[data-description], img.lms-img, img[data-seo]') {
    this.images = document.querySelectorAll<HTMLImageElement>(selector);
    this.initSEOEngine();
  }

  private async initSEOEngine(): Promise<void> {
    await this.ensureImagesLoaded();
    this.fixMissingAltAttributes(); // 🟢 Auto-fix missing alt in DOM
    this.applyDynamicFocalPoints();
    this.injectGoogleSchemaJSONLD();
    this.setupAccessibilityToggles();
  }

  private ensureImagesLoaded(): Promise<void[]> {
    const promises = Array.from(this.images).map((img) => {
      if (img.complete && img.naturalWidth !== 0) {
        return Promise.resolve();
      }
      return new Promise<void>((resolve) => {
        img.onload = () => resolve();
        img.onerror = () => resolve();
      });
    });
    return Promise.all(promises);
  }

  // 🟢 2. AUTO-FIX MISSING ALT TAGS IN THE HTML DOM
  private fixMissingAltAttributes(): void {
    this.images.forEach((img, index) => {
      if (!img.alt || img.alt.trim() === '') {
        // If alt is missing, auto-generate alt text from title or fallback name
        const generatedAlt = img.title ? img.title : `BSETEC Training Center Course Asset ${index + 1}`;
        img.alt = generatedAlt;
        console.warn(`⚠️ [SEO Fixed] Image #${index + 1} was missing 'alt'. Auto-assigned: "${generatedAlt}"`);
      }
    });
  }

  // 3. CATEGORY DETECTOR (Portfolio, Case Study, Blog Cover, Course Media)
  private detectImageCategory(img: HTMLImageElement): string {
    const explicitCategory = img.getAttribute('data-category');
    if (explicitCategory && explicitCategory.trim() !== '') {
      return explicitCategory;
    }

    const src = img.src.toLowerCase();
    const parentClasses = img.closest('section, article, div, figure')?.className.toLowerCase() || '';

    if (src.includes('/portfolio/') || parentClasses.includes('portfolio')) return 'Portfolio';
    if (src.includes('/case-study/') || src.includes('/casestudy/') || parentClasses.includes('case-study')) return 'Case Study';
    if (src.includes('/blog/') || parentClasses.includes('blog')) return 'Blog Cover';
    if (src.includes('banner') || parentClasses.includes('hero')) return 'Course Banner';
    if (src.includes('certificate') || parentClasses.includes('certificate')) return 'Certificate';

    return 'Course Media';
  }

  // 4. DYNAMIC FOCAL POINT
  private calculateDynamicFocalPoint(img: HTMLImageElement): string {
    const width = img.naturalWidth || 1200;
    const height = img.naturalHeight || 630;
    const aspectRatio = width / height;

    if (aspectRatio > 1.7) return 'center right';
    if (aspectRatio < 0.85) return 'top center';
    return 'center center';
  }

  private applyDynamicFocalPoints(): void {
    this.images.forEach((img) => {
      const focalPoint = this.calculateDynamicFocalPoint(img);
      img.style.objectFit = 'cover';
      img.style.objectPosition = focalPoint;
    });
  }

  // 🟢 5. INJECT GOOGLE SCHEMA JSON-LD WITH DYNAMIC ATTRIBUTES & @GRAPH WRAPPER
  private injectGoogleSchemaJSONLD(): void {
    const schemaList: object[] = [];

    this.images.forEach((img) => {
      const card = img.closest('.card, article, figure');
      const domCaption = card?.querySelector('.caption-text, figcaption')?.textContent?.trim();
      const domDesc = card?.querySelector('.image-description p')?.textContent?.trim();

      // 🟢 DYNAMICALLY EXTRACT ATTRIBUTES (IMAGE LEVEL ATTRIBUTES FIRST, DOM FALLBACK SECOND)
      const titleText = img.getAttribute('title') || img.title || img.alt || 'BSETEC Training Center Course Image';
      const altText = img.alt || titleText;
      const captionText = img.getAttribute('data-caption') || domCaption || '';
      const descriptionText = img.getAttribute('data-description') || domDesc || `${altText}. ${ImageSEOManager.CREDIT_TEXT}`;

      const seoData: ImageSEOData = {
        contentUrl: img.src,
        alt: altText,                                   // 🟢 ALT TEXT
        title: titleText,
        caption: captionText,
        description: descriptionText,
        category: this.detectImageCategory(img),
        width: img.naturalWidth || 1200,
        height: img.naturalHeight || 630,
        focalPoint: this.calculateDynamicFocalPoint(img),
        creditText: ImageSEOManager.CREDIT_TEXT,
        licenseUrl: ImageSEOManager.LICENSE_URL
      };

      // 🟢 Google Schema.org ImageObject INCLUDING DYNAMIC ATTRIBUTES
      schemaList.push({
        "@type": "ImageObject",
        "contentUrl": seoData.contentUrl,
        "name": seoData.title,
        "alternateName": seoData.alt,                  // 🟢 MAPS ALT TEXT FOR GOOGLE
        "caption": seoData.caption,
        "description": seoData.description,
        "category": seoData.category,
        "genre": seoData.category,
        "width": {
          "@type": "QuantitativeValue",
          "value": seoData.width,
          "unitText": "PX"
        },
        "height": {
          "@type": "QuantitativeValue",
          "value": seoData.height,
          "unitText": "PX"
        },
        "creator": {
          "@type": "Organization",
          "name": "Bsetec Pvt.Ltd"
        },
        "copyrightHolder": {
          "@type": "Organization",
          "name": "Bsetec Pvt.Ltd"
        },
        "copyrightNotice": `© ${new Date().getFullYear()} Bsetec Pvt.Ltd. All rights reserved.`,
        "creditText": seoData.creditText,
        "license": seoData.licenseUrl,
        "acquireLicensePage": seoData.licenseUrl
      });
    });

    if (schemaList.length > 0) {
      const schemaGraph = {
        "@context": "https://schema.org",
        "@graph": schemaList
      };

      // Inject JSON-LD Script tag into HTML <head>
      const script = document.createElement('script');
      script.type = 'application/ld+json';
      script.text = JSON.stringify(schemaGraph, null, 2);
      document.head.appendChild(script);

      console.log('✅ [SEO Success] Google Schema.org JSON-LD Injected with dynamic attributes:', schemaGraph);
    }
  }

  private setupAccessibilityToggles(): void {
    const toggleButtons = document.querySelectorAll<HTMLButtonElement>('.btn-toggle');
    toggleButtons.forEach((btn) => {
      btn.addEventListener('click', (e: Event) => {
        const button = e.currentTarget as HTMLButtonElement;
        const targetId = button.getAttribute('data-target');
        if (!targetId) return;

        const descBox = document.getElementById(targetId);
        if (descBox) {
          descBox.classList.toggle('hidden');
          const isExpanded = !descBox.classList.contains('hidden');
          button.setAttribute('aria-expanded', isExpanded.toString());
          descBox.setAttribute('aria-hidden', (!isExpanded).toString());
        }
      });
    });
  }
}

document.addEventListener('DOMContentLoaded', () => {
  new ImageSEOManager();
});