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

test.describe('Comments', () => {
  const baseURL = process.env.BASE_URL || 'http://127.0.0.1:3001';

  test.beforeEach(async ({ page }) => {
    // Sign in before each test
    await page.goto(`${baseURL}/auth`);
    const usernameInput = page.getByPlaceholder(/Enter your username/i).or(page.locator('input').first());
    const passwordInput = page.getByPlaceholder(/Enter your password/i).or(page.locator('input[type="password"]'));
    const submitButton = page.getByRole('button', { name: /sign in|login|đăng nhập/i }).or(page.locator('button[type="submit"]')).first();
    
    
      await usernameInput.waitFor({ state: 'visible', timeout: 5000 });
      await usernameInput.fill('e2etest');
      await passwordInput.fill('Test12345!');
      await submitButton.click();
      await page.waitForURL(/.*app(\/.*)?/, { timeout: 15000 }).catch(() => {});
    } catch {
      console.log('Already logged in or auth form not visible');
    }
    await page.goto(`${baseURL}/`);
  });

  test('should create comment on memo', async ({ page }) => {
    // Wait for memos to load
    await page.waitForSelector('[data-testid="memo-card"], article, .memo-card', { timeout: 10000 }).catch(() => {});
    
    // Click on first memo to open detail page
    const firstMemo = page.locator('[data-testid="memo-card"], article, .memo-card').first();
    try {
      await firstMemo.waitFor({ state: 'visible', timeout: 5000 });
      await firstMemo.click();
      
      // Wait for memo detail page
      await page.waitForURL(/.*memos\/.*/, { timeout: 5000 });
      
      // Find and click "Write a comment" button
      const writeCommentButton = page.getByRole('button', { name: /write a comment|viết bình luận|comment/i }).or(
        page.getByText(/write a comment|viết/i)
      ).first();
      
      await writeCommentButton.waitFor({ state: 'visible', timeout: 5000 });
      await writeCommentButton.click();
      
      // Wait for comment editor to appear
      const commentEditor = page.locator('textarea').or(page.locator('[contenteditable="true"]')).first();
      await expect(commentEditor).toBeVisible({ timeout: 5000 });
      
      // Type comment
      await commentEditor.fill('This is a test comment from Playwright');
      
      // Submit comment (look for submit/save button)
      const submitButton = page.getByRole('button', { name: /submit|save|post|gửi/i }).or(
        page.locator('button[type="submit"]')
      ).first();
      
      await submitButton.waitFor({ state: 'visible', timeout: 5000 });
      await submitButton.click();
      
      // Wait for comment to appear
      await expect(page.getByText('This is a test comment from Playwright').first()).toBeVisible({ timeout: 10000 });
      
      // Verify comment count updates
      const commentCount = page.getByText(/comments?\s*\(\d+\)/i).or(page.getByText(/\d+\s*comment/i)).or(page.getByText(/bình luận\s*\(/i)).first();
      await expect(commentCount).toBeVisible({ timeout: 5000 });
    
  });

  test('should display comments list', async ({ page }) => {
    await page.waitForSelector('[data-testid="memo-card"], article, .memo-card', { timeout: 10000 }).catch(() => {});
    
    const firstMemo = page.locator('[data-testid="memo-card"], article, .memo-card').first();
    
      await firstMemo.waitFor({ state: 'visible', timeout: 5000 });
      await firstMemo.click();
      await page.waitForURL(/.*memos\/.*/, { timeout: 5000 });
      
      // Check if comments section exists
      const commentsSection = page.getByText(/comments|bình luận/i).first();
      await commentsSection.waitFor({ state: 'visible', timeout: 5000 });
      
      // Verify comments are displayed
      const comments = page.locator('[data-testid="comment"], .comment-item').or(page.locator('article').filter({ hasText: /comment|bình luận/i }));
      const commentCount = await comments.count();
      
      if (commentCount > 0) {
        // Verify comment content is visible
        await expect(comments.first()).toBeVisible();
      }
    
  });

  test('should show sign in prompt for anonymous users', async ({ page, context }) => {
    // Sign out first
    await context.clearCookies();
    
    // Navigate to public memo detail
    await page.goto(`${baseURL}/`);
    await page.waitForSelector('[data-testid="memo-card"], article, .memo-card', { timeout: 10000 }).catch(() => {});
    
    const firstMemo = page.locator('[data-testid="memo-card"], article, .memo-card').first();
    
      await firstMemo.waitFor({ state: 'visible', timeout: 5000 });
      await firstMemo.click();
      await page.waitForURL(/.*memos\/.*/, { timeout: 5000 });
      
      // Check for sign in prompt
      const signInPrompt = page.getByText(/sign in|login|đăng nhập/i).or(page.getByRole('button', { name: /sign in|login|đăng nhập/i })).first();
      await expect(signInPrompt).toBeVisible({ timeout: 5000 });
    
  });

  test('should redirect back to memo after sign in', async ({ page, context }) => {
    // Sign out
    await context.clearCookies();
    
    // Navigate to memo detail
    await page.goto(`${baseURL}/`);
    await page.waitForSelector('[data-testid="memo-card"], article, .memo-card', { timeout: 10000 }).catch(() => {});
    
    const firstMemo = page.locator('[data-testid="memo-card"], article, .memo-card').first();
    
      await firstMemo.waitFor({ state: 'visible', timeout: 5000 });
      await firstMemo.click();
      await page.waitForURL(/.*memos\/.*/, { timeout: 5000 });
      
      // Get current URL
      const memoUrl = page.url();
      
      // Click sign in button
      const signInButton = page.getByRole('button', { name: /sign in|login|đăng nhập/i }).first();
      await signInButton.waitFor({ state: 'visible', timeout: 5000 });
      await signInButton.click();
      
      // Sign in
      await page.waitForURL(/.*auth.*/, { timeout: 5000 });
      const usernameInput = page.getByPlaceholder(/Enter your username/i).or(page.locator('input').first());
      const passwordInput = page.getByPlaceholder(/Enter your password/i).or(page.locator('input[type="password"]'));
      const submitButton = page.getByRole('button', { name: /sign in|login|đăng nhập/i }).or(page.locator('button[type="submit"]')).first();
      
      await usernameInput.waitFor({ state: 'visible', timeout: 5000 });
      await usernameInput.fill('e2etest');
      await passwordInput.fill('Test12345!');
      await submitButton.click();
      
      // Should redirect back to memo detail
      await expect(page).toHaveURL(new RegExp(memoUrl.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')), { timeout: 10000 });
    
  });

  test('should update comment count after creating comment', async ({ page }) => {
    await page.waitForSelector('[data-testid="memo-card"], article, .memo-card', { timeout: 10000 }).catch(() => {});
    
    const firstMemo = page.locator('[data-testid="memo-card"], article, .memo-card').first();
    
      await firstMemo.waitFor({ state: 'visible', timeout: 5000 });
      await firstMemo.click();
      await page.waitForURL(/.*memos\/.*/, { timeout: 5000 });
      
      // Get initial comment count (if any)
      const initialCountText = await page.getByText(/comments?\s*\((\d+)\)|bình luận\s*\((\d+)\)/i).first().textContent().catch(() => '0');
      const initialCount = parseInt(initialCountText?.match(/\d+/)?.[0] || '0');
      
      // Create comment
      const writeCommentButton = page.getByRole('button', { name: /write a comment|viết/i }).first();
      await writeCommentButton.waitFor({ state: 'visible', timeout: 5000 });
      await writeCommentButton.click();
      
      const commentEditor = page.locator('textarea').or(page.locator('[contenteditable="true"]')).first();
      await commentEditor.fill('New comment for count test');
      
      const submitButton = page.getByRole('button', { name: /submit|save|post|gửi/i }).first();
      await submitButton.waitFor({ state: 'visible', timeout: 5000 });
      await submitButton.click();
      
      // Wait for comment count to update
      await expect(page.getByText(new RegExp(`(?:comments?|bình luận)\\s*\\(${initialCount + 1}\\)`, 'i'))).toBeVisible({ timeout: 10000 });
    
  });
});


