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

test.describe('Comments', () => {
  test.beforeEach(async ({ page }) => {
    // Sign in before each test
    await page.goto('/auth');
    const emailInput = page.locator('input[type="email"]').or(page.locator('input[name="email"]')).first();
    const passwordInput = page.locator('input[type="password"]').first();
    const submitButton = page.getByRole('button', { name: /sign in/i }).or(page.locator('button[type="submit"]')).first();
    
    if (await emailInput.isVisible()) {
      await emailInput.fill('test@example.com');
      await passwordInput.fill('testpassword123');
      await submitButton.click();
      await page.waitForURL(/.*app.*/, { timeout: 10000 });
    }
  });

  test('should create comment on memo', async ({ page }) => {
    // Navigate to a memo detail page (assuming there's at least one memo)
    await page.goto('/app');
    
    // Wait for memos to load
    await page.waitForSelector('[data-testid="memo-card"]', { timeout: 10000 }).catch(() => {});
    
    // Click on first memo to open detail page
    const firstMemo = page.locator('[data-testid="memo-card"]').or(page.locator('article').first()).first();
    if (await firstMemo.isVisible()) {
      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/i }).or(
        page.getByText(/write a comment/i)
      ).first();
      
      if (await writeCommentButton.isVisible()) {
        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/i }).or(
          page.locator('button[type="submit"]')
        ).first();
        
        if (await submitButton.isVisible()) {
          await submitButton.click();
          
          // Wait for comment to appear
          await expect(page.getByText('This is a test comment from Playwright')).toBeVisible({ timeout: 10000 });
          
          // Verify comment count updates
          const commentCount = page.getByText(/comments?\s*\(\d+\)/i).or(page.getByText(/\d+\s*comment/i)).first();
          await expect(commentCount).toBeVisible({ timeout: 5000 });
        }
      }
    }
  });

  test('should display comments list', async ({ page }) => {
    // Navigate to memo with comments
    await page.goto('/app');
    await page.waitForSelector('[data-testid="memo-card"]', { timeout: 10000 }).catch(() => {});
    
    const firstMemo = page.locator('[data-testid="memo-card"]').or(page.locator('article').first()).first();
    if (await firstMemo.isVisible()) {
      await firstMemo.click();
      await page.waitForURL(/.*memos\/.*/, { timeout: 5000 });
      
      // Check if comments section exists
      const commentsSection = page.getByText(/comments/i).first();
      if (await commentsSection.isVisible()) {
        // Verify comments are displayed
        const comments = page.locator('[data-testid="comment"]').or(page.locator('article').filter({ hasText: /comment/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('/app');
    await page.waitForSelector('[data-testid="memo-card"]', { timeout: 10000 }).catch(() => {});
    
    const firstMemo = page.locator('[data-testid="memo-card"]').or(page.locator('article').first()).first();
    if (await firstMemo.isVisible()) {
      await firstMemo.click();
      await page.waitForURL(/.*memos\/.*/, { timeout: 5000 });
      
      // Check for sign in prompt
      const signInPrompt = page.getByText(/sign in|login/i).or(page.getByRole('button', { name: /sign in/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('/app');
    await page.waitForSelector('[data-testid="memo-card"]', { timeout: 10000 }).catch(() => {});
    
    const firstMemo = page.locator('[data-testid="memo-card"]').or(page.locator('article').first()).first();
    if (await firstMemo.isVisible()) {
      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/i }).first();
      if (await signInButton.isVisible()) {
        await signInButton.click();
        
        // Sign in
        await page.waitForURL(/.*auth.*/, { timeout: 5000 });
        const emailInput = page.locator('input[type="email"]').or(page.locator('input[name="email"]')).first();
        const passwordInput = page.locator('input[type="password"]').first();
        const submitButton = page.getByRole('button', { name: /sign in/i }).or(page.locator('button[type="submit"]')).first();
        
        if (await emailInput.isVisible()) {
          await emailInput.fill('test@example.com');
          await passwordInput.fill('testpassword123');
          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.goto('/app');
    await page.waitForSelector('[data-testid="memo-card"]', { timeout: 10000 }).catch(() => {});
    
    const firstMemo = page.locator('[data-testid="memo-card"]').or(page.locator('article').first()).first();
    if (await firstMemo.isVisible()) {
      await firstMemo.click();
      await page.waitForURL(/.*memos\/.*/, { timeout: 5000 });
      
      // Get initial comment count (if any)
      const initialCountText = await page.getByText(/comments?\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/i }).first();
      if (await writeCommentButton.isVisible()) {
        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/i }).first();
        if (await submitButton.isVisible()) {
          await submitButton.click();
          
          // Wait for comment count to update
          await expect(page.getByText(new RegExp(`comments?\\s*\\(${initialCount + 1}\\)`, 'i'))).toBeVisible({ timeout: 10000 });
        }
      }
    }
  });
});

