import { test, expect } from '@playwright/test';
import { BASE_URL, ensureLoggedIn } from './helpers/auth';

// ─────────────────────────────────────────────────────────────────────────────
// 7. DEADLINES — Quản lý hạn chót / task có deadline
// ─────────────────────────────────────────────────────────────────────────────
test.describe('7. Deadlines — Quản lý hạn chót', () => {
  test.beforeEach(async ({ page }) => {
    await ensureLoggedIn(page);
  });

  test('7.1 Điều hướng tới Deadlines qua sidebar', async ({ page }) => {
    // Navigation.tsx renders deadlines with id="header-deadlines"
    const deadlinesLink = page.locator('#header-deadlines');
    await deadlinesLink.waitFor({ state: 'visible', timeout: 12000 });
    await deadlinesLink.click();
    await expect(page).toHaveURL(/\/app\/deadlines/, { timeout: 12000 });
  });

  test('7.2 Deadlines page render không bị lỗi 500', async ({ page }) => {
    await page.goto(`${BASE_URL}/app/deadlines`, { waitUntil: 'domcontentloaded' });

    // Page should not show 500 error
    await expect(page.locator('body')).not.toContainText(/500 internal server error/i, { timeout: 10000 });

    // Should see either the deadline header or loading state
    const content = page
      .locator('.deadlines-page')
      .or(page.locator('.deadlines-loading'))
      .or(page.getByRole('heading', { name: /deadline/i }))
      .first();
    await expect(content).toBeVisible({ timeout: 15000 });
  });

  test('7.3 Deadline page hiển thị 4 sections (Overdue, Today, Upcoming, No Date)', async ({ page }) => {
    await page.goto(`${BASE_URL}/app/deadlines`, { waitUntil: 'domcontentloaded' });

    // Wait for loading to complete
    const loadingSpinner = page.locator('.deadlines-loading');
    try {
      await loadingSpinner.waitFor({ state: 'hidden', timeout: 15000 });
    } catch {
      // May already be hidden
    }

    // Check that all 4 sections render (visible via section headers)
    const sectionHeaders = page.locator('.deadline-section__header');
    const headerCount = await sectionHeaders.count();

    // Should have exactly 4 sections: overdue, today, upcoming, no_date
    expect(headerCount).toBe(4);

    // Verify specific section texts
    const sectionTexts = await sectionHeaders.allTextContents();
    const allTexts = sectionTexts.join(' ').toLowerCase();
    expect(allTexts).toContain('quá hạn');
    expect(allTexts).toContain('hôm nay');
    expect(allTexts).toContain('sắp tới');
    console.log('[7.3] Deadline sections rendered:', sectionTexts);
  });

  test('7.4 Toggle complete/incomplete trên deadline card', async ({ page }) => {
    await page.goto(`${BASE_URL}/app/deadlines`, { waitUntil: 'domcontentloaded' });

    // Wait for loading
    try {
      await page.locator('.deadlines-loading').waitFor({ state: 'hidden', timeout: 15000 });
    } catch {}

    // Find a deadline card
    const card = page.locator('.memo-deadline-card').first();
    try {
      await card.waitFor({ state: 'visible', timeout: 8000 });

      // Click the checkmark button to toggle complete
      const checkBtn = card.locator('.memo-deadline-card__check');
      await checkBtn.click();

      // Card should get the "--done" modifier class
      await page.waitForTimeout(1000);

      // Click again to undo
      await checkBtn.click();
      await page.waitForTimeout(1000);

      console.log('[7.4] Toggle complete/incomplete OK');
    } catch {
      // No deadline cards exist — that's OK (empty state)
      console.log('[7.4] No deadline cards found — page is empty, soft skip');
    }
  });

  test('7.5 DeadlineBadge hiển thị status chính xác', async ({ page }) => {
    await page.goto(`${BASE_URL}/app/deadlines`, { waitUntil: 'domcontentloaded' });

    try {
      await page.locator('.deadlines-loading').waitFor({ state: 'hidden', timeout: 15000 });
    } catch {}

    const cards = page.locator('.memo-deadline-card');
    const count = await cards.count();

    if (count > 0) {
      // Each card should have a DeadlineBadge with status info
      const firstCardBody = cards.first().locator('.memo-deadline-card__body');
      await expect(firstCardBody).toBeVisible({ timeout: 5000 });

      // Card should have a title (first line of content)
      const title = firstCardBody.locator('.memo-deadline-card__title');
      await expect(title).toBeVisible({ timeout: 5000 });
      const titleText = await title.textContent();
      expect((titleText ?? '').length).toBeGreaterThan(0);

      console.log(`[7.5] First deadline card title: "${titleText?.slice(0, 60)}"`);
    } else {
      console.log('[7.5] No deadline cards to verify — empty state OK');
    }
  });
});
