from unittest.mock import MagicMock

from fastpluggy.core.topbar import TopbarAction


class TestToAdminRow:
    def test_modal_action(self):
        widget_cls = MagicMock(__name__="ButtonListWidget")
        action = TopbarAction(
            id="test-modal",
            icon="ti ti-star",
            tooltip="Modal action",
            position=10,
            modal_widgets=[{"widget": widget_cls}],
        )
        row = action.to_admin_row()

        assert "<code>test-modal</code>" in row["id"]
        assert row["tooltip"] == "Modal action"
        assert "modal" in row["type"]
        assert "ButtonListWidget" in row["widgets"]
        assert "10" in row["position"]

    def test_modal_action_multiple_widgets(self):
        w1 = MagicMock(__name__="WidgetA")
        w2 = MagicMock(__name__="WidgetB")
        action = TopbarAction(
            id="multi",
            icon="ti ti-star",
            modal_widgets=[{"widget": w1}, {"widget": w2}],
        )
        row = action.to_admin_row()

        assert "WidgetA" in row["widgets"]
        assert "WidgetB" in row["widgets"]

    def test_js_onclick_action(self):
        action = TopbarAction(
            id="test-js",
            icon="ti ti-bug",
            tooltip="JS action",
            js_onclick="doSomething()",
        )
        row = action.to_admin_row()

        assert "js" in row["type"]
        assert "doSomething()" in row["widgets"]

    def test_js_onclick_escapes_xss(self):
        action = TopbarAction(
            id="xss",
            icon="ti ti-bug",
            js_onclick='alert("<script>xss</script>")',
        )
        row = action.to_admin_row()

        assert "<script>" not in row["widgets"]
        assert "&lt;script&gt;" in row["widgets"]

    def test_url_action(self):
        action = TopbarAction(
            id="test-url",
            icon="ti ti-link",
            tooltip="URL action",
            url="/my-page",
        )
        row = action.to_admin_row()

        assert "url" in row["type"]
        assert 'href="/my-page"' in row["widgets"]
        assert "/my-page</a>" in row["widgets"]

    def test_url_escapes_xss(self):
        action = TopbarAction(
            id="xss-url",
            icon="ti ti-link",
            url='"><script>xss</script>',
        )
        row = action.to_admin_row()

        assert "<script>" not in row["widgets"]

    def test_empty_action(self):
        action = TopbarAction(id="test-empty", icon="ti ti-x")
        row = action.to_admin_row()

        assert "—" in row["type"]
        assert row["widgets"] == ""
        assert row["tooltip"] == "—"

    def test_default_position(self):
        action = TopbarAction(id="default-pos", icon="ti ti-x")
        row = action.to_admin_row()

        assert "50" in row["position"]
