# retoor <retoor@molodetz.nl>

import re
from playwright.sync_api import expect
from tests.conftest import BASE_URL

UNICORN = "\U0001F984"
def _open_composer(page):
    page.goto(f"{BASE_URL}/feed", wait_until="domcontentloaded")
    page.locator(".feed-fab").first.wait_for(state="visible", timeout=10000)
    page.locator(".feed-fab").first.click()
def _create_plain_post_engagement_ui(page, content):
    _open_composer(page)
    page.fill("#post-content", content)
    page.locator("#create-post-modal button.btn-primary:has-text('Post')").click()
    page.wait_for_url(f"{BASE_URL}/posts/*", wait_until="domcontentloaded")


def test_poll_builder_hidden_until_add_poll(alice):
    page, _ = alice
    _open_composer(page)
    expect(page.locator("[data-poll-builder]")).to_be_hidden()
    page.locator("[data-poll-toggle]").click()
    expect(page.locator("[data-poll-builder]")).to_be_visible()


def test_reaction_palette_toggle_and_react(alice):
    page, _ = alice
    _create_plain_post_engagement_ui(page, "Post to react to in the reaction UI test.")

    expect(page.locator(".reaction-chip:visible")).to_have_count(0)
    expect(page.locator(".reaction-palette").first).to_be_hidden()

    page.locator(".reaction-add-btn").first.click()
    expect(page.locator(".reaction-palette").first).to_be_visible()

    page.locator(".reaction-palette-btn").first.click()
    expect(page.locator(".reaction-chip.reacted").first).to_be_visible()
    expect(
        page.locator(".reaction-chip.reacted").first.locator(".reaction-count")
    ).to_have_text("1")


def test_reaction_with_an_emoji_outside_the_palette(alice):
    page, _ = alice
    _create_plain_post_engagement_ui(page, "Post to react to with an off-palette emoji.")

    page.locator(".reaction-add-btn").first.click()
    page.locator(".reaction-palette-more").first.click()

    picker = page.locator(".reaction-picker").first
    picker.wait_for(state="visible")
    picker.locator("emoji-picker").wait_for(state="attached")

    page.evaluate(
        """(unicode) => {
            const picker = document.querySelector(".reaction-picker emoji-picker");
            picker.dispatchEvent(new CustomEvent("emoji-click", { detail: { unicode } }));
        }""",
        UNICORN,
    )

    chip = page.locator(f'.reaction-chip[data-reaction-emoji="{UNICORN}"]')
    expect(chip).to_be_visible()
    expect(chip).to_have_class(re.compile("reacted"))
    expect(chip.locator(".reaction-count")).to_have_text("1")
    expect(picker).to_be_hidden()

    page.reload(wait_until="domcontentloaded")
    reloaded = page.locator(f'.reaction-chip[data-reaction-emoji="{UNICORN}"]')
    expect(reloaded).to_be_visible()
    expect(reloaded.locator(".reaction-count")).to_have_text("1")
