import xbmcgui
import xbmcaddon
import xbmc
from wcs.ai import AIHandler as ai_handler
from wcs import user_data
from wcs.games.GameManager import GameController
import threading
import time

class TextGameWindow(xbmcgui.WindowXMLDialog):
    def __init__(self, xmlFilename, addonPath, skin="Default", theme="Default", title="", fanart="", plot="", genre="", media_type="movie", actor_data=None, banner_fanart=None, episode_title="", season_number=None, episode_number=None):
        super().__init__(xmlFilename, addonPath, skin, theme)
        self.addon = xbmcaddon.Addon()
        self.title = title
        self.fanart = fanart
        self.banner_fanart = banner_fanart or fanart  # Fallback na původní fanart
        if media_type == "tv":
            self.media_type = "series"
        else:
            self.media_type = media_type or "movie"
        
        # Uložení data osoby (pro media_type 'actor' nebo 'director')
        self.actor_data = actor_data or {}
        
        # Nové parametry pro epizody
        self.episode_title = episode_title
        self.season_number = season_number
        self.episode_number = episode_number
        
        # Proměnná pro uložení aktuálního herního textu
        self.current_game_text = ""
        
        # Vytvoření game controlleru s media_type a parametry epizod
        self.game_controller = GameController(
            title=title, 
            plot=plot, 
            genre=genre, 
            media_type=self.media_type, 
            episode_title=self.episode_title,
            season_number=self.season_number,
            episode_number=self.episode_number,
            actor_data=self.actor_data
        )
        self.game_controller.set_ui_callbacks(
            self.update_display_callback,
            self.update_buttons_callback, 
            self.update_sidebar_callback,
            self.show_error_callback,
            self.set_button_focus,
            self.start_countdown,
            self.close,
            self.update_millionaire_ladder_callback,
            self.set_answer_button_colors_callback
        )
        self._highlight_thread = None
        self._highlight_question_id = None

    def onInit(self):
        # Nastavení property pro XML
        self.setProperty('WCS.TextGame.Title', self.title)
        self.setProperty('WCS.TextGame.Fanart', self.fanart)
        # Nastavit banner fanart pro header
        self.setProperty('WCS.TextGame.BannerFanart', self.banner_fanart)
        # Nastavit poster (pokud je fanart, jinak prázdné)
        self.setProperty('WCS.TextGame.Poster', self.fanart)

        # Nastavení hardcoded barev pro celý dialog
        self.apply_theme_properties()
        # Počáteční nastavení typu hry (bude se aktualizovat podle potřeby)
        self.setProperty('WCS.Game.Type', 'none')
        # Spuštění výběru hry přes controller
        self.game_controller.start_game_selection()
        self.update_lifeline_buttons()
        # Nastavit správný fokus podle stavu hry
        self.set_initial_focus()

    def set_initial_focus(self):
        """Nastaví správný fokus podle stavu hry."""
        try:
            current_state = self.game_controller.current_game_state
            if current_state == "millionaire_welcome":
                # Ve welcome screenu použít tlačítko 301
                try:
                    self.setFocus(self.getControl(301))
                except:
                    # Pokud tlačítko 301 není dostupné, zkusit 305
                    self.setFocus(self.getControl(305))
            else:
                # V ostatních stavech použít tlačítko 305
                try:
                    self.setFocus(self.getControl(305))
                except:
                    # Pokud tlačítko 305 není dostupné, zkusit 301
                    self.setFocus(self.getControl(301))
        except Exception as e:
            xbmc.log(f"[plugin.video.milionar] Error setting initial focus: {e}", level=xbmc.LOGERROR)

    # Callback metody pro komunikaci s GameController
    def update_display_callback(self, text):
        """Callback pro aktualizaci hlavního textu a property typu/stavu hry."""
        try:
            # Detekce typu a stavu hry podle aktivního controlleru
            game_type = ''
            game_state = ''
            header_text = 'Herní menu'
            
            ctrl = getattr(self.game_controller, 'active_controller', None)
            if ctrl and hasattr(ctrl, 'game_type'):
                # Získání typu média a jeho překlad
                media_type_text = 'Film'
                if hasattr(ctrl, 'media_type'):
                    if ctrl.media_type == 'series':
                        media_type_text = 'Seriál'
                    elif ctrl.media_type == 'actor':
                        media_type_text = 'Herec'
                    elif ctrl.media_type == 'director':
                        media_type_text = 'Režisér'
                    elif ctrl.media_type == 'creator':
                        media_type_text = 'Tvůrce'
                    else:
                        media_type_text = 'Film'
                
                if ctrl.game_type == 'adventure':
                    game_type = 'adventure'
                    if hasattr(ctrl, 'game_state'):
                        game_state = ctrl.game_state  # Nastavit game_state pro XML
                        if ctrl.game_state == 'playing':
                            header_text = f'Adventure ({media_type_text}) - Hraje se'
                        elif ctrl.game_state in ['adventure_welcome', 'adventure_instructions']:
                            header_text = f'Adventure ({media_type_text})'
                        elif ctrl.game_state == 'ended':
                            header_text = f'Adventure ({media_type_text}) - Konec'
                        else:
                            header_text = f'Adventure ({media_type_text})'
                elif ctrl.game_type == 'millionaire':
                    game_type = 'millionaire'
                    if hasattr(ctrl, 'game_state'):
                        game_state = ctrl.game_state  # Nastavit game_state pro XML
                        if ctrl.game_state in ['playing']:
                            question_num = getattr(ctrl, 'get_total_question_number', lambda: 0)()
                            header_text = f'Milionář ({media_type_text}) - Otázka {question_num}'
                        elif ctrl.game_state == 'millionaire_welcome':
                            header_text = f'Milionář ({media_type_text})'
                        elif ctrl.game_state == 'millionaire_rules':
                            header_text = f'Milionář ({media_type_text}) - Pravidla'
                        elif ctrl.game_state == 'game_over':
                            header_text = f'Milionář ({media_type_text}) - Konec hry'
                        elif ctrl.game_state == 'game_finished':
                            header_text = f'Milionář ({media_type_text}) - Vítěz!'
                        elif ctrl.game_state in ['generating_welcome', 'generating_question']:
                            header_text = f'Milionář ({media_type_text}) - Načítání'
                        elif ctrl.game_state == 'answer_pending':
                            header_text = f'Milionář ({media_type_text}) - Vyhodnocuje se'
                        elif ctrl.game_state == 'answer_feedback':
                            header_text = f'Milionář ({media_type_text}) - Výsledek'
                        else:
                            header_text = f'Milionář ({media_type_text})'
                elif ctrl.game_type == 'quiz':
                    game_type = 'quiz'
                    if hasattr(ctrl, 'game_state'):
                        game_state = ctrl.game_state  # Nastavit game_state pro XML
                        if ctrl.game_state == 'quiz_playing':
                            question_num = getattr(ctrl, 'quiz_question_number', 0)
                            header_text = f'Kvíz ({media_type_text}) - Otázka {question_num}'
                        elif ctrl.game_state == 'quiz_welcome':
                            header_text = f'Kvíz ({media_type_text})'
                        elif ctrl.game_state == 'quiz_instructions':
                            header_text = f'Kvíz ({media_type_text}) - Návod'
                        elif ctrl.game_state == 'quiz_answer_pending':
                            header_text = f'Kvíz ({media_type_text}) - Vyhodnocuje se'
                        elif ctrl.game_state == 'quiz_transition':
                            header_text = f'Kvíz ({media_type_text}) - Výsledek'
                        elif ctrl.game_state == 'ended':
                            header_text = f'Kvíz ({media_type_text}) - Výsledky'
                        else:
                            header_text = f'Kvíz ({media_type_text})'
            elif hasattr(self.game_controller, 'game_state') and self.game_controller.game_state == 'game_selection':
                # Pro game_selection můžeme získat media_type z hlavního controlleru
                media_type_text = 'Film'
                if hasattr(self.game_controller, 'media_type'):
                    if self.game_controller.media_type == 'series':
                        media_type_text = 'Seriál'
                    elif self.game_controller.media_type == 'actor':
                        media_type_text = 'Herec'
                    elif self.game_controller.media_type == 'director':
                        media_type_text = 'Režisér'
                    elif self.game_controller.media_type == 'creator':
                        media_type_text = 'Tvůrce'
                header_text = f'Výběr hry ({media_type_text})'
                game_state = 'game_selection'
            
            self.setProperty('WCS.Game.Type', game_type)
            self.setProperty('WCS.Game.State', game_state)
            self.setProperty('WCS.Game.Header', header_text)
            
            # Explicitně aktualizovat sidebar po změně stavu (kromě game_selection)
            if game_state != 'game_selection' and game_state != '':
                self.update_sidebar()
            

            # Uložit text pro countdown použití
            self.current_game_text = text
            # Nastavit text do správného textboxu (200 nebo 201)
            try:
                if game_type == 'adventure' and game_state == 'playing':
                    textbox = self.getControl(200)
                else:
                    textbox = self.getControl(201)
                textbox.setText(text)
            except Exception as e:
                xbmc.log(f"[plugin.video.milionar] Error setting textbox text: {e}", level=xbmc.LOGERROR)
            
            # Nastavit správný fokus při změně stavu
            self.set_initial_focus()
        except Exception as e:
            xbmc.log(f"[plugin.video.milionar] Error updating display: {e}", level=xbmc.LOGERROR)
            
    def update_buttons_callback(self, text1, text2, text3, text4=""):
        """Callback pro aktualizaci tlačítek."""
        try:
            self.set_dynamic_buttons(text1, text2, text3, text4)
        except Exception as e:
            xbmc.log(f"[plugin.video.milionar] Error updating buttons: {e}", level=xbmc.LOGERROR)

    def set_answer_button_colors_callback(self, selected_index, correct_index=None):
        """Callback pro nastavení barev odpovědí na tlačítkách.
        
        Fáze 1 (countdown): correct_index=None -> vybraná = modrá focus barva
        Fáze 2 (reveal): correct_index set -> správná = zelená, špatná = červená
        """
        try:
            btn_bg = self.getProperty('WCS.Game.ButtonBG')
            focus_bg = self.getProperty('WCS.Game.ButtonBGFocus')
            
            for i in range(4):
                prop_name = f'WCS.Game.ButtonBG.{305 + i}'
                if correct_index is not None:
                    # Fáze 2: Reveal
                    if i == correct_index:
                        self.setProperty(prop_name, 'FF3CB371')  # zelená
                    elif i == selected_index and selected_index != correct_index:
                        self.setProperty(prop_name, 'FFB22222')  # červená
                    else:
                        self.setProperty(prop_name, btn_bg)
                else:
                    # Fáze 1: Countdown
                    if i == selected_index:
                        self.setProperty(prop_name, focus_bg)  # modrá (focus)
                    else:
                        self.setProperty(prop_name, btn_bg)
        except Exception as e:
            xbmc.log(f"[plugin.video.milionar] Error setting answer button colors: {e}", level=xbmc.LOGERROR)
            
    def update_sidebar_callback(self):
        """Callback pro aktualizaci sidebaru."""
        try:
            # Aktualizovat sidebar pro všechny stavy kromě game_selection (který má statický welcome sidebar)
            if hasattr(self.game_controller, 'game_state') and self.game_controller.game_state == 'game_selection':
                # Pouze aktualizovat lifeline tlačítka, ale NIKDY neaktualizovat welcome sidebar
                self.update_lifeline_buttons()
                return
            self.update_sidebar()
        except Exception as e:
            xbmc.log(f"[plugin.video.milionar] Error updating sidebar: {e}", level=xbmc.LOGERROR)
            
    def show_error_callback(self, message):
        """Callback pro zobrazení chyby."""
        try:
            self.show_error(message)
        except Exception as e:
            xbmc.log(f"[plugin.video.milionar] Error showing error: {e}", level=xbmc.LOGERROR)
            
    def set_button_focus(self, button_index):
        """Callback pro nastavení fokusu na tlačítko."""
        try:
            # Určit správný control ID podle stavu hry
            current_state = self.game_controller.current_game_state
            if current_state == "millionaire_welcome":
                # Ve welcome screenu použít tlačítka 301-304
                control_id = 301 + button_index
            else:
                # V ostatních stavech použít tlačítka 305-308
                control_id = 305 + button_index
            
            try:
                self.setFocus(self.getControl(control_id))
                xbmc.log(f"[plugin.video.milionar] Focus set to button {button_index} (control {control_id}) in state {current_state}", level=xbmc.LOGINFO)
            except:
                # Pokud první tlačítko není dostupné, zkusit druhé
                if current_state == "millionaire_welcome":
                    control_id = 305 + button_index
                else:
                    control_id = 301 + button_index
                self.setFocus(self.getControl(control_id))
                xbmc.log(f"[plugin.video.milionar] Focus set to fallback button {button_index} (control {control_id}) in state {current_state}", level=xbmc.LOGINFO)
        except Exception as e:
            xbmc.log(f"[plugin.video.milionar] Error setting focus to button {button_index}: {e}", level=xbmc.LOGERROR)
    
    def start_countdown(self, seconds, finish_callback):
        """Callback pro spuštění countdown timeru."""
        
        def countdown_worker():
            try:
                # Použít uložený text místo čtení z textboxu
                base_text = self.current_game_text
                
                # Najít kde končí původní text (před "Vyhodnocení odpovědi...")
                if "Vyhodnocení odpovědi..." in base_text:
                    base_text = base_text.split("Vyhodnocení odpovědi...")[0]
                
                # Countdown - pouze aktualizovat časovou část
                for i in range(seconds, 0, -1):
                    # Vytvořit nový text s aktualizovaným časem
                    countdown_text = base_text + f"Vyhodnocení za {i} sekund..."
                    
                    # Aktualizovat textbox
                    try:
                        textbox = self.getControl(200)
                        textbox.setText(countdown_text)
                    except:
                        pass
                    time.sleep(1)
                
                # Po countdown zavolat finish callback
                finish_callback()
                
            except Exception as e:
                xbmc.log(f"[plugin.video.milionar] Error in countdown: {e}", level=xbmc.LOGERROR)
                # V případě chyby zavolat finish callback
                finish_callback()
        
        # Spustit countdown v separátním threadu
        countdown_thread = threading.Thread(target=countdown_worker)
        countdown_thread.daemon = True
        countdown_thread.start()

    def update_sidebar(self):
        """Aktualizuje sidebar podle stavu hry."""
        try:
            # Pro ostatní hry aktualizovat jejich sidebary
            sidebar = self.getControl(100)
            sidebar.reset()
            
            items = self.game_controller.get_sidebar_items()
            
            for label in items:
                item = xbmcgui.ListItem(label=label)
                sidebar.addItem(item)
            
            self.update_lifeline_buttons()
        except Exception as e:
            xbmc.log(f"[plugin.video.milionar] Error in update_sidebar: {e}", level=xbmc.LOGERROR)
    
    def update_millionaire_ladder_callback(self):
        """Callback pro aktualizaci grafického žebříčku v hře Milionář."""
        try:
            self.setProperty('WCS.Game.Type', 'millionaire')
            if (hasattr(self.game_controller, 'active_controller') and 
                self.game_controller.active_controller and 
                hasattr(self.game_controller.active_controller, 'get_millionaire_ladder_states')):
                ladder_states = self.game_controller.active_controller.get_millionaire_ladder_states()
                default_bg = self.getProperty('WCS.Game.ButtonBG')
                for control_id, state_info in ladder_states.items():
                    try:
                        button = self.getControl(control_id)
                        button.setLabel(state_info['text'])
                        # Pokud je barva 'default' nebo '', použij barvu motivu, jinak zachovej zvýraznění
                        bgcolor = state_info.get('bgcolor', '')
                        if not bgcolor or bgcolor == 'default':
                            bgcolor = default_bg
                        self.setProperty(f'WCS.Ladder.BG.{control_id}', bgcolor)
                        if state_info['color'] == 'button_focus':
                            button.setProperty('textcolor', 'button_focus')
                        else:
                            button.setProperty('textcolor', state_info['color'])
                    except Exception as e:
                        xbmc.log(f"[plugin.video.milionar] Error updating ladder button {control_id}: {e}", level=xbmc.LOGERROR)
        except Exception as e:
            xbmc.log(f"[plugin.video.milionar] Error updating millionaire ladder: {e}", level=xbmc.LOGERROR)

    def set_button_bg_properties(self, correct_index=None, highlight=False):
        """Nastaví property pro barvu pozadí každého tlačítka zvlášť (305–308). Zvýrazní správnou odpověď zeleně, pokud je aktivní nastavení a highlight=True."""
        btn_bg = self.getProperty('WCS.Game.ButtonBG')
        addon = self.addon
        show_correct = addon.getSettingBool('millionaire_show_correct_answer')
        for i in range(4):
            prop_name = f'WCS.Game.ButtonBG.{305 + i}'
            if show_correct and highlight and correct_index is not None and i == correct_index:
                self.setProperty(prop_name, 'FF3CB371')  # zelená
            else:
                self.setProperty(prop_name, btn_bg)

    def set_dynamic_buttons(self, text1, text2, text3, text4=""):
        """Nastaví dynamická tlačítka podle délky textu a nastaví property pro barvu pozadí každého tlačítka. Zvýraznění správné odpovědi až po uživatelem nastaveném zpoždění, pouze pokud jsou na tlačítkách odpovědi."""
        try:
            # Zjistit index správné odpovědi pokud je aktivní Milionář
            correct_index = None
            question_id = None
            ctrl = getattr(self.game_controller, 'active_controller', None)
            game_state = None
            if ctrl and hasattr(ctrl, 'game_type') and ctrl.game_type == 'millionaire':
                current_question = getattr(ctrl, 'current_question', None)
                game_state = getattr(ctrl, 'game_state', None)
                if current_question and isinstance(current_question, dict):
                    correct_index = current_question.get('correct', None)
                    # Unikátní ID otázky: použij text otázky + index otázky
                    q_text = current_question.get('question', '')
                    q_idx = getattr(ctrl, 'current_question_index', None)
                    question_id = f'{q_text}|{q_idx}'
            # Nastav všem tlačítkům barvu motivu (žádné zvýraznění)
            self.set_button_bg_properties(correct_index, highlight=False)
            # Správa threadu pro zvýraznění
            self._highlight_question_id = question_id
            if self._highlight_thread and self._highlight_thread.is_alive():
                # Starý thread necháme doběhnout, ale už nebude mít efekt
                pass
            if correct_index is not None and question_id is not None:
                # Získat zpoždění ze settings (v sekundách)
                try:
                    delay = int(self.addon.getSetting('millionaire_highlight_delay'))
                except Exception:
                    delay = 5
                def delayed_highlight(expected_id, idx, delay_s):
                    time.sleep(delay_s)
                    # Po zpoždění zkontroluj, zda je otázka stále stejná a stav hry je odpovídací
                    ctrl2 = getattr(self.game_controller, 'active_controller', None)
                    state2 = getattr(ctrl2, 'game_state', None) if ctrl2 else None
                    if self._highlight_question_id == expected_id and state2 in ("playing",):
                        self.set_button_bg_properties(idx, highlight=True)
                t = threading.Thread(target=delayed_highlight, args=(question_id, correct_index, delay))
                t.daemon = True
                self._highlight_thread = t
                t.start()
            # Tlačítka pro welcome screen (301-304)
            button1_welcome = self.getControl(301)
            button2_welcome = self.getControl(302)
            button3_welcome = self.getControl(303)
            button4_welcome = self.getControl(304)
            
            # Tlačítka pro hru (305-308)
            button1_game = self.getControl(305)
            button2_game = self.getControl(306)
            button3_game = self.getControl(307)
            button4_game = self.getControl(308)
            
            # Vycentrované pozice ve footeru (30px od horního okraje footeru)
            center_y = 25
            
            # Výpočet šířky s dostatečným prostorem - více pixelů na znak a větší padding
            base_width1 = len(text1) * 18 + 100 if text1 else 0
            base_width2 = len(text2) * 18 + 100 if text2 else 0
            base_width3 = len(text3) * 18 + 100 if text3 else 0
            base_width4 = len(text4) * 18 + 100 if text4 else 0
            
            # Pouze aktivní tlačítka pro welcome screen
            active_buttons_welcome = []
            if text1: active_buttons_welcome.append((button1_welcome, text1, base_width1))
            if text2: active_buttons_welcome.append((button2_welcome, text2, base_width2))
            if text3: active_buttons_welcome.append((button3_welcome, text3, base_width3))
            if text4: active_buttons_welcome.append((button4_welcome, text4, base_width4))
            
            # Pouze aktivní tlačítka pro hru
            active_buttons_game = []
            if text1: active_buttons_game.append((button1_game, text1, base_width1))
            if text2: active_buttons_game.append((button2_game, text2, base_width2))
            if text3: active_buttons_game.append((button3_game, text3, base_width3))
            if text4: active_buttons_game.append((button4_game, text4, base_width4))
            
            # Skryj neaktivní tlačítka welcome
            if not text1: button1_welcome.setVisible(False)
            else: button1_welcome.setVisible(True)
            if not text2: button2_welcome.setVisible(False)
            else: button2_welcome.setVisible(True)
            if not text3: button3_welcome.setVisible(False)
            else: button3_welcome.setVisible(True)
            if not text4: button4_welcome.setVisible(False)
            else: button4_welcome.setVisible(True)
            
            # Skryj neaktivní tlačítka hry
            if not text1: button1_game.setVisible(False)
            else: button1_game.setVisible(True)
            if not text2: button2_game.setVisible(False)
            else: button2_game.setVisible(True)
            if not text3: button3_game.setVisible(False)
            else: button3_game.setVisible(True)
            if not text4: button4_game.setVisible(False)
            else: button4_game.setVisible(True)
            
            if not active_buttons_welcome and not active_buttons_game:
                return
            
            # Minimální šířka 200px, maximální až 500px pro welcome
            for i, (btn, text, base_width) in enumerate(active_buttons_welcome):
                width = max(200, min(500, base_width))
                active_buttons_welcome[i] = (btn, text, width)
            
            # Minimální šířka 200px, maximální až 500px pro hru
            for i, (btn, text, base_width) in enumerate(active_buttons_game):
                width = max(200, min(500, base_width))
                active_buttons_game[i] = (btn, text, width)
            
            # Celková šířka + mezery pro welcome
            num_buttons_welcome = len(active_buttons_welcome)
            total_width_welcome = sum(width for _, _, width in active_buttons_welcome) + (num_buttons_welcome - 1) * 20 if num_buttons_welcome > 0 else 0
            
            # Celková šířka + mezery pro hru
            num_buttons_game = len(active_buttons_game)
            total_width_game = sum(width for _, _, width in active_buttons_game) + (num_buttons_game - 1) * 20 if num_buttons_game > 0 else 0
            
            # Pokud je celková šířka větší než obrazovka, přerozdělí proporcionálně
            available_width = 1840  # 1920 - 80px okraje
            
            if total_width_welcome > available_width:
                # Přerozdělí šířky proporcionálně, ale zachová minimální velikost
                scale_factor = available_width / total_width_welcome
                for i, (btn, text, width) in enumerate(active_buttons_welcome):
                    new_width = max(180, int(width * scale_factor))
                    active_buttons_welcome[i] = (btn, text, new_width)
                total_width_welcome = sum(width for _, _, width in active_buttons_welcome) + (num_buttons_welcome - 1) * 20
            
            if total_width_game > available_width:
                # Přerozdělí šířky proporcionálně, ale zachová minimální velikost
                scale_factor = available_width / total_width_game
                for i, (btn, text, width) in enumerate(active_buttons_game):
                    new_width = max(180, int(width * scale_factor))
                    active_buttons_game[i] = (btn, text, new_width)
                total_width_game = sum(width for _, _, width in active_buttons_game) + (num_buttons_game - 1) * 20
            
            # Vypočítej pozice - vycentrované pro welcome
            start_x_welcome = (1920 - total_width_welcome) // 2
            current_x_welcome = start_x_welcome
            
            # Vypočítej pozice - vycentrované pro hru
            start_x_game = (1920 - total_width_game) // 2
            current_x_game = start_x_game
            
            # Nastav pozice a velikosti pro welcome
            for btn, text, width in active_buttons_welcome:
                btn.setPosition(current_x_welcome, center_y)
                btn.setWidth(width)
                btn.setLabel(text)
                current_x_welcome += width + 20
            
            # Nastav pozice a velikosti pro hru
            for btn, text, width in active_buttons_game:
                btn.setPosition(current_x_game, center_y)
                btn.setWidth(width)
                btn.setLabel(text)
                current_x_game += width + 20
            
        except Exception as e:
            xbmc.log(f"[plugin.video.milionar] Error setting dynamic buttons: {e}", level=xbmc.LOGERROR)

    def show_error(self, message):
        """Zobrazí chybovou zprávu."""
        textbox = self.getControl(200)
        textbox.setText(f"Chyba: {message}\n\nStiskni 'Zavřít' pro návrat.")
        
        # Nastavit texty na obě sady tlačítek
        self.setControlLabel(301, "")
        self.setControlLabel(302, "")
        self.setControlLabel(303, "Zavřít")
        self.setControlLabel(305, "")
        self.setControlLabel(306, "")
        self.setControlLabel(307, "Zavřít")

    def onClick(self, controlId):
        """Obsluha kliknutí na tlačítka - deleguje na GameController."""
        try:
            xbmc.log(f"[plugin.video.milionar] TextGameWindow.onClick: controlId={controlId}, game_state={self.game_controller.game_state}", level=xbmc.LOGINFO)
            
            # Nápovědy
            if controlId == 120:
                ctrl = getattr(self.game_controller, 'active_controller', None)
                if ctrl and hasattr(ctrl, 'use_5050_lifeline'):
                    ctrl.use_5050_lifeline()
                    self.update_lifeline_buttons()
                return
            elif controlId == 121:
                ctrl = getattr(self.game_controller, 'active_controller', None)
                if ctrl and hasattr(ctrl, 'use_tip_lifeline'):
                    ctrl.use_tip_lifeline()
                    self.update_lifeline_buttons()
                return
            elif controlId == 122:
                ctrl = getattr(self.game_controller, 'active_controller', None)
                if ctrl and hasattr(ctrl, 'use_audience_poll_lifeline'):
                    ctrl.use_audience_poll_lifeline()
                    self.update_lifeline_buttons()
                return
            elif controlId == 929:  # Tlačítko Podvádění
                self.open_cheating_settings()
                return
            elif controlId == 930:  # Tlačítko Obtížnost
                self.open_difficulty_settings()
                return

            # Mapování tlačítek na indexy
            if controlId in [301, 305]:  # První tlačítko (welcome i hra)
                choice_index = 0
            elif controlId in [302, 306]:  # Druhé tlačítko (welcome i hra)
                choice_index = 1 
            elif controlId in [303, 307]:  # Třetí tlačítko (welcome i hra)
                choice_index = 2
            elif controlId in [304, 308]:  # Čtvrté tlačítko (welcome i hra)
                choice_index = 3
            elif controlId == 100:  # Sidebar listbox
                # Zjisti, na kterou položku bylo kliknuto
                sidebar = self.getControl(100)
                selected = sidebar.getSelectedPosition()
                ctrl = getattr(self.game_controller, 'active_controller', None)
                items = self.game_controller.get_sidebar_items()
                lifeline_5050_used = False
                if ctrl and hasattr(ctrl, 'game_type') and ctrl.game_type == 'millionaire':
                    lifeline_5050_used = getattr(ctrl, 'lifeline_5050_used', False)
                    if selected == len(items):
                        # Kliknuto na nápovědu 50:50
                        if not lifeline_5050_used:
                            ctrl.use_5050_lifeline()
                        else:
                            xbmcgui.Dialog().info("Nápověda 50:50", "Tato nápověda již byla použita.")
                        return
                return  # Ostatní položky sidebaru zatím neřešíme
            else:
                return

            xbmc.log(f"[plugin.video.milionar] TextGameWindow mapped controlId {controlId} to choice_index {choice_index}", level=xbmc.LOGINFO)

            # Chytrá logika pro tlačítko 4 - stejná jako v episode_info_dialog.py
            if choice_index == 3:
                current_state = self.game_controller.current_game_state
                # Pouze ve specifických stavech zavřít dialog
                if current_state in [
                    "game_selection", "ended", "quiz_transition", "millionaire_welcome", "millionaire_rules", 
                    "adventure_welcome", "adventure_instructions", "error", "game_finished", "game_over", 
                    "quiz_welcome", "quiz_instructions"]:
                    # Zavřít dialog úplně
                    self.close()
                    return
                else:
                    # Ve všech ostatních stavech (včetně millionaire_playing) předat do game_controller
                    self.game_controller.make_choice(choice_index)
            else:
                # Pro tlačítka 1-3 vždy delegovat na GameController
                self.game_controller.make_choice(choice_index)
                
        except Exception as e:
            xbmc.log(f"[plugin.video.milionar] Error in onClick: {e}", level=xbmc.LOGERROR)

    def setControlLabel(self, controlId, label):
        """Pomocná metoda pro nastavení textu tlačítka."""
        try:
            control = self.getControl(controlId)
            control.setLabel(label)
        except Exception as e:
            xbmc.log(f"[plugin.video.milionar] Error setting control label {controlId}: {e}", level=xbmc.LOGERROR)

    def open_addon_settings(self):
        """Otevře Kodi nastavení doplňku (připraveno, nikde se nevolá)."""
        try:
            import xbmc
            xbmc.executebuiltin('Addon.OpenSettings(plugin.video.milionar)')
        except Exception as e:
            import xbmc
            xbmc.log(f"[plugin.video.milionar] Error opening Kodi addon settings: {e}", level=xbmc.LOGERROR)
    
    def open_difficulty_settings(self):
        """Otevře dialog s výběrem obtížnosti."""
        try:
            xbmc.log("[plugin.video.milionar] Opening difficulty selection dialog", level=xbmc.LOGINFO)
            
            # Získat aktuální obtížnost
            current_difficulty = self.addon.getSetting('millionaire_difficulty')
            current_index = int(current_difficulty) if current_difficulty else 0
            
            # Možnosti obtížnosti
            difficulties = [
                "Lehká",
                "Střední", 
                "Těžká"
            ]
            
            # Zobrazit dialog s výběrem
            dialog = xbmcgui.Dialog()
            selected = dialog.select("Výběr obtížnosti", difficulties, preselect=current_index)
            
            if selected != -1:  # Uživatel neklikl Cancel
                # Uložit novou obtížnost
                self.addon.setSetting('millionaire_difficulty', str(selected))
                xbmc.log(f"[plugin.video.milionar] Difficulty changed to: {difficulties[selected]}", level=xbmc.LOGINFO)
                
                # Zobrazit potvrzení
                xbmc.executebuiltin(f'Notification("Obtížnost", "Nastavena na: {difficulties[selected]}", 2000)')
                
        except Exception as e:
            xbmc.log(f"[plugin.video.milionar] Error opening difficulty settings: {e}", level=xbmc.LOGERROR)

    def open_cheating_settings(self):
        """Otevře dialog pro zapnutí/vypnutí podvádění (millionaire_show_correct_answer)."""
        try:
            xbmc.log("[plugin.video.milionar] Opening cheating settings dialog", level=xbmc.LOGINFO)
            # Získat aktuální hodnotu
            current_value = self.addon.getSettingBool('millionaire_show_correct_answer')
            current_index = 1 if current_value else 0
            # Možnosti
            options = [
                self.addon.getLocalizedString(32131) + ": Vypnuto",
                self.addon.getLocalizedString(32131) + ": Zapnuto"
            ]
            dialog = xbmcgui.Dialog()
            selected = dialog.select("Podvádění", options, preselect=current_index)
            if selected != -1:
                self.addon.setSettingBool('millionaire_show_correct_answer', bool(selected))
                xbmc.executebuiltin(f'Notification("Podvádění", "{options[selected]}", 2000)')
        except Exception as e:
            xbmc.log(f"[plugin.video.milionar] Error opening cheating settings: {e}", level=xbmc.LOGERROR)

    def update_lifeline_buttons(self):
        """Aktualizuje stav a vzhled tlačítek nápověd podle stavu hry a použití."""
        ctrl = getattr(self.game_controller, 'active_controller', None)
        is_millionaire = ctrl and hasattr(ctrl, 'game_type') and ctrl.game_type == 'millionaire'
        
        # 50:50
        btn_5050 = self.getControl(120)
        used_5050 = False
        if is_millionaire:
            used_5050 = getattr(ctrl, 'lifeline_5050_used', False)
        btn_5050.setEnabled(is_millionaire and not used_5050)
        btn_5050.setLabel('Nápověda 50:50')
        
        # Tip od režiséra/tvůrce
        btn_tip = self.getControl(121)
        used_tip = False
        tip_label = 'Tip od režiséra'  # Default
        if is_millionaire:
            used_tip = getattr(ctrl, 'lifeline_tip_used', False)
            # Použít centrální metodu pro krátký tip text
            if hasattr(ctrl, '_get_tip_text'):
                tip_label = ctrl._get_tip_text(short=True)
        btn_tip.setEnabled(is_millionaire and not used_tip)
        btn_tip.setLabel(tip_label)
        
        # Hlasování diváků
        btn_vote = self.getControl(122)
        used_audience = False
        if is_millionaire:
            used_audience = getattr(ctrl, 'lifeline_audience_used', False)
        btn_vote.setEnabled(is_millionaire and not used_audience)
        btn_vote.setLabel('Hlasování diváků')

    def apply_theme_properties(self):
        """Nastaví hardcoded property pro barvy dialogu."""
        self.setProperty('WCS.Game.MainBG', 'A0232323')
        self.setProperty('WCS.Game.HeaderTextColor', 'white')
        self.setProperty('WCS.Game.ButtonTextColor', 'white')
        self.setProperty('WCS.Game.ButtonBG', '90232323')
        self.setProperty('WCS.Game.ButtonBGFocus', 'FF335C8F')