import { test, expect } from '@playwright/test';

test.describe('Email Preview Logo', () => {
  test('should display SmoothSchedule logo in email preview', async ({ page }) => {
    // Increase timeout for this test
    test.setTimeout(90000);

    // Go directly to the business subdomain login
    await page.goto('http://pixel8ed.lvh.me:5173/login');
    await page.waitForLoadState('networkidle');

    // Login using input types
    const emailInput = page.locator('input[type="email"]');
    const passwordInput = page.locator('input[type="password"]');

    await expect(emailInput).toBeVisible({ timeout: 10000 });
    await emailInput.fill('timm50@hotmail.com');
    await passwordInput.fill('starry12');

    // Click sign in button
    await page.getByRole('button', { name: /sign in/i }).click();

    // Wait for navigation after login
    await page.waitForURL(/pixel8ed\.lvh\.me:5173/, { timeout: 15000 });
    await page.waitForLoadState('networkidle');
    await page.waitForTimeout(2000);

    // Navigate to email templates
    await page.goto('http://pixel8ed.lvh.me:5173/dashboard/settings/email-templates');
    await page.waitForLoadState('networkidle');
    await page.waitForTimeout(2000);

    // Click the first template's expand button
    const templateCards = page.locator('.space-y-4 > div');
    const firstCard = templateCards.first();
    const cardButtons = firstCard.locator('button');
    const buttonCount = await cardButtons.count();
    console.log(`Found ${buttonCount} buttons in first card`);

    if (buttonCount > 0) {
      await cardButtons.last().click();
      await page.waitForTimeout(1000);
    }

    // Click the Preview button
    const previewButton = page.getByRole('button', { name: /preview/i });
    await expect(previewButton).toBeVisible({ timeout: 5000 });
    await previewButton.click();

    // Wait for modal to appear
    await page.waitForTimeout(2000);

    // Find the iframe using frameLocator
    const iframeLocator = page.locator('iframe[title="Email Preview"]');
    await expect(iframeLocator).toBeVisible({ timeout: 5000 });

    // Wait for iframe content to load
    await page.waitForTimeout(1500);

    // Use frameLocator to access iframe content
    const frame = page.frameLocator('iframe[title="Email Preview"]');

    // Look for the branding section with the logo
    const brandingImg = frame.locator('img[alt="SmoothSchedule"]');

    // Scroll the iframe element itself to see the footer
    await brandingImg.scrollIntoViewIfNeeded();
    await page.waitForTimeout(500);

    // Check if image exists
    const imgCount = await brandingImg.count();
    console.log(`Found ${imgCount} SmoothSchedule logo image(s)`);

    if (imgCount > 0) {
      // Check if the image has a valid src (data URL)
      const imgSrc = await brandingImg.first().getAttribute('src');
      console.log(`Image src starts with: ${imgSrc?.substring(0, 50)}`);

      // Verify it's a data URL
      expect(imgSrc).toContain('data:image/png;base64');

      // Check all image attributes
      const width = await brandingImg.first().getAttribute('width');
      const height = await brandingImg.first().getAttribute('height');
      const style = await brandingImg.first().getAttribute('style');
      console.log(`Image attributes - width: ${width}, height: ${height}, style: ${style}`);

      // Check if image has natural dimensions (meaning it loaded)
      const naturalWidth = await brandingImg.first().evaluate((img: HTMLImageElement) => img.naturalWidth);
      const naturalHeight = await brandingImg.first().evaluate((img: HTMLImageElement) => img.naturalHeight);
      console.log(`Image natural dimensions: ${naturalWidth}x${naturalHeight}`);

      // Check computed/displayed dimensions
      const boundingBox = await brandingImg.first().boundingBox();
      console.log(`Image bounding box: ${JSON.stringify(boundingBox)}`);

      // Check if parent element is visible
      const parentHtml = await brandingImg.first().evaluate((img) => img.parentElement?.outerHTML);
      console.log(`Parent element: ${parentHtml?.substring(0, 300)}`);

      expect(naturalWidth).toBeGreaterThan(0);
      expect(naturalHeight).toBeGreaterThan(0);

      // Check if image is actually visible (has non-zero display dimensions)
      if (boundingBox) {
        console.log(`Image displayed at ${boundingBox.width}x${boundingBox.height} pixels`);
        expect(boundingBox.width).toBeGreaterThan(0);
        expect(boundingBox.height).toBeGreaterThan(0);
      }

      // Take screenshot focused on the branding area
      await page.screenshot({ path: 'test-results/email-preview-footer.png', fullPage: true });

      console.log('SUCCESS: Logo image loaded correctly');
    } else {
      // Debug: get the HTML
      const html = await frame.locator('body').innerHTML();
      console.log('Iframe body HTML:', html);

      throw new Error('SmoothSchedule logo image not found in iframe');
    }
  });
});
