"""
Tests for the unified navigation overlay (TOC + Bookmarks tabs)
"""
import pytest
from pathlib import Path
from PIL import Image

from dreader.application import EbookReader
from dreader.state import OverlayState
from dreader.gesture import TouchEvent, GestureType, ActionType


@pytest.fixture
def reader_with_book():
    """Create a reader with a test book loaded"""
    reader = EbookReader(page_size=(400, 600), margin=10)

    # Load a simple test book
    test_book = Path(__file__).parent.parent / "examples" / "books" / "hamlet.epub"
    if test_book.exists():
        reader.load_epub(str(test_book))
    else:
        # Fallback: create simple HTML for testing
        html = """
        <html>
        <body>
        <h1>Chapter 1</h1>
        <p>This is chapter 1 content</p>
        <h1>Chapter 2</h1>
        <p>This is chapter 2 content</p>
        </body>
        </html>
        """
        reader.load_html(html, title="Test Book", author="Test Author", document_id="test")

    yield reader
    reader.close()


def test_open_navigation_overlay_contents_tab(reader_with_book):
    """Test opening navigation overlay with Contents tab active"""
    reader = reader_with_book

    # Open navigation overlay with contents tab
    image = reader.open_navigation_overlay(active_tab="contents")

    assert image is not None
    assert isinstance(image, Image.Image)
    assert reader.get_overlay_state() == OverlayState.NAVIGATION
    assert reader.is_overlay_open()


def test_open_navigation_overlay_bookmarks_tab(reader_with_book):
    """Test opening navigation overlay with Bookmarks tab active"""
    reader = reader_with_book

    # Save a bookmark first
    reader.save_position("Test Bookmark")

    # Open navigation overlay with bookmarks tab
    image = reader.open_navigation_overlay(active_tab="bookmarks")

    assert image is not None
    assert isinstance(image, Image.Image)
    assert reader.get_overlay_state() == OverlayState.NAVIGATION


def test_switch_navigation_tabs(reader_with_book):
    """Test switching between Contents and Bookmarks tabs"""
    reader = reader_with_book

    # Open with contents tab
    reader.open_navigation_overlay(active_tab="contents")

    # Switch to bookmarks
    image = reader.switch_navigation_tab("bookmarks")
    assert image is not None
    assert reader.get_overlay_state() == OverlayState.NAVIGATION

    # Switch back to contents
    image = reader.switch_navigation_tab("contents")
    assert image is not None
    assert reader.get_overlay_state() == OverlayState.NAVIGATION


def test_close_navigation_overlay(reader_with_book):
    """Test closing navigation overlay"""
    reader = reader_with_book

    # Open overlay
    reader.open_navigation_overlay()
    assert reader.is_overlay_open()

    # Close overlay
    image = reader.close_overlay()
    assert image is not None
    assert not reader.is_overlay_open()
    assert reader.get_overlay_state() == OverlayState.NONE


def test_navigation_overlay_tab_switching_gesture(reader_with_book):
    """Test tab switching via gesture/touch handling"""
    reader = reader_with_book

    # Open navigation overlay
    reader.open_navigation_overlay(active_tab="contents")

    # Query the overlay to find the bookmarks tab button
    # This would normally be done by finding the coordinates of the "Bookmarks" tab
    # For now, we test that the switch method works
    result = reader.switch_navigation_tab("bookmarks")

    assert result is not None
    assert reader.get_overlay_state() == OverlayState.NAVIGATION


def test_navigation_overlay_with_no_bookmarks(reader_with_book):
    """Test navigation overlay when there are no bookmarks"""
    reader = reader_with_book

    # Open bookmarks tab (should show "No bookmarks yet")
    image = reader.open_navigation_overlay(active_tab="bookmarks")

    assert image is not None
    # The overlay should still open successfully
    assert reader.get_overlay_state() == OverlayState.NAVIGATION


def test_navigation_overlay_preserves_page_position(reader_with_book):
    """Test that opening/closing navigation overlay preserves reading position"""
    reader = reader_with_book

    # Go to page 2
    reader.next_page()
    initial_position = reader.get_position_info()

    # Open and close navigation overlay
    reader.open_navigation_overlay()
    reader.close_overlay()

    # Verify position hasn't changed
    final_position = reader.get_position_info()
    assert initial_position == final_position


def test_navigation_overlay_chapter_selection(reader_with_book):
    """Test selecting a chapter from the navigation overlay"""
    reader = reader_with_book

    # Get chapters
    chapters = reader.get_chapters()
    if len(chapters) < 2:
        pytest.skip("Test book doesn't have enough chapters")

    # Open navigation overlay
    reader.open_navigation_overlay(active_tab="contents")

    # Get initial position
    initial_position = reader.get_position_info()

    # Jump to chapter via the reader method (simulating a tap on chapter)
    reader.jump_to_chapter(chapters[1][1])  # chapters[1] = (title, index)
    reader.close_overlay()

    # Verify position changed
    new_position = reader.get_position_info()
    assert new_position != initial_position


def test_navigation_overlay_bookmark_selection(reader_with_book):
    """Test selecting a bookmark from the navigation overlay"""
    reader = reader_with_book

    # Save a bookmark at page 1
    reader.save_position("Bookmark 1")

    # Move to a different page
    reader.next_page()
    position_before = reader.get_position_info()

    # Open navigation overlay with bookmarks tab
    reader.open_navigation_overlay(active_tab="bookmarks")

    # Load the bookmark (simulating a tap on bookmark)
    page = reader.load_position("Bookmark 1")
    assert page is not None

    reader.close_overlay()

    # Verify position changed back to bookmark
    position_after = reader.get_position_info()
    assert position_after != position_before


if __name__ == "__main__":
    pytest.main([__file__, "-v"])
