"""Tests for sidebar collapse/expand and localStorage persistence."""

from __future__ import annotations

import re
from typing import TYPE_CHECKING

import pytest
from playwright.sync_api import expect

if TYPE_CHECKING:
    from playwright.sync_api import Page

pytestmark = pytest.mark.e2e


class TestSidebar:
    """Sidebar collapse/expand behavior and localStorage persistence."""

    def test_collapse_button(self, dashboard: Page) -> None:
        """Clicking collapse hides the sidebar full content."""
        dashboard.locator("#collapse-btn").click()
        expect(dashboard.locator("#sidebar")).to_have_class(re.compile(r"collapsed"))

    def test_expand_button(self, dashboard: Page) -> None:
        """Clicking expand restores the sidebar."""
        dashboard.locator("#collapse-btn").click()
        expect(dashboard.locator("#sidebar")).to_have_class(re.compile(r"collapsed"))
        dashboard.locator("#expand-btn").click()
        sidebar_classes = dashboard.locator("#sidebar").get_attribute("class") or ""
        assert "collapsed" not in sidebar_classes

    def test_collapse_persists_to_localstorage(self, dashboard: Page) -> None:
        """Collapsing sets localStorage sidebar-collapsed to '1'."""
        dashboard.locator("#collapse-btn").click()
        value = dashboard.evaluate("() => localStorage.getItem('sidebar-collapsed')")
        assert "1" == value

    def test_state_restored_on_reload(self, dashboard: Page, base_url: str) -> None:
        """Collapsed state persists across page reloads."""
        dashboard.locator("#collapse-btn").click()
        dashboard.goto(base_url)
        expect(dashboard.locator("#sidebar")).to_have_class(re.compile(r"collapsed"))

    def test_expand_clears_localstorage(self, dashboard: Page) -> None:
        """Expanding sets localStorage sidebar-collapsed to '0'."""
        dashboard.locator("#collapse-btn").click()
        dashboard.locator("#expand-btn").click()
        value = dashboard.evaluate("() => localStorage.getItem('sidebar-collapsed')")
        assert "0" == value
