Skip to content

Open-source social media scheduler built for AI agents and the teams behind them. Create, schedule and publish posts to every network through MCP or the REST API, or write them yourself in a composer your team will love.

59.0 KB
Raw Blame
<?php

declare(strict_types=1);

use App\Ai\Agents\MediaAltTextGenerator;
use App\Enums\Media\Type as MediaType;
use App\Enums\PostPlatform\ContentType;
use App\Models\Media;
use App\Models\Post;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
use Illuminate\Support\Facades\Storage;

/**
 * A draft whose images are the 200x200 quadrant fixture, inlined as data URLs so
 * the editor canvas can read their pixels without a signed storage URL.
 *
 * @return array{0: Post}
 */
function seedMediaEditorPost(ContentType $contentType = ContentType::InstagramFeed, int $imageCount = 1, ?string $firstMediaId = null): array
{
    $user = User::factory()->create();
    $workspace = Workspace::factory()->create(['user_id' => $user->id]);
    $workspace->members()->attach($user->id, membershipPivot('member'));
    $user->update(['current_workspace_id' => $workspace->id]);
    $base64 = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));

    $platform = $contentType->platform();
    $account = SocialAccount::factory()->create([
        'workspace_id' => $workspace->id,
        'platform' => $platform,
        'scopes' => $platform->requiredPublishScopes(),
    ]);

    $post = Post::factory()->forAccount($account, $contentType)->create([
        'user_id' => $user->id,
        'content' => 'Editing media',
        'media' => array_map(fn (int $index): array => [
            'id' => $index === 1 && $firstMediaId ? $firstMediaId : "image-{$index}",
            'type' => 'image',
            'mime_type' => 'image/png',
            'path' => "uploads/image-{$index}.png",
            'url' => "data:image/png;base64,{$base64}",
            'size' => 1024,
            'meta' => ['width' => 200, 'height' => 200],
        ], range(1, $imageCount)),
    ]);

    test()->actingAs($user);

    return [$post];
}

function openMediaEditor(mixed $page, string $accountId, int $index = 0): void
{
    openMediaEditorPanel($page, $accountId, $index);
    waitForState($page, '@media-editor-selection', 'element.getBoundingClientRect().width > 0');
}

/**
 * Opens the editor without waiting for the stage image, whose signed URL only the
 * Herd host serves.
 */
function openMediaEditorPanel(mixed $page, string $accountId, int $index = 0): void
{
    waitForState($page, "@composer-{$accountId}-edit-{$index}", 'true');
    $page->click("@composer-{$accountId}-edit-{$index}");
    waitForState($page, '@crop-aspect-freeform', 'true');
}

/**
 * @return list<string>
 */
function mediaEditorSegmentIds(mixed $page): array
{
    return $page->script('Array.from(document.querySelectorAll(\'[data-testid="media-editor-segments"] button\')).map((segment) => segment.dataset.testid)');
}

function clickMediaEditorStage(mixed $page, float $x, float $y): void
{
    $page->script(<<<JS
        (() => {
            const stage = document.querySelector('[data-testid="media-editor-stage"]');
            const box = stage.getBoundingClientRect();
            stage.dispatchEvent(new MouseEvent('click', {
                bubbles: true,
                clientX: box.left + box.width * {$x},
                clientY: box.top + box.height * {$y},
            }));
        })();
    JS);
}

function saveMediaEditorDraft(mixed $page): void
{
    waitForGone($page, '@media-editor');
    waitForState($page, '@composer-save-draft', 'element.disabled === false');
    $page->click('@composer-save-draft');
    waitForGone($page, '@post-composer-dialog');
}

test('the media editor keeps its preview and controls separate at every viewport', function (int $width, int $height) {
    [$post] = seedMediaEditorPost(imageCount: 2);
    $page = visit(route('app.posts.edit', $post))->resize($width, $height);
    openMediaEditor($page, $post->social_account_id);

    $page->assertScript(<<<'JS'
        (() => {
            const editor = document.querySelector('[data-testid="media-editor"]');
            const stage = editor.querySelector('[data-testid="media-editor-stage"]').getBoundingClientRect();
            const thumbnails = editor.querySelector('[data-testid="media-editor-thumbnails"]');
            const preview = thumbnails.parentElement.getBoundingClientRect();
            const strip = thumbnails.getBoundingClientRect();
            const controls = editor.querySelector('aside').getBoundingClientRect();
            const footer = editor.querySelector('[data-slot="dialog-footer"]').getBoundingClientRect();

            return stage.width > 0 && stage.height > 0
                && preview.top <= stage.top && preview.bottom >= strip.bottom
                && strip.top >= stage.bottom
                && (window.innerWidth < 1024 ? controls.top >= preview.bottom : controls.left >= preview.right)
                && editor.scrollWidth <= editor.clientWidth
                && footer.top >= 0 && footer.bottom <= window.innerHeight;
        })()
    JS, true);

    $page->click('@crop-aspect-4-5')
        ->assertAttribute('@crop-aspect-4-5', 'aria-pressed', 'true')
        ->click('@media-editor-rotate-right')
        ->click('@media-editor-appearance-section')
        ->click('@media-filter-sepia')
        ->assertVisible('@media-filter-intensity')
        ->click('@media-editor-thumb-1')
        ->assertAttribute('@media-editor-thumb-1', 'aria-current', 'true')
        ->click('@media-editor-alt-tab')
        ->fill('@media-editor-alt-text', 'Second image on a small screen')
        ->assertSee('Apply changes to 2 items')
        ->assertScript(<<<'JS'
            (() => {
                const button = document.querySelector('[data-testid="media-editor-apply"]');
                const box = button.getBoundingClientRect();
                return !button.disabled && box.top >= 0 && box.bottom <= window.innerHeight;
            })()
        JS, true)
        ->click('@media-editor-cancel')
        ->assertMissing('@media-editor')
        ->assertNoJavaScriptErrors();
})->with([
    'small phone' => [375, 667],
    'tablet' => [768, 1024],
    'desktop' => [1280, 800],
]);

test('rotating an image uploads the rotated pixels', function (int $width, int $height) {
    [$post] = seedMediaEditorPost();
    $page = visit(route('app.posts.edit', $post))->resize($width, $height);
    openMediaEditor($page, $post->social_account_id);

    $page->click('@media-editor-rotate-right')
        ->assertSee('Apply changes to 1 item')
        ->click('@media-editor-apply');
    saveMediaEditorDraft($page);

    $source = imagecreatefrompng(base_path('tests/fixtures/crop-quadrants.png'));
    $owned = $post->ownedMedia()->sole();
    $rotated = imagecreatefromstring(Storage::get($owned->path));
    $bottomLeftBefore = imagecolorsforindex($source, imagecolorat($source, 50, 150));
    $topLeftAfter = imagecolorsforindex($rotated, imagecolorat($rotated, 50, 50));

    expect($post->fresh()->media[0]['id'])->toBe($owned->id)
        ->and($owned->collection)->toBe(Media::COLLECTION_MEDIA)
        ->and($owned->upload_token)->toBeNull()
        ->and(Media::where('collection', Media::COLLECTION_UPLOADS)->count())->toBe(0)
        ->and(imagesx($rotated))->toBe(200)
        ->and(abs($topLeftAfter['red'] - $bottomLeftBefore['red']))->toBeLessThan(8)
        ->and(abs($topLeftAfter['green'] - $bottomLeftBefore['green']))->toBeLessThan(8)
        ->and(abs($topLeftAfter['blue'] - $bottomLeftBefore['blue']))->toBeLessThan(8);
})->with([
    'desktop' => [1280, 800],
    'mobile' => [375, 667],
]);

test('one apply saves edits made to several images', function () {
    [$post] = seedMediaEditorPost(imageCount: 2);
    $page = visit(route('app.posts.edit', $post));
    openMediaEditor($page, $post->social_account_id);

    $page->click('@crop-aspect-1-1')
        ->click('@media-editor-thumb-1')
        ->click('@media-editor-alt-tab')
        ->fill('@media-editor-alt-text', 'Four coloured squares')
        ->assertSee('Apply changes to 2 items')
        ->click('@media-editor-apply');
    saveMediaEditorDraft($page);

    $media = $post->fresh()->media;
    expect($media[0]['id'])->not->toBe('image-1')
        ->and($media[1]['id'])->toBe('image-2')
        ->and($media[1]['meta']['alt_text'])->toBe('Four coloured squares');
});

test('a tagged person can be moved to a new position on the image', function () {
    [$post] = seedMediaEditorPost();
    $page = visit(route('app.posts.edit', $post));
    openMediaEditor($page, $post->social_account_id);

    $page->click('@media-editor-tags-tab')
        ->click('@media-editor-tags-start');
    clickMediaEditorStage($page, 0.25, 0.75);
    $page->fill('@media-editor-tag-username', 'paulo')
        ->click('@media-editor-tag-save')
        ->assertSeeIn('@media-editor-tags-count', '1 / 20')
        ->click('@media-editor-tags-finish')
        ->click('@media-editor-tag-move-0')
        ->assertVisible('@media-editor-tag-move-pill')
        ->assertVisible('@media-editor-tag-move-hint');
    clickMediaEditorStage($page, 0.6, 0.3);
    $page->assertMissing('@media-editor-tag-move-pill')
        ->assertMissing('@media-editor-tag-form')
        ->click('@media-editor-apply');
    saveMediaEditorDraft($page);

    $tags = $post->fresh()->media[0]['meta']['user_tags'];
    expect($tags)->toHaveCount(1)
        ->and($tags[0]['username'])->toBe('paulo')
        ->and($tags[0]['x'])->toEqualWithDelta(0.6, 0.02)
        ->and($tags[0]['y'])->toEqualWithDelta(0.3, 0.02);
    $page->assertNoJavaScriptErrors();
});

test('removing one of several tagged people keeps the others', function () {
    [$post] = seedMediaEditorPost();
    $page = visit(route('app.posts.edit', $post));
    openMediaEditor($page, $post->social_account_id);

    $page->click('@media-editor-tags-tab')
        ->click('@media-editor-tags-start');
    clickMediaEditorStage($page, 0.25, 0.75);
    $page->fill('@media-editor-tag-username', 'alice')
        ->click('@media-editor-tag-save');
    clickMediaEditorStage($page, 0.6, 0.3);
    $page->fill('@media-editor-tag-username', 'bob')
        ->click('@media-editor-tag-save')
        ->assertSeeIn('@media-editor-tags-count', '2 / 20')
        ->click('@media-editor-tags-finish')
        ->click('@media-editor-tag-remove-0')
        ->assertSeeIn('@media-editor-tags-count', '1 / 20')
        ->click('@media-editor-apply');
    saveMediaEditorDraft($page);

    $tags = $post->fresh()->media[0]['meta']['user_tags'];
    expect($tags)->toHaveCount(1)
        ->and($tags[0]['username'])->toBe('bob');
    $page->assertNoJavaScriptErrors();
});

test('people tagged on an Instagram image are saved with their position', function () {
    [$post] = seedMediaEditorPost();
    $page = visit(route('app.posts.edit', $post));
    openMediaEditor($page, $post->social_account_id);

    $page->click('@media-editor-tags-tab')
        ->click('@media-editor-tags-start');
    clickMediaEditorStage($page, 0.25, 0.75);
    $page->fill('@media-editor-tag-username', 'not a username')
        ->click('@media-editor-tag-save')
        ->assertVisible('@media-editor-tag-username')
        ->fill('@media-editor-tag-username', '@paulo.castellano')
        ->click('@media-editor-tag-save')
        ->assertVisible('@media-editor-tag-0')
        ->assertAttribute('@media-editor-tag-link-0', 'href', 'https://www.instagram.com/paulo.castellano/')
        ->assertAttribute('@media-editor-tag-link-0', 'target', '_blank')
        ->click('@media-editor-apply');
    saveMediaEditorDraft($page);

    $tag = $post->fresh()->media[0]['meta']['user_tags'][0];
    expect($tag['username'])->toBe('paulo.castellano')
        ->and($tag['x'])->toEqualWithDelta(0.25, 0.02)
        ->and($tag['y'])->toEqualWithDelta(0.75, 0.02)
        ->and($post->fresh()->media[0]['id'])->toBe('image-1');
});

test('alt text can be generated with AI for a post image', function () {
    MediaAltTextGenerator::fake(['Four coloured squares in a grid.']);
    [$post] = seedMediaEditorPost(firstMediaId: '00000000-0000-4000-8000-000000000001');
    Media::factory()->ownedByPost($post)->create(['id' => '00000000-0000-4000-8000-000000000001']);
    $page = visit(route('app.posts.edit', $post));
    openMediaEditor($page, $post->social_account_id);

    $page->click('@media-editor-alt-tab')
        ->click('@media-editor-alt-generate');
    waitForState($page, '@media-editor-alt-text', 'element.value.length > 0');

    expect($page->script('document.querySelector("[data-testid=media-editor-alt-text]").value'))
        ->toBe('Four coloured squares in a grid.');
    $page->assertNoJavaScriptErrors();
});

test('an Instagram feed post offers Edit, Alt Text and Tag People', function () {
    [$post] = seedMediaEditorPost(ContentType::InstagramFeed);
    $page = visit(route('app.posts.edit', $post));
    openMediaEditor($page, $post->social_account_id);

    expect(mediaEditorSegmentIds($page))->toBe(['media-editor-edit-tab', 'media-editor-alt-tab', 'media-editor-tags-tab']);
    $page->assertNoJavaScriptErrors();
});

test('center and reset only enable once the geometry changes', function () {
    [$post] = seedMediaEditorPost();
    $page = visit(route('app.posts.edit', $post));
    openMediaEditor($page, $post->social_account_id);

    $isDisabled = fn (string $testId): bool => $page->script("document.querySelector('[data-testid=\"{$testId}\"]').disabled");

    expect($isDisabled('media-editor-center'))->toBeTrue()
        ->and($isDisabled('media-editor-reset'))->toBeTrue();

    $page->click('@crop-aspect-freeform')
        ->drag('@media-editor-handle-nw', '@media-editor-stage');
    waitForState($page, '@media-editor-center', 'element.disabled === false');

    expect($isDisabled('media-editor-center'))->toBeFalse()
        ->and($isDisabled('media-editor-reset'))->toBeFalse();

    $page->click('@media-editor-reset');
    waitForState($page, '@media-editor-reset', 'element.disabled === true');

    expect($isDisabled('media-editor-center'))->toBeTrue()
        ->and($isDisabled('media-editor-reset'))->toBeTrue();
    $page->assertNoJavaScriptErrors();
});

test('the stage only takes tags while tagging and switching tabs ends tagging mode', function () {
    [$post] = seedMediaEditorPost();
    $page = visit(route('app.posts.edit', $post));
    openMediaEditor($page, $post->social_account_id);

    $page->click('@media-editor-tags-tab');
    clickMediaEditorStage($page, 0.5, 0.5);
    $page->assertMissing('@media-editor-tag-point')
        ->assertMissing('@media-editor-tag-form')
        ->click('@media-editor-tags-start')
        ->assertVisible('@media-editor-tags-finish');

    clickMediaEditorStage($page, 0.5, 0.5);
    $page->assertVisible('@media-editor-tag-form')
        ->fill('@media-editor-tag-username', 'paulo')
        ->click('@media-editor-tag-save')
        ->assertVisible('@media-editor-tag-0');

    clickMediaEditorStage($page, 0.25, 0.25);
    $page->assertVisible('@media-editor-tag-form')
        ->click('@media-editor-tags-finish')
        ->assertMissing('@media-editor-tag-form')
        ->assertVisible('@media-editor-tags-start');

    $page->click('@media-editor-tags-tab')
        ->click('@media-editor-tags-start')
        ->assertVisible('@media-editor-tags-finish')
        ->click('@media-editor-alt-tab')
        ->click('@media-editor-tags-tab')
        ->assertVisible('@media-editor-tags-start')
        ->assertMissing('@media-editor-tags-finish');

    clickMediaEditorStage($page, 0.5, 0.5);
    $page->assertMissing('@media-editor-tag-form')
        ->assertNoJavaScriptErrors();
});

test('closing with the × discards edits like Cancel', function () {
    [$post] = seedMediaEditorPost();
    $page = visit(route('app.posts.edit', $post));
    openMediaEditor($page, $post->social_account_id);

    $page->click('@media-editor-rotate-right')
        ->assertSee('Apply changes to 1 item')
        ->click('@media-editor-close');
    waitForGone($page, '@media-editor');
    $page->assertMissing('@media-editor');

    openMediaEditor($page, $post->social_account_id);
    $page->assertDisabled('@media-editor-apply')
        ->assertDisabled('@media-editor-reset')
        ->click('@media-editor-close');
    waitForGone($page, '@media-editor');

    expect($post->fresh()->media[0]['id'])->toBe('image-1');
    $page->assertNoJavaScriptErrors();
});

test('at 20 tags tagging cannot start and the stage opens no form', function () {
    [$post] = seedMediaEditorPost();
    $media = $post->media;
    $media[0]['meta']['user_tags'] = array_map(
        fn (int $index): array => ['username' => "person{$index}", 'x' => 0.5, 'y' => 0.5],
        range(1, 20),
    );
    $post->update(['media' => $media]);
    $page = visit(route('app.posts.edit', $post));
    openMediaEditor($page, $post->social_account_id);

    $page->click('@media-editor-tags-tab')
        ->assertDisabled('@media-editor-tags-start');
    clickMediaEditorStage($page, 0.25, 0.25);
    $page->assertMissing('@media-editor-tag-point')
        ->assertMissing('@media-editor-tag-form')
        ->assertNoJavaScriptErrors();
});

/**
 * Opens a new post with the given accounts selected and uploads the files into
 * the shared list (step 1). Image `src` values pointing at storage get the
 * fixture bytes (the private local disk serves no unsigned URL); the value Vue
 * set is kept in `data-original-src`.
 *
 * @param  list<SocialAccount>  $accounts
 * @param  list<array{name: string, type: string, base64: string}>  $files
 */
function openMediaEditorComposer(User $user, array $accounts, array $files): mixed
{
    test()->actingAs($user);
    $fixture = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
    $page = visit(route('app.posts.create'));
    waitForOpen($page, '@post-composer-dialog');
    waitFor($page, '@composer-add-account');
    $page->fill('@composer-base-content', 'Editing shared media');

    $encodedFiles = json_encode($files);
    $page->script(<<<JS
        (() => {
            const fixture = 'data:image/png;base64,{$fixture}';
            const property = Object.getOwnPropertyDescriptor(HTMLImageElement.prototype, 'src');
            Object.defineProperty(HTMLImageElement.prototype, 'src', {
                configurable: true,
                get() { return property.get.call(this); },
                set(value) {
                    this.dataset.originalSrc = value;
                    return property.set.call(this, String(value).includes('/storage/') ? fixture : value);
                },
            });
            const input = document.querySelector('[data-testid="composer-file-input"]');
            const transfer = new DataTransfer();
            for (const file of {$encodedFiles}) {
                const bytes = Uint8Array.from(atob(file.base64), (character) => character.charCodeAt(0));
                transfer.items.add(new File([bytes], file.name, { type: file.type }));
            }
            input.files = transfer.files;
            input.dispatchEvent(new Event('change', { bubbles: true }));
        })();
    JS);
    $count = count($files);
    waitForCount($page, '@composer-media-item', $count);
    waitForGone($page, '@composer-upload-item');
    if ($accounts !== []) {
        $page->click('@composer-add-account');
        foreach ($accounts as $account) {
            $page->click("@composer-account-option-{$account->id}");
        }
        $prefix = count($accounts) === 1 ? "composer-{$accounts[0]->id}" : 'composer';
        waitForCount($page, "@{$prefix}-media-item", $count);
    }

    return $page;
}

/**
 * @return array{name: string, type: string, base64: string}
 */
function mediaEditorPng(string $name): array
{
    return ['name' => $name, 'type' => 'image/png', 'base64' => base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')))];
}

function mediaEditorComposerUser(): User
{
    $user = User::factory()->create();
    $workspace = Workspace::factory()->create(['user_id' => $user->id, 'account_id' => $user->account_id]);
    $workspace->members()->attach($user->id, membershipPivot('admin'));
    $user->update(['current_workspace_id' => $workspace->id]);
    subscribeAccount($user->account);

    return $user;
}

/**
 * @return list<string>
 */
function mediaEditorTileButtons(mixed $page, string $prefix, int $index): array
{
    return $page->script(<<<JS
        Array.from(document.querySelectorAll('[data-testid="{$prefix}-media-item-{$index}"] button'))
            .map((button) => button.dataset.testid)
            .filter((testId) => !testId.includes('-drag-handle-'))
    JS);
}

function mediaEditorTileSrc(mixed $page, string $prefix, int $index): ?string
{
    return $page->script("document.querySelector('[data-testid=\"{$prefix}-media-item-{$index}\"] img')?.dataset.originalSrc ?? null");
}

test('step 1 tiles offer the buttons the selected channels support', function () {
    $user = mediaEditorComposerUser();
    $instagram = SocialAccount::factory()->instagram()->create(['workspace_id' => $user->current_workspace_id]);
    $x = SocialAccount::factory()->x()->create(['workspace_id' => $user->current_workspace_id]);
    $page = openMediaEditorComposer($user, [$instagram, $x], [
        mediaEditorPng('photo.png'),
        ['name' => 'animation.gif', 'type' => 'image/gif', 'base64' => 'R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'],
        ['name' => 'brochure.pdf', 'type' => 'application/pdf', 'base64' => base64_encode("%PDF-1.4\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj 2 0 obj<</Type/Pages/Kids[]/Count 0>>endobj\ntrailer<</Root 1 0 R>>\n%%EOF")],
    ]);

    expect(mediaEditorTileButtons($page, 'composer', 0))->toBe(['composer-remove-0', 'composer-tag-0', 'composer-alt-0', 'composer-edit-0'])
        ->and(mediaEditorTileButtons($page, 'composer', 1))->toBe(['composer-remove-1'])
        ->and(mediaEditorTileButtons($page, 'composer', 2))->toBe(['composer-remove-2']);
    $page->assertNoJavaScriptErrors();
});

test('step 1 tiles offer only the pencil for a TikTok image', function () {
    $user = mediaEditorComposerUser();
    $tiktok = SocialAccount::factory()->tiktok()->create(['workspace_id' => $user->current_workspace_id]);
    $page = openMediaEditorComposer($user, [$tiktok], [mediaEditorPng('photo.png')]);

    expect(mediaEditorTileButtons($page, "composer-{$tiktok->id}", 0))->toBe(["composer-{$tiktok->id}-remove-0", "composer-{$tiktok->id}-edit-0"]);
    $page->assertNoJavaScriptErrors();
});

test('the ALT button opens the editor on the Alt Text segment', function () {
    $user = mediaEditorComposerUser();
    $instagram = SocialAccount::factory()->instagram()->create(['workspace_id' => $user->current_workspace_id]);
    $page = openMediaEditorComposer($user, [$instagram], [mediaEditorPng('photo.png')]);

    $page->click("@composer-{$instagram->id}-alt-0");
    waitForState($page, '@media-editor-alt-text', 'true');

    expect($page->script("document.querySelector('[data-testid=\"media-editor-alt-tab\"]').getAttribute('aria-pressed')"))->toBe('true');
    $page->assertVisible('@media-editor-alt-text')
        ->assertNoJavaScriptErrors();
});

/**
 * Opens the ALT editor of a tile, types `$altText` and applies it.
 */
function applyMediaEditorAltText(mixed $page, string $prefix, string $altText): void
{
    waitForState($page, "@{$prefix}-alt-0", 'true');
    $page->click("@{$prefix}-alt-0");
    waitForState($page, '@media-editor-alt-text', 'true');
    $page->fill('@media-editor-alt-text', $altText);
    waitForState($page, '@media-editor-apply', 'element.disabled === false');
    $page->click('@media-editor-apply');
    waitForGone($page, '@media-editor');
}

/**
 * @return array<string, ?string>
 */
function mediaEditorSavedAltTexts(SocialAccount ...$accounts): array
{
    return collect($accounts)->mapWithKeys(fn (SocialAccount $account): array => [
        $account->id => data_get(Post::query()->where('social_account_id', $account->id)->sole()->media, '0.meta.alt_text'),
    ])->all();
}

test('alt text is offered only once a channel is selected', function () {
    $user = mediaEditorComposerUser();
    $linkedin = SocialAccount::factory()->linkedin()->create(['workspace_id' => $user->current_workspace_id]);
    $page = openMediaEditorComposer($user, [], [mediaEditorPng('photo.png')]);

    expect(mediaEditorTileButtons($page, 'composer', 0))->toBe(['composer-remove-0', 'composer-edit-0']);
    $page->click('@composer-edit-0');
    waitForState($page, '@crop-aspect-freeform', 'true');
    $page->assertMissing('@media-editor-alt-tab')
        ->click('@media-editor-cancel');
    waitForGone($page, '@media-editor');

    if (! $page->script("Boolean(document.querySelector('[data-testid=\"composer-account-option-{$linkedin->id}\"]'))")) {
        $page->click('@composer-add-account');
    }
    $page->click("@composer-account-option-{$linkedin->id}");
    waitForState($page, "@composer-{$linkedin->id}-alt-0", 'true');

    expect(mediaEditorTileButtons($page, "composer-{$linkedin->id}", 0))->toBe(["composer-{$linkedin->id}-remove-0", "composer-{$linkedin->id}-alt-0", "composer-{$linkedin->id}-edit-0"]);
    $page->assertNoJavaScriptErrors();
});

test('a step 1 alt text is saved on every channel', function () {
    $user = mediaEditorComposerUser();
    $first = SocialAccount::factory()->linkedin()->create(['workspace_id' => $user->current_workspace_id]);
    $second = SocialAccount::factory()->x()->create(['workspace_id' => $user->current_workspace_id]);
    $page = openMediaEditorComposer($user, [$first, $second], [mediaEditorPng('photo.png')]);

    applyMediaEditorAltText($page, 'composer', 'Four coloured squares');
    saveMediaEditorDraft($page);

    expect(mediaEditorSavedAltTexts($first, $second))->toBe([
        $first->id => 'Four coloured squares',
        $second->id => 'Four coloured squares',
    ]);
});

test('a step 2 alt text stays on its channel and the others keep the shared one', function () {
    $user = mediaEditorComposerUser();
    $first = SocialAccount::factory()->linkedin()->create(['workspace_id' => $user->current_workspace_id]);
    $second = SocialAccount::factory()->x()->create(['workspace_id' => $user->current_workspace_id]);
    $page = openMediaEditorComposer($user, [$first, $second], [mediaEditorPng('photo.png')]);

    applyMediaEditorAltText($page, 'composer', 'Shared description');
    $page->click('@composer-next')
        ->click("@composer-account-{$first->id}");
    applyMediaEditorAltText($page, "composer-{$first->id}", 'First channel description');

    $page->click("@composer-account-{$second->id}");
    waitForState($page, "@composer-{$second->id}-alt-0", 'true');
    $page->click("@composer-{$second->id}-alt-0");
    waitForState($page, '@media-editor-alt-text', 'true');
    expect($page->script("document.querySelector('[data-testid=\"media-editor-alt-text\"]').value"))->toBe('Shared description');
    $page->click('@media-editor-cancel');
    saveMediaEditorDraft($page);

    expect(mediaEditorSavedAltTexts($first, $second))->toBe([
        $first->id => 'First channel description',
        $second->id => 'Shared description',
    ]);
});

test('a step 1 edit replaces the shared item in place and every post owns its own file', function () {
    $user = mediaEditorComposerUser();
    $first = SocialAccount::factory()->linkedin()->create(['workspace_id' => $user->current_workspace_id]);
    $second = SocialAccount::factory()->x()->create(['workspace_id' => $user->current_workspace_id]);
    $page = openMediaEditorComposer($user, [$first, $second], [mediaEditorPng('first.png'), mediaEditorPng('second.png')]);
    $originals = Media::query()->where('collection', Media::COLLECTION_UPLOADS)->orderBy('original_filename')->get()->keyBy('original_filename');
    $firstSrc = mediaEditorTileSrc($page, 'composer', 0);
    $secondSrc = mediaEditorTileSrc($page, 'composer', 1);

    $page->click('@composer-edit-1');
    waitForState($page, '@media-editor-selection', 'element.getBoundingClientRect().width > 0');
    $page->click('@media-editor-rotate-right');
    waitForState($page, '@media-editor-apply', 'element.disabled === false');
    $page->click('@media-editor-apply');
    waitForGone($page, '@media-editor');
    waitForState($page, '@composer-save-draft', 'element.disabled === false');

    expect(mediaEditorTileSrc($page, 'composer', 0))->toBe($firstSrc)
        ->and(mediaEditorTileSrc($page, 'composer', 1))->not->toBe($secondSrc)
        ->and(mediaEditorTileSrc($page, 'composer', 1))->not->toBeNull();

    $page->click('@composer-save-draft');
    waitForGone($page, '@post-composer-dialog');

    $posts = Post::query()->whereIn('social_account_id', [$first->id, $second->id])->get();
    expect($posts)->toHaveCount(2);
    $paths = [];
    foreach ($posts as $post) {
        $owned = $post->ownedMedia()->orderBy('order')->get();
        expect($owned)->toHaveCount(2)
            ->and($owned[1]->path)->not->toBe($originals['second.png']->path)
            ->and($owned[1]->original_filename)->not->toBe('second.png');
        $paths = [...$paths, ...$owned->pluck('path')->all()];
    }
    expect(array_unique($paths))->toHaveCount(4);
});

test('a step 2 edit replaces only that channel\'s item and leaves the shared list alone', function () {
    $user = mediaEditorComposerUser();
    $first = SocialAccount::factory()->linkedin()->create(['workspace_id' => $user->current_workspace_id]);
    $second = SocialAccount::factory()->x()->create(['workspace_id' => $user->current_workspace_id]);
    $page = openMediaEditorComposer($user, [$first, $second], [mediaEditorPng('shared.png')]);
    $sharedSrc = mediaEditorTileSrc($page, 'composer', 0);

    $page->click('@composer-next')
        ->click("@composer-account-{$first->id}");
    openMediaEditor($page, $first->id);
    $page->click('@media-editor-rotate-right');
    waitForState($page, '@media-editor-apply', 'element.disabled === false');
    $page->click('@media-editor-apply');
    waitForGone($page, '@media-editor');
    waitForState($page, '@composer-save-draft', 'element.disabled === false');

    expect(mediaEditorTileSrc($page, "composer-{$first->id}", 0))->not->toBe($sharedSrc);

    $page->click("@composer-account-{$second->id}");
    waitForState($page, "@composer-{$second->id}-media-item-0", 'true');
    expect(mediaEditorTileSrc($page, "composer-{$second->id}", 0))->toBe($sharedSrc);

    $page->click('@composer-back');
    waitForState($page, '@composer-back-confirm-go', 'true');
    $page->click('@composer-back-confirm-go');
    waitForState($page, '@composer-media-item-0', 'true');
    expect(mediaEditorTileSrc($page, 'composer', 0))->toBe($sharedSrc);
    $page->assertNoJavaScriptErrors();
});

test('a failed edit upload shows the inline error and keeps the original tile', function () {
    $user = mediaEditorComposerUser();
    $linkedin = SocialAccount::factory()->linkedin()->create(['workspace_id' => $user->current_workspace_id]);
    $page = openMediaEditorComposer($user, [$linkedin], [mediaEditorPng('photo.png')]);
    $originalSrc = mediaEditorTileSrc($page, "composer-{$linkedin->id}", 0);
    $uploadUrl = route('app.media.store-chunked', absolute: false);
    $page->script(<<<JS
        (() => {
            const { open, send } = XMLHttpRequest.prototype;
            XMLHttpRequest.prototype.open = function (method, url, ...rest) {
                this.__url = String(url);
                return open.call(this, method, url, ...rest);
            };
            XMLHttpRequest.prototype.send = function (body) {
                if (! this.__url.includes('{$uploadUrl}')) return send.call(this, body);
                window.__editUploadFailed = true;
                Object.defineProperty(this, 'status', { value: 500 });
                Object.defineProperty(this, 'responseText', { value: 'failed' });
                setTimeout(() => this.dispatchEvent(new ProgressEvent('load')));
            };
        })();
    JS);

    $page->click("@composer-{$linkedin->id}-edit-0");
    waitForState($page, '@media-editor-selection', 'element.getBoundingClientRect().width > 0');
    $page->click('@media-editor-rotate-right');
    waitForState($page, '@media-editor-apply', 'element.disabled === false');
    $page->click('@media-editor-apply');
    waitForCondition($page, 'window.__editUploadFailed');
    waitForState($page, "@composer-{$linkedin->id}-crop-error", 'true');
    waitForState($page, '@composer-save-draft', 'element.disabled === false');

    expect($page->script('Boolean(window.__editUploadFailed)'))->toBeTrue()
        ->and(mediaEditorTileSrc($page, "composer-{$linkedin->id}", 0))->toBe($originalSrc)
        ->and($page->script("document.querySelector('[data-testid=\"composer-save-draft\"]').disabled"))->toBeFalse();
    $page->assertVisible("@composer-{$linkedin->id}-crop-error")
        ->assertNoJavaScriptErrors();
});

/**
 * @return array{0: Post}
 */
function seedMediaEditorVideoPost(ContentType $contentType): array
{
    [$post] = seedMediaEditorPost($contentType);
    $webm = base64_encode((string) file_get_contents(base_path('tests/fixtures/cover-3s.webm')));
    $post->update(['media' => [[
        'id' => 'video-1',
        'type' => 'video',
        'mime_type' => 'video/webm',
        'path' => 'uploads/video-1.webm',
        'url' => "data:video/webm;base64,{$webm}",
        'size' => 855,
        'meta' => ['width' => 16, 'height' => 16],
    ]]]);

    return [$post];
}

test('a reel video gets a Thumbnail segment whose frame is saved as the cover offset', function () {
    [$post] = seedMediaEditorVideoPost(ContentType::InstagramReel);
    $accountId = $post->social_account_id;
    $page = visit(route('app.posts.edit', $post));
    waitForState($page, "@composer-{$accountId}-edit-0", 'true');
    $page->click("@composer-{$accountId}-edit-0");
    waitForState($page, '@media-editor-cover', 'true');

    expect(mediaEditorSegmentIds($page))->toBe(['media-editor-thumbnail-tab'])
        ->and($page->script("document.querySelector('[data-testid=\"media-editor-thumbnail-tab\"]').getAttribute('aria-pressed')"))->toBe('true')
        ->and($page->script("document.querySelector('[data-testid=\"media-editor-apply\"]').disabled"))->toBeTrue();

    $page->click('@media-editor-thumbnail-tab')
        ->assertSee('Choose a thumbnail')
        ->assertVisible('@media-editor-stage-video')
        ->assertMissing('@media-editor-thumbnails');
    waitForState($page, '@media-editor-cover', "element.max === '3'");

    expect($page->script("document.querySelector('[data-testid=\"media-editor-cover\"]').max"))->toBe('3');
    $page->script(<<<'JS'
        (() => {
            const slider = document.querySelector('[data-testid="media-editor-cover"]');
            slider.value = '2.5';
            slider.dispatchEvent(new Event('input', { bubbles: true }));
        })();
    JS);
    waitForState($page, '@media-editor-apply', 'element.disabled === false');

    waitForState($page, '@media-editor-stage-video', 'Math.abs(element.currentTime - 2.5) < 0.01');

    expect($page->script("document.querySelector('[data-testid=\"media-editor-cover-value\"]').textContent.trim()"))->toBe('0:02.5')
        ->and($page->script("document.querySelector('[data-testid=\"media-editor-cover\"]').getAttribute('aria-valuetext')"))->toBe('2.5 seconds')
        ->and($page->script("document.querySelector('[data-testid=\"media-editor-stage-video\"]').currentTime"))->toEqualWithDelta(2.5, 0.01);

    $page->click('@media-editor-apply');
    saveMediaEditorDraft($page);

    expect($post->fresh()->media[0]['meta']['cover_offset_ms'])->toBe(2500)
        ->and($post->fresh()->media[0]['id'])->toBe('video-1')
        ->and(data_get($post->fresh()->media, '0.meta.cover'))->toBeNull();
    $page->assertNoJavaScriptErrors();
});

test('a video takes alt text, written by hand, where its network accepts it', function (ContentType $contentType) {
    [$post] = seedMediaEditorVideoPost($contentType);
    $post->update(['media' => [[...$post->media[0], 'meta' => [...$post->media[0]['meta'], 'cover_offset_ms' => 1500]]]]);
    $accountId = $post->social_account_id;
    $page = visit(route('app.posts.edit', $post));
    waitFor($page, "@composer-{$accountId}-alt-0");
    $page->assertMissing("@composer-{$accountId}-edit-0")
        ->click("@composer-{$accountId}-alt-0");
    waitFor($page, '@media-editor-alt-text');

    $page->assertVisible('@media-editor-stage-video')
        ->assertMissing('@media-editor-alt-generate');

    $page->type('@media-editor-alt-text', 'A cyclist crossing a bridge at sunset');
    waitForState($page, '@media-editor-apply', 'element.disabled === false');
    $page->click('@media-editor-apply');
    saveMediaEditorDraft($page);

    expect(data_get($post->fresh()->media, '0.meta.alt_text'))->toBe('A cyclist crossing a bridge at sunset')
        ->and(data_get($post->fresh()->media, '0.meta.cover_offset_ms'))->toBe(1500)
        ->and($post->fresh()->media[0]['id'])->toBe('video-1');
    $page->assertNoJavaScriptErrors();
})->with([
    'mastodon' => [ContentType::MastodonPost],
    'bluesky' => [ContentType::BlueskyPost],
    'threads' => [ContentType::ThreadsPost],
    'discord' => [ContentType::DiscordMessage],
]);

function pickMediaEditorCoverImage(mixed $page): void
{
    $png = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
    $page->script(<<<JS
        (() => {
            const input = document.querySelector('[data-testid="media-editor-cover-image-input"]');
            const bytes = Uint8Array.from(atob('{$png}'), (character) => character.charCodeAt(0));
            const transfer = new DataTransfer();
            transfer.items.add(new File([bytes], 'cover.png', { type: 'image/png' }));
            input.files = transfer.files;
            input.dispatchEvent(new Event('change', { bubbles: true }));
        })();
    JS);
}

test('a reel video takes an uploaded image as its cover', function () {
    [$post] = seedMediaEditorVideoPost(ContentType::InstagramReel);
    $accountId = $post->social_account_id;
    $page = visit(route('app.posts.edit', $post));
    waitForState($page, "@composer-{$accountId}-edit-0", 'true');
    $page->click("@composer-{$accountId}-edit-0");
    waitFor($page, '@media-editor-cover-source');

    $page->assertAttribute('@media-editor-cover-source-frame', 'aria-pressed', 'true');

    $page->click('@media-editor-cover-source-image')
        ->assertSee('Your video shows this image as its cover.')
        ->assertMissing('@media-editor-cover')
        ->assertMissing('@media-editor-selection');

    pickMediaEditorCoverImage($page);
    waitForState($page, '@media-editor-selection', 'element.getBoundingClientRect().width > 0');
    waitForState($page, '@media-editor-apply', 'element.disabled === false');
    $page->assertSee('Replace image')
        ->assertPresent('@media-editor-handle-nw')
        ->assertPresent('@media-editor-center')
        ->assertMissing('@crop-aspect-9-16')
        ->click('@media-editor-apply');
    saveMediaEditorDraft($page);

    $cover = data_get($post->fresh()->media, '0.meta.cover');
    $owned = Media::query()->find(data_get($cover, 'id'));
    [$width, $height] = getimagesizefromstring(Storage::get($owned->path));

    expect($owned->post_id)->toBe($post->id)
        ->and($owned->type)->toBe(MediaType::Image)
        ->and($owned->upload_token)->toBeNull()
        ->and($height / $width)->toEqualWithDelta(16 / 9, 0.02)
        ->and(data_get($post->fresh()->media, '0.id'))->toBe('video-1');
    $page->assertNoJavaScriptErrors();
});

test('switching a reel back to a video frame saves the frame time and drops the image', function () {
    [$post] = seedMediaEditorVideoPost(ContentType::InstagramReel);
    $png = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
    $media = $post->media;
    $media[0]['meta']['cover'] = [
        'id' => 'cover-1',
        'type' => 'image',
        'mime_type' => 'image/png',
        'path' => 'uploads/cover-1.png',
        'url' => "data:image/png;base64,{$png}",
        'size' => 1024,
    ];
    $post->update(['media' => $media]);
    $accountId = $post->social_account_id;
    $page = visit(route('app.posts.edit', $post));
    waitForState($page, "@composer-{$accountId}-edit-0", 'true');
    $page->click("@composer-{$accountId}-edit-0");
    waitFor($page, '@media-editor-selection');

    $page->click('@media-editor-cover-source-frame');
    waitFor($page, '@media-editor-cover');
    waitForState($page, '@media-editor-apply', 'element.disabled === false');
    $page->click('@media-editor-apply');
    saveMediaEditorDraft($page);

    expect(data_get($post->fresh()->media, '0.meta.cover'))->toBeNull()
        ->and(data_get($post->fresh()->media, '0.meta.cover_offset_ms'))->toBe(0);
    $page->assertNoJavaScriptErrors();
});

test('switching a youtube short back to a video frame saves a screenshot of that frame as the cover', function () {
    [$post] = seedMediaEditorVideoPost(ContentType::YouTubeShort);
    $png = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
    $media = $post->media;
    $media[0]['meta']['cover'] = [
        'id' => 'cover-1',
        'type' => 'image',
        'mime_type' => 'image/png',
        'path' => 'uploads/cover-1.png',
        'url' => "data:image/png;base64,{$png}",
        'size' => 1024,
    ];
    $post->update(['media' => $media]);
    $accountId = $post->social_account_id;
    $page = visit(route('app.posts.edit', $post));
    waitForState($page, "@composer-{$accountId}-edit-0", 'true');
    $page->click("@composer-{$accountId}-edit-0");
    waitFor($page, '@media-editor-selection');

    $page->assertAttribute('@media-editor-cover-source-image', 'aria-pressed', 'true');
    waitForState($page, '@media-editor-apply', 'element.disabled === true');

    $page->click('@media-editor-cover-source-frame');
    waitFor($page, '@media-editor-cover');
    waitForState($page, '@media-editor-apply', 'element.disabled === false');
    $page->click('@media-editor-apply');
    saveMediaEditorDraft($page);

    $cover = data_get($post->fresh()->media, '0.meta.cover');
    $owned = Media::query()->find(data_get($cover, 'id'));

    expect(data_get($cover, 'id'))->not->toBe('cover-1')
        ->and($owned->post_id)->toBe($post->id)
        ->and($owned->type)->toBe(MediaType::Image)
        ->and(data_get($post->fresh()->media, '0.meta.cover_offset_ms'))->toBe(0);
    $page->assertNoJavaScriptErrors();
});

test('picking an image as the cover keeps the frame picked for the networks that only take one', function () {
    [$post] = seedMediaEditorVideoPost(ContentType::InstagramReel);
    $media = $post->media;
    $media[0]['meta']['cover_offset_ms'] = 2500;
    $post->update(['media' => $media]);
    $accountId = $post->social_account_id;
    $page = visit(route('app.posts.edit', $post));
    waitForState($page, "@composer-{$accountId}-edit-0", 'true');
    $page->click("@composer-{$accountId}-edit-0");
    waitFor($page, '@media-editor-cover-source');

    $page->click('@media-editor-cover-source-image');
    pickMediaEditorCoverImage($page);
    waitForState($page, '@media-editor-selection', 'element.getBoundingClientRect().width > 0');
    waitForState($page, '@media-editor-apply', 'element.disabled === false');
    $page->click('@media-editor-apply');
    saveMediaEditorDraft($page);

    $meta = data_get($post->fresh()->media, '0.meta');

    expect(data_get($meta, 'cover_source'))->toBe('image')
        ->and(data_get($meta, 'cover_offset_ms'))->toBe(2500)
        ->and(data_get($meta, 'cover.id'))->not->toBeNull();
    $page->assertNoJavaScriptErrors();
});

test('picking image over a frame cover waits for an image instead of reusing the frame screenshot', function () {
    [$post] = seedMediaEditorVideoPost(ContentType::InstagramReel);
    $png = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
    $media = $post->media;
    $media[0]['meta'] = [...$media[0]['meta'], 'cover_offset_ms' => 2500, 'cover_source' => 'frame', 'cover' => [
        'id' => 'cover-1', 'type' => 'image', 'mime_type' => 'image/png', 'path' => 'uploads/cover.png', 'url' => "data:image/png;base64,{$png}",
    ]];
    $post->update(['media' => $media]);
    $accountId = $post->social_account_id;
    $page = visit(route('app.posts.edit', $post));
    waitForState($page, "@composer-{$accountId}-edit-0", 'true');
    $page->click("@composer-{$accountId}-edit-0");
    waitFor($page, '@media-editor-cover-timeline');

    $page->click('@media-editor-cover-source-image');
    waitFor($page, '@media-editor-stage-video');

    $page->assertMissing('@media-editor-selection')
        ->assertSee('Upload image')
        ->assertNoJavaScriptErrors();
});

test('reframing a stored cover saves the new frame of it', function () {
    [$post] = seedMediaEditorVideoPost(ContentType::InstagramReel);
    $png = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
    $media = $post->media;
    $media[0]['meta']['cover'] = [
        'id' => 'cover-1',
        'type' => 'image',
        'mime_type' => 'image/png',
        'path' => 'uploads/cover-1.png',
        'url' => "data:image/png;base64,{$png}",
        'size' => 1024,
    ];
    $post->update(['media' => $media]);
    $accountId = $post->social_account_id;
    $page = visit(route('app.posts.edit', $post));
    waitForState($page, "@composer-{$accountId}-edit-0", 'true');
    $page->click("@composer-{$accountId}-edit-0");
    waitForState($page, '@media-editor-selection', 'element.getBoundingClientRect().width > 0');
    waitForState($page, '@media-editor-apply', 'element.disabled === true');

    $page->drag('@media-editor-handle-nw', '@media-editor-stage');
    waitForState($page, '@media-editor-apply', 'element.disabled === false');
    $page->click('@media-editor-apply');
    saveMediaEditorDraft($page);

    $owned = Media::query()->find(data_get($post->fresh()->media, '0.meta.cover.id'));
    [$width, $height] = getimagesizefromstring(Storage::get($owned->path));

    expect($owned->post_id)->toBe($post->id)
        ->and($height / $width)->toEqualWithDelta(16 / 9, 0.02);
    $page->assertNoJavaScriptErrors();
});

test('a youtube short offers a frame or an image as its cover', function () {
    [$post] = seedMediaEditorVideoPost(ContentType::YouTubeShort);
    $accountId = $post->social_account_id;
    $page = visit(route('app.posts.edit', $post));
    waitForState($page, "@composer-{$accountId}-edit-0", 'true');
    $page->click("@composer-{$accountId}-edit-0");
    waitFor($page, '@media-editor-cover-source');

    expect(mediaEditorSegmentIds($page))->toBe(['media-editor-thumbnail-tab']);
    $page->assertVisible('@media-editor-cover')
        ->assertVisible('@media-editor-cover-source-image')
        ->assertNoJavaScriptErrors();
});

test('a feed video offers only the cover frame', function () {
    [$post] = seedMediaEditorVideoPost(ContentType::InstagramFeed);
    $accountId = $post->social_account_id;
    $page = visit(route('app.posts.edit', $post));
    waitForState($page, "@composer-{$accountId}-edit-0", 'true');
    $page->click("@composer-{$accountId}-edit-0");
    waitFor($page, '@media-editor-cover');

    $page->assertMissing('@media-editor-cover-source')
        ->assertNoJavaScriptErrors();
});

test('the thumbnail tab picks the frame by dragging along a strip under the video', function () {
    [$post] = seedMediaEditorVideoPost(ContentType::InstagramReel);
    $accountId = $post->social_account_id;
    $page = visit(route('app.posts.edit', $post));
    waitForState($page, "@composer-{$accountId}-edit-0", 'true');
    $page->click("@composer-{$accountId}-edit-0");
    waitFor($page, '@media-editor-cover-timeline');
    waitForState($page, '@media-editor-cover-timeline canvas:last-of-type', 'element.width > 0');

    $page->assertMissing('@media-editor-play');

    $page->script(<<<'JS'
        (() => {
            const slider = document.querySelector('[data-testid="media-editor-cover"]');
            slider.value = '3';
            slider.dispatchEvent(new Event('input', { bubbles: true }));
        })();
    JS);
    waitForState($page, '@media-editor-cover-selector', 'Math.abs(element.getBoundingClientRect().right - element.parentElement.getBoundingClientRect().right) < 2');

    waitForText($page, '@media-editor-cover-value', '0:03.0');
    $page->assertNoJavaScriptErrors();
});

test('the composer shows the picked cover on the media tile and on the preview until it plays', function (string $picked, string $tileElement, string $tileShows) {
    [$post] = seedMediaEditorVideoPost(ContentType::InstagramReel);
    $png = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
    $image = ['id' => 'cover-1', 'type' => 'image', 'mime_type' => 'image/png', 'path' => 'uploads/cover.png', 'url' => "data:image/png;base64,{$png}"];
    $cover = match ($picked) {
        'frame' => ['cover_offset_ms' => 2500],
        'captured frame' => ['cover_offset_ms' => 2500, 'cover' => $image, 'cover_source' => 'frame'],
        'image' => ['cover' => $image],
    };
    $media = $post->media;
    $media[0]['meta'] = [...$media[0]['meta'], ...$cover];
    $post->update(['media' => $media]);
    $accountId = $post->social_account_id;
    $page = visit(route('app.posts.edit', $post));
    waitFor($page, "@composer-{$accountId}-media-item-0");
    waitFor($page, '@video-preview-cover');

    waitForState($page, "@composer-{$accountId}-media-item-0 {$tileElement}", $tileShows);

    $page->click('@video-preview-play');
    waitForGone($page, '@video-preview-cover');
    $page->assertNoJavaScriptErrors();
})->with([
    'a picked frame' => ['frame', 'video', "element.src.endsWith('#t=2.5')"],
    'a frame with its screenshot' => ['captured frame', 'video', "element.src.endsWith('#t=2.5')"],
    'an uploaded image' => ['image', 'img', "element.src.startsWith('data:image/png')"],
]);

test('a tiktok preview shows the picked frame, not an image uploaded for another network', function () {
    [$post] = seedMediaEditorVideoPost(ContentType::TikTokVideo);
    $png = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
    $media = $post->media;
    $media[0]['meta'] = [...$media[0]['meta'], 'cover_offset_ms' => 2500, 'cover_source' => 'image', 'cover' => [
        'id' => 'cover-1', 'type' => 'image', 'mime_type' => 'image/png', 'path' => 'uploads/cover.png', 'url' => "data:image/png;base64,{$png}",
    ]];
    $post->update(['media' => $media]);
    $page = visit(route('app.posts.edit', $post));
    waitForState($page, '@video-preview-cover', "element.tagName === 'VIDEO' && element.src.endsWith('#t=2.5')");

    $page->assertNoJavaScriptErrors();
});

test('a frame picked before youtube was added gets its screenshot when the editor applies', function () {
    [$post] = seedMediaEditorVideoPost(ContentType::YouTubeShort);
    $media = $post->media;
    $media[0]['meta']['cover_offset_ms'] = 1500;
    $post->update(['media' => $media]);
    $accountId = $post->social_account_id;
    $page = visit(route('app.posts.edit', $post));
    waitForState($page, "@composer-{$accountId}-edit-0", 'true');
    $page->click("@composer-{$accountId}-edit-0");
    waitFor($page, '@media-editor-cover-timeline');
    waitForState($page, '@media-editor-apply', 'element.disabled === false');
    $page->click('@media-editor-apply');
    saveMediaEditorDraft($page);

    $owned = Media::query()->find(data_get($post->fresh()->media, '0.meta.cover.id'));

    expect($owned->post_id)->toBe($post->id)
        ->and(data_get($post->fresh()->media, '0.meta.cover_source'))->toBe('frame')
        ->and(data_get($post->fresh()->media, '0.meta.cover_offset_ms'))->toBe(1500);
    $page->assertNoJavaScriptErrors();
});

test('a feed post\'s media tile shows the picked frame, not an image only a reel takes', function () {
    [$post] = seedMediaEditorVideoPost(ContentType::InstagramFeed);
    $png = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
    $media = $post->media;
    $media[0]['meta'] = [...$media[0]['meta'], 'cover_offset_ms' => 2500, 'cover_source' => 'image', 'cover' => [
        'id' => 'cover-1', 'type' => 'image', 'mime_type' => 'image/png', 'path' => 'uploads/cover.png', 'url' => "data:image/png;base64,{$png}",
    ]];
    $post->update(['media' => $media]);
    $accountId = $post->social_account_id;
    $page = visit(route('app.posts.edit', $post));

    waitForState($page, "@composer-{$accountId}-media-item-0 video", "element.src.endsWith('#t=2.5')");
    $page->assertMissing("@composer-{$accountId}-media-item-0 img")
        ->assertNoJavaScriptErrors();
});

test('a video without a picked cover shows the video itself on the preview', function () {
    [$post] = seedMediaEditorVideoPost(ContentType::TikTokVideo);
    $accountId = $post->social_account_id;
    $page = visit(route('app.posts.edit', $post));
    waitFor($page, "@composer-{$accountId}-media-item-0");
    letPageRun($page, 500);

    $page->assertMissing('@video-preview-cover')
        ->assertNoJavaScriptErrors();
});

test('a video on an X post shows no pencil', function () {
    [$post] = seedMediaEditorVideoPost(ContentType::XPost);
    $accountId = $post->social_account_id;
    $page = visit(route('app.posts.edit', $post));
    waitForState($page, "@composer-{$accountId}-media-item-0", 'true');

    $page->assertPresent("@composer-{$accountId}-media-item-0")
        ->assertMissing("@composer-{$accountId}-edit-0")
        ->assertNoJavaScriptErrors();
});

test('only a freeform crop can be resized; a chosen ratio only moves', function () {
    [$post] = seedMediaEditorPost();
    $page = visit(route('app.posts.edit', $post));
    openMediaEditor($page, $post->social_account_id);

    $page->click('@crop-aspect-4-5');
    waitForGone($page, '@media-editor-handle-nw');
    $page->assertMissing('@media-editor-handle-nw')
        ->assertPresent('@media-editor-selection')
        ->click('@crop-aspect-freeform');
    waitForState($page, '@media-editor-handle-nw', 'true');

    $page->assertPresent('@media-editor-handle-nw')
        ->assertPresent('@media-editor-handle-se')
        ->assertNoJavaScriptErrors();
});

test('filter intensity shows for a filter, not for the original, and sliders fill from their origin', function () {
    [$post] = seedMediaEditorPost();
    $page = visit(route('app.posts.edit', $post));
    openMediaEditor($page, $post->social_account_id);

    $page->click('@media-editor-appearance-section');
    waitForState($page, '@media-filter-sepia', 'true');
    $page->assertMissing('@media-filter-intensity')
        ->click('@media-filter-sepia');
    waitForState($page, '@media-filter-intensity', 'true');

    $page->script(<<<'JS'
        (() => {
            const set = (testId, value) => {
                const input = document.querySelector(`[data-testid="${testId}"]`);
                input.value = value;
                input.dispatchEvent(new Event('input', { bubbles: true }));
            };
            set('media-filter-intensity', 40);
            set('media-adjust-brightness', 60);
        })()
    JS);
    waitForState($page, '@media-adjust-brightness', "element.style.getPropertyValue('--range-to').includes('0.8')");

    expect($page->script(<<<'JS'
        (() => {
            const fill = (testId) => {
                const style = document.querySelector(`[data-testid="${testId}"]`).style;
                return [style.getPropertyValue('--range-from'), style.getPropertyValue('--range-to')];
            };
            return { intensity: fill('media-filter-intensity'), brightness: fill('media-adjust-brightness'), contrast: fill('media-adjust-contrast') };
        })()
    JS))->toBe([
        'intensity' => ['0%', 'calc(7px + (100% - 14px) * 0.4)'],
        'brightness' => ['calc(7px + (100% - 14px) * 0.5)', 'calc(7px + (100% - 14px) * 0.8)'],
        'contrast' => ['calc(7px + (100% - 14px) * 0.5)', 'calc(7px + (100% - 14px) * 0.5)'],
    ]);

    $page->click('@media-filter-original');
    waitForGone($page, '@media-filter-intensity');
    $page->assertMissing('@media-filter-intensity')
        ->assertNoJavaScriptErrors();
});

test('an image stored on another host is edited through the app, so applying works without CORS', function () {
    [$post] = seedMediaEditorPost();
    $row = Media::factory()->ownedByPost($post)->create(['path' => 'uploads/remote.png', 'mime_type' => 'image/png', 'collection' => Media::COLLECTION_MEDIA]);
    Storage::put('uploads/remote.png', (string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
    $post->update(['media' => [[
        'id' => $row->id,
        'type' => 'image',
        'mime_type' => 'image/png',
        'path' => 'uploads/remote.png',
        'url' => 'https://storage.example.test/uploads/remote.png',
        'size' => 1024,
        'meta' => ['width' => 200, 'height' => 200],
    ]]]);
    $page = visit(route('app.posts.edit', $post));
    openMediaEditorPanel($page, $post->social_account_id);

    $page->click('@media-editor-rotate-right')
        ->click('@media-editor-apply');
    waitForGoneOrShown($page, gone: '@media-editor', shown: '@media-editor-error');

    $page->assertMissing('@media-editor-error')
        ->assertMissing('@media-editor');
});

/**
 * @return array{red: int, green: int, blue: int}
 */
function mediaEditorSavedPixel(Post $post, int $x, int $y): array
{
    $image = imagecreatefromstring(Storage::get($post->ownedMedia()->sole()->path));
    $color = imagecolorsforindex($image, imagecolorat($image, $x, $y));

    return ['red' => $color['red'], 'green' => $color['green'], 'blue' => $color['blue']];
}

function setMediaEditorRange(mixed $page, string $testId, int $value): void
{
    $page->script("(() => { const input = document.querySelector('[data-testid=\"{$testId}\"]'); input.value = {$value}; input.dispatchEvent(new Event('input', { bubbles: true })); })()");
}

test('the filter intensity reaches the saved pixels', function (int $intensity) {
    [$post] = seedMediaEditorPost();
    $page = visit(route('app.posts.edit', $post));
    openMediaEditor($page, $post->social_account_id);

    $page->click('@media-editor-appearance-section')->click('@media-filter-mono');
    waitForState($page, '@media-filter-intensity', 'true');
    setMediaEditorRange($page, 'media-filter-intensity', $intensity);
    $page->click('@media-editor-apply');
    saveMediaEditorDraft($page);

    $red = mediaEditorSavedPixel($post, 50, 50);

    if ($intensity === 100) {
        expect(abs($red['red'] - $red['green']))->toBeLessThan(6);

        return;
    }

    expect($red['red'])->toBeGreaterThan($red['green'] + 60)
        ->and($red['green'])->toBeGreaterThan(20);
})->with([100]);

test('a crop with a filter on an image stored on another host is applied and saved', function () {
    [$post] = seedMediaEditorPost();
    $row = Media::factory()->ownedByPost($post)->create(['path' => 'uploads/remote.png', 'mime_type' => 'image/png', 'collection' => Media::COLLECTION_MEDIA]);
    Storage::put('uploads/remote.png', (string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
    $post->update(['media' => [[
        'id' => $row->id,
        'type' => 'image',
        'mime_type' => 'image/png',
        'path' => 'uploads/remote.png',
        'url' => 'https://storage.example.test/uploads/remote.png',
        'size' => 1024,
        'meta' => ['width' => 200, 'height' => 200],
    ]]]);
    $page = visit(route('app.posts.edit', $post));
    openMediaEditorPanel($page, $post->social_account_id);

    $page->click('@crop-aspect-1-91-1')
        ->click('@media-editor-appearance-section')
        ->click('@media-filter-sepia')
        ->click('@media-editor-apply');
    saveMediaEditorDraft($page);

    $saved = $post->fresh()->ownedMedia()->get()->firstWhere('id', '!=', $row->id);
    [$width, $height] = getimagesizefromstring(Storage::get($saved->path));

    expect($width / $height)->toEqualWithDelta(1.91, 0.02);
    $page->assertNoJavaScriptErrors();
});