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

test.describe('Bug: Note move to notebook', () => {
  test('should update UI immediately when moving note to notebook', async ({ page }) => {
    // Step 1: Login
    await page.goto('http://localhost:3000/login')
    await page.fill('input[name="email"]', 'test@example.com')
    await page.fill('input[name="password"]', 'password123')
    await page.click('button[type="submit"]')
    await page.waitForURL('http://localhost:3000/')

    // Step 2: Create a test note in "Notes générales"
    const testNoteContent = `Test note for move bug ${Date.now()}`
    await page.fill('textarea[placeholder*="note"]', testNoteContent)
    await page.click('button[type="submit"]')

    // Wait for note creation
    await page.waitForTimeout(2000)

    // Step 3: Find the created note
    const notes = await page.locator('.note-card').all()
    expect(notes.length).toBeGreaterThan(0)

    const firstNote = notes[0]
    const noteId = await firstNote.getAttribute('data-note-id')
    console.log('Created note with ID:', noteId)

    // Step 4: Create a test notebook
    await page.click('button:has-text("Créer un notebook")')
    await page.fill('input[name="name"]', `Test Notebook ${Date.now()}`)
    await page.click('button:has-text("Créer")')
    await page.waitForTimeout(2000)

    // Step 5: Move the note to the notebook
    // Open notebook menu on the note
    await firstNote.click('button[aria-label*="notebook"]')
    await page.waitForTimeout(500)

    // Select the first notebook in the list
    const notebookOption = page.locator('[role="menuitem"]').first()
    const notebookName = await notebookOption.textContent()
    await notebookOption.click()

    // Wait for the move operation
    await page.waitForTimeout(2000)

    // Step 6: Verify the note is NO LONGER visible in "Notes générales"
    const notesAfterMove = await page.locator('.note-card').all()
    console.log('Notes in "Notes générales" after move:', notesAfterMove.length)

    // The note should be gone from "Notes générales"
    const movedNote = await page.locator(`.note-card[data-note-id="${noteId}"]`).count()
    console.log('Moved note still visible in "Notes générales":', movedNote)
    expect(movedNote).toBe(0) // This should pass!

    // Step 7: Navigate to the notebook
    await page.click(`text="${notebookName}"`)
    await page.waitForTimeout(2000)

    // Step 8: Verify the note IS visible in the notebook
    const notesInNotebook = await page.locator('.note-card').all()
    console.log('Notes in notebook:', notesInNotebook.length)

    const movedNoteInNotebook = await page.locator(`.note-card[data-note-id="${noteId}"]`).count()
    console.log('Moved note visible in notebook:', movedNoteInNotebook)
    expect(movedNoteInNotebook).toBe(1) // This should pass!
  })
})
