<?php

namespace Tests\Browser;

use Illuminate\Foundation\Testing\DatabaseTruncation;
use Laravel\Dusk\Browser;
use Tests\Browser\Concerns\AuthenticatesUsers;
use Tests\DuskTestCase;

class CreateEntryAdminTest extends DuskTestCase
{
    use DatabaseTruncation;
    use AuthenticatesUsers;

    public function test_create_entry_admin_panel(): void
    {
        $user = $this->createTestUser("login-test@example.com");

        $filePath = base_path('tests/Browser/fixtures/robot.webp');

        $this->browse(function (Browser $browser) use ($user, $filePath) {
            $this->loginUser($browser, $user);
            $this->assertWithDebugPause(
                $browser,
                fn($b) =>
                $b->visit('/admin/media')
                    ->waitForLocation('/admin/media')
                    ->assertPathIs('/admin/media')
                    ->assertTitleContains('Media')
                    ->clickLink('New media')
                    ->waitForText('Create Media')
                    ->type('#form\\.name', 'test image')
                    ->assertVisible('.filepond--drop-label')
                    ->attach('.filepond--browser', $filePath)
                    ->pause(7000)
                    ->waitForText('Create')
                    ->waitFor('#key-bindings-1:not([disabled])')
                    ->click('#key-bindings-1')
                    ->assertSee('Collection name')
                    ->pause(5000)

                    ->visit('/admin/entries')
                    ->waitForLocation('/admin/entries')
                    ->assertPathIs('/admin/entries')
                    ->assertTitleContains('Entries')
                    ->clickLink('New entry')
                    ->waitForText('Create Entry')
                    ->type('#form\\.title', 'TEST ENTRY')
                    ->keys('#form\\.title', '{tab}')
                    ->waitForText('Create')

                    ->click('#key-bindings-1')
                    ->waitForText('Updated at')
                    ->assertSee('Updated at')
                    ->visit('/admin/entries/1/edit')
                    ->waitForText('Edit TEST ENTRY')
                    ->pause(2000)
                    ->waitForText('Featured Image')
                    ->click('#featured-picker-button')
                    ->waitForText('Select an existing image')
                    ->click('.fi-select-input-btn')
                    ->pause(2000)
                    ->click('li:first-child')
                    ->waitForText('Submit')
                    ->clickAtXPath('//button[contains(., "Submit")]')

                    ->waitForText('Edit TEST ENTRY')
                    ->click('#key-bindings-1'),
                    // ->pause(20000),
                1000  // Custom pause time for this test
            );
        });
    }
}
