import random
import threading
import time

import xbmc
import xbmcaddon
from wcs import user_data
from wcs.games import text_formatter as fmt
from wcs.games.millionaire_tts import strip_audio_tags


QUESTION_WAIT_S = 190


class MillionaireGameController:
    """
    Kontrolér specificky pro hru Filmový Milionář.
    Obsahuje logiku pro otázky ve stylu "Chcete být milionářem" na téma filmů.
    """
    
    def __init__(self, title="", plot="", genre="", media_type="movie", episode_title="", season_number=None, episode_number=None, actor_data=None, content=None):
        self.addon = xbmcaddon.Addon()
        
        # Informace o médiu
        self.title = title
        self.plot = plot
        self.genre = genre
        self.media_type = media_type  # "movie", "series", "actor" nebo "director"
        self.episode_title = episode_title  # Pro seriály
        self.season_number = season_number  # Pro seriály
        self.episode_number = episode_number  # Pro seriály
        self.actor_data = actor_data or {}

        # Odkud hra bere slova moderátora a otázky: živý AI chat, nebo offline demo (wcs/games/content)
        if content is None:
            from wcs.games.content.ai import AiContent          # the AI client stays unloaded for the offline demo
            content = AiContent(media_type, title, plot, genre, episode_title, season_number, episode_number,
                                self.actor_data)
        self.content = content
        self.voice = self.content.voice

        # Základní herní stav
        self.game_state = "intro"
        self.game_type = "millionaire"
        
        # UI callbacks
        self.update_display_callback = None
        self.update_buttons_callback = None
        self.update_sidebar_callback = None
        self.show_error_callback = None
        self.set_focus_callback = None
        self.start_countdown_callback = None
        self.close_dialog_callback = None
        self.set_answer_button_colors_callback = None
        
        # Continuous chat state
        self.current_round = 1  # 1-9
        self.score = 0
        self.total_winnings = 0
        self.current_question = None
        self.tip_view = self.poll_view = None
        self.help_kind = ''
        self.countdown = 0
        self.prefetched_question = None
        self.prefetch_thread = None
        self.prefetch_ready = threading.Event()
        self._prefetch_round = None  # round whose question is being / was prepared
        self.feedback_data = None  # AI-generated feedback
        self.feedback_ready = threading.Event()
        
        # Legacy compatibility
        self.current_level = "easy"
        self.current_question_index = 0
        
        # Lifelines
        self.lifelines_used = []
        self.current_choices = []
        self.lifeline_5050_used = False
        self.lifeline_5050_indices = None
        self.lifeline_audience_used = False
        self.lifeline_audience_results = None
        self.lifeline_tip_used = False
        # What a design may show of the running lifelines / countdown (read by game_view.py, not parsed from texts)
        self.tip_view = None            # {'state': 'loading' | 'ready' | 'error', 'text': str}
        self.poll_view = None           # {'results': [4 ints], 'status': str, 'final': bool}
        self.countdown = 0              # seconds left until the answer is evaluated (0: not counting)
        self.help_kind = ''             # the lifeline whose answer is on screen: 'tip' | 'poll' ('' none)
        self.ladder_anim_toggle = False
        self.ladder_anim_running = False
        self.moderator_welcome = None
        self.rules_summary = ""
        
        # Auto-play (spectator mode) state
        self._autoplay_enabled = False
        self._autoplay_fail_round = 0  # 0=never, 3/5/7/9=specific, -1=random
        self._autoplay_speed = 5  # seconds delay before AI answers
        self._autoplay_lifeline_freq = 1  # 0=off, 1=rarely, 2=sometimes, 3=often
        self._autoplay_timer = None
        self._autoplay_overridden = False  # player intervened this round
        self._autoplay_acting = False  # the auto-play worker itself is using a lifeline right now
        
    def set_ui_callbacks(self, update_display, update_buttons, update_sidebar, show_error, set_focus=None, start_countdown=None, close_dialog=None, update_millionaire_ladder=None, set_answer_button_colors=None):
        """Nastaví callback funkce pro komunikaci s UI."""
        self.update_display_callback = update_display
        self.update_buttons_callback = update_buttons
        self.update_sidebar_callback = update_sidebar
        self.show_error_callback = show_error
        self.set_focus_callback = set_focus
        self.start_countdown_callback = start_countdown
        self.close_dialog_callback = close_dialog
        self.update_millionaire_ladder_callback = update_millionaire_ladder
        self.set_answer_button_colors_callback = set_answer_button_colors
    
    def set_return_to_menu_callback(self, callback):
        """Nastaví callback pro návrat na hlavní menu."""
        self.return_to_menu_callback = callback
    
    def _add_ai_info_header(self, text: str) -> str:
        """Přidá informaci o AI modelu na začátek textu velmi malým písmem."""
        # AI info odstraněno na požádání uživatele
        return text
        
    def _get_tip_text(self, short=False):
        """Vrací dynamický text pro tip podle typu média."""
        base_text = ""
        if self.media_type in ("series", "channel"):
            base_text = "Tip od tvůrce"
        elif self.media_type == "actor":
            base_text = "Tip od herce"
        elif self.media_type == "director":
            base_text = "Tip od režiséra"
        elif self.media_type == "writer":
            base_text = "Tip od scénáristy"
        elif self.media_type == "creator":
            base_text = "Tip od tvůrce"
        else:
            base_text = "Tip od režiséra"
        
        if short:
            return base_text
        else:
            # Přidat pomlčku a popis
            if self.media_type in ("series", "channel"):
                return f"{base_text} - osobní rada od tvůrce seriálu"
            elif self.media_type == "actor":
                return f"{base_text} - osobní rada od herce"
            elif self.media_type == "director":
                return f"{base_text} - osobní rada od režiséra"
            elif self.media_type == "writer":
                return f"{base_text} - osobní rada od scénáristy"
            elif self.media_type == "creator":
                return f"{base_text} - osobní rada od tvůrce"
            else:
                return f"{base_text} - osobní rada od režiséra"
    
    # ---------------------------------------------------------------
    # Auto-play (spectator mode)
    # ---------------------------------------------------------------

    def _load_autoplay_settings(self):
        """Load auto-play settings from addon."""
        addon = xbmcaddon.Addon()
        self._autoplay_enabled = addon.getSetting("milionar_autoplay") == "true"
        if not self._autoplay_enabled:
            return
        fail_map = {"0": 0, "1": 3, "2": 5, "3": 7, "4": 9, "5": -1}
        fail_raw = addon.getSetting("milionar_autoplay_fail_round") or "0"
        self._autoplay_fail_round = fail_map.get(fail_raw, 0)
        try:
            self._autoplay_speed = int(addon.getSetting("milionar_autoplay_speed") or "5")
        except ValueError:
            self._autoplay_speed = 5
        try:
            self._autoplay_lifeline_freq = int(addon.getSetting("milionar_autoplay_lifelines") or "1")
        except ValueError:
            self._autoplay_lifeline_freq = 1
        self._autoplay_overridden = False
        xbmc.log(f"[plugin.video.milionar] Autoplay loaded: enabled={self._autoplay_enabled}, "
                 f"fail_round={self._autoplay_fail_round}, speed={self._autoplay_speed}s, "
                 f"lifelines={self._autoplay_lifeline_freq}", level=xbmc.LOGINFO)

    def _cancel_autoplay_timer(self):
        """Cancel any pending autoplay timer."""
        if self._autoplay_timer:
            # Thread objects don't have .cancel() -- set override flag
            # so worker thread exits on next check
            self._autoplay_overridden = True
            self._autoplay_timer = None

    def _schedule_autoplay_answer(self):
        """Schedule AI to answer the current question after delay + TTS."""
        if not self._autoplay_enabled or self._autoplay_overridden or self._autoplay_acting:
            return                        # acting: 50:50 redraws the question, the running worker still answers it
        self._cancel_autoplay_timer()

        def _autoplay_worker():
            try:
                # Wait for TTS to finish first
                self.voice.wait(60)
                # Wait the configured delay
                for _ in range(self._autoplay_speed * 2):
                    if self._autoplay_overridden or self.game_state != "playing":
                        return
                    time.sleep(0.5)
                if self._autoplay_overridden or self.game_state != "playing":
                    return
                # Maybe use a lifeline first
                self._autoplay_acting = True
                try:
                    self._autoplay_maybe_use_lifeline()
                finally:
                    self._autoplay_acting = False
                # Small pause after lifeline
                time.sleep(1.0)
                if self._autoplay_overridden or self.game_state != "playing":
                    return
                # Choose answer
                answer_index = self._autoplay_choose_answer()
                xbmc.log(f"[plugin.video.milionar] Autoplay answering: index={answer_index}, "
                         f"round={self.current_round}", level=xbmc.LOGINFO)
                self.answer_question(answer_index)
            except Exception as e:
                xbmc.log(f"[plugin.video.milionar] Autoplay error: {e}", level=xbmc.LOGERROR)

        self._autoplay_timer = threading.Thread(target=_autoplay_worker, daemon=True)
        self._autoplay_timer.start()

    def _autoplay_choose_answer(self):
        """Choose answer index -- correct or wrong based on fail settings."""
        if not self.current_question:
            return 0
        correct_index = self.current_question.get("correct", 0)
        should_fail = False
        if self._autoplay_fail_round == -1:
            # Random: pick a random round to fail (decided once per game)
            if not hasattr(self, '_autoplay_random_fail'):
                self._autoplay_random_fail = random.choice([3, 5, 7, 9])
            should_fail = (self.current_round == self._autoplay_random_fail)
        elif self._autoplay_fail_round > 0:
            should_fail = (self.current_round == self._autoplay_fail_round)

        if should_fail:
            # Pick a wrong answer
            wrong_indices = [i for i in range(4) if i != correct_index]
            # Respect 50:50 if active
            if self.lifeline_5050_used and self.lifeline_5050_indices:
                wrong_indices = [i for i in wrong_indices if i in self.lifeline_5050_indices]
            if wrong_indices:
                return random.choice(wrong_indices)
        return correct_index

    def _autoplay_maybe_use_lifeline(self):
        """Maybe use a lifeline based on frequency setting and difficulty."""
        if self._autoplay_lifeline_freq == 0:
            return  # Disabled
        if self.game_state != "playing":
            return
        difficulty = self._get_difficulty_for_round(self.current_round)
        # Probability matrix: [freq][difficulty]
        prob_matrix = {
            1: {"easy": 0.05, "medium": 0.15, "hard": 0.25},  # Rarely
            2: {"easy": 0.15, "medium": 0.30, "hard": 0.50},  # Sometimes
            3: {"easy": 0.30, "medium": 0.50, "hard": 0.70},  # Often
        }
        prob = prob_matrix.get(self._autoplay_lifeline_freq, {}).get(difficulty, 0)
        if random.random() > prob:
            return  # No lifeline this round
        # Pick a random unused lifeline
        available = []
        if not self.lifeline_5050_used:
            available.append("5050")
        if not self.lifeline_audience_used:
            available.append("audience")
        if not self.lifeline_tip_used:
            available.append("tip")
        if not available:
            return
        lifeline = random.choice(available)
        xbmc.log(f"[plugin.video.milionar] Autoplay using lifeline: {lifeline}", level=xbmc.LOGINFO)
        if lifeline == "5050":
            self.use_5050_lifeline()
        elif lifeline == "audience":
            self.use_audience_poll_lifeline()
        elif lifeline == "tip":
            self.use_tip_lifeline()

    def _schedule_autoplay_continue(self):
        """Schedule auto-continue after feedback screen."""
        if not self._autoplay_enabled:
            return
        self._autoplay_overridden = False  # Reset for next round

        def _continue_worker():
            try:
                self.voice.wait(60)
                for _ in range(self._autoplay_speed * 2):
                    if self.game_state not in ("answer_feedback", "game_finished"):
                        return
                    time.sleep(0.5)
                if self.game_state == "answer_feedback":
                    self.continue_after_feedback()
                elif self.game_state == "game_finished":
                    if not hasattr(self, '_results_shown') or not self._results_shown:
                        self.show_final_score()
            except Exception as e:
                xbmc.log(f"[plugin.video.milionar] Autoplay continue error: {e}", level=xbmc.LOGERROR)

        t = threading.Thread(target=_continue_worker, daemon=True)
        t.start()
        
    def start_specific_game(self):
        """Spustí hru Filmový Milionář s welcome screenem."""
        xbmc.log("[plugin.video.milionar] MillionaireGameController.start_specific_game called", level=xbmc.LOGINFO)
        self.reset_lifelines()
        self.game_state = "millionaire_welcome"
        self.current_level = 0
        self.total_winnings = 0
        self.lifelines_used = []
        
        if self.update_sidebar_callback:
            self.update_sidebar_callback()
            
        # Zobrazit welcome screen
        self.show_millionaire_welcome()

    def _get_game_title(self):
        """Vrátí název hry podle typu média."""
        titles = {
            "series": "SERIÁLOVÝ MILIONÁŘ",
            "channel": "SERIÁLOVÝ MILIONÁŘ",
            "actor": "MILIONÁŘ S HERCEM",
            "director": "MILIONÁŘ S REŽISÉREM",
            "writer": "MILIONÁŘ SE SCÉNÁRISTOU",
            "creator": "MILIONÁŘ S TVŮRCEM",
        }
        return titles.get(self.media_type, "FILMOVÝ MILIONÁŘ")

    def _get_media_label(self):
        """Vrátí label pro typ média (Film: X, Seriál: X, atd.)."""
        labels = {
            "movie": "Film",
            "series": "Seriál",
            "channel": "Kanál",
            "actor": "Herec",
            "director": "Režisér",
            "writer": "Scénárista",
            "creator": "Tvůrce",
        }
        prefix = labels.get(self.media_type, "Film")
        return f"{prefix}: {self.title}"

    def _get_challenge_line(self):
        """Vrátí výzvu podle typu média."""
        lines = {
            "series": "Jste připraveni vsadit své znalosti seriálu?",
            "channel": "Jste připraveni vsadit své znalosti seriálů?",
            "actor": "Jste připraveni vsadit své znalosti o herci?",
            "director": "Jste připraveni vsadit své znalosti o režiséru?",
            "writer": "Jste připraveni vsadit své znalosti o scénáristovi?",
            "creator": "Jste připraveni vsadit své znalosti o tvůrci?",
        }
        return lines.get(self.media_type, "Jste připraveni vsadit své znalosti filmu?")

    def _get_knowledge_reference(self):
        """Vrátí referenci na znalosti podle typu média."""
        refs = {
            "series": "seriálové znalosti",
            "channel": "seriálové znalosti",
            "actor": "znalosti o herci",
            "director": "znalosti o režiséru",
            "writer": "znalosti o scénáristovi",
            "creator": "znalosti o tvůrci",
        }
        return refs.get(self.media_type, "filmové znalosti")

    def _get_role_name(self, genitive=False):
        """Vrátí název role (režisér/tvůrce/herec). genitive=True pro 2. pád."""
        if genitive:
            roles = {
                "series": "TVŮRCE",
                "actor": "HERCE",
                "director": "REŽISÉRA",
                "writer": "SCÉNÁRISTY",
                "creator": "TVŮRCE",
            }
            return roles.get(self.media_type, "REŽISÉRA")
        roles = {
            "series": "TVŮRCE SERIÁLU",
            "actor": "HEREC",
            "director": "REŽISÉR",
            "writer": "SCÉNÁRISTA",
            "creator": "TVŮRCE",
        }
        return roles.get(self.media_type, "REŽISÉR FILMU")

    def show_millionaire_welcome(self):
        """Zobrazí uvítací obrazovku hry Filmový Milionář."""
        game_title = self._get_game_title()

        # Sestavení media info
        media_info = f'"{self.title}"'
        if self.media_type == "series" and self.episode_title:
            media_info = f'"{self.title}" — {self.episode_title}'
            if self.season_number and self.episode_number:
                media_info += f" (S{self.season_number:02d}E{self.episode_number:02d})"

        # Tip text
        tip_label = self._get_tip_text(short=True)

        # Formátovaný welcome text
        media_type_label = {
            "series": "seriálu", "channel": "kanálu", "actor": "herci", "director": "režisérovi",
            "writer": "scénáristovi", "creator": "tvůrci",
        }.get(self.media_type, "filmu")

        lines = [
            fmt.heading(game_title),
            "",
            f"9 otázek o {media_type_label} {fmt.highlight(media_info)}",
        ]
        if self.content.badge:
            lines.insert(1, fmt.dim(self.content.badge))

        # Krátký popis děje / seznam seriálů
        if self.media_type == "channel" and self.plot:
            lines.append("")
            lines.append(fmt.heading("Seriály v kanálu:"))
            lines.append(fmt.dim(self.plot[:200]))
        elif self.plot and len(self.plot) > 50:
            short_plot = self.plot[:120]
            if len(self.plot) > 120:
                short_plot = short_plot.rsplit(' ', 1)[0] + "..."
            lines.append("")
            lines.append(fmt.dim(short_plot))

        lines += [
            "",
            fmt.heading("Pomocníci"),
            fmt.separator(),
            fmt.labeled_bullet("50:50", "odstraní 2 špatné odpovědi"),
            fmt.labeled_bullet(tip_label, "osobní rada"),
            fmt.labeled_bullet("Diváci", "statistická pomoc"),
            "",
            f"Připravte se na cestu za {fmt.money('miliónem')}!",
        ]

        welcome_text = "\n".join(lines)

        # Nastavit property pro welcome sidebar
        self._set_millionaire_film_info()

        if self.update_display_callback:
            self.update_display_callback(welcome_text)
        if self.update_buttons_callback:
            self.update_buttons_callback("Začít hru", "Pravidla", "Zpět na menu", "Zavřít")
        if self.update_sidebar_callback:
            self.update_sidebar_callback()
        if self.update_millionaire_ladder_callback:
            self.update_millionaire_ladder_callback()
        # Nastavit fokus na tlačítko "Začít hru" (index 0)
        if self.set_focus_callback:
            self.set_focus_callback(0)

    def _set_millionaire_film_info(self):
        """Nastaví property s informacemi o filmu pro welcome sidebar."""
        try:
            # Získat reference na hlavní window pro nastavení property
            import xbmcgui
            window = xbmcgui.Window(xbmcgui.getCurrentWindowId())
            
            # Sestavit informace o filmu podle typu média
            if self.media_type == "series" and self.episode_title:
                film_info = f"Seriál: {self.title}\nEpizoda: {self.episode_title}"
                if self.season_number and self.episode_number:
                    film_info += f" (S{self.season_number:02d}E{self.episode_number:02d})"
            elif self.media_type == "series":
                film_info = f"Seriál: {self.title}"
            elif self.media_type == "actor":
                film_info = f"Herec: {self.title}"
            elif self.media_type == "director":
                film_info = f"Režisér: {self.title}"
            elif self.media_type == "creator":
                film_info = f"Tvůrce: {self.title}"
            elif self.media_type == "channel":
                film_info = f"Kanál: {self.title}"
            else:
                film_info = f"Film: {self.title}"
            
            # Přidat žánr pokud je dostupný
            if self.genre:
                film_info += f"\nŽánr: {self.genre}"
            
            window.setProperty('WCS.Millionaire.FilmInfo', film_info)
            
        except Exception as e:
            xbmc.log(f"[plugin.video.milionar] Error setting millionaire film info: {e}", level=xbmc.LOGERROR)

    def show_millionaire_rules(self):
        """Zobrazí detailní pravidla hry."""
        game_title = self._get_game_title()
        tip_label = self._get_tip_text(short=True)

        lines = [
            fmt.title(f"PRAVIDLA — {game_title}"),
            "",
            fmt.heading("Průběh hry"),
            fmt.separator(),
            "• Odpovídáte na 9 otázek",
            "• 3 úrovně: snadná, střední, těžká",
            "• Rostoucí virtuální výhry",
            f"• Špatná odpověď = {fmt.error('konec hry')}",
            "",
            fmt.heading("Herní mechanika"),
            fmt.separator(),
            f"• {self.content.rules_note}",
            "• 4 možnosti odpovědí (A, B, C, D)",
            "• Postupná eskalace obtížnosti",
            "",
            fmt.heading("Pomocníci"),
            fmt.separator(),
            fmt.labeled_bullet("50:50", "odstraní 2 špatné odpovědi"),
            fmt.labeled_bullet(tip_label, "osobní rada"),
            fmt.labeled_bullet("Diváci", "statistická pomoc"),
            "",
            fmt.highlight(self._get_challenge_line()),
        ]

        rules_text = "\n".join(lines)

        if self.update_display_callback:
            self.update_display_callback(rules_text)
        if self.update_buttons_callback:
            self.update_buttons_callback("Začít hru", "Zpět", "Zpět na menu", "Zavřít")

    def make_choice(self, choice_index):
        """Hlavní metoda pro zpracování voleb."""
        self.handle_game_choice(choice_index)
    
    def handle_game_choice(self, choice_index):
        """Zpracuje volbu specifickou pro millionaire hru."""
        if self.game_state == "millionaire_welcome":
            if choice_index == 0:  # Zacit hru
                self.show_placeholder_game()
            elif choice_index == 1:  # Pravidla
                self.game_state = "millionaire_rules"
                self.show_millionaire_rules()
            elif choice_index == 2:  # Zpet na menu
                self.start_game_selection()
            elif choice_index == 3:  # Zavrit
                self.end_game()
        elif self.game_state == "millionaire_rules":
            if choice_index == 0:  # Zacit hru
                self.show_placeholder_game()
            elif choice_index == 1:  # Zpet
                self.game_state = "millionaire_welcome"
                self.show_millionaire_welcome()
            elif choice_index == 2:  # Zpet na menu
                self.start_game_selection()
            elif choice_index == 3:  # Zavrit
                self.end_game()
        elif self.game_state == "welcome_screen":
            if choice_index == 0:  # Zacit hru
                if hasattr(self, '_welcome_timer') and self._welcome_timer:
                    self._welcome_timer.cancel()
                self._transition_to_question()
        elif self.game_state in ["generating_welcome", "generating_question", "generating_feedback"]:
            pass  # Loading -- tlacitka nedelaji nic
        elif self.game_state == "answer_pending":
            pass  # Behem countdown nelze nic delat
        elif self.game_state == "playing":
            xbmc.log(f"[plugin.video.milionar] Button {choice_index} pressed in game state {self.game_state}", level=xbmc.LOGINFO)
            # Player intervened -- cancel autoplay for this round
            if self._autoplay_enabled:
                self._autoplay_overridden = True
                self._cancel_autoplay_timer()
            self.answer_question(choice_index)
        elif self.game_state == "answer_feedback":
            if choice_index == 0:  # Pokracovat
                self.continue_after_feedback()
            elif choice_index == 1:  # Nova hra
                self.show_placeholder_game()
            elif choice_index == 2:  # Zpet na menu
                self.start_game_selection()  
            elif choice_index == 3:  # Zavrit
                self.end_game()
        elif self.game_state == "error":
            if choice_index == 0:  # Zkusit znovu
                self.start_millionaire_game()
            elif choice_index == 1:  # Ukoncit hru
                self.end_game()
        elif self.game_state == "game_over":
            if choice_index == 0:  # Nova hra
                self.show_placeholder_game()
            elif choice_index == 1:  # Zpet na menu
                self.start_game_selection()
            elif choice_index == 2:  # Jina hra
                self.start_game_selection()
            elif choice_index == 3:  # Zavrit
                self.end_game()
        elif self.game_state == "game_finished":
            if not hasattr(self, '_results_shown') or not self._results_shown:
                if choice_index == 0:  # Vysledky
                    self.show_final_score()
                elif choice_index == 1:  # Nova hra
                    self.show_placeholder_game()
                elif choice_index == 2:  # Zpet na menu
                    self.start_game_selection()
                elif choice_index == 3:  # Zavrit
                    self.end_game()
            else:
                if choice_index == 0:  # Nova hra
                    self.show_placeholder_game()
                elif choice_index == 1:  # Zpet na menu
                    self.start_game_selection()
                elif choice_index == 2:  # Zavrit
                    self.end_game()

    def show_placeholder_game(self):
        """Spustí skutečnou hru Filmový Milionář."""
        self.start_millionaire_game()
    
    def start_millionaire_game(self):
        """Spustí hru Milionář -- continuous chat."""
        xbmc.log("[plugin.video.milionar] Starting Millionaire game (continuous chat)", level=xbmc.LOGINFO)
        
        self.reset_lifelines()
        self._load_autoplay_settings()
        if hasattr(self, '_autoplay_random_fail'):
            del self._autoplay_random_fail
        self.game_state = "generating_welcome"
        self.current_round = 1
        self.current_level = "easy"
        self.current_question_index = 0
        self.score = 0
        self.current_question = None
        self.prefetched_question = None
        self.prefetch_thread = None
        self.prefetch_ready = threading.Event()
        self._prefetch_round = None
        self.feedback_data = None
        self.feedback_ready = threading.Event()
        
        # Nová herní relace zdroje obsahu (AI: nová historie chatu a system prompt)
        self.content.begin()

        # Zobrazit loading screen
        game_title = self._get_game_title()
        media_label = self._get_media_label()
        lines = [
            fmt.title(game_title),
            "",
            fmt.heading("Příprava hry"),
            fmt.separator(),
            fmt.highlight(media_label),
        ]
        if self.media_type == "series" and self.episode_title:
            ep_info = f"Epizoda: {self.episode_title}"
            if self.season_number and self.episode_number:
                ep_info += f" (S{self.season_number:02d}E{self.episode_number:02d})"
            lines.append(fmt.silver(ep_info))
        lines += [
            "",
            fmt.dim("Moderátor se připravuje..."),
        ]
        loading_text = "\n".join(lines)
        if self.update_display_callback:
            self.update_display_callback(loading_text)
        if self.update_buttons_callback:
            self.update_buttons_callback("Načítání...", "", "", "")
        if self.update_sidebar_callback:
            self.update_sidebar_callback()
        if self.update_millionaire_ladder_callback:
            self.update_millionaire_ladder_callback()
        self.stop_ladder_animation()
        
        # Spustit generování welcome v threadu; první otázka se připravuje současně (zdroj obsahu to umí)
        thread = threading.Thread(target=self._generate_welcome)
        thread.daemon = True
        thread.start()
        self._prefetch_next_question()

    # ---------------------------------------------------------------
    # Moderator words and questions come from the content source (wcs/games/content)
    # ---------------------------------------------------------------

    def _generate_welcome(self):
        """Thread target: the welcome of the moderator."""
        try:
            data = self.content.welcome()
            self.moderator_welcome_raw = data.get("moderator_welcome", "")
            rules_summary = data.get("rules_summary", "")
            self.rules_summary = rules_summary
            # Strip audio tags for UI display
            display_welcome = strip_audio_tags(self.moderator_welcome_raw)
            display_rules = strip_audio_tags(rules_summary)
            self.moderator_welcome = display_welcome
            if display_rules:
                self.moderator_welcome += "\n\n" + display_rules
            xbmc.log("[plugin.video.milionar] Welcome generated", level=xbmc.LOGINFO)
            # Prefetch the first question during the welcome. It is started first: a click on "Začít hru" must already
            # find it under way (with the instant demo content it could otherwise come before the prefetch begins).
            self._prefetch_next_question()
            self.show_moderator_welcome_screen()
        except Exception as e:
            xbmc.log(f"[plugin.video.milionar] Error generating welcome: {e}", level=xbmc.LOGERROR)
            self.show_generation_error(str(e))

    def _generate_question(self, round_num):
        """Generate a single question for the given round.

        Returns parsed question dict with keys:
        moderator_intro, question, options (list), correct (index), explanation.
        """
        data = self.content.question(round_num)
        # Normalize options from dict {A,B,C,D} to list
        options_dict = data.get("options", {})
        if isinstance(options_dict, dict):
            options = [
                options_dict.get("A", ""),
                options_dict.get("B", ""),
                options_dict.get("C", ""),
                options_dict.get("D", ""),
            ]
        else:
            options = list(options_dict) if options_dict else ["", "", "", ""]
        correct_letter = data.get("correct", "A")
        correct_index = {"A": 0, "B": 1, "C": 2, "D": 3}.get(
            correct_letter.upper(), 0
        )
        # Strip audio tags for UI display, keep raw for TTS
        return {
            "question": strip_audio_tags(data.get("question", "")),
            "options": [strip_audio_tags(o) for o in options],
            "correct": correct_index,
            "explanation": strip_audio_tags(data.get("explanation", "")),
            "explanation_raw": data.get("explanation", ""),
            "moderator_intro": strip_audio_tags(data.get("moderator_intro", "")),
            "moderator_intro_raw": data.get("moderator_intro", ""),
        }

    def _generate_feedback(self, round_num, player_answer_index, is_correct):
        """Thread target: generate feedback after player answers."""
        try:
            is_last = (round_num >= 9)
            data = self.content.feedback(round_num, player_answer_index, is_correct, self.current_question)
            # Strip audio tags for UI display, keep raw for TTS
            self.feedback_data = {
                'result_announcement': strip_audio_tags(data.get('result_announcement', '')),
                'result_announcement_raw': data.get('result_announcement', ''),
                'transition_text': strip_audio_tags(data.get('transition_text', '')),
                'transition_text_raw': data.get('transition_text', ''),
            }
            xbmc.log(f"[plugin.video.milionar] Feedback generated for round {round_num}", level=xbmc.LOGINFO)
            # Prefetch next question if correct and not last. Started before the feedback is released: the action
            # buttons (and so "Další otázka") only appear after that, and the prefetch must already be marked running.
            if is_correct and not is_last:
                self._prefetch_next_question()
            self.feedback_ready.set()
        except Exception as e:
            xbmc.log(f"[plugin.video.milionar] Error generating feedback: {e}", level=xbmc.LOGERROR)
            self.feedback_data = {
                "result_announcement": "Dámy a pánové, omlouvám se, máme tu drobné technické potíže...",
                "transition_text": "Zkusíme to znovu, nebo si raději dáme pauzu?",
            }
            self.feedback_ready.set()

    def _prefetch_next_question(self):
        """Start generating the next question in background."""
        next_round = self.current_round + 1
        if self.game_state == "generating_welcome" or self.game_state == "welcome_screen":
            next_round = 1  # First question during welcome
        if next_round > 9:
            return
        if self._prefetch_round == next_round:
            return  # already asked for (with the welcome, or right after the answer)
        self._prefetch_round = next_round
        self.prefetch_ready.clear()
        self.prefetched_question = None

        def _prefetch_worker():
            try:
                q = self._generate_question(next_round)
                self.prefetched_question = q
                self.prefetch_ready.set()
                xbmc.log(f"[plugin.video.milionar] Prefetched question for round {next_round}", level=xbmc.LOGINFO)
            except Exception as e:
                xbmc.log(f"[plugin.video.milionar] Prefetch error: {e}", level=xbmc.LOGERROR)
                self.prefetch_ready.set()  # Unblock even on error
            # The intro shows "preparing the first question" until it is ready: let the window know now (otherwise
            # the hint stayed until the next change of the game)
            if self.game_state in ("generating_welcome", "welcome_screen") and self.update_sidebar_callback:
                self.update_sidebar_callback()

        self.prefetch_thread = threading.Thread(target=_prefetch_worker)
        self.prefetch_thread.daemon = True
        self.prefetch_thread.start()

    def _transition_to_question(self):
        """Transition to showing the current/prefetched question.

        If prefetch is ready, show immediately. Otherwise show loading
        and wait.
        """
        if self.prefetched_question:
            self.current_question = self.prefetched_question
            self.prefetched_question = None
            self.game_state = "playing"
            self.show_current_question()
        else:
            # Show brief loading
            self.game_state = "generating_question"
            game_title = self._get_game_title()
            money = self.get_money_amount_for_question(self.current_round)
            lines = [
                fmt.title(f"{game_title} — KOLO {self.current_round}"),
                "",
                f"Otázka za: {fmt.money(money)}",
                fmt.separator(),
                "",
                fmt.dim("Moderátor připravuje otázku..."),
            ]
            if self.update_display_callback:
                self.update_display_callback("\n".join(lines))
            if self.update_buttons_callback:
                self.update_buttons_callback("Načítání...", "", "", "")

            def _wait_for_question():
                # The prefetch always ends (question or error); wait for it longer than the AI clients' HTTP timeouts
                # (up to 180 s), so a slow answer does not end the game on an error screen while it is still coming.
                self.prefetch_ready.wait(timeout=QUESTION_WAIT_S)
                if self.prefetched_question:
                    self.current_question = self.prefetched_question
                    self.prefetched_question = None
                    self.game_state = "playing"
                    self.show_current_question()
                else:
                    self.show_generation_error("Nepodařilo se vygenerovat otázku.")

            t = threading.Thread(target=_wait_for_question)
            t.daemon = True
            t.start()

    def _get_difficulty_for_round(self, round_num):
        """Return difficulty label for current round."""
        if round_num <= 3:
            return "easy"
        elif round_num <= 6:
            return "medium"
        return "hard"
    
    def show_moderator_welcome_screen(self):
        """Zobrazí welcome obrazovku moderátora.

        Prefetch otázky 1 už běží na pozadí.
        Auto-přechod po 15 sekundách nebo kliknutím.
        """
        self.game_state = "welcome_screen"
        game_title = self._get_game_title()
        media_label = self._get_media_label()

        lines = [
            fmt.title(game_title),
            "",
            fmt.highlight(media_label),
            fmt.separator(),
            self.moderator_welcome or "",
            "",
        ]

        welcome_text = "\n".join(lines)

        if self.update_display_callback:
            self.update_display_callback(welcome_text)
        if self.update_buttons_callback:
            self.update_buttons_callback("Začít hru", "", "", "")
        if self.update_sidebar_callback:
            self.update_sidebar_callback()
        if self.update_millionaire_ladder_callback:
            self.update_millionaire_ladder_callback()
        self.stop_ladder_animation()

        # TTS welcome
        self.voice.welcome(
            self.moderator_welcome_raw or "",
            self.rules_summary or "",
        )

        # Auto-prechod: pouze v autoplay modu (po TTS + delay)
        # V manualnim rezimu hrac musi kliknout "Zacit hru"
        if self._autoplay_enabled:
            def _autoplay_welcome_transition():
                self.voice.wait(60)
                time.sleep(2)
                if self.game_state == "welcome_screen":
                    self._transition_to_question()
            t = threading.Thread(target=_autoplay_welcome_transition, daemon=True)
            t.start()



    def show_generation_error(self, error_message):
        """Zobrazí chybu při generování -- moderátorský styl."""
        game_title = self._get_game_title()

        lines = [
            fmt.title(f"{game_title}"),
            "",
            fmt.heading("Technické potíže"),
            fmt.separator(),
            "Dámy a pánové, omlouvám se, máme tu drobné technické potíže...",
            "",
            fmt.dim(error_message),
            "",
            "Zkusíme to znovu, nebo si raději dáme pauzu?",
        ]

        error_text = "\n".join(lines)

        self.game_state = "error"
        if self.update_display_callback:
            self.update_display_callback(error_text)
        if self.update_buttons_callback:
            self.update_buttons_callback("Zkusit znovu", "Ukončit hru", "", "")
    

    
    def show_current_question(self):
        """Zobrazí aktuální otázku a případně ji přečte AI hlasem."""
        if not self.current_question:
            return
        question_data = self.current_question
        # Update legacy state for ladder/sidebar compatibility
        self.current_level = self._get_difficulty_for_round(self.current_round)
        self.current_question_index = (self.current_round - 1) % 3
        total_question_number = self.current_round
        money_amount = self.get_money_amount_for_question(total_question_number)
        game_title = self._get_game_title()

        # Moderátor uvede otázku
        moderator_intro = question_data.get('moderator_intro', '')
        lines = [
            fmt.title(f"{game_title} — OTÁZKA {total_question_number}"),
            "",
            f"Otázka za: {fmt.money(money_amount)}",
            fmt.separator(),
        ]
        if moderator_intro:
            lines.append(moderator_intro)
        else:
            lines.append(f"{question_data['question']}")

        question_text = "\n".join(lines)
        if self.update_display_callback:
            self.update_display_callback(question_text)
        # --- TTS (use raw text with audio tags for TTS expressivity) ---
        options_list = question_data.get('options', [])
        if isinstance(options_list, dict):
            options_list = [options_list.get(l, "") for l in ["A", "B", "C", "D"]]
        self.voice.question(
            question_data.get('moderator_intro_raw', '') or moderator_intro,
            question_data.get('question', ''),
            options_list,
        )
        # ---
        # Nastavit odpovedi na tlacitka
        options = question_data.get('options', [])
        if self.lifeline_5050_used and self.lifeline_5050_indices:
            keep = set(self.lifeline_5050_indices)
            button_texts = []
            for i in range(4):
                if i in keep:
                    button_texts.append(options[i])
                else:
                    button_texts.append("")
        else:
            button_texts = []
            for i in range(4):
                if i < len(options):
                    button_texts.append(options[i])
                else:
                    button_texts.append("")
        if self.update_buttons_callback:
            self.update_buttons_callback(*button_texts)
            xbmc.log(f"[plugin.video.milionar] Setting question buttons: {button_texts}", level=xbmc.LOGINFO)
        if self.update_sidebar_callback:
            self.update_sidebar_callback()
        if self.update_millionaire_ladder_callback:
            self.update_millionaire_ladder_callback()
        # Auto-play: schedule AI answer after TTS finishes
        self._schedule_autoplay_answer()
    
    def get_total_question_number(self):
        """Vrátí celkové číslo aktuální otázky (1-9)."""
        return self.current_round

    def get_money_amount_for_question(self, question_number):
        """Vrátí peněžní částku pro danou otázku (1-9)."""
        money_amounts = {
            1: "1 000 Kč",
            2: "2 000 Kč", 
            3: "5 000 Kč",
            4: "10 000 Kč",
            5: "20 000 Kč",
            6: "50 000 Kč",
            7: "100 000 Kč",
            8: "500 000 Kč",
            9: "1 000 000 Kč"
        }
        return money_amounts.get(question_number, "1 000 Kč")

    def get_continue_text(self, next_question_number, next_money_amount):
        """Vrátí dynamický text pro pokračování podle čísla otázky."""
        import random
        
        q = next_question_number
        m = fmt.money(next_money_amount)
        
        continue_texts = {
            2: [
                f"Výborně! To byla jednoduchá rozcvička!\nČeká vás otázka č. {q} za {m}.",
                f"Správně! Pěkný začátek!\nNyní přichází otázka č. {q} za {m}.",
                f"Výtečně! Zatím vám to jde skvěle!\nPřed vámi je otázka č. {q} za {m}.",
            ],
            3: [
                f"Správně! Zatím to jde snadno, že?\nOtázka č. {q} za {m} vás čeká.",
                f"Perfektně! Máte dobrou formu!\nČeká vás otázka č. {q} za {m}.",
                f"Skvěle! Dosud žádný problém!\nPřed vámi stojí otázka č. {q} za {m}.",
            ],
            4: [
                f"Skvěle! Nyní vstupujete do vážnějších vod...\nPřed vámi je otázka č. {q} za {m}.",
                f"Výborně! Teď se to začíná komplikovat!\nČeká vás otázka č. {q} za {m}.",
                f"Úžasně! Přicházejí těžší časy...\nOtázka č. {q} za {m} je před vámi.",
            ],
            5: [
                f"Výborně! Už to začíná být zajímavé!\nČeká vás otázka č. {q} za {m}.",
                f"Fantastické! Částky rostou a s nimi i riziko!\nPřed vámi je otázka č. {q} za {m}.",
                f"Skvěle! Vstupujete do nebezpečnější zóny!\nOtázka č. {q} za {m} vás čeká.",
            ],
            6: [
                f"Fantastické! Nyní se hra začíná správně rozbíhat!\nPřed vámi stojí otázka č. {q} za {m}!",
                f"Neuvěřitelné! Dostáváte se do vysokých částek!\nČeká vás otázka č. {q} za {m}!",
                f"Úžasné! Teď to začíná být vážné!\nOtázka č. {q} za {m} je před vámi!",
            ],
            7: [
                f"Úžasné! Dostáváte se do velmi vysokých částek!\nOtázka č. {q} za {m} je před vámi.",
                f"Senzační! Jste v nebezpečné zóně velkých peněz!\nPřed vámi čeká otázka č. {q} za {m}.",
                f"Neuvěřitelné! Částky jsou už opravdu vysoké!\nČeká vás otázka č. {q} za {m}.",
            ],
            8: [
                f"Neuvěřitelné! Jste jen dva kroky od {fmt.money('miliónu')}!\nČeká vás kritická otázka č. {q} za {m}!",
                f"Senzační! Miliónová meta je na dosah ruky!\nPřed vámi je osudová otázka č. {q} za {m}!",
                f"Fantastické! Dva kroky od životního triumfu!\nKritická otázka č. {q} za {m} vás čeká!",
            ],
            9: [
                f"Senzační! Pouze jedna otázka vás dělí od {fmt.money('MILIÓNU')}!\nFinální otázka č. {q} za {m}!",
                f"Neuvěřitelné! Finále! Poslední krok k {fmt.money('MILIÓNU')}!\nOsudová otázka č. {q} za {m}!",
                f"Úžasné! Toto je ten okamžik! {fmt.money('MILIÓN')} je na dosah!\nZávěrečná otázka č. {q} za {m}!",
            ]
        }
        
        # Vybrat náhodný text pro dané číslo otázky
        if next_question_number in continue_texts:
            return random.choice(continue_texts[next_question_number])
        
        return f"Výborně! Postoupili jste dál!\nČeká vás otázka č. {q} za {m}!"
    
    def answer_question(self, answer_index):
        """Zpracuje odpoved na otazku - spusti countdown a feedback generovani."""
        if self.game_state != "playing":
            # One answer per question: a second click during the countdown (or after the result) is ignored
            xbmc.log(f"[plugin.video.milionar] Answer {answer_index} ignored in state {self.game_state}", level=xbmc.LOGINFO)
            return
        self._cancel_autoplay_timer()
        if self.lifeline_5050_used and self.lifeline_5050_indices:
            if answer_index not in self.lifeline_5050_indices:
                return  # Ignoruj kliknuti na prazdne tlacitko
        if not self.current_question:
            xbmc.log(f"[plugin.video.milionar] No current question for answer {answer_index}", level=xbmc.LOGWARNING)
            return
            
        options = self.current_question.get('options', [])
        if answer_index >= len(options):
            xbmc.log(f"[plugin.video.milionar] Invalid answer index {answer_index}, only {len(options)} options available", level=xbmc.LOGWARNING)
            return
            
        # Ulozit vybranou odpoved
        self.selected_answer = options[answer_index]
        self.selected_answer_index = answer_index
        
        self.game_state = "answer_pending"
        
        # Aktualizovat display text
        total_question_number = self.current_round
        money_amount = self.get_money_amount_for_question(total_question_number)
        game_title = self._get_game_title()
            
        display_text = f"""{game_title} — OTÁZKA {total_question_number}

Otázka za: {money_amount}

{self.current_question['question']}

Vaše odpověď: {self.selected_answer}

Vyhodnocení odpovědi za 3s"""

        if self.update_display_callback:
            self.update_display_callback(self._add_ai_info_header(display_text))
        
        # Fáze 1: Modrý highlight vybrané odpovědi, tlačítka zůstanou s odpověďmi
        color_cb = self.set_answer_button_colors_callback
        if not color_cb and self.update_display_callback:
            try:
                dialog = self.update_display_callback.__self__
                if hasattr(dialog, 'set_answer_button_colors_callback'):
                    color_cb = dialog.set_answer_button_colors_callback
                    self.set_answer_button_colors_callback = color_cb
            except Exception:
                pass
        if color_cb:
            color_cb(answer_index)
        
        if self.update_sidebar_callback:
            self.update_sidebar_callback()
        if self.update_millionaire_ladder_callback:
            self.update_millionaire_ladder_callback()
        
        xbmc.log(f"[plugin.video.milionar] Answer {answer_index} selected: {self.selected_answer}", level=xbmc.LOGINFO)
        
        # Start feedback generation in parallel with countdown
        correct_index = self.current_question.get('correct', 0)
        is_correct = (answer_index == correct_index)
        self.feedback_ready.clear()
        self.feedback_data = None
        feedback_thread = threading.Thread(
            target=self._generate_feedback,
            args=(self.current_round, answer_index, is_correct),
        )
        feedback_thread.daemon = True
        feedback_thread.start()
        # The next question is prepared at once, alongside the feedback (it does not depend on the feedback's words)
        if is_correct and self.current_round < 9:
            self._prefetch_next_question()
        
        # Spustit countdown (4 sekundy) v background threadu
        def countdown_and_evaluate():
            import time
            for i in range(3, 0, -1):
                self.countdown = i
                # Aktualizovat countdown číslo v textu
                countdown_text = f"""{game_title} — OTÁZKA {total_question_number}

Otázka za: {money_amount}

{self.current_question['question']}

Vaše odpověď: {self.selected_answer}

Vyhodnocení odpovědi za {i}s"""
                if self.update_display_callback:
                    self.update_display_callback(self._add_ai_info_header(countdown_text))
                time.sleep(1)
            # Po countdown zavolat finish
            self.countdown = 0
            self.finish_answer_evaluation()
        
        thread = threading.Thread(target=countdown_and_evaluate)
        thread.daemon = True
        thread.start()
        
        # Po odpovedi resetuj 50:50 pro dalsi otazku
        self.lifeline_5050_indices = None
    
    def finish_answer_evaluation(self):
        """Dokonci vyhodnoceni odpovedi po countdown.

        Ceka na feedback inference (mela dobehnout behem countdown).
        Nastavi reveal barvy a po delay zobrazi akcni tlacitka.
        """
        correct_index = self.current_question.get('correct', 0)
        is_correct = (self.selected_answer_index == correct_index)
        
        xbmc.log(f"[plugin.video.milionar] Answer evaluation: selected {self.selected_answer_index}, correct {correct_index}, result: {'CORRECT' if is_correct else 'WRONG'}", level=xbmc.LOGINFO)
        
        # Fáze 2: Reveal barvy na tlačítkách
        color_cb = self.set_answer_button_colors_callback
        # Fallback: pokud callback nebyl předán přes GameManager, získej ho z Dialog instance
        if not color_cb and self.update_display_callback:
            try:
                dialog = self.update_display_callback.__self__
                if hasattr(dialog, 'set_answer_button_colors_callback'):
                    color_cb = dialog.set_answer_button_colors_callback
                    self.set_answer_button_colors_callback = color_cb
            except Exception:
                pass
        if color_cb:
            color_cb(self.selected_answer_index, correct_index)
        
        # Wait for feedback inference to complete (should be done already)
        if not self.feedback_ready.is_set():
            # Show brief waiting message
            if self.update_display_callback:
                game_title = self._get_game_title()
                self.update_display_callback(f"{game_title}\n\nModerator pripravuje hodnoceni...")
            self.feedback_ready.wait(timeout=15)
        
        # Zobrazit feedback text
        if is_correct:
            self._show_feedback_content(True)
        else:
            correct_option = self.current_question.get('options', [])[correct_index]
            self._show_game_over_content(correct_option, self.current_question.get('explanation', ''))
        
        # TTS (use raw text with audio tags for expressivity)
        feedback = self.feedback_data or {}
        result_text = feedback.get('result_announcement_raw', '') or feedback.get('result_announcement', '')
        transition_text = feedback.get('transition_text_raw', '') or feedback.get('transition_text', '')
        explanation = self.current_question.get('explanation_raw', '') or self.current_question.get('explanation', '')
        self.voice.feedback(result_text, transition_text, explanation)
        
        # Delay: počkat na TTS nebo 5s
        def wait_and_show_buttons():
            import time
            if self.voice.speaks_feedback():
                # Počkat na konec TTS
                self.voice.wait(30)
            else:
                # 5s bez TTS
                time.sleep(5)
            
            # Fáze 3: Akční tlačítka
            if is_correct:
                self._show_feedback_buttons()
            else:
                self._show_game_over_buttons()
        
        thread = threading.Thread(target=wait_and_show_buttons)
        thread.daemon = True
        thread.start()
    
    def _show_feedback_content(self, is_correct):
        """Zobrazí feedback text (fáze 2) -- bez změny tlačítek."""
        question_data = self.current_question
        explanation = question_data.get('explanation', '')
        total_question_number = self.current_round
        money_amount = self.get_money_amount_for_question(total_question_number)
        game_title = self._get_game_title()

        # Use AI-generated feedback
        feedback = self.feedback_data or {}
        result_text = feedback.get('result_announcement', '')
        transition_text = feedback.get('transition_text', '')

        lines = [
            fmt.title(f"{game_title} — OTÁZKA {total_question_number}"),
            "",
            f"Otázka za: {fmt.money(money_amount)} — {fmt.success('SPRÁVNĚ!')}",
            fmt.separator(),
        ]
        if explanation:
            lines.append(explanation)
        if result_text:
            lines += ["", result_text]
        if transition_text:
            lines += ["", fmt.separator(), transition_text]

        feedback_text = "\n".join(lines)

        # Nastavit stav
        self.score += 1
        if total_question_number == 9:
            self.game_state = "game_finished"
            self._results_shown = False
        else:
            self.game_state = "answer_feedback"

        if self.update_display_callback:
            self.update_display_callback(feedback_text)
        if self.update_sidebar_callback:
            self.update_sidebar_callback()
        if self.update_millionaire_ladder_callback:
            self.update_millionaire_ladder_callback()

    def _show_feedback_buttons(self):
        """Zobrazí akční tlačítka po feedback delay (fáze 3)."""
        total_question_number = self.current_round
        
        # Reset barev tlačítek
        if self.set_answer_button_colors_callback:
            self.set_answer_button_colors_callback(-1)  # žádný highlight
        
        if total_question_number == 9:
            if self.update_buttons_callback:
                self.update_buttons_callback("Výsledky", "Nová hra", "Zpět na menu", "Zavřít")
        else:
            if self.update_buttons_callback:
                self.update_buttons_callback("Další otázka", "Nová hra", "Zpět na menu", "Zavřít")
        
        if self.set_focus_callback:
            self.set_focus_callback(0)
        # Auto-play: schedule auto-continue
        self._schedule_autoplay_continue()
    
    def _show_game_over_content(self, correct_option, explanation):
        """Zobrazí game over text (fáze 2) -- bez změny tlačítek."""
        total_questions = self.current_round
        money_amount = self.get_money_amount_for_question(total_questions)
        game_title = self._get_game_title()

        # Use AI-generated feedback
        feedback = self.feedback_data or {}
        result_text = feedback.get('result_announcement', '')
        transition_text = feedback.get('transition_text', '')
        
        lines = [
            fmt.title(f"{game_title} — OTÁZKA {total_questions}"),
            "",
            f"Otázka za: {fmt.money(money_amount)} — {fmt.error('ŠPATNĚ!')}",
            fmt.separator(),
            f"Otázka: {self.current_question['question']}",
            f"Vaše odpověď: {fmt.highlight(self.selected_answer)}",
            f"Správná odpověď: {fmt.success(correct_option)}",
            "",
        ]
        if explanation:
            lines.append(explanation)
        if result_text:
            lines += ["", result_text]
        if transition_text:
            lines += ["", transition_text]

        game_over_text = "\n".join(lines)

        self.game_state = "game_over"

        if self.update_display_callback:
            self.update_display_callback(game_over_text)
        if self.update_sidebar_callback:
            self.update_sidebar_callback()
        if self.update_millionaire_ladder_callback:
            self.update_millionaire_ladder_callback()

    def _show_game_over_buttons(self):
        """Zobrazí akční tlačítka po game over delay (fáze 3)."""
        # Reset barev tlačítek
        if self.set_answer_button_colors_callback:
            self.set_answer_button_colors_callback(-1)  # žádný highlight
        
        if self.update_buttons_callback:
            self.update_buttons_callback("Nová hra", "Zpět na menu", "Jiná hra", "Zavřít")
        if self.set_focus_callback:
            self.set_focus_callback(0)
        # Auto-play: no auto-actions after game over
    
    def continue_after_feedback(self):
        """Pokracuje na dalsi otazku -- pouzije prefetch."""
        self.current_round += 1
        self.current_level = self._get_difficulty_for_round(self.current_round)
        self.current_question_index = (self.current_round - 1) % 3
        self.tip_view = self.poll_view = None
        self.help_kind = ''
        self._transition_to_question()
    
    def show_final_score(self):
        """Zobrazí finální skóre hry - pouze při dokončení všech 9 otázek."""
        game_title = self._get_game_title()
        knowledge_ref = self._get_knowledge_reference()

        lines = [
            fmt.title(f"{game_title} — GRATULUJEME!"),
            "",
            fmt.success("VÍTĚZSTVÍ!"),
            "",
            fmt.heading("Finální skóre"),
            fmt.separator(),
            f"Výsledek: {fmt.money('9/9 (100%)')}",
            "",
            f"Úžasné! Odpověděli jste správně na všech 9 otázek!",
            f"Prokázali jste skvělé {fmt.highlight(knowledge_ref)}!",
            "",
            fmt.dim("Děkujeme za hraní!"),
        ]

        final_text = "\n".join(lines)

        self.game_state = "game_finished"
        self._results_shown = True
        if self.update_display_callback:
            self.update_display_callback(final_text)
        if self.update_buttons_callback:
            self.update_buttons_callback("Nová hra", "Zpět na menu", "Zavřít", "")
        if self.update_sidebar_callback:
            self.update_sidebar_callback()
        if self.update_millionaire_ladder_callback:
            self.update_millionaire_ladder_callback()

    def get_sidebar_items(self):
        """Vrací aktuální sidebar položky."""
        game_name = "Seriálový Milionář" if self.media_type == "series" else "Filmový Milionář"
        
        # Pyramida peněžních částek (odspoda nahoru jako v originále)
        money_pyramid = [
            "1 000 000 Kč",      # Otázka 9 (Hard 3/3)
            "500 000 Kč",        # Otázka 8 (Hard 2/3)  
            "100 000 Kč",        # Otázka 7 (Hard 1/3)
            "50 000 Kč",         # Otázka 6 (Medium 3/3)
            "20 000 Kč",         # Otázka 5 (Medium 2/3)
            "10 000 Kč",         # Otázka 4 (Medium 1/3)
            "5 000 Kč",          # Otázka 3 (Easy 3/3)
            "2 000 Kč",          # Otázka 2 (Easy 2/3)
            "1 000 Kč"           # Otázka 1 (Easy 1/3)
        ]
        
        # Speciální stavy s prázdnou pyramidou
        if self.game_state == "millionaire_welcome":
            # Zobrazit prázdnou pyramidu s nadpisem
            pyramid_display = [
                "ŽEBŘÍČEK VÝHER:",
                "================",  # Podtržení nadpisu
                "",  # Prázdný řádek pro oddělení
            ]
            for amount in money_pyramid:
                pyramid_display.append(f"[ ] {amount}")
            return pyramid_display
        elif self.game_state == "millionaire_rules":
            # Zobrazit prázdnou pyramidu s nadpisem
            pyramid_display = [
                "ŽEBŘÍČEK VÝHER:",
                "================",  # Podtržení nadpisu
                "",  # Prázdný řádek pro oddělení
            ]
            for amount in money_pyramid:
                pyramid_display.append(f"[ ] {amount}")
            return pyramid_display
        elif self.game_state in ["generating_welcome", "generating_question"]:
            # Pri generovani zobrazit pyramidu s oznacenim
            pyramid_display = [
                "ZEBRICEK VYHER:",
                "================",
                "",
            ]
            for i, amount in enumerate(money_pyramid):
                question_num = 9 - i
                if question_num <= self.score:
                    pyramid_display.append(f"[X] {amount}")
                elif question_num == self.current_round:
                    pyramid_display.append(f"[?] {amount}")
                else:
                    pyramid_display.append(f"[ ] {amount}")
            return pyramid_display
        elif self.game_state == "error":
            media_suggestion = "jiný seriál" if self.media_type == "series" else "jiný film"
            return ["Chyba", "Zkuste znovu", f"nebo zvolte {media_suggestion}"]

        
        # Pro herní stavy zobrazit pyramidu s nadpisem
        pyramid_display = [
            "ŽEBŘÍČEK VÝHER:",
            "================",  # Podtržení nadpisu
            "",  # Prázdný řádek pro oddělení
        ]
        
        # Určení aktuálního čísla otázky podle stavu hry
        if self.game_state in ["playing"]:
            current_total_question = self.get_total_question_number()
        elif self.game_state == "answer_pending":
            # Během čekání na vyhodnocení - aktuální otázka
            current_total_question = self.get_total_question_number()
        elif self.game_state == "answer_feedback":
            # Po správné odpovědi - score už je zvýšen, takže score = počet zodpovězených
            current_total_question = self.score
        elif self.game_state == "game_over":
            # Při prohře - score = počet správných, +1 = aktuální nesprávná
            current_total_question = self.score + 1
        elif self.game_state == "game_finished":
            # Při dokončení - všechny zodpovězené
            current_total_question = 10  # Všech 9 otázek zodpovězeno
        else:
            # Pro ostatní stavy (welcome, rules, atd.) - žádná otázka
            current_total_question = 0
        
        for i, amount in enumerate(money_pyramid):
            question_num = 9 - i  # Převod indexu na číslo otázky (9,8,7...1)
            
            if self.game_state == "game_finished":
                # Všechny otázky zodpovězené
                pyramid_display.append(f"[X] {amount}")
            elif self.game_state == "game_over":
                # Nesprávná odpověď - správné do score, pak [!] pro nesprávnou
                if question_num <= self.score:
                    pyramid_display.append(f"[X] {amount}")  # Správně zodpovězené
                elif question_num == current_total_question:
                    pyramid_display.append(f"[!] {amount}")  # Nesprávně zodpovězená
                else:
                    pyramid_display.append(f"[ ] {amount}")  # Nehrané
            elif self.game_state == "answer_feedback":
                # Správná odpověď - všechny otázky až do score jsou zodpovězené
                if question_num <= current_total_question:
                    pyramid_display.append(f"[X] {amount}")
                else:
                    pyramid_display.append(f"[ ] {amount}")
            elif question_num < current_total_question:
                # Zodpovězená otázka
                pyramid_display.append(f"[X] {amount}")
            elif question_num == current_total_question:
                # Aktuální otázka
                pyramid_display.append(f"[>] {amount}")
            else:
                # Nezodpovězená otázka  
                pyramid_display.append(f"[ ] {amount}")
        
        return pyramid_display

    def get_millionaire_ladder_states(self):
        """Vrací stavy jednotlivých řádků grafického žebříčku pro UI."""
        question_to_control_id = {
            1: 111, 2: 112, 3: 113, 4: 114, 5: 115, 6: 116, 7: 107, 8: 108, 9: 109
        }
        question_to_amount = {
            1: "1 000 Kč", 2: "2 000 Kč", 3: "5 000 Kč", 4: "10 000 Kč", 5: "20 000 Kč", 6: "50 000 Kč", 7: "100 000 Kč", 8: "500 000 Kč", 9: "1 000 000 Kč"
        }
        if self.game_state in ["playing"]:
            current_total_question = self.get_total_question_number()
        elif self.game_state == "answer_pending":
            current_total_question = self.get_total_question_number()
        elif self.game_state == "answer_feedback":
            current_total_question = self.score
        elif self.game_state == "game_over":
            current_total_question = self.score + 1
        elif self.game_state == "game_finished":
            current_total_question = 10
        else:
            current_total_question = 0
        ladder_states = {}
        for question_num in range(1, 10):
            control_id = question_to_control_id[question_num]
            amount = question_to_amount[question_num]
            # Výchozí barvy
            bg_default = "FF232323"  # tmavá (sidebar/nápověda)
            bg_correct = "FF3CB371"   # decentní zelená
            bg_wrong = "FFB04A4A"     # tlumená červená
            bg_current = "FF335C8F"   # decentní modrá
            # Animované barvy pro generování
            colors = ["AFBBAA33", "BFBBAA33", "CFBBAA33", "DFBBAA33", "EFBBAA33", "FFBBAA33"]
            # Určení stavu a barvy
            if self.game_state in ["millionaire_welcome", "millionaire_rules"]:
                state = "empty"
                text = amount
                color = "white"
                bgcolor = bg_default
            elif self.game_state in ["generating_welcome", "generating_question"]:
                if question_num <= self.score:
                    state = "completed"
                    text = amount
                    color = "white"
                    bgcolor = bg_correct
                elif question_num == self.current_round:
                    state = "generating"
                    text = amount
                    color = "black"
                    try:
                        idx = int(self.ladder_anim_toggle)
                    except Exception:
                        idx = 0
                    bgcolor = colors[idx % len(colors)]
                else:
                    state = "empty"
                    text = amount
                    color = "white"
                    bgcolor = bg_default
            elif self.game_state == "game_finished":
                state = "completed"
                text = amount
                color = "white"
                bgcolor = bg_correct
            elif self.game_state == "game_over":
                if question_num <= self.score:
                    state = "completed"
                    text = amount
                    color = "white"
                    bgcolor = bg_correct
                elif question_num == current_total_question:
                    state = "failed"
                    text = amount
                    color = "white"
                    bgcolor = bg_wrong
                else:
                    state = "empty"
                    text = amount
                    color = "white"
                    bgcolor = bg_default
            elif self.game_state == "answer_feedback":
                if question_num <= current_total_question:
                    state = "completed"
                    text = amount
                    color = "white"
                    bgcolor = bg_correct
                else:
                    state = "empty"
                    text = amount
                    color = "white"
                    bgcolor = bg_default
            elif question_num < current_total_question:
                state = "completed"
                text = amount
                color = "white"
                bgcolor = bg_correct
            elif question_num == current_total_question:
                state = "current"
                text = amount
                color = "white"
                bgcolor = bg_current
            else:
                state = "empty"
                text = amount
                color = "white"
                bgcolor = bg_default
            ladder_states[control_id] = {
                'state': state,
                'text': text,
                'color': color,
                'bgcolor': bgcolor,
                'question_num': question_num
            }
        return ladder_states

    def start_game_selection(self):
        """Návrat na hlavní výběr typu hry."""
        self.reset_lifelines()
        if hasattr(self, 'return_to_menu_callback') and self.return_to_menu_callback:
            self.return_to_menu_callback()
        else:
            if self.close_dialog_callback:
                self.close_dialog_callback()

    def end_game(self):
        """Ukončí hru - zavře dialog."""
        self.reset_lifelines()
        if self.close_dialog_callback:
            self.close_dialog_callback()

    def use_5050_lifeline(self):
        """Aktivuje nápovědu 50:50, pokud je dostupná a ve správném stavu."""
        if self.lifeline_5050_used:
            return  # Již použito
        if self.game_state not in ["playing"]:
            return  # Nápověda není dostupná
        if not self.current_question:
            return
        options = self.current_question.get('options', [])
        correct_index = self.current_question.get('correct', 0)
        # Najdi všechny špatné odpovědi
        wrong_indices = [i for i in range(len(options)) if i != correct_index]
        import random
        if not wrong_indices:
            return
        random_wrong = random.choice(wrong_indices)
        # Ulož indexy, které mají zůstat
        self.lifeline_5050_indices = (correct_index, random_wrong)
        self.lifeline_5050_used = True
        # Aktualizuj tlačítka a sidebar
        self.show_current_question()
        
        # Automaticky přesměrovat fokus na první viditelné tlačítko
        if self.set_focus_callback:
            # Najít první neprázdné tlačítko
            keep = set(self.lifeline_5050_indices)
            first_visible_index = next((i for i in range(4) if i in keep), 0)
            self.set_focus_callback(first_visible_index)
            xbmc.log(f"[plugin.video.milionar] 50:50 lifeline used, focus moved to button {first_visible_index}", level=xbmc.LOGINFO)
        
        if self.update_sidebar_callback:
            self.update_sidebar_callback()
        if self.update_millionaire_ladder_callback:
            self.update_millionaire_ladder_callback()

    def use_audience_poll_lifeline(self):
        """Aktivuje nápovědu hlasování diváků - simuluje věrohodné hlasování."""
        if self.lifeline_audience_used:
            return  # Již použito
            
        if self.game_state not in ["playing"]:
            return  # Nápověda není dostupná
            
        if not self.current_question:
            return
            
        import random
        correct_index = self.current_question.get('correct', 0)
        options = self.current_question.get('options', [])
        
        # Zohlednit 50:50 nápovědu - pokud je aktivní, hlasovat pouze pro zbývající možnosti
        available_indices = list(range(4))
        if self.lifeline_5050_used and self.lifeline_5050_indices:
            available_indices = list(self.lifeline_5050_indices)
            xbmc.log(f"[plugin.video.milionar] Audience poll with 50:50 active, voting only for indices: {available_indices}", level=xbmc.LOGINFO)
        
        # Určit sílu správné odpovědi podle úrovně obtížnosti
        if self.current_level == "easy":
            correct_confidence = random.randint(60, 85)  # 60-85% pro snadné otázky
        elif self.current_level == "medium":
            correct_confidence = random.randint(45, 70)  # 45-70% pro střední otázky
        else:  # hard
            correct_confidence = random.randint(30, 55)  # 30-55% pro těžké otázky
        
        # Rozdělit zbývající procenta mezi ostatní dostupné odpovědi
        remaining = 100 - correct_confidence
        poll_results = [0] * 4
        poll_results[correct_index] = correct_confidence
        
        # Najít ostatní dostupné odpovědi (kromě správné)
        other_available_indices = [i for i in available_indices if i != correct_index]
        
        # Pokud je správná odpověď mimo dostupné, přesunout ji tam
        if correct_index not in available_indices and available_indices:
            # Najít nejlepší náhradní odpověď (nejméně špatnou)
            best_wrong_index = available_indices[0]
            poll_results[correct_index] = 0  # Vynulovat původní správnou
            poll_results[best_wrong_index] = correct_confidence  # Přesunout na dostupnou
            other_available_indices = [i for i in available_indices if i != best_wrong_index]
        
        # Minimální procento pro každou nesprávnou odpověď
        if other_available_indices:
            min_per_wrong = max(1, remaining // (len(other_available_indices) * 2))
        else:
            min_per_wrong = 1
        
        # Rozdělit zbývající procenta mezi ostatní dostupné odpovědi
        for i, idx in enumerate(other_available_indices):
            if i == len(other_available_indices) - 1:
                # Poslední odpověď dostane zbytek
                poll_results[idx] = max(0, remaining)
            else:
                # Náhodná část zbývajících procent
                max_share = min(remaining - min_per_wrong, remaining // 2)  # Nech něco pro ostatní
                max_share = max(min_per_wrong, max_share)  # Ale minimálně min_per_wrong
                
                if max_share >= min_per_wrong:
                    share = random.randint(min_per_wrong, max_share)
                else:
                    share = min_per_wrong
                    
                poll_results[idx] = share
                remaining -= share
        
        # Ujistit se, že součet je 100% a žádné procento není záporné
        current_sum = sum(poll_results)
        if current_sum != 100:
            # Přidat rozdíl k nejvyššímu procentu
            max_index = poll_results.index(max(poll_results))
            poll_results[max_index] += (100 - current_sum)
            
        # Zajistit, že žádné procento není záporné
        for i in range(4):
            if poll_results[i] < 0:
                poll_results[i] = 0
        
        self.lifeline_audience_results = poll_results
        
        # Označit jako použito PŘED zobrazením výsledků
        self.lifeline_audience_used = True
        
        # Zobrazit výsledky hlasování
        self.show_audience_poll_results()
        
        if self.update_sidebar_callback:
            self.update_sidebar_callback()
        if self.update_millionaire_ladder_callback:
            self.update_millionaire_ladder_callback()

    def show_audience_poll_results(self):
        """Zobrazí výsledky hlasování diváků s animací načítání."""
        if not self.lifeline_audience_results:
            return
            
        # Spustit animaci hlasování
        self.animate_audience_poll()

    def animate_audience_poll(self):
        """Animuje postupné načítání výsledků hlasování během 10 sekund s napínavým efektem."""
        import threading
        import time
        import random
        
        def animation_thread():
            options = self.current_question.get('options', [])
            final_results = self.lifeline_audience_results
            labels = ["A", "B", "C", "D"]
            
            # Napínavé texty pro různé fáze
            status_texts = [
                "Sčítání hlasů...",
                "Zpracování výsledků...", 
                "Analyzování odpovědí...",
                "Kontrola dat...",
                "Finalizace výsledků...",
                "Poslední hlasy...",
                "Téměř hotovo...",
                "Dokončování...",
                "Výsledky připraveny...",
                "Vyberte svou odpověď:"
            ]
            
            # Nastavit odpovědi na tlačítka na začátku a nechat je tam po celou dobu
            if self.update_buttons_callback:
                correct_index = self.current_question.get('correct', 0)
                
                # Kontrola nastavení pro zobrazení "x" u správné odpovědi
                show_correct_marker = self.addon.getSetting('millionaire_show_correct_answer') == 'true'
                
                # 50:50 nápověda - pokud je aktivní, zobraz jen dvě možnosti
                if self.lifeline_5050_used and self.lifeline_5050_indices:
                    keep = set(self.lifeline_5050_indices)
                    button_texts = []
                    for i in range(4):
                        if i in keep:
                            text = options[i]
                            button_texts.append(text)
                        else:
                            button_texts.append("")
                else:
                    button_texts = []
                    for i in range(4):
                        if i < len(options):
                            text = options[i]
                            button_texts.append(text)
                        else:
                            button_texts.append("")
                self.update_buttons_callback(*button_texts)
            
            # 20 kroků animace (0.5 sekundy každý = 10 sekund celkem)
            total_steps = 20
            for step in range(total_steps + 1):
                
                # Nelineární růst - pomalý start, pak rychlejší, pak zase pomalý (S-křivka)
                if step == 0:
                    progress = 0.0
                elif step <= total_steps:
                    # S-křivka pro napínavější efekt
                    t = step / total_steps
                    progress = t * t * (3.0 - 2.0 * t)  # Smooth step funkce
                else:
                    progress = 1.0
                
                # Vypočítat aktuální hodnoty s malým náhodným rozptylem pro napětí
                if step < total_steps:
                    current_results = []
                    for final_val in final_results:
                        base_val = int(final_val * progress)
                        # Přidat malé náhodné kolísání (±2%) pro napětí
                        if step > 2:  # Po prvních krocích
                            wobble = random.randint(-2, 2)
                            wobble_val = max(0, base_val + wobble)
                        else:
                            wobble_val = base_val
                        current_results.append(wobble_val)
                else:
                    # Finální krok - přesné hodnoty
                    current_results = final_results
                
                # Vybrat status text podle kroku
                status_index = min(step // 2, len(status_texts) - 1)
                status_text = status_texts[status_index]
                
                # Sestavit text výsledků
                results_text = f"\nVÝSLEDKY HLASOVÁNÍ DIVÁKŮ:\n"
                results_text += "=" * 35 + "\n\n"
                
                # Zohlednit 50:50 nápovědu při zobrazení výsledků
                available_indices = list(range(4))
                if self.lifeline_5050_used and self.lifeline_5050_indices:
                    available_indices = list(self.lifeline_5050_indices)
                
                for i, (label, option, percentage) in enumerate(zip(labels, options, current_results)):
                    if option and i in available_indices:  # Pouze pokud existuje odpověď a je dostupná
                        results_text += f"{label}: {percentage}%\n"
                
                results_text += f"\n{status_text}"
                
                self.poll_view = {'results': list(current_results), 'status': status_text, 'final': step == total_steps}
                self.help_kind = 'poll'
                # Aktualizovat display
                if self.update_display_callback:
                    total_question_number = self.get_total_question_number()
                    money_amount = self.get_money_amount_for_question(total_question_number)
                    game_title = self._get_game_title()

                    lines = [
                        fmt.title(f"{game_title} — OTÁZKA {total_question_number}"),
                        "",
                        f"Otázka za: {fmt.money(money_amount)}",
                        fmt.separator(),
                        "",
                        self.current_question['question'],
                        "",
                        results_text,
                    ]

                    question_text = "\n".join(lines)
                    self.update_display_callback(question_text)
                
                # Pokud není poslední krok, počkat 0.5 sekundy
                if step < total_steps:
                    time.sleep(0.5)

        
        # Spustit animaci v background threadu
        thread = threading.Thread(target=animation_thread)
        thread.daemon = True
        thread.start()

    def use_tip_lifeline(self):
        """Aktivuje nápovědu tip od režiséra - osobní radu od tvůrce."""
        if self.lifeline_tip_used:
            return  # Již použito
            
        if self.game_state not in ["playing"]:
            return  # Nápověda není dostupná
            
        if not self.current_question:
            return
            
        # Označit jako použito PŘED voláním AI
        self.lifeline_tip_used = True
        
        # Zobrazit loading zprávu
        self.show_tip_loading()
        
        # Spustit generování tipu v background
        import threading
        thread = threading.Thread(target=self._generate_director_tip)
        thread.daemon = True
        thread.start()
        
        if self.update_sidebar_callback:
            self.update_sidebar_callback()
        if self.update_millionaire_ladder_callback:
            self.update_millionaire_ladder_callback()

    def show_tip_loading(self):
        """Zobrazí loading zprávu během generování tipu."""
        self.tip_view = {'state': 'loading', 'text': ''}
        self.help_kind = 'tip'
        role_name = self._get_role_name()
        total_question_number = self.get_total_question_number()
        money_amount = self.get_money_amount_for_question(total_question_number)
        game_title = self._get_game_title()

        lines = [
            fmt.title(f"{game_title} — OTÁZKA {total_question_number}"),
            "",
            f"Otázka za: {fmt.money(money_amount)}",
            fmt.separator(),
            "",
            self.current_question['question'],
            "",
            fmt.highlight(f"{role_name} PŘIPRAVUJE TIP..."),
            fmt.dim("Chvíli strpení..."),
        ]

        display_text = "\n".join(lines)

        if self.update_display_callback:
            self.update_display_callback(display_text)
        if self.update_buttons_callback:
            self.update_buttons_callback("Načítání...", "...", "...", "...")

    def _generate_director_tip(self):
        """Získá osobní radu od režiséra/tvůrce od zdroje obsahu (AI, nebo předpřipravená v demu)."""
        try:
            director_tip = self.content.tip(self.current_question)

            if director_tip and director_tip.strip():
                self.show_director_tip(director_tip.strip())
            else:
                self.show_tip_error("Nepodařilo se vygenerovat osobní radu od režiséra.")
                
        except Exception as e:
            xbmc.log(f"[plugin.video.milionar] Error generating director tip: {e}", level=xbmc.LOGERROR)
            self.show_tip_error(f"Chyba při generování tipu: {str(e)}")

    def show_director_tip(self, tip_text):
        """Zobrazí osobní radu od režiséra/tvůrce."""
        self.tip_view = {'state': 'ready', 'text': tip_text}
        role_name = self._get_role_name(genitive=True)
        total_question_number = self.get_total_question_number()
        money_amount = self.get_money_amount_for_question(total_question_number)
        game_title = self._get_game_title()

        lines = [
            fmt.title(f"{game_title} — OTÁZKA {total_question_number}"),
            "",
            f"Otázka za: {fmt.money(money_amount)}",
            fmt.separator(),
            "",
            self.current_question['question'],
            "",
            fmt.heading(f"TIP OD {role_name}:"),
            fmt.highlight(tip_text),
            "",
            fmt.dim("Vyberte svou odpověď:"),
        ]

        display_text = "\n".join(lines)

        if self.update_display_callback:
            self.update_display_callback(display_text)
            
        # Tlačítka zůstávají stejná (odpovědi)
        options = self.current_question.get('options', [])
        correct_index = self.current_question.get('correct', 0)
        
        # Kontrola nastavení pro zobrazení "x" u správné odpovědi
        show_correct_marker = self.addon.getSetting('millionaire_show_correct_answer') == 'true'
        
        if self.lifeline_5050_used and self.lifeline_5050_indices:
            keep = set(self.lifeline_5050_indices)
            button_texts = []
            for i in range(4):
                if i in keep:
                    text = options[i]
                    button_texts.append(text)
                else:
                    button_texts.append("")
        else:
            button_texts = []
            for i in range(4):
                if i < len(options):
                    text = options[i]
                    button_texts.append(text)
                else:
                    button_texts.append("")
        if self.update_buttons_callback:
            self.update_buttons_callback(*button_texts)

    def show_tip_error(self, error_message):
        """Zobrazí chybu při generování tipu."""
        self.tip_view = {'state': 'error', 'text': error_message}
        role_name = self._get_role_name(genitive=True)
        total_question_number = self.get_total_question_number()
        money_amount = self.get_money_amount_for_question(total_question_number)
        game_title = self._get_game_title()

        lines = [
            fmt.title(f"{game_title} — OTÁZKA {total_question_number}"),
            "",
            f"Otázka za: {fmt.money(money_amount)}",
            fmt.separator(),
            "",
            self.current_question['question'],
            "",
            fmt.error(f"CHYBA PŘI GENEROVÁNÍ TIPU OD {role_name}:"),
            error_message,
            "",
            fmt.dim("Zkuste to znovu později nebo použijte jinou nápovědu."),
            fmt.dim("Vyberte svou odpověď:"),
        ]

        display_text = "\n".join(lines)

        if self.update_display_callback:
            self.update_display_callback(display_text)
            
        # Tlačítka zůstávají stejná (odpovědi)
        options = self.current_question.get('options', [])
        correct_index = self.current_question.get('correct', 0)
        
        # Kontrola nastavení pro zobrazení "x" u správné odpovědi
        show_correct_marker = self.addon.getSetting('millionaire_show_correct_answer') == 'true'
        
        if self.lifeline_5050_used and self.lifeline_5050_indices:
            keep = set(self.lifeline_5050_indices)
            button_texts = []
            for i in range(4):
                if i in keep:
                    text = options[i]
                    button_texts.append(text)
                else:
                    button_texts.append("")
        else:
            button_texts = []
            for i in range(4):
                if i < len(options):
                    text = options[i]
                    button_texts.append(text)
                else:
                    button_texts.append("")
        if self.update_buttons_callback:
            self.update_buttons_callback(*button_texts)

    def reset_lifelines(self):
        """Resetuje všechny nápovědy na začátku nové hry nebo při návratu do menu."""
        self.lifeline_5050_used = False
        self.lifeline_5050_indices = None
        self.lifeline_audience_used = False
        self.lifeline_audience_results = None
        self.lifeline_tip_used = False
        # Rezerva pro další nápovědy (např. self.lifeline_tip_used = False, ...) 

    def animate_generating_ladder(self, control_ids, duration=3.0, interval=0.2):
        import threading, time
        self.ladder_anim_running = True
        colors = ["AFBBAA33", "BFBBAA33", "CFBBAA33", "DFBBAA33", "EFBBAA33", "FFBBAA33"]
        def anim():
            try:
                start = time.time()
                idx = 0
                self.ladder_anim_toggle = 0
                while time.time() - start < duration and self.ladder_anim_running:
                    self.ladder_anim_toggle = idx
                    if self.update_millionaire_ladder_callback:
                        self.update_millionaire_ladder_callback()
                    idx = (idx + 1) % len(colors)
                    time.sleep(interval)
            except Exception as e:
                import xbmc
                xbmc.log(f"[plugin.video.milionar] Ladder animation error: {e}", level=xbmc.LOGERROR)
            finally:
                self.ladder_anim_running = False
                self.ladder_anim_toggle = 0
        t = threading.Thread(target=anim)
        t.daemon = True
        t.start()

    def stop_ladder_animation(self):
        self.ladder_anim_running = False
        self.ladder_anim_toggle = 0