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

test.describe('Bug: Note visibility after creation', () => {
  test('should display note immediately after creation in inbox WITHOUT page refresh', async ({ page }) => {
    const timestamp = Date.now()

    // Step 1: Go to homepage
    await page.goto('/')
    await page.waitForLoadState('networkidle')
    await page.waitForTimeout(2000)

    // Step 2: Count notes before creation
    const notesBefore = await page.locator('[data-draggable="true"]').count()
    console.log('[TEST] Notes count before creation:', notesBefore)

    // Step 3: Create a test note in inbox
    const testNoteTitle = `TEST-${timestamp}-Visibility Inbox`
    const testNoteContent = `This is a test note to verify visibility bug. Timestamp: ${timestamp}`

    console.log('[TEST] Creating test note in inbox:', testNoteTitle)
    
    // Click the note input
    const noteInput = page.locator('input[placeholder*="Take a note"], textarea[placeholder*="Take a note"]').first()
    await noteInput.click()
    await page.waitForTimeout(500)

    // Fill title if input exists
    const titleInput = page.locator('input[placeholder*="Title"], input[name="title"]').first()
    if (await titleInput.count() > 0) {
      await titleInput.fill(testNoteTitle)
      await page.waitForTimeout(300)
    }

    // Fill content
    const contentInput = page.locator('textarea[placeholder*="Take a note"], textarea').first()
    await contentInput.fill(testNoteContent)
    await page.waitForTimeout(300)

    // Submit note
    const submitBtn = page.locator('button:has-text("Add"), button:has-text("Ajouter"), button[type="submit"]').first()
    await submitBtn.click()
    await page.waitForTimeout(2000)

    // Step 4: Verify note appears immediately WITHOUT refresh
    const notesAfter = await page.locator('[data-draggable="true"]').count()
    console.log('[TEST] Notes count after creation (NO REFRESH):', notesAfter)
    
    // Note count should increase
    expect(notesAfter).toBeGreaterThan(notesBefore)

    // Verify the note is visible with the correct title
    const noteCards = page.locator('[data-draggable="true"]')
    let noteFound = false
    const noteCount = await noteCards.count()
    
    for (let i = 0; i < noteCount; i++) {
      const noteText = await noteCards.nth(i).textContent()
      if (noteText?.includes(testNoteTitle) || noteText?.includes(testNoteContent.substring(0, 20))) {
        noteFound = true
        console.log('[SUCCESS] Note found immediately after creation!')
        break
      }
    }

    expect(noteFound).toBe(true)
  })

  test('should display note immediately after creation in notebook WITHOUT page refresh', async ({ page }) => {
    const timestamp = Date.now()

    // Step 1: Go to homepage
    await page.goto('/')
    await page.waitForLoadState('networkidle')
    await page.waitForTimeout(2000)

    // Step 2: Create a test notebook
    const testNotebookName = `TEST-NOTEBOOK-${timestamp}`
    console.log('[TEST] Creating test notebook:', testNotebookName)

    const createNotebookBtn = page.locator('button:has-text("Créer"), button:has-text("Create"), button:has-text("+")').first()
    await createNotebookBtn.click()
    await page.waitForTimeout(500)

    const notebookInput = page.locator('input[name="name"], input[placeholder*="notebook"], input[placeholder*="nom"]').first()
    await notebookInput.fill(testNotebookName)

    const submitNotebookBtn = page.locator('button:has-text("Créer"), button:has-text("Create"), button[type="submit"]').first()
    await submitNotebookBtn.click()
    await page.waitForTimeout(2000)

    // Step 3: Select the notebook
    const notebooksList = page.locator('[class*="notebook"], [class*="sidebar"]')
    const notebookItem = notebooksList.locator(`text=${testNotebookName}`).first()
    await notebookItem.click()
    await page.waitForTimeout(2000)

    // Step 4: Count notes in notebook before creation
    const notesBefore = await page.locator('[data-draggable="true"]').count()
    console.log('[TEST] Notes count in notebook before creation:', notesBefore)

    // Step 5: Create a test note in the notebook
    const testNoteTitle = `TEST-${timestamp}-Visibility Notebook`
    const testNoteContent = `This is a test note in notebook. Timestamp: ${timestamp}`

    console.log('[TEST] Creating test note in notebook:', testNoteTitle)
    
    // Click the note input
    const noteInput = page.locator('input[placeholder*="Take a note"], textarea[placeholder*="Take a note"]').first()
    await noteInput.click()
    await page.waitForTimeout(500)

    // Fill title if input exists
    const titleInput = page.locator('input[placeholder*="Title"], input[name="title"]').first()
    if (await titleInput.count() > 0) {
      await titleInput.fill(testNoteTitle)
      await page.waitForTimeout(300)
    }

    // Fill content
    const contentInput = page.locator('textarea[placeholder*="Take a note"], textarea').first()
    await contentInput.fill(testNoteContent)
    await page.waitForTimeout(300)

    // Submit note
    const submitBtn = page.locator('button:has-text("Add"), button:has-text("Ajouter"), button[type="submit"]').first()
    await submitBtn.click()
    await page.waitForTimeout(2000)

    // Step 6: Verify note appears immediately WITHOUT refresh
    const notesAfter = await page.locator('[data-draggable="true"]').count()
    console.log('[TEST] Notes count in notebook after creation (NO REFRESH):', notesAfter)
    
    // Note count should increase
    expect(notesAfter).toBeGreaterThan(notesBefore)

    // Verify the note is visible with the correct title
    const noteCards = page.locator('[data-draggable="true"]')
    let noteFound = false
    const noteCount = await noteCards.count()
    
    for (let i = 0; i < noteCount; i++) {
      const noteText = await noteCards.nth(i).textContent()
      if (noteText?.includes(testNoteTitle) || noteText?.includes(testNoteContent.substring(0, 20))) {
        noteFound = true
        console.log('[SUCCESS] Note found immediately after creation in notebook!')
        break
      }
    }

    expect(noteFound).toBe(true)
  })

  test('should maintain scroll position after note creation', async ({ page }) => {
    const timestamp = Date.now()

    // Step 1: Go to homepage
    await page.goto('/')
    await page.waitForLoadState('networkidle')
    await page.waitForTimeout(2000)

    // Step 2: Scroll down a bit
    await page.evaluate(() => window.scrollTo(0, 300))
    await page.waitForTimeout(500)

    // Get scroll position before
    const scrollBefore = await page.evaluate(() => window.scrollY)
    console.log('[TEST] Scroll position before creation:', scrollBefore)

    // Step 3: Create a test note
    const testNoteContent = `TEST-${timestamp}-Scroll Position`

    console.log('[TEST] Creating test note...')
    
    const noteInput = page.locator('input[placeholder*="Take a note"], textarea[placeholder*="Take a note"]').first()
    await noteInput.click()
    await page.waitForTimeout(500)

    const contentInput = page.locator('textarea[placeholder*="Take a note"], textarea').first()
    await contentInput.fill(testNoteContent)
    await page.waitForTimeout(300)

    const submitBtn = page.locator('button:has-text("Add"), button:has-text("Ajouter"), button[type="submit"]').first()
    await submitBtn.click()
    await page.waitForTimeout(2000)

    // Step 4: Verify scroll position is maintained (should be similar, not reset to 0)
    const scrollAfter = await page.evaluate(() => window.scrollY)
    console.log('[TEST] Scroll position after creation:', scrollAfter)

    // Scroll position should be maintained (not reset to 0)
    // Allow some tolerance for UI updates
    expect(Math.abs(scrollAfter - scrollBefore)).toBeLessThan(100)
  })
})
