# Unified Media Info Dialog (Movie + Episode)

import xbmc
import xbmcgui
import xbmcaddon
import threading
import time
from wcs.games.GameManager import GameController

# Sdílené menu stavy, ve kterých má tlačítko Zavřít (index 3) ukončit herní panel
CLOSE_DIALOG_STATES = [
    "game_selection",
    "ended",
    "quiz_transition",
    "quiz_welcome",
    "quiz_instructions",
    "millionaire_welcome",
    "millionaire_rules",
    "adventure_welcome",
    "adventure_instructions",
    "error",
    "game_finished",
    "game_over",
    "placeholder",
]


class MediaInfoDialog(xbmcgui.WindowXMLDialog):
    """
    Jednotný dialog pro zobrazení informací o filmu nebo epizodě včetně textové hry.

    media_type:
      - "movie": používá prefix `WCS.Movie.*` a filmové XML
      - "series": používá prefix `WCS.Episode.*` a epizodní XML
    """

    def __init__(
        self,
        xmlFilename,
        addonPath,
        skin="Default",
        theme="Default",
        *,
        media_type="movie",
        # Movie fields
        movie_title="",
        movie_year="",
        movie_thumb="",
        genre="",
        director="",
        runtime="",
        # Episode fields
        series_name="",
        episode_title="",
        season_number=None,
        episode_number=None,
        episode_thumb="",
        year="",
        # Common fields
        rating="",
        plot="",
        tmdb_id="",
        fanart="",
    ):
        super().__init__()
        self.media_type = media_type

        # Common
        self.rating = rating
        self.plot = plot
        self.tmdb_id = tmdb_id
        self.fanart = fanart

        # Movie
        self.movie_title = movie_title
        self.movie_year = movie_year
        self.movie_thumb = movie_thumb
        self.genre = genre
        self.director = director
        self.runtime = runtime

        # Episode
        self.series_name = series_name
        self.episode_title = episode_title
        self.season_number = season_number
        self.episode_number = episode_number
        self.episode_thumb = episode_thumb
        self.year = year

        # State
        self.auto_close_thread = None
        self.is_running = False
        self.plot_visible = False
        self.game_visible = False
        self.game_controller = None
        self.future_feature_mode = False

    # ---------- Utilities ----------
    @staticmethod
    def _get_dialog_xml_filename_for_media(media_type: str) -> str:
        try:
            addon = xbmcaddon.Addon()
            style_index = int(addon.getSetting('dialog_style') or 0)
            if media_type == "movie":
                style_files = [
                    'notifications/classic/DialogMovieInfoWithGame.xml',
                    'notifications/modern/DialogMovieInfoWithGame.xml',
                    'notifications/minimal/DialogMovieInfoWithGame.xml',
                ]
            else:
                style_files = [
                    'notifications/classic/DialogEpisodeInfoWithGame.xml',
                    'notifications/modern/DialogEpisodeInfoWithGame.xml',
                    'notifications/minimal/DialogEpisodeInfoWithGame.xml',
                ]
            filename = style_files[style_index] if 0 <= style_index < len(style_files) else style_files[0]
            xbmc.log(f"[plugin.video.wcs] MediaInfoDialog: Using style index '{style_index}' -> {filename}", level=xbmc.LOGINFO)
            return filename
        except Exception as e:
            xbmc.log(f"[plugin.video.wcs] MediaInfoDialog: Error getting dialog style, using default: {e}", level=xbmc.LOGWARNING)
            return 'notifications/classic/DialogMovieInfoWithGame.xml' if media_type == "movie" else 'notifications/classic/DialogEpisodeInfoWithGame.xml'

    def _prefix(self) -> str:
        return 'WCS.Movie' if self.media_type == 'movie' else 'WCS.Episode'

    # ---------- Lifecycle ----------
    def onInit(self):
        xbmc.log("[plugin.video.wcs] MediaInfoDialog: Initializing", level=xbmc.LOGINFO)

        if self.media_type == 'movie':
            self._init_movie_properties()
        else:
            self._init_episode_properties()

        # Inicializace viditelnosti sekcí
        self.setProperty(f'{self._prefix()}.ShowPlot', 'false')
        self.setProperty(f'{self._prefix()}.ShowGame', 'false')

        # Herní properties
        self.setProperty('WCS.Game.Title', '')
        self.setProperty('WCS.Game.Text', '')
        self.setProperty('WCS.Game.Button1', '')
        self.setProperty('WCS.Game.Button2', '')
        self.setProperty('WCS.Game.Button3', '')
        self.setProperty('WCS.Game.Button4', '')

        # Auto-close
        self.is_running = True
        self.auto_close_thread = threading.Thread(target=self._auto_close_worker)
        self.auto_close_thread.daemon = True
        self.auto_close_thread.start()

    def _auto_close_worker(self):
        time.sleep(5)
        if self.is_running:
            xbmc.executebuiltin("Action(Back)")

    # ---------- Init helpers ----------
    def _format_rating_properties(self, rating_value: str, year_value: str):
        rating_formatted = ""
        rating_only_text = ""
        year_only_text = ""
        if rating_value:
            try:
                rating_float = float(rating_value)
                rating_formatted = f"{rating_float:.1f}"
            except (ValueError, TypeError):
                rating_formatted = str(rating_value)
            rating_only_text = f"★ {rating_formatted}/10"
            if year_value:
                rating_text = f"★ {rating_formatted}/10 • {year_value}"
                year_only_text = f"• {year_value}"
            else:
                rating_text = f"★ {rating_formatted}/10"
        else:
            rating_text = year_value if year_value else ""
            if year_value:
                year_only_text = f"• {year_value}"

        try:
            rating_progress = min(100, max(0, int(float(rating_formatted) * 10))) if rating_formatted else 0
        except (ValueError, TypeError):
            rating_progress = 0
        return rating_text, rating_formatted, rating_only_text, year_only_text, rating_progress

    def _init_movie_properties(self):
        # Základní
        self.setProperty('WCS.Movie.Title', self.movie_title)
        self.setProperty('WCS.Movie.Year', self.movie_year)
        self.setProperty('WCS.Movie.Fanart', self.fanart)
        self.setProperty('WCS.Movie.Genre', self.genre)
        self.setProperty('WCS.Movie.Director', self.director)
        self.setProperty('WCS.Movie.Runtime', self.runtime)

        rating_text, rating_formatted, rating_only_text, year_only_text, rating_progress = self._format_rating_properties(self.rating, self.movie_year)
        self.setProperty('WCS.Movie.Rating', rating_text)
        self.setProperty('WCS.Movie.RatingFormatted', rating_formatted)
        self.setProperty('WCS.Movie.RatingOnly', rating_only_text)
        self.setProperty('WCS.Movie.YearOnly', year_only_text)
        self.setProperty('WCS.Movie.RatingProgress', str(rating_progress))

        self.setProperty('WCS.Movie.TMDBID', self.tmdb_id)
        self.setProperty('WCS.Movie.Fanart', self.fanart)
        self.setProperty('WCS.Movie.Plot', self.plot or "Popis filmu není dostupný.")

        full_info_text = self._create_full_info_text_movie()
        self.setProperty('WCS.Movie.FullInfo', full_info_text)

    def _init_episode_properties(self):
        # Základní
        self.setProperty('WCS.Episode.SeriesName', self.series_name)
        self.setProperty('WCS.Episode.Title', self.episode_title)

        if self.season_number and self.episode_number:
            season_episode = f"S{int(self.season_number):02d}E{int(self.episode_number):02d}"
        else:
            season_episode = "Neznámá epizoda"
        self.setProperty('WCS.Episode.SeasonEpisode', season_episode)

        self.setProperty('WCS.Episode.Thumb', self.episode_thumb)

        rating_text, rating_formatted, rating_only_text, year_only_text, rating_progress = self._format_rating_properties(self.rating, self.year)
        self.setProperty('WCS.Episode.Rating', rating_text)
        self.setProperty('WCS.Episode.RatingFormatted', rating_formatted)
        self.setProperty('WCS.Episode.RatingOnly', rating_only_text)
        self.setProperty('WCS.Episode.YearOnly', year_only_text)
        self.setProperty('WCS.Episode.RatingProgress', str(rating_progress))

        self.setProperty('WCS.Episode.SeriesTMDBID', self.tmdb_id)
        self.setProperty('WCS.Episode.SeriesFanart', self.fanart)
        self.setProperty('WCS.Episode.Plot', self.plot or "Popis epizody není dostupný.")

        full_info_text = self._create_full_info_text_episode()
        self.setProperty('WCS.Episode.FullInfo', full_info_text)

    # ---------- Kodi actions ----------
    def onAction(self, action):
        navigation_actions = [
            xbmcgui.ACTION_MOVE_LEFT,
            xbmcgui.ACTION_MOVE_RIGHT,
            xbmcgui.ACTION_MOVE_UP,
            xbmcgui.ACTION_MOVE_DOWN,
            xbmcgui.ACTION_SELECT_ITEM,
            xbmcgui.ACTION_MOUSE_MOVE,
        ]
        if action.getId() in navigation_actions:
            self.is_running = False
            xbmc.log("[plugin.video.wcs] MediaInfoDialog: Auto-close cancelled due to user navigation", level=xbmc.LOGINFO)
            return

        if action.getId() in (xbmcgui.ACTION_PREVIOUS_MENU, xbmcgui.ACTION_NAV_BACK):
            self.is_running = False
            self.close()

    def onClick(self, controlId):
        prefix = self._prefix()
        if controlId == 101:  # Info tlačítko - toggle plot
            if self.game_visible:
                self.game_visible = False
                self.setProperty(f'{prefix}.ShowGame', 'false')
            self.plot_visible = not self.plot_visible
            self.setProperty(f'{prefix}.ShowPlot', 'true' if self.plot_visible else 'false')
            xbmc.log(f"[plugin.video.wcs] MediaInfoDialog: Plot visibility toggled to {self.plot_visible}", level=xbmc.LOGINFO)

        elif controlId == 104:  # Hrát hru - toggle game
            if self.plot_visible:
                self.plot_visible = False
                self.setProperty(f'{prefix}.ShowPlot', 'false')
            self.game_visible = not self.game_visible
            self.setProperty(f'{prefix}.ShowGame', 'true' if self.game_visible else 'false')

            if self.game_visible and not self.game_controller:
                self.start_game()
                try:
                    self.setFocus(self.getControl(301))
                except Exception:
                    pass
            elif not self.game_visible and self.game_controller:
                self.game_controller = None
            xbmc.log(f"[plugin.video.wcs] MediaInfoDialog: Game visibility toggled to {self.game_visible}", level=xbmc.LOGINFO)

        elif controlId == 102:  # Zavřít
            self.is_running = False
            self.close()

        elif controlId == 501:  # Upravit příběh (future)
            title = "Upravit příběh"
            if self.media_type == 'movie':
                desc = (
                    "Tato funkce umožní upravovat původní příběhy filmů pomocí pokročilé AI.\n\n"
                    "Budete moci:\n"
                    "• Měnit děj podle vlastních představ\n"
                    "• Vytvářet alternativní zakončení\n"
                    "• Přidávat nové postavy a situace\n"
                    "• Upravovat dialogy a scény\n"
                    "• Měnit žánr nebo atmosféru\n\n"
                    "Funkce bude dostupná, až bude AI dostatečně pokročilá pro tvorbu kvalitních upravených filmů."
                )
            else:
                desc = (
                    "Tato funkce umožní upravovat původní příběhy seriálů a epizod pomocí pokročilé AI.\n\n"
                    "Budete moci:\n"
                    "• Měnit děj podle vlastních představ\n"
                    "• Vytvářet alternativní zakončení\n"
                    "• Přidávat nové postavy a situace\n"
                    "• Upravovat dialogy a scény\n\n"
                    "Funkce bude dostupná, až bude AI dostatečně pokročilá pro tvorbu kvalitních upravených seriálů."
                )
            self.show_future_feature_info(title, desc)

        elif controlId == 502:  # Uložené úpravy (future)
            title = "Uložené úpravy"
            if self.media_type == 'movie':
                desc = (
                    "Zde budete moci spravovat všechny své uložené úpravy příběhů filmů.\n\n"
                    "Funkce zahrnuje:\n"
                    "• Seznam všech upravených filmů\n"
                    "• Možnost obnovení původních verzí\n"
                    "• Sdílení úprav s jinými uživateli\n"
                    "• Export upravených příběhů\n"
                    "• Verzování a historie změn\n"
                    "• Kategorizace podle žánru\n\n"
                    "Tato funkce bude implementována společně s funkcí úprav příběhů."
                )
            else:
                desc = (
                    "Zde budete moci spravovat všechny své uložené úpravy příběhů.\n\n"
                    "Funkce zahrnuje:\n"
                    "• Seznam všech upravených seriálů a epizod\n"
                    "• Možnost obnovení původních verzí\n"
                    "• Sdílení úprav s jinými uživateli\n"
                    "• Export upravených příběhů\n"
                    "• Verzování a historie změn\n\n"
                    "Tato funkce bude implementována společně s funkcí úprav příběhů."
                )
            self.show_future_feature_info(title, desc)

        elif controlId == 503:  # Návrat
            if self.future_feature_mode:
                self.future_feature_mode = False
                full_info_text = (
                    self._create_full_info_text_movie()
                    if self.media_type == 'movie'
                    else self._create_full_info_text_episode()
                )
                self.setProperty(f'{prefix}.FullInfo', full_info_text)
                try:
                    self.setFocus(self.getControl(501))
                except Exception:
                    pass
            else:
                self.plot_visible = False
                self.setProperty(f'{prefix}.ShowPlot', 'false')
                try:
                    self.setFocus(self.getControl(101))
                except Exception:
                    pass

        elif controlId in [301, 302, 303, 304] and self.game_controller:
            choice_index = controlId - 301
            current_state = self.game_controller.current_game_state
            xbmc.log(
                f"[plugin.video.wcs] MediaInfoDialog button {choice_index} pressed, game_state: {current_state}",
                level=xbmc.LOGINFO,
            )

            if choice_index == 3 and current_state in CLOSE_DIALOG_STATES:
                xbmc.log(
                    f"[plugin.video.wcs] MediaInfoDialog: Closing game dialog (button 3 in menu state {current_state})",
                    level=xbmc.LOGINFO,
                )
                self.game_visible = False
                self.setProperty(f'{prefix}.ShowGame', 'false')
                self.game_controller = None
                try:
                    self.setFocus(self.getControl(104))
                except Exception:
                    pass
            else:
                xbmc.log(
                    f"[plugin.video.wcs] MediaInfoDialog: Delegating choice {choice_index} to game_controller (state: {current_state})",
                    level=xbmc.LOGINFO,
                )
                self.game_controller.make_choice(choice_index)

    # ---------- Game ----------
    def start_game(self):
        try:
            if self.media_type == 'movie':
                self.game_controller = GameController(
                    title=self.movie_title,
                    plot=self.plot,
                    genre=self.genre,
                    media_type="movie",
                )
                self.setProperty('WCS.Game.Title', f"pro {self.movie_title}")
            else:
                self.game_controller = GameController(
                    title=self.series_name,
                    plot=self.plot,
                    genre="",
                    media_type="series",
                    episode_title=self.episode_title,
                    season_number=self.season_number,
                    episode_number=self.episode_number,
                )
                self.setProperty('WCS.Game.Title', self.series_name)

            self.game_controller.set_ui_callbacks(
                self.update_game_display,
                self.update_game_buttons,
                self.update_game_sidebar,
                self.show_game_error,
                self.set_game_focus,
                self.start_countdown,
            )
            self.game_controller.start_game_selection()
        except Exception as e:
            xbmc.log(f"[plugin.video.wcs] MediaInfoDialog: Error starting game: {e}", level=xbmc.LOGERROR)
            self.show_game_error("Chyba při spuštění hry.")

    def update_game_display(self, text):
        try:
            self.setProperty('WCS.Game.Text', text)
        except Exception as e:
            xbmc.log(f"[plugin.video.wcs] Error updating game display: {e}", level=xbmc.LOGERROR)

    def update_game_buttons(self, text1, text2, text3, text4=""):
        try:
            self.setProperty('WCS.Game.Button1', text1)
            self.setProperty('WCS.Game.Button2', text2)
            self.setProperty('WCS.Game.Button3', text3)
            self.setProperty('WCS.Game.Button4', text4)
        except Exception as e:
            xbmc.log(f"[plugin.video.wcs] Error updating game buttons: {e}", level=xbmc.LOGERROR)

    def update_game_sidebar(self):
        # Pro kompatibilitu – sidebar v těchto dialozích nepoužíváme
        pass

    def show_game_error(self, message):
        try:
            self.setProperty('WCS.Game.Text', f"Chyba: {message}")
            # Zobrazení jednoho akčního tlačítka, ostatní prázdná
            self.setProperty('WCS.Game.Button1', "Zavřít")
            self.setProperty('WCS.Game.Button2', "")
            self.setProperty('WCS.Game.Button3', "")
            self.setProperty('WCS.Game.Button4', "")
        except Exception as e:
            xbmc.log(f"[plugin.video.wcs] Error showing game error: {e}", level=xbmc.LOGERROR)

    def set_game_focus(self, button_index):
        try:
            control_id = 301 + button_index  # 0->301, 1->302, 2->303, 3->304
            self.setFocus(self.getControl(control_id))
            xbmc.log(
                f"[plugin.video.wcs] Focus set to game button {button_index} (control {control_id})",
                level=xbmc.LOGINFO,
            )
        except Exception as e:
            xbmc.log(f"[plugin.video.wcs] Error setting game focus to button {button_index}: {e}", level=xbmc.LOGERROR)

    def start_countdown(self, seconds, finish_callback):
        def countdown_worker():
            try:
                original_text = ""
                try:
                    original_text = self.getProperty('WCS.Game.Text')
                except Exception:
                    pass

                if "Vyhodnocení odpovědi..." in original_text:
                    base_text = original_text.split("Vyhodnocení odpovědi...")[0]
                else:
                    base_text = original_text

                for i in range(seconds, 0, -1):
                    countdown_text = base_text + f"Vyhodnocení za {i} sekund..."
                    self.setProperty('WCS.Game.Text', countdown_text)
                    time.sleep(1)

                finish_callback()
            except Exception as e:
                xbmc.log(f"[plugin.video.wcs] Error in countdown: {e}", level=xbmc.LOGERROR)
                finish_callback()

        countdown_thread = threading.Thread(target=countdown_worker)
        countdown_thread.daemon = True
        countdown_thread.start()

    # ---------- Info text ----------
    def _create_full_info_text_movie(self) -> str:
        info_parts = []
        info_parts.append("[COLOR FF87CEEB]INFO:[/COLOR]")
        try:
            import json
            json_request = {
                "jsonrpc": "2.0",
                "method": "Player.GetItem",
                "params": {
                    "playerid": 1,
                    "properties": [
                        "director",
                        "genre",
                        "studio",
                        "country",
                        "premiered",
                        "runtime",
                        "tagline",
                        "originaltitle",
                    ],
                },
                "id": 1,
            }
            json_response = xbmc.executeJSONRPC(json.dumps(json_request))
            response_data = json.loads(json_response)
            if "result" in response_data and "item" in response_data["result"]:
                item = response_data["result"]["item"]
                if item.get("director"):
                    directors = ", ".join(item["director"]) if isinstance(item["director"], list) else str(item["director"])
                    info_parts.append(f"Režie: {directors}")
                elif self.director:
                    info_parts.append(f"Režie: {self.director}")

                if item.get("genre"):
                    genres = ", ".join(item["genre"]) if isinstance(item["genre"], list) else str(item["genre"])
                    info_parts.append(f"Žánr: {genres}")
                elif self.genre:
                    info_parts.append(f"Žánr: {self.genre}")

                year_runtime = []
                if self.movie_year:
                    year_runtime.append(f"Rok: {self.movie_year}")
                if item.get("runtime"):
                    runtime_mins = item["runtime"] // 60
                    year_runtime.append(f"Délka: {runtime_mins} min")
                elif self.runtime:
                    year_runtime.append(f"Délka: {self.runtime}")
                if year_runtime:
                    info_parts.append(" • ".join(year_runtime))

                if item.get("studio"):
                    studios = ", ".join(item["studio"]) if isinstance(item["studio"], list) else str(item["studio"])
                    info_parts.append(f"Studio: {studios}")

                if item.get("country"):
                    countries = ", ".join(item["country"]) if isinstance(item["country"], list) else str(item["country"])
                    info_parts.append(f"Země původu: {countries}")

                if item.get("premiered"):
                    info_parts.append(f"Premiéra: {item['premiered']}")

                if item.get("tagline"):
                    info_parts.append(f"Slogan: {item['tagline']}")

                if self.rating:
                    info_parts.append(f"Hodnocení: {self.rating}/10")
        except Exception as e:
            xbmc.log(f"[plugin.video.wcs] Error getting movie metadata: {e}", level=xbmc.LOGWARNING)
            tech_info = []
            if self.director:
                tech_info.append(f"Režie: {self.director}")
            if self.genre:
                tech_info.append(f"Žánr: {self.genre}")
            if self.movie_year:
                tech_info.append(f"Rok: {self.movie_year}")
            if self.runtime:
                tech_info.append(f"Délka: {self.runtime}")
            if self.rating:
                tech_info.append(f"Hodnocení: {self.rating}/10")
            if tech_info:
                info_parts.extend(tech_info)
            else:
                info_parts.append("Technické informace nejsou dostupné.")

        info_parts.append("")
        info_parts.append("[COLOR FF87CEEB]DĚJ:[/COLOR]")
        if self.plot:
            info_parts.append(self.plot)
        else:
            info_parts.append("Popis filmu není dostupný.")
        return "\n".join(info_parts)

    def _create_full_info_text_episode(self) -> str:
        info_parts = []
        info_parts.append("[COLOR FF87CEEB]INFO:[/COLOR]")
        try:
            import json
            json_request = {
                "jsonrpc": "2.0",
                "method": "Player.GetItem",
                "params": {
                    "playerid": 1,
                    "properties": [
                        "director",
                        "genre",
                        "studio",
                        "country",
                        "premiered",
                        "runtime",
                        "showlink",
                        "originaltitle",
                    ],
                },
                "id": 1,
            }
            json_response = xbmc.executeJSONRPC(json.dumps(json_request))
            response_data = json.loads(json_response)
            if "result" in response_data and "item" in response_data["result"]:
                item = response_data["result"]["item"]
                if item.get("director"):
                    directors = ", ".join(item["director"]) if isinstance(item["director"], list) else str(item["director"])
                    info_parts.append(f"Režie: {directors}")
                if item.get("genre"):
                    genres = ", ".join(item["genre"]) if isinstance(item["genre"], list) else str(item["genre"])
                    info_parts.append(f"Žánr: {genres}")
                if item.get("runtime"):
                    runtime_mins = item["runtime"] // 60
                    info_parts.append(f"Délka epizody: {runtime_mins} min")
                elif self.year:
                    info_parts.append(f"Rok: {self.year}")
                if item.get("studio"):
                    studios = ", ".join(item["studio"]) if isinstance(item["studio"], list) else str(item["studio"])
                    info_parts.append(f"Síť/Studio: {studios}")
                if item.get("country"):
                    countries = ", ".join(item["country"]) if isinstance(item["country"], list) else str(item["country"])
                    info_parts.append(f"Země původu: {countries}")
                if item.get("premiered"):
                    info_parts.append(f"Premiéra epizody: {item['premiered']}")
                if self.rating:
                    info_parts.append(f"Hodnocení: {self.rating}/10")
                if self.season_number and self.episode_number:
                    info_parts.append(f"Sezóna {self.season_number}, Epizoda {self.episode_number}")
        except Exception as e:
            xbmc.log(f"[plugin.video.wcs] Error getting episode metadata: {e}", level=xbmc.LOGWARNING)
            tech_info = []
            if self.year:
                tech_info.append(f"Rok: {self.year}")
            if self.rating:
                tech_info.append(f"Hodnocení: {self.rating}/10")
            if self.season_number and self.episode_number:
                tech_info.append(f"Sezóna {self.season_number}, Epizoda {self.episode_number}")
            if tech_info:
                info_parts.extend(tech_info)
            else:
                info_parts.append("Technické informace nejsou dostupné.")

        info_parts.append("")
        info_parts.append("[COLOR FF87CEEB]DĚJ:[/COLOR]")
        if self.plot:
            info_parts.append(self.plot)
        else:
            info_parts.append("Popis epizody není dostupný.")
        return "\n".join(info_parts)

    # ---------- Future feature screen ----------
    def show_future_feature_info(self, title, description):
        try:
            prefix = self._prefix()
            if self.media_type == 'movie':
                info_text = f"[COLOR FFFF6B6B]{title.upper()}[/COLOR]\n\n{description}\n\n[COLOR FF87CEEB]Stiskni 'Návrat' pro pokračování...[/COLOR]"
            else:
                info_text = f"[COLOR FFFF6B6B]{title.upper()}[/COLOR]\n\n{description}\n\n[COLOR FF87CEEB]Stiskni 'Zavřít' pro pokračování...[/COLOR]"
            self.setProperty(f'{prefix}.FullInfo', info_text)

            if self.media_type == 'series':
                # Epizodní varianta mění též texty info tlačítek
                self.setProperty('WCS.Episode.InfoButton1', "")
                self.setProperty('WCS.Episode.InfoButton2', "")
                self.setProperty('WCS.Episode.InfoButton3', "Návrat")

            self.future_feature_mode = True
            try:
                self.setFocus(self.getControl(503))
            except Exception:
                pass
        except Exception as e:
            xbmc.log(f"[plugin.video.wcs] Error showing future feature info: {e}", level=xbmc.LOGERROR)


# ---------------- Managers (API kompatibilita) ----------------

class MovieInfoManager:
    def __init__(self, addon):
        self.addon = addon

    @staticmethod
    def get_dialog_xml_filename():
        return MediaInfoDialog._get_dialog_xml_filename_for_media('movie')

    def show_movie_info(self, movie_title, movie_year="", movie_thumb="", rating="",
                        plot="", tmdb_id="", fanart="", genre="", director="", runtime=""):
        xbmc.log(f"[plugin.video.wcs] MovieInfoManager: Showing movie info dialog for {movie_title} ({movie_year})", level=xbmc.LOGINFO)
        dialog_xml = MovieInfoManager.get_dialog_xml_filename()
        dialog = MediaInfoDialog(
            dialog_xml,
            self.addon.getAddonInfo('path'),
            media_type='movie',
            movie_title=movie_title,
            movie_year=movie_year,
            movie_thumb=movie_thumb,
            rating=rating,
            plot=plot,
            tmdb_id=tmdb_id,
            fanart=fanart,
            genre=genre,
            director=director,
            runtime=runtime,
        )
        xbmc.log("[plugin.video.wcs] MovieInfoManager: About to show dialog modal", level=xbmc.LOGINFO)
        dialog.doModal()
        xbmc.log("[plugin.video.wcs] MovieInfoManager: Dialog modal completed", level=xbmc.LOGINFO)
        del dialog


class EpisodeInfoManager:
    def __init__(self, addon):
        self.addon = addon

    @staticmethod
    def get_dialog_xml_filename():
        return MediaInfoDialog._get_dialog_xml_filename_for_media('series')

    def show_episode_info(self, series_name, episode_title, season_number, episode_number,
                          episode_thumb="", rating="", year="", plot="", tmdb_id="", fanart=""):
        xbmc.log(
            f"[plugin.video.wcs] EpisodeInfoManager: Showing episode info dialog for {series_name} S{season_number}E{episode_number}",
            level=xbmc.LOGINFO,
        )
        dialog_xml = EpisodeInfoManager.get_dialog_xml_filename()
        dialog = MediaInfoDialog(
            dialog_xml,
            self.addon.getAddonInfo('path'),
            media_type='series',
            series_name=series_name,
            episode_title=episode_title,
            season_number=season_number,
            episode_number=episode_number,
            episode_thumb=episode_thumb,
            rating=rating,
            year=year,
            plot=plot,
            tmdb_id=tmdb_id,
            fanart=fanart,
        )
        xbmc.log("[plugin.video.wcs] EpisodeInfoManager: About to show dialog modal", level=xbmc.LOGINFO)
        dialog.doModal()
        xbmc.log("[plugin.video.wcs] EpisodeInfoManager: Dialog modal completed", level=xbmc.LOGINFO)
        del dialog


# Global getters (zachování API)
_movie_info_manager = None
_episode_info_manager = None
_autoplay_manager = None


def get_movie_info_manager():
    global _movie_info_manager
    if _movie_info_manager is None:
        addon = xbmcaddon.Addon()
        _movie_info_manager = MovieInfoManager(addon)
    return _movie_info_manager


def get_episode_info_manager():
    global _episode_info_manager
    if _episode_info_manager is None:
        addon = xbmcaddon.Addon()
        _episode_info_manager = EpisodeInfoManager(addon)
    return _episode_info_manager


# ---------------- AUTOPLAY COUNTDOWN (sjednoceno) ----------------

class AutoplayCountdownDialog(xbmcgui.WindowXMLDialog):
    ACTION_PLAY_NOW = 1
    ACTION_CANCEL_AUTOPLAY = 2
    ACTION_TIMEOUT = 3

    def __init__(self, xmlFilename, addonPath, skin="Default", theme="Default",
                 show_countdown_at=25, next_episode_title="", next_episode_season_episode="", next_episode_thumb="",
                 series_name="", series_tmdb_id="", series_fanart="", current_episode_plot="", next_episode_rating="",
                 next_episode_rating_only="", next_episode_year_only="", timeout_callback=None):
        super().__init__()
        self.countdown_duration = show_countdown_at
        self.next_episode_title = next_episode_title
        self.next_episode_season_episode = next_episode_season_episode
        self.next_episode_thumb = next_episode_thumb
        self.series_name = series_name
        self.series_tmdb_id = series_tmdb_id
        self.series_fanart = series_fanart
        self.current_episode_plot = current_episode_plot
        self.next_episode_rating = next_episode_rating
        self.next_episode_rating_only = next_episode_rating_only
        self.next_episode_year_only = next_episode_year_only
        self.user_action = None
        self.countdown_thread = None
        self.is_running = False
        self.player = xbmc.Player()
        self.timeout_callback = timeout_callback

        # Herní panel pro autoplay dialog – používá vlastní prefix
        self.game_visible = False
        self.game_controller = None

    @staticmethod
    def get_dialog_xml_filename():
        try:
            addon = xbmcaddon.Addon()
            style_index = int(addon.getSetting('dialog_style') or 0)
            style_files = [
                'notifications/classic/DialogAutoplayCountdown.xml',
                'notifications/modern/DialogAutoplayCountdown.xml',
                'notifications/minimal/DialogAutoplayCountdown.xml',
            ]
            filename = style_files[style_index] if 0 <= style_index < len(style_files) else style_files[0]
            xbmc.log(f"[plugin.video.wcs] AutoplayCountdownDialog: Using style index '{style_index}' -> {filename}", level=xbmc.LOGINFO)
            return filename
        except Exception as e:
            xbmc.log(f"[plugin.video.wcs] AutoplayCountdownDialog: Error getting dialog style, using default: {e}", level=xbmc.LOGWARNING)
            return 'notifications/classic/DialogAutoplayCountdown.xml'

    def onInit(self):
        xbmc.log("[plugin.video.wcs] AutoplayCountdownDialog: Initializing with dynamic countdown", level=xbmc.LOGINFO)

        # Properties pro XML
        self.setProperty('WCS.Autoplay.NextEpisode.Title', self.next_episode_title)
        self.setProperty('WCS.Autoplay.NextEpisode.SeasonEpisode', self.next_episode_season_episode)
        self.setProperty('WCS.Autoplay.NextEpisode.Thumb', self.next_episode_thumb)
        self.setProperty('WCS.Autoplay.NextEpisode.Rating', self.next_episode_rating)
        self.setProperty('WCS.Autoplay.NextEpisode.RatingOnly', self.next_episode_rating_only)
        self.setProperty('WCS.Autoplay.NextEpisode.YearOnly', self.next_episode_year_only)

        # Seriálové properties pro herní panel
        self.setProperty('WCS.Autoplay.SeriesTitle', self.series_name)
        self.setProperty('WCS.Autoplay.SeriesTMDBID', self.series_tmdb_id)
        self.setProperty('WCS.Autoplay.SeriesFanart', self.series_fanart)
        self.setProperty('WCS.Autoplay.EpisodeDescription', self.current_episode_plot)

        # Inicializace countdown
        self.setProperty('WCS.Autoplay.CountdownTime', str(self.countdown_duration))
        self.setProperty('WCS.Autoplay.Progress', '0')
        try:
            progress_control = self.getControl(103)
            if progress_control:
                progress_control.setPercent(0)
        except Exception:
            pass

        self.is_running = True
        self.countdown_thread = threading.Thread(target=self._dynamic_countdown_worker)
        self.countdown_thread.daemon = True
        self.countdown_thread.start()
        self.setFocusId(101)

    def onClick(self, controlId):
        if controlId == 101:  # Přehrát ihned
            self.user_action = self.ACTION_PLAY_NOW
            self._stop_countdown()
            self.close()
        elif controlId == 102:  # Zrušit autoplay
            self.user_action = self.ACTION_CANCEL_AUTOPLAY
            self._stop_countdown()
            self.close()
        elif controlId == 104:  # Hrát hru – toggle
            self.game_visible = not self.game_visible
            self.setProperty('WCS.Autoplay.ShowGame', 'true' if self.game_visible else 'false')
            if self.game_visible and not self.game_controller:
                self.start_game()
                try:
                    self.setFocus(self.getControl(301))
                except Exception:
                    pass
            elif not self.game_visible and self.game_controller:
                self.game_controller = None
        elif controlId in [301, 302, 303, 304] and self.game_controller:
            choice_index = controlId - 301
            current_state = self.game_controller.current_game_state
            if choice_index == 3 and current_state in CLOSE_DIALOG_STATES:
                # Zavřít herní panel
                self.game_visible = False
                self.setProperty('WCS.Autoplay.ShowGame', 'false')
                self.game_controller = None
                if self.user_action == self.ACTION_TIMEOUT:
                    # Už došlo k timeoutu → rovnou zavři dialog
                    self.user_action = None
                    self.close()
                else:
                    try:
                        self.setFocus(self.getControl(104))
                    except Exception:
                        pass
            else:
                self.game_controller.make_choice(choice_index)

    def onAction(self, action):
        if action.getId() in (xbmcgui.ACTION_PREVIOUS_MENU, xbmcgui.ACTION_NAV_BACK):
            if self.user_action is None:
                self.user_action = self.ACTION_CANCEL_AUTOPLAY
            self._stop_countdown()
            self.close()

    def _dynamic_countdown_worker(self):
        xbmc.log(f"[plugin.video.wcs] AutoplayCountdownDialog: Starting countdown from {self.countdown_duration}s to 0", level=xbmc.LOGINFO)
        countdown_time = self.countdown_duration
        while self.is_running and countdown_time > 0:
            try:
                if not self.player.isPlaying():
                    xbmc.log("[plugin.video.wcs] AutoplayCountdownDialog: Player stopped, ending countdown", level=xbmc.LOGINFO)
                    break
                progress = ((self.countdown_duration - countdown_time) / self.countdown_duration) * 100
                progress = max(0, min(100, progress))
                self.setProperty('WCS.Autoplay.CountdownTime', str(int(countdown_time)))
                self.setProperty('WCS.Autoplay.Progress', str(int(progress)))
                try:
                    progress_control = self.getControl(103)
                    if progress_control:
                        progress_control.setPercent(progress)
                except Exception:
                    pass
                countdown_time -= 1
                time.sleep(1)
            except Exception as e:
                xbmc.log(f"[plugin.video.wcs] AutoplayCountdownDialog: Error in countdown: {e}", level=xbmc.LOGERROR)
                break

        if countdown_time <= 0 and self.is_running:
            self.user_action = self.ACTION_TIMEOUT
            self._stop_countdown()
            if self.game_visible and self.game_controller:
                if self.timeout_callback:
                    try:
                        self.timeout_callback()
                    except Exception as e:
                        xbmc.log(f"[plugin.video.wcs] AutoplayCountdownDialog: Error calling timeout callback: {e}", level=xbmc.LOGERROR)
                return
            else:
                xbmc.executebuiltin("Action(Back)")

        self._stop_countdown()

    def _stop_countdown(self):
        self.is_running = False

    def get_user_action(self):
        return self.user_action

    # --- Reuse: herní panel ---
    def start_game(self):
        try:
            self.game_controller = GameController(
                title=self.series_name,
                plot=self.current_episode_plot,
                genre="",
                media_type="series",
                episode_title=self.next_episode_title,
                season_number=None,
                episode_number=None,
            )
            self.game_controller.set_ui_callbacks(
                self.update_game_display,
                self.update_game_buttons,
                self.update_game_sidebar,
                self.show_game_error,
                self.set_game_focus,
                self.start_countdown,
            )
            self.setProperty('WCS.Autoplay.Game.Title', self.series_name)
            self.game_controller.start_game_selection()
        except Exception as e:
            xbmc.log(f"[plugin.video.wcs] Error starting game: {e}", level=xbmc.LOGERROR)
            self.show_game_error("Chyba při spouštění hry.")

    def update_game_display(self, text):
        try:
            self.setProperty('WCS.Autoplay.Game.Text', text)
        except Exception as e:
            xbmc.log(f"[plugin.video.wcs] Error updating game display: {e}", level=xbmc.LOGERROR)

    def update_game_buttons(self, text1, text2, text3, text4=""):
        try:
            self.setProperty('WCS.Autoplay.Game.Button1', text1)
            self.setProperty('WCS.Autoplay.Game.Button2', text2)
            self.setProperty('WCS.Autoplay.Game.Button3', text3)
            self.setProperty('WCS.Autoplay.Game.Button4', text4)
        except Exception as e:
            xbmc.log(f"[plugin.video.wcs] Error updating game buttons: {e}", level=xbmc.LOGERROR)

    def update_game_sidebar(self):
        pass

    def show_game_error(self, message):
        try:
            self.setProperty('WCS.Autoplay.Game.Text', f"Chyba: {message}\n\nStiskni 'Zavřít' pro návrat.")
            self.setProperty('WCS.Autoplay.Game.Button1', "")
            self.setProperty('WCS.Autoplay.Game.Button2', "")
            self.setProperty('WCS.Autoplay.Game.Button3', "Zavřít")
        except Exception as e:
            xbmc.log(f"[plugin.video.wcs] Error showing game error: {e}", level=xbmc.LOGERROR)

    def set_game_focus(self, button_index):
        try:
            control_id = 301 + button_index
            self.setFocus(self.getControl(control_id))
        except Exception:
            pass

    def start_countdown(self, seconds, finish_callback):
        def countdown_worker():
            try:
                original_text = ""
                try:
                    original_text = self.getProperty('WCS.Autoplay.Game.Text')
                except Exception:
                    pass
                if "Vyhodnocení odpovědi..." in original_text:
                    base_text = original_text.split("Vyhodnocení odpovědi...")[0]
                else:
                    base_text = original_text
                for i in range(seconds, 0, -1):
                    countdown_text = base_text + f"Vyhodnocení za {i} sekund..."
                    self.setProperty('WCS.Autoplay.Game.Text', countdown_text)
                    time.sleep(1)
                finish_callback()
            except Exception as e:
                xbmc.log(f"[plugin.video.wcs] Error in countdown: {e}", level=xbmc.LOGERROR)
                finish_callback()
        countdown_thread = threading.Thread(target=countdown_worker)
        countdown_thread.daemon = True
        countdown_thread.start()


class AutoplayManager:
    ACTION_PLAY_NOW = 1
    ACTION_CANCEL_AUTOPLAY = 2
    ACTION_TIMEOUT = 3

    def __init__(self, addon):
        self.addon = addon
        self.autoplay_enabled = False
        try:
            self.countdown_seconds = int(addon.getSetting('autoplay_countdown_seconds') or '30')
            if self.countdown_seconds < 10:
                self.countdown_seconds = 10
            elif self.countdown_seconds > 120:
                self.countdown_seconds = 120
        except (ValueError, TypeError):
            self.countdown_seconds = 30
        try:
            self.trigger_seconds = int(addon.getSetting('autoplay_trigger_seconds') or '5')
            if self.trigger_seconds < 3:
                self.trigger_seconds = 3
            elif self.trigger_seconds >= self.countdown_seconds:
                self.trigger_seconds = max(3, self.countdown_seconds - 5)
        except (ValueError, TypeError):
            self.trigger_seconds = 5
        self.countdown_duration = self.countdown_seconds - self.trigger_seconds
        if self.countdown_duration <= 0:
            self.countdown_duration = 5
        self.current_series_info = None
        self.current_episode_info = None

    def set_autoplay_enabled(self, enabled):
        self.autoplay_enabled = enabled
        xbmc.log(f"[plugin.video.wcs] AutoplayManager: Autoplay {'enabled' if enabled else 'disabled'}", level=xbmc.LOGINFO)

    def set_current_episode(self, series_name, season, episode, tmdb_id=None, current_quality=None):
        self.current_series_info = {
            'name': series_name,
            'tmdb_id': tmdb_id,
        }
        self.current_episode_info = {
            'season': season,
            'episode': episode,
            'quality': current_quality,
        }

    def get_next_episode_info(self):
        if not self.current_series_info or not self.current_episode_info:
            return None
        series_name = self.current_series_info['name']
        current_season = self.current_episode_info['season']
        current_episode = self.current_episode_info['episode']
        try:
            from wcs.library.LibraryManager import get_next_episode_metadata_from_library
            next_metadata = get_next_episode_metadata_from_library(series_name, current_season, current_episode)
            if next_metadata:
                season_episode = f"S{next_metadata['season_number']:02d}E{next_metadata['episode_number']:02d}"
                rating_formatted = ""
                rating_only_text = ""
                year_only_text = ""
                if next_metadata.get('episode_rating') and next_metadata['episode_rating'] > 0:
                    try:
                        rating_float = float(next_metadata['episode_rating'])
                        rating_formatted = f"{rating_float:.1f}"
                    except (ValueError, TypeError):
                        rating_formatted = str(next_metadata['episode_rating'])
                    rating_only_text = f"★ {rating_formatted}/10"
                    if next_metadata.get('episode_year'):
                        rating_text = f"★ {rating_formatted}/10 • {next_metadata['episode_year']}"
                        year_only_text = f"• {next_metadata['episode_year']}"
                    else:
                        rating_text = f"★ {rating_formatted}/10"
                else:
                    rating_text = next_metadata.get('episode_year', '') if next_metadata.get('episode_year') else ""
                    if next_metadata.get('episode_year'):
                        year_only_text = f"• {next_metadata['episode_year']}"
                return {
                    'title': next_metadata['episode_title'],
                    'season_episode': season_episode,
                    'thumb': next_metadata.get('episode_thumb', ''),
                    'season': next_metadata['season_number'],
                    'episode': next_metadata['episode_number'],
                    'rating': rating_text,
                    'rating_only': rating_only_text,
                    'year_only': year_only_text,
                }
        except Exception as e:
            xbmc.log(f"[plugin.video.wcs] AutoplayManager: Error getting next episode metadata: {e}", level=xbmc.LOGERROR)
            return None
        # Fallback
        next_episode = current_episode + 1
        season_episode = f"S{current_season:02d}E{next_episode:02d}"
        return {
            'title': 'Další epizoda',
            'season_episode': season_episode,
            'thumb': '',
            'season': current_season,
            'episode': next_episode,
            'rating': '',
            'rating_only': '',
            'year_only': '',
        }

    def show_countdown_dialog(self, current_remaining_time=None):
        if not self.autoplay_enabled:
            return None
        next_episode = self.get_next_episode_info()
        if not next_episode:
            xbmc.log("[plugin.video.wcs] AutoplayManager: No next episode found", level=xbmc.LOGINFO)
            return None
        if current_remaining_time is not None:
            real_countdown_duration = current_remaining_time - self.trigger_seconds
            real_countdown_duration = max(3, min(real_countdown_duration, self.countdown_duration))
        else:
            real_countdown_duration = self.countdown_duration
        xbmc.log(
            f"[plugin.video.wcs] AutoplayManager: Showing countdown dialog - countdown duration: {real_countdown_duration}s (from {self.countdown_seconds}s before end to {self.trigger_seconds}s before end)",
            level=xbmc.LOGINFO,
        )
        def timeout_callback():
            try:
                def play_next():
                    import time
                    time.sleep(0.5)
                    from wcs.playback.PlayerMonitor import get_player_monitor
                    player_instance = get_player_monitor()
                    if player_instance:
                        player_instance._handle_next_episode(is_manual=False)
                thread = threading.Thread(target=play_next)
                thread.daemon = True
                thread.start()
            except Exception as e:
                xbmc.log(f"[plugin.video.wcs] AutoplayManager: Error in timeout callback: {e}", level=xbmc.LOGERROR)
        dialog_xml = AutoplayCountdownDialog.get_dialog_xml_filename()
        dialog = AutoplayCountdownDialog(
            dialog_xml,
            self.addon.getAddonInfo('path'),
            show_countdown_at=real_countdown_duration,
            next_episode_title=next_episode['title'],
            next_episode_season_episode=next_episode.get('season_episode', ''),
            next_episode_thumb=next_episode['thumb'],
            series_name=self.current_series_info['name'],
            series_tmdb_id=str(self.current_series_info.get('tmdb_id', '')),
            series_fanart='',
            current_episode_plot='',
            next_episode_rating=next_episode.get('rating', ''),
            next_episode_rating_only=next_episode.get('rating_only', ''),
            next_episode_year_only=next_episode.get('year_only', ''),
            timeout_callback=timeout_callback,
        )
        dialog.doModal()
        user_action = dialog.get_user_action()
        del dialog
        return user_action


def get_autoplay_manager():
    global _autoplay_manager
    if _autoplay_manager is None:
        addon = xbmcaddon.Addon()
        _autoplay_manager = AutoplayManager(addon)
    return _autoplay_manager


