# wcs/ui.py

import xbmc
import xbmcgui
import xbmcplugin
import xml.etree.ElementTree as ET # Přidán import ET
from urllib.parse import quote_plus
from wcs import utils # Import modulu utils
from wcs.webshare import WebshareClient as webshare_api # Import modulu webshare_api
from wcs import user_data # Import modulu user_data
import datetime
import os
from wcs.ui.ContextMenu import create_series_context_menu, create_movie_context_menu
import xbmcaddon
import time
import shutil  # <-- PŘIDÁN IMPORT

# Notifikace a dialogy

def popinfo(message, heading, icon=xbmcgui.NOTIFICATION_INFO, time=3000, sound=False):
    xbmcgui.Dialog().notification(heading, message, icon, time, sound=sound)

# Generování položky seznamu

def labelize(file):
    name = file.get('name', '')
    size_str = file.get('size')
    formatted_size = ''
    if size_str:
        try:
            size_bytes = int(size_str)
            formatted_size = utils.format_size(size_bytes)
        except (ValueError, TypeError):
            # Pokud velikost není platné číslo, ponecháme prázdné
            formatted_size = '' 
    
    # Přidáme velikost v hranatých závorkách, pokud je dostupná
    if formatted_size:
        label = f"{name} [{formatted_size}]"
    else:
        label = name # Bez velikosti, pokud není dostupná nebo platná
        
    return label

def tolistitem(file, addon, addcommands=None):
    label = labelize(file)
    listitem = xbmcgui.ListItem(label=label)
    if 'img' in file:
        listitem.setArt({'thumb': file['img']})
    utils.set_video_info_tag(listitem, {'title': label})
    listitem.setProperty('IsPlayable', 'true')
    commands = []
    commands.append((addon.getLocalizedString(30211), f"RunPlugin({file['info_url']})"))
    commands.append((addon.getLocalizedString(30212), f"RunPlugin({file['download_url']})"))
    if addcommands:
        commands += addcommands
    listitem.addContextMenuItems(commands)
    return listitem

# Dialog pro zadání textu

def ask(what, addon):
    if what is None:
        what = ''
    kb = xbmc.Keyboard(what, addon.getLocalizedString(30600))
    kb.doModal()
    if kb.isConfirmed():
        return kb.getText()
    return None

# Hlavní menu (bude implementováno v routeru, zde pouze pomocné funkce)
# Funkce menu, generování položek, atd. budou přesunuty a refaktorovány v dalším kroku dle potřeb routeru. 

# Zobrazení informací o souboru
def display_file_info(ident, addon):
    """Získá informace o souboru z API a zobrazí je v dialogu."""
    # --- Kontrola přihlášení --- 
    if not user_data._check_credentials_and_prompt(addon):
        return # Nezobrazovat dialog, pokud není přihlášen
    # Ověření tokenu
    token = webshare_api.revalidate(addon, popinfo) # Použijeme lokální popinfo
    if not token or not ident:
        return
    # Získání informací o souboru
    xml_info = webshare_api.getinfo(ident, token)
    if xml_info is not None:
        info = {e.tag: e.text for e in xml_info}
        text = ''
        text += f"{addon.getLocalizedString(30601)}: {info.get('name', '')}\n"
        # Použití utils.format_size pro formátování velikosti
        size_bytes = None
        try:
            size_bytes = int(info.get('size', ''))
        except (ValueError, TypeError):
            pass
        text += f"{addon.getLocalizedString(30602)}: {utils.format_size(size_bytes)}\n"
        text += f"{addon.getLocalizedString(30603)}: {info.get('type', '')}\n"
        text += f"{addon.getLocalizedString(30604)}: {info.get('format', '')}\n"
        text += f"{addon.getLocalizedString(30605)}: {info.get('width', '')}x{info.get('height', '')}\n"
        text += f"{addon.getLocalizedString(30606)}: {info.get('fps', '')}\n"
        text += f"{addon.getLocalizedString(30607)}: {info.get('bitrate', '')}\n"
        text += f"{addon.getLocalizedString(30608)}: {addon.getLocalizedString(30609) if info.get('removed', '0') == '1' else addon.getLocalizedString(30610)}\n"
        xbmcgui.Dialog().textviewer(addon.getAddonInfo('name'), text)
    else:
        # Zobrazit chybovou notifikaci, pokud getinfo selže
        popinfo(addon.getLocalizedString(30107), addon.getAddonInfo('name'), icon=xbmcgui.NOTIFICATION_WARNING) 

# Otevření nastavení doplňku
def open_settings(addon):
    """Otevře dialogové okno nastavení doplňku."""
    addon.openSettings()

# Spuštění aktualizace knihovny Kodi
def trigger_kodi_library_update(addon):
    """Spustí skenování video knihovny Kodi a zobrazí notifikaci."""
    xbmc.executebuiltin('UpdateLibrary(video)') # Základní volání
    # Použijeme popinfo definované v tomto modulu
    popinfo(addon.getLocalizedString(30611), addon.getAddonInfo('name')) 

# Zobrazení fronty stahování
def display_queue(addon, params, handle):
    """Získá a zobrazí frontu stahování z Webshare API."""
    # --- Kontrola přihlášení --- 
    if not user_data._check_credentials_and_prompt(addon):
        xbmcplugin.endOfDirectory(handle) # Ukončit
        return
    # Ověření tokenu
    token = webshare_api.revalidate(addon, popinfo)
    if not token:
        return
    
    # Odebrání položky z fronty (volitelné)
    if 'dequeue' in params:
        response = webshare_api.api_call('dequeue_file', {'ident': params['dequeue'], 'wst': token})
        xml = ET.fromstring(response.content)
        if webshare_api.is_ok(xml):
            popinfo(addon.getLocalizedString(30106), addon.getAddonInfo('name'))
            xbmc.executebuiltin('Container.Refresh') # Refresh seznamu po smazání
        else:
            popinfo(addon.getLocalizedString(30107), addon.getAddonInfo('name'), icon=xbmcgui.NOTIFICATION_WARNING)
    
    # Získání fronty
    response = webshare_api.api_call('queue', {'wst': token})
    xml = ET.fromstring(response.content)
    if not webshare_api.is_ok(xml):
        popinfo(addon.getLocalizedString(30107), addon.getAddonInfo('name'), icon=xbmcgui.NOTIFICATION_WARNING)
        xbmcplugin.endOfDirectory(handle) # Ukončit i při chybě
        return
    
    # Generování položek
    for file in xml.iter('file'):
        item = {e.tag: e.text for e in file}
        item['name'] = item.get('name', '')
        item['info_url'] = f"plugin://{addon.getAddonInfo('id')}?action=info&ident={item.get('ident')}"
        item['download_url'] = f"plugin://{addon.getAddonInfo('id')}?action=download&ident={item.get('ident')}"
        
        # Přidání kontextového menu pro odebrání z fronty
        # Akce dequeue volá přímo tuto funkci display_queue s parametrem dequeue
        commands = [(addon.getLocalizedString(30215), f"Container.Update(plugin://{addon.getAddonInfo('id')}?action=queue&dequeue={item.get('ident')})")]
        
        listitem = tolistitem(item, addon, addcommands=commands)
        # URL pro přehrání položky
        play_url = f"plugin://{addon.getAddonInfo('id')}?action=play&ident={item.get('ident')}&name={item.get('name')}"
        xbmcplugin.addDirectoryItem(handle, play_url, listitem, False)
        
    xbmcplugin.endOfDirectory(handle) 

# Zobrazení historie
def display_history(addon, params, handle):
    """Získá a zobrazí historii z Webshare API."""
    # --- Kontrola přihlášení --- 
    if not user_data._check_credentials_and_prompt(addon):
        xbmcplugin.endOfDirectory(handle) # Ukončit
        return
    # Ověření tokenu
    token = webshare_api.revalidate(addon, popinfo)
    if not token:
        return

    # Odebrání položky z historie (volitelné)
    if 'remove' in params:
        # Získání download_id pro daný ident (API clear_history vyžaduje download_id)
        # Musíme nejprve načíst historii, abychom našli ID
        response_hist_for_id = webshare_api.api_call('history', {'wst': token})
        xml_hist_for_id = ET.fromstring(response_hist_for_id.content)
        ids_to_remove = []
        if webshare_api.is_ok(xml_hist_for_id):
            for file_node in xml_hist_for_id.iter('file'):
                if params['remove'] == file_node.findtext('ident'):
                    download_id = file_node.findtext('download_id')
                    if download_id:
                         ids_to_remove.append(download_id)
        if ids_to_remove:
            # API může přijmout pole IDček
            response_clear = webshare_api.api_call('clear_history', {'ids[]': ids_to_remove, 'wst': token})
            xml_clear = ET.fromstring(response_clear.content)
            if webshare_api.is_ok(xml_clear):
                popinfo(addon.getLocalizedString(30104), addon.getAddonInfo('name'))
                xbmc.executebuiltin('Container.Refresh') # Refresh seznamu po smazání
            else:
                popinfo(addon.getLocalizedString(30107), addon.getAddonInfo('name'), icon=xbmcgui.NOTIFICATION_WARNING)
        else:
             popinfo(addon.getLocalizedString(30612).replace('%s', str(params['remove'])), addon.getAddonInfo('name'), icon=xbmcgui.NOTIFICATION_WARNING)

    # Přidání do fronty (volitelné)
    if 'toqueue' in params:
        response_queue = webshare_api.api_call('queue_file', {'ident': params['toqueue'], 'wst': token})
        xml_queue = ET.fromstring(response_queue.content) # Kontrola odpovědi (i když API obvykle nic nevrací)
        # Můžeme předpokládat úspěch, pokud nedošlo k výjimce
        popinfo(addon.getLocalizedString(30105), addon.getAddonInfo('name'))
        # Zde refresh není nutný, fronta se aktualizuje při příštím zobrazení

    # Získání historie pro zobrazení
    response = webshare_api.api_call('history', {'wst': token})
    xml = ET.fromstring(response.content)
    if not webshare_api.is_ok(xml):
        popinfo(addon.getLocalizedString(30107), addon.getAddonInfo('name'), icon=xbmcgui.NOTIFICATION_WARNING)
        xbmcplugin.endOfDirectory(handle)
        return

    # Generování položek
    files = []
    for file in xml.iter('file'):
        item = {e.tag: e.text for e in file}
        item['name'] = item.get('name', '')
        item['info_url'] = f"plugin://{addon.getAddonInfo('id')}?action=info&ident={item.get('ident')}"
        item['download_url'] = f"plugin://{addon.getAddonInfo('id')}?action=download&ident={item.get('ident')}"
        files.append(item)
        
    for item in files:
        commands = [
            (addon.getLocalizedString(30213), f"Container.Update(plugin://{addon.getAddonInfo('id')}?action=history&remove={item.get('ident')})"),
            (addon.getLocalizedString(30214), f"Container.Update(plugin://{addon.getAddonInfo('id')}?action=history&toqueue={item.get('ident')})")
        ]
        listitem = tolistitem(item, addon, addcommands=commands)
        play_url = f"plugin://{addon.getAddonInfo('id')}?action=play&ident={item.get('ident')}&name={item.get('name')}"
        xbmcplugin.addDirectoryItem(handle, play_url, listitem, False)
        
    xbmcplugin.endOfDirectory(handle) 

# Zobrazení "Moje soubory"
def display_my_files(addon, params, handle):
    """Získá a zobrazí seznam souborů uživatele z Webshare API."""
    # --- Kontrola přihlášení --- 
    if not user_data._check_credentials_and_prompt(addon):
        xbmcplugin.endOfDirectory(handle) # Ukončit
        return
    # Ověření tokenu
    token = webshare_api.revalidate(addon, popinfo)
    if not token:
        return

    # Získání seznamu souborů
    response = webshare_api.api_call('file_list', {'wst': token})
    xml = ET.fromstring(response.content)
    if not webshare_api.is_ok(xml):
        popinfo(addon.getLocalizedString(30107), addon.getAddonInfo('name'), icon=xbmcgui.NOTIFICATION_WARNING)
        xbmcplugin.endOfDirectory(handle)
        return

    # Generování položek
    for file in xml.iter('file'):
        item = {e.tag: e.text for e in file}
        item['name'] = item.get('name', '')
        item['info_url'] = f"plugin://{addon.getAddonInfo('id')}?action=info&ident={item.get('ident')}"
        item['download_url'] = f"plugin://{addon.getAddonInfo('id')}?action=download&ident={item.get('ident')}"
        # TODO: Zvážit přidání kontextového menu (např. smazat soubor? přejmenovat?)
        listitem = tolistitem(item, addon)
        play_url = f"plugin://{addon.getAddonInfo('id')}?action=play&ident={item.get('ident')}&name={item.get('name')}"
        xbmcplugin.addDirectoryItem(handle, play_url, listitem, False)

    xbmcplugin.endOfDirectory(handle)

# Zobrazení informace o placeholderu "DB"
def display_db_placeholder_info(addon, handle):
    """Zobrazí notifikaci, že funkce DB není implementována."""
    popinfo(addon.getLocalizedString(30613), addon.getAddonInfo('name'), icon=xbmcgui.NOTIFICATION_INFO)
    # Konec adresáře
    xbmcplugin.endOfDirectory(handle)

def search_history_select(params, addon, handle):
    """
    Zobrazí dialog pro výběr typu vyhledávání historie (TMDb metadata nebo Manuální Webshare).
    """
    query = params.get('query')
    if not query:
        return

    # Vytvoříme jednoduchý dialog se třemi tlačítky
    # Indexy: 0 - TMDb Vyhledávání, 1 - Webshare Manuální, 2 - Zrušit
    dialog = xbmcgui.Dialog()
    
    # Možnosti v dialogu
    options = ["TMDb Vyhledávání (S metadaty, plakáty)", "Webshare Manuální (Přímo soubory)", "Zrušit"]
    
    # Zobrazíme dialog
    ret = dialog.select(f"Jak chcete vyhledat '{query}'?", options)
    
    if ret == 0:
        # TMDb Vyhledávání
        # Přesměrujeme zpět na tmdb_universal_search
        # Container.Update nefunguje spolehlivě uvnitř dialog callbacku
        # Zavoláme funkci přímo, ale musíme upravit params
        new_params = params.copy()
        new_params['action'] = 'tmdb_universal_search'
        # Query už je v params
        
        # Zavoláme přímo funkci universal_search
        # POZOR: Musíme zajistit, aby se předchozí běh ukončil
        # Ale protože jsme volali z routeru, který zavolal nás, jsme v tomtéž threadu.
        # Router už nic dalšího nedělá.
        universal_search(new_params, addon, handle)
        return
        
    elif ret == 1:
        # Webshare Manuální Vyhledávání
        # Zavoláme přímo funkci pro manuální hledání, ale musíme předat parametry
        from wcs.search import MovieSearch as search_movies
        from wcs.webshare import WebshareClient as webshare_api
        
        # U manuálního vyhledávání chceme rovnou hledat, ne se ptát znovu
        selected_file = search_movies.search_and_select_movie_file(
            search_query=query,
            addon=addon,
            manual_search=True
        )
        
        # Pokud uživatel něco vybral, musíme to přehrát!
        # Tady chyběla logika pro zpracování výsledku.
        if selected_file and 'ident' in selected_file and 'name' in selected_file:
             ident = selected_file['ident']
             name = selected_file['name']
             
             # Pro manuální přehrání nemusíme předávat TMDB metadata
             params_dict = {
                 'tmdb_title': name, # Použijeme název souboru jako titul
             }
             
             webshare_api.resolve_playable_item(ident, name, addon, params_dict, handle, use_player=True)
             return
        
    # Pokud ret == 2 nebo ret == -1 (Zrušeno), nic neděláme (zůstane v historii) 

# --- Funkce pro zobrazení TMDb menu ---

def display_main_menu(addon, handle):
    """Zobrazí hlavní menu TMDb (Seriály, Filmy)."""
    xbmcplugin.setPluginCategory(handle, 'TMDb')
    # Podsložka Universální hledání
    listitem = xbmcgui.ListItem(label=addon.getLocalizedString(30614))
    listitem.setArt({'icon': 'DefaultAddonsSearch.png'})
    utils.set_video_info_tag(listitem, {'title': addon.getLocalizedString(30615), 'plot': addon.getLocalizedString(30616)})
    utils.set_video_info_tag(listitem, {'title': addon.getLocalizedString(30615), 'plot': addon.getLocalizedString(30616)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=tmdb_universal_search", listitem, True)
    
    # Podsložka Seriály
    listitem = xbmcgui.ListItem(label=addon.getLocalizedString(30103))
    listitem.setArt({'icon': 'DefaultTVShows.png'})
    utils.set_video_info_tag(listitem, {'title': addon.getLocalizedString(30103), 'plot': addon.getLocalizedString(30618)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=tmdb_series", listitem, True)
    # Podsložka Filmy
    listitem = xbmcgui.ListItem(label=addon.getLocalizedString(30102))
    listitem.setArt({'icon': 'DefaultMovies.png'})
    utils.set_video_info_tag(listitem, {'title': addon.getLocalizedString(30102), 'plot': addon.getLocalizedString(30620)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=tmdb_movies", listitem, True)
    # Podsložka Moje přidané
    listitem = xbmcgui.ListItem(label=addon.getLocalizedString(30621))
    listitem.setArt({'icon': 'DefaultFavourites.png'})
    utils.set_video_info_tag(listitem, {'title': addon.getLocalizedString(30621), 'plot': addon.getLocalizedString(32111)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=my_added_items", listitem, True)
    # Oblíbení herci
    listitem = xbmcgui.ListItem(label=addon.getLocalizedString(30624))
    listitem.setArt({'icon': 'DefaultActor.png'})
    utils.set_video_info_tag(listitem, {'title': addon.getLocalizedString(30624), 'plot': addon.getLocalizedString(30625)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=favorite_actors", listitem, True)
    # Oblíbení režiséři
    listitem = xbmcgui.ListItem(label=addon.getLocalizedString(30626))
    listitem.setArt({'icon': 'DefaultDirector.png'})
    utils.set_video_info_tag(listitem, {'title': addon.getLocalizedString(30626), 'plot': addon.getLocalizedString(30627)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=favorite_directors", listitem, True)
    # Oblíbení scénáristé
    listitem = xbmcgui.ListItem(label=addon.getLocalizedString(30628))
    listitem.setArt({'icon': 'DefaultProgram.png'})
    utils.set_video_info_tag(listitem, {'title': addon.getLocalizedString(30628), 'plot': addon.getLocalizedString(30629)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=favorite_writers", listitem, True)
    # Přidání položky AI statistiky
    listitem = xbmcgui.ListItem(label=addon.getLocalizedString(30630))
    listitem.setArt({'icon': 'DefaultAddonProgram.png'})
    utils.set_video_info_tag(listitem, {'title': addon.getLocalizedString(30630), 'plot': addon.getLocalizedString(30631)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=ai_usage_stats", listitem, True)
    # Přidání položky Nastavení
    label_settings = addon.getLocalizedString(30632)
    listitem = xbmcgui.ListItem(label=label_settings)
    listitem.setArt({'icon': 'DefaultAddonService.png'})
    utils.set_video_info_tag(listitem, {
        'title': label_settings,
        'plot': addon.getLocalizedString(35057)
    })
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=settings", listitem, False)
    xbmcplugin.endOfDirectory(handle)

def display_series_menu(addon, handle):
    """Zobrazí menu pro sekci TMDb Seriály."""
    import time
    xbmcplugin.setPluginCategory(handle, 'TMDb / Seriály')
    # 1. Vyhledat Seriál
    label_search = addon.getLocalizedString(31011)
    plot_search = addon.getLocalizedString(31012)
    listitem = xbmcgui.ListItem(label=label_search)
    listitem.setArt({'icon': 'DefaultAddonsSearch.png'})
    utils.set_video_info_tag(listitem, {'title': label_search, 'plot': plot_search})
    url = f"plugin://{addon.getAddonInfo('id')}?action=tmdb_add_series&refresh={int(time.time())}"
    xbmcplugin.addDirectoryItem(handle, url, listitem, True)
    # 2. Moje seriály
    label_my_series = addon.getLocalizedString(31034)
    plot_my_series = addon.getLocalizedString(31161)
    listitem = xbmcgui.ListItem(label=label_my_series)
    listitem.setArt({'icon': 'DefaultFavourites.png'})
    utils.set_video_info_tag(listitem, {'title': label_my_series, 'plot': plot_my_series})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=tmdb_added_series", listitem, True)
    # 3. Kategorie ČSFD
    label_csfd = addon.getLocalizedString(31015)
    plot_csfd = addon.getLocalizedString(31016)
    listitem = xbmcgui.ListItem(label=label_csfd)
    listitem.setArt({'icon': 'DefaultTVShows.png'})
    utils.set_video_info_tag(listitem, {'title': label_csfd, 'plot': plot_csfd})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=csfd_series_menu", listitem, True)
    # 4. Kategorie TMDb
    label_tmdb = addon.getLocalizedString(31017)
    plot_tmdb = addon.getLocalizedString(31018)
    listitem = xbmcgui.ListItem(label=label_tmdb)
    listitem.setArt({'icon': 'DefaultTags.png'})
    utils.set_video_info_tag(listitem, {'title': label_tmdb, 'plot': plot_tmdb})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=tmdb_browse_series_categories", listitem, True)
    # 6. Podle žánru
    label_genre = addon.getLocalizedString(31019)
    plot_genre = addon.getLocalizedString(31020)
    listitem = xbmcgui.ListItem(label=label_genre)
    listitem.setArt({'icon': 'DefaultGenre.png'})
    utils.set_video_info_tag(listitem, {'title': label_genre, 'plot': plot_genre})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=tmdb_browse_series_genres", listitem, True)
    # 7. Podle země původu
    label_country = addon.getLocalizedString(31021)
    plot_country = addon.getLocalizedString(31022)
    listitem = xbmcgui.ListItem(label=label_country)
    listitem.setArt({'icon': 'DefaultCountry.png'})
    utils.set_video_info_tag(listitem, {'title': label_country, 'plot': plot_country})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=tmdb_browse_series_countries", listitem, True)
    # 8. Kombinovaný výběr
    label_combo = addon.getLocalizedString(31023)
    plot_combo = addon.getLocalizedString(31024)
    listitem = xbmcgui.ListItem(label=label_combo)
    listitem.setArt({'icon': 'DefaultAddonsSearch.png'})
    utils.set_video_info_tag(listitem, {'title': label_combo, 'plot': plot_combo})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=tmdb_combo_genres&media_type=tv", listitem, True)
    xbmcplugin.endOfDirectory(handle)

def display_movies_menu(addon, handle):
    """Zobrazí menu pro sekci TMDb Filmy."""
    import time
    xbmcplugin.setPluginCategory(handle, 'TMDb / Filmy')
    # 1. Vyhledat Film
    listitem = xbmcgui.ListItem(label=addon.getLocalizedString(30857))
    listitem.setArt({'icon': 'DefaultAddonsSearch.png'})
    utils.set_video_info_tag(listitem, {'title': addon.getLocalizedString(30857), 'plot': addon.getLocalizedString(30858)})
    url = f"plugin://{addon.getAddonInfo('id')}?action=tmdb_add_movie&refresh={int(time.time())}"
    xbmcplugin.addDirectoryItem(handle, url, listitem, True)
    # 2. Moje filmy
    listitem = xbmcgui.ListItem(label=addon.getLocalizedString(30859))
    listitem.setArt({'icon': 'DefaultFavourites.png'})
    utils.set_video_info_tag(listitem, {'title': addon.getLocalizedString(30859), 'plot': addon.getLocalizedString(30860)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=tmdb_added_movies", listitem, True)
    # 3. Kolekce
    listitem = xbmcgui.ListItem(label=addon.getLocalizedString(30826))
    listitem.setArt({'icon': 'DefaultSets.png'})
    utils.set_video_info_tag(listitem, {'title': addon.getLocalizedString(30826), 'plot': addon.getLocalizedString(30827)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=display_my_movie_collections", listitem, True)
    # 4. Kategorie ČSFD (před TMDb)
    listitem = xbmcgui.ListItem(label=addon.getLocalizedString(30855))
    listitem.setArt({'icon': 'DefaultMovies.png'})
    utils.set_video_info_tag(listitem, {'title': addon.getLocalizedString(30855), 'plot': addon.getLocalizedString(31159)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=csfd_movies_menu", listitem, True)
    # 5. Kategorie TMDb
    listitem = xbmcgui.ListItem(label=addon.getLocalizedString(30633))
    listitem.setArt({'icon': 'DefaultTags.png'})
    utils.set_video_info_tag(listitem, {'title': addon.getLocalizedString(30633), 'plot': addon.getLocalizedString(30634) + '\n\n' + addon.getLocalizedString(30635)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=tmdb_browse_categories", listitem, True)
    # 6. Podle žánru
    listitem = xbmcgui.ListItem(label=addon.getLocalizedString(30636))
    listitem.setArt({'icon': 'DefaultGenre.png'})
    utils.set_video_info_tag(listitem, {'title': addon.getLocalizedString(30636), 'plot': addon.getLocalizedString(30637)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=tmdb_browse_genres", listitem, True)
    # 7. Podle země původu
    listitem = xbmcgui.ListItem(label=addon.getLocalizedString(30638))
    listitem.setArt({'icon': 'DefaultCountry.png'})
    utils.set_video_info_tag(listitem, {'title': addon.getLocalizedString(30638), 'plot': addon.getLocalizedString(30639)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=tmdb_browse_countries", listitem, True)
    # 8. Kombinovaný výběr
    listitem = xbmcgui.ListItem(label=addon.getLocalizedString(30640))
    listitem.setArt({'icon': 'DefaultAddonsSearch.png'})
    utils.set_video_info_tag(listitem, {'title': addon.getLocalizedString(30640), 'plot': addon.getLocalizedString(30641)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=tmdb_combo_genres&media_type=movie", listitem, True)
    xbmcplugin.endOfDirectory(handle)

# --- Nová funkce pro zobrazení oblíbených herců (přesunutá z tmdb_handler.py) ---
def display_favorite_actors(addon, handle):
    xbmcplugin.setPluginCategory(handle, 'TMDb / Filmy / Oblíbení herci')
    favorite_actors = user_data.load_favorite_actors(addon)
    listitem = xbmcgui.ListItem(label=addon.getLocalizedString(30642))
    listitem.setArt({'icon': 'DefaultAddSource.png'})
    utils.set_video_info_tag(listitem, {'title': addon.getLocalizedString(30642), 'plot': addon.getLocalizedString(30643)})
    xbmcplugin.addDirectoryItem(
        handle, 
        f"plugin://{addon.getAddonInfo('id')}?action=tmdb_search_actor", 
        listitem, 
        False
    )
    if favorite_actors:
        delete_all_actors_item = xbmcgui.ListItem(label=f"[COLOR red]{addon.getLocalizedString(30644)}[/COLOR]")
        delete_all_actors_item.setArt({'icon': 'none.png'})
        utils.set_video_info_tag(delete_all_actors_item, {'title': f"[COLOR red]{addon.getLocalizedString(30644)}[/COLOR]", 'plot': addon.getLocalizedString(30645)})
        xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=tmdb_remove_all_favorite_actors", delete_all_actors_item, False)
    ai_item = xbmcgui.ListItem(label=addon.getLocalizedString(30646))
    ai_item.setArt({'icon': 'DefaultMusicSearch.png'})
    utils.set_video_info_tag(ai_item, {'title': addon.getLocalizedString(30646), 'plot': addon.getLocalizedString(30647)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=ai_recommend_by_actors", ai_item, True)
    if not favorite_actors:
        popinfo(addon.getLocalizedString(30648), addon.getLocalizedString(30624))
    
    for idx, actor in enumerate(favorite_actors):
        name = actor.get('name', '')
        profile_path = actor.get('profile_path', '')
        profile_url = f"https://image.tmdb.org/t/p/w500{profile_path}" if profile_path else ''
        
        listitem = xbmcgui.ListItem(label=name)
        if profile_url:
            listitem.setArt({'thumb': profile_url})
        
        # Informace o herci
        utils.set_video_info_tag(listitem, {
            'title': name,
            'plot': actor.get('biography', ''),
            'originaltitle': actor.get('known_for_department', '')
        })
        
        # Kontextové menu pro oblíbené herce
        from wcs.ui.ContextMenu import create_favorite_actor_context_menu
        commands = create_favorite_actor_context_menu(
            addon=addon,
            actor_id=actor['id'],
            name=name,
            biography=actor.get('biography', ''),
            profile_url=profile_url,
            idx=idx
        )
        listitem.addContextMenuItems(commands)
        
        # Kliknutí na herce zobrazí jeho filmy
        url = f"plugin://{addon.getAddonInfo('id')}?action=tmdb_search_actor_movies&actor_id={actor['id']}&actor_name={quote_plus(name)}"
        xbmcplugin.addDirectoryItem(handle, url, listitem, True)
    
    xbmcplugin.endOfDirectory(handle)

# --- Nová funkce pro zobrazení oblíbených režisérů ---
def display_favorite_directors(addon, handle):
    xbmcplugin.setPluginCategory(handle, addon.getLocalizedString(30739))
    favorite_directors = user_data.load_favorite_directors(addon)
    listitem = xbmcgui.ListItem(label=addon.getLocalizedString(30651))
    listitem.setArt({'icon': 'DefaultAddSource.png'})
    utils.set_video_info_tag(listitem, {'title': addon.getLocalizedString(30651), 'plot': addon.getLocalizedString(30652)})
    xbmcplugin.addDirectoryItem(
        handle, 
        f"plugin://{addon.getAddonInfo('id')}?action=tmdb_search_director", 
        listitem, 
        False
    )
    if favorite_directors:
        delete_all_directors_item = xbmcgui.ListItem(label=f"[COLOR red]{addon.getLocalizedString(30653)}[/COLOR]")
        delete_all_directors_item.setArt({'icon': 'none.png'})
        utils.set_video_info_tag(delete_all_directors_item, {'title': f"[COLOR red]{addon.getLocalizedString(30653)}[/COLOR]", 'plot': addon.getLocalizedString(30654)})
        xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=tmdb_remove_all_favorite_directors", delete_all_directors_item, False)
    ai_item = xbmcgui.ListItem(label=addon.getLocalizedString(30646))
    ai_item.setArt({'icon': 'DefaultMusicSearch.png'})
    utils.set_video_info_tag(ai_item, {'title': addon.getLocalizedString(30646), 'plot': addon.getLocalizedString(30655)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=ai_recommend_by_directors", ai_item, True)
    if not favorite_directors:
        popinfo(addon.getLocalizedString(30656), addon.getLocalizedString(30739))
    
    for idx, director in enumerate(favorite_directors):
        name = director.get('name', '')
        profile_path = director.get('profile_path', '')
        profile_url = f"https://image.tmdb.org/t/p/w500{profile_path}" if profile_path else ''
        
        listitem = xbmcgui.ListItem(label=name)
        if profile_url:
            listitem.setArt({'thumb': profile_url})
        
        # Informace o režiséru
        utils.set_video_info_tag(listitem, {
            'title': name,
            'plot': director.get('biography', ''),
            'originaltitle': director.get('known_for_department', '')
        })
        
        # Kontextové menu pro oblíbené režiséry
        from wcs.ui.ContextMenu import create_favorite_director_context_menu
        commands = create_favorite_director_context_menu(
            addon=addon,
            director_id=director['id'],
            name=name,
            biography=director.get('biography', ''),
            profile_url=profile_url,
            idx=idx
        )
        listitem.addContextMenuItems(commands)
        
        # Kliknutí na režiséra zobrazí jeho filmy
        url = f"plugin://{addon.getAddonInfo('id')}?action=tmdb_search_director_movies&director_id={director['id']}&director_name={quote_plus(name)}"
        xbmcplugin.addDirectoryItem(handle, url, listitem, True)
    
    xbmcplugin.endOfDirectory(handle) 

# --- Nová funkce pro zobrazení oblíbených scénáristů ---
def display_favorite_writers(addon, handle):
    xbmcplugin.setPluginCategory(handle, 'TMDb / Filmy / Oblíbení scénáristé')
    favorite_writers = user_data.load_favorite_writers(addon)
    listitem = xbmcgui.ListItem(label=addon.getLocalizedString(30659))
    listitem.setArt({'icon': 'DefaultAddSource.png'})
    utils.set_video_info_tag(listitem, {'title': addon.getLocalizedString(30659), 'plot': addon.getLocalizedString(30660)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=tmdb_search_writer", listitem, False)
    if favorite_writers:
        delete_all_writers_item = xbmcgui.ListItem(label=f"[COLOR red]{addon.getLocalizedString(30661)}[/COLOR]")
        delete_all_writers_item.setArt({'icon': 'none.png'})
        utils.set_video_info_tag(delete_all_writers_item, {'title': f"[COLOR red]{addon.getLocalizedString(30661)}[/COLOR]", 'plot': addon.getLocalizedString(30662)})
        xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=tmdb_remove_all_favorite_writers", delete_all_writers_item, False)
    ai_item = xbmcgui.ListItem(label=addon.getLocalizedString(30646))
    ai_item.setArt({'icon': 'DefaultMusicSearch.png'})
    utils.set_video_info_tag(ai_item, {'title': addon.getLocalizedString(30646), 'plot': addon.getLocalizedString(30663)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=ai_recommend_by_writers", ai_item, True)
    if not favorite_writers:
        popinfo(addon.getLocalizedString(30664), addon.getLocalizedString(30628))
    
    for idx, writer in enumerate(favorite_writers):
        name = writer.get('name', '')
        profile_path = writer.get('profile_path', '')
        profile_url = f"https://image.tmdb.org/t/p/w500{profile_path}" if profile_path else ''
        listitem = xbmcgui.ListItem(label=name)
        if profile_url:
            listitem.setArt({'thumb': profile_url})
        utils.set_video_info_tag(listitem, {'title': name, 'plot': writer.get('biography', '')})
        
        # Kontextové menu pro oblíbené scénáristy
        from wcs.ui.ContextMenu import create_favorite_writer_context_menu
        commands = create_favorite_writer_context_menu(
            addon=addon,
            writer_id=writer['id'],
            name=name,
            biography=writer.get('biography', ''),
            profile_url=profile_url,
            idx=idx
        )
        listitem.addContextMenuItems(commands)
        
        url = f"plugin://{addon.getAddonInfo('id')}?action=tmdb_search_writer_movies&writer_id={writer['id']}&writer_name={quote_plus(name)}"
        xbmcplugin.addDirectoryItem(handle, url, listitem, True)
    
    xbmcplugin.endOfDirectory(handle)

# Pomocná funkce pro vložení AI doporučení
def add_ai_recommend_button(handle, addon, action, label_text=None):
    """Přidá tlačítko pro AI doporučení."""
    if label_text is None:
        label_text = addon.getLocalizedString(31830)
    listitem = xbmcgui.ListItem(label=label_text)
    ai_item = xbmcgui.ListItem(label=label_text)
    ai_item.setArt({'icon': 'DefaultMusicSearch.png'})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action={action}", ai_item, True)
    return True

# --- Nová funkce pro zobrazení menu AI účtu ---
def display_ai_account_menu(addon, handle):
    """Zobrazí menu pro nastavení AI účtu a beta přístupu."""
    xbmcplugin.setPluginCategory(handle, 'Účet AI')
    
    # Beta heslo
    listitem = xbmcgui.ListItem(label=addon.getLocalizedString(31100))
    listitem.setArt({'icon': 'DefaultAddonFont.png'})
    utils.set_video_info_tag(listitem, {'title': addon.getLocalizedString(31100), 'plot': addon.getLocalizedString(31100)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=ai_settings_beta", listitem, False)
    
    # Detailní statistiky využití AI
    listitem = xbmcgui.ListItem(label=addon.getLocalizedString(31101))
    listitem.setArt({'icon': 'DefaultChart.png'})
    
    # Získání detailních statistik z nového systému
    try:
        from wcs.ai.UsageTracker import get_usage_summary, format_cost
        summary = get_usage_summary()
        
        if "error" not in summary:
            totals = summary.get("totals", {})
            today = summary.get("today", {})
            
            plot = f"Celkové náklady: {format_cost(totals.get('cost', 0.0), addon)}[CR]"
            plot += f"Celkem požadavků: {totals.get('requests', 0)}[CR]"
            plot += f"Náklady dnes: {format_cost(today.get('cost', 0.0), addon)}[CR]"
            plot += f"Požadavků dnes: {today.get('requests', 0)}[CR]"
            plot += f"Průměr na požadavek: {format_cost(totals.get('avg_cost_per_request', 0.0), addon)}"
        else:
            plot = f"Chyba načítání statistik: {summary.get('error', 'Neznámá chyba')}"
            
    except Exception as e:
        plot = f"Chyba při načítání AI statistik: {e}"

    utils.set_video_info_tag(listitem, {
        'title': addon.getLocalizedString(30669),
        'plot': plot
    })
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=ai_usage_menu", listitem, True)
    
    # Reset statistik AI API
    listitem = xbmcgui.ListItem(label=addon.getLocalizedString(30671))
    listitem.setArt({'icon': 'DefaultAddonNone.png'})
    utils.set_video_info_tag(listitem, {'title': addon.getLocalizedString(30671), 'plot': addon.getLocalizedString(30672)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=ai_reset_stats", listitem, False)
    
    xbmcplugin.endOfDirectory(handle)

def display_movie_genres(addon, handle, genres):
    """Zobrazí seznam filmových žánrů v Kodi UI."""
    xbmcplugin.setPluginCategory(handle, addon.getLocalizedString(30102) + " / " + addon.getLocalizedString(30104))
    if not genres:
        popinfo(addon.getLocalizedString(31103), addon.getAddonInfo('name'))
    for genre in genres:
        genre_id = genre['id']
        genre_name = genre['name']
        listitem = xbmcgui.ListItem(label=genre_name)
        listitem.setArt({'icon': 'DefaultGenre.png'})
        utils.set_video_info_tag(listitem, {'title': genre_name, 'plot': addon.getLocalizedString(31105) % genre_name})
        url = f"plugin://{addon.getAddonInfo('id')}?action=tmdb_list_movies&genre_id={genre_id}&genre_name={quote_plus(genre_name)}"
        xbmcplugin.addDirectoryItem(handle, url, listitem, True)
    xbmcplugin.endOfDirectory(handle)

def display_series_genres(addon, handle, genres):
    """Zobrazí seznam seriálových žánrů v Kodi UI."""
    xbmcplugin.setPluginCategory(handle, addon.getLocalizedString(30103) + " / " + addon.getLocalizedString(30104))
    if not genres:
        popinfo(addon.getLocalizedString(31104), addon.getAddonInfo('name'))
    for genre in genres:
        genre_id = genre['id']
        genre_name = genre['name']
        listitem = xbmcgui.ListItem(label=genre_name)
        listitem.setArt({'icon': 'DefaultGenre.png'})
        utils.set_video_info_tag(listitem, {'title': genre_name, 'plot': addon.getLocalizedString(31105) % genre_name})
        url = f"plugin://{addon.getAddonInfo('id')}?action=tmdb_list_series&genre_id={genre_id}&genre_name={quote_plus(genre_name)}"
        xbmcplugin.addDirectoryItem(handle, url, listitem, True)
    xbmcplugin.endOfDirectory(handle)

def display_movie_countries(addon, handle, countries):
    """Zobrazí seznam zemí pro filmy v Kodi UI."""
    xbmcplugin.setPluginCategory(handle, addon.getLocalizedString(31111))
    for country in countries:
        listitem = xbmcgui.ListItem(label=country['name'])
        listitem.setArt({'icon': 'DefaultCountry.png'})
        url = f"plugin://{addon.getAddonInfo('id')}?action=tmdb_list_movies&country_code={country['code']}&country_name={quote_plus(country['name'])}"
        xbmcplugin.addDirectoryItem(handle, url, listitem, True)
    xbmcplugin.endOfDirectory(handle)

def display_series_countries(addon, handle, countries):
    """Zobrazí seznam zemí pro seriály v Kodi UI."""
    xbmcplugin.setPluginCategory(handle, addon.getLocalizedString(31110))
    for country in countries:
        country_name = country['name']
        listitem = xbmcgui.ListItem(label=country_name)
        listitem.setArt({'icon': 'DefaultCountry.png'})
        utils.set_video_info_tag(listitem, {'title': country_name, 'plot': f'Seriály ze země: {country_name}.'})
        url = f"plugin://{addon.getAddonInfo('id')}?action=tmdb_list_series&country_code={country['code']}&country_name={quote_plus(country['name'])}"
        xbmcplugin.addDirectoryItem(handle, url, listitem, True)
    xbmcplugin.endOfDirectory(handle)

def display_movie_categories(addon, handle, categories):
    """Zobrazí seznam kategorií filmů v Kodi UI."""
    xbmcplugin.setPluginCategory(handle, addon.getLocalizedString(31106))
    for category_key, label_id in categories.items():
        label = addon.getLocalizedString(label_id)
        listitem = xbmcgui.ListItem(label=label)
        listitem.setArt({'icon': 'DefaultMovies.png'})
        # Popisky pro jednotlivé kategorie
        if category_key == 'popular':
            plot = addon.getLocalizedString(31107)
            plot += '\n\n' + addon.getLocalizedString(31108)
        elif category_key == 'top_rated':
            plot = addon.getLocalizedString(30683)
            plot += '\n\n' + addon.getLocalizedString(30684)
        elif category_key == 'now_playing':
            plot = addon.getLocalizedString(30685)
            plot += '\n\n' + addon.getLocalizedString(30686)
        elif category_key == 'upcoming':
            plot = addon.getLocalizedString(30687)
            plot += '\n\n' + addon.getLocalizedString(30688)
        else:
            plot = addon.getLocalizedString(30689)
            plot += '\n\n' + addon.getLocalizedString(30690)
        utils.set_video_info_tag(listitem, {'title': label, 'plot': plot})
        url = f"plugin://{addon.getAddonInfo('id')}?action=tmdb_list_movies&category={category_key}"
        xbmcplugin.addDirectoryItem(handle, url, listitem, True)
    xbmcplugin.endOfDirectory(handle)

def display_series_categories(addon, handle, categories):
    """Zobrazí seznam kategorií seriálů v Kodi UI."""
    xbmcplugin.setPluginCategory(handle, 'TMDb / Seriály / Kategorie')
    for category_key, label_id in categories.items():
        label = addon.getLocalizedString(label_id)
        listitem = xbmcgui.ListItem(label=label)
        listitem.setArt({'icon': 'DefaultTVShows.png'})
        # Vtipné popisky pro jednotlivé kategorie
        if category_key == 'popular':
            plot = addon.getLocalizedString(31006)
        elif category_key == 'top_rated':
            plot = addon.getLocalizedString(31004)
        elif category_key == 'on_the_air':
            plot = addon.getLocalizedString(31002)
        elif category_key == 'airing_today':
            plot = addon.getLocalizedString(31008)
        else:
            plot = addon.getLocalizedString(31010)
        utils.set_video_info_tag(listitem, {'title': label, 'plot': plot})
        url = f"plugin://{addon.getAddonInfo('id')}?action=tmdb_list_series&category={category_key}"
        xbmcplugin.addDirectoryItem(handle, url, listitem, True)
    xbmcplugin.endOfDirectory(handle)

def display_collection_movies(addon, handle, collection_name, parts):
    """Zobrazí filmy v kolekci."""
    if not parts:
        xbmcgui.Dialog().ok(addon.getAddonInfo('name'), addon.getLocalizedString(31828))
        xbmcplugin.endOfDirectory(handle)
        return
    xbmcplugin.setPluginCategory(handle, addon.getLocalizedString(30748) % collection_name)
    xbmcplugin.setContent(handle, 'movies')
    # Seřadíme filmy podle data vydání (pokud je k dispozici)
    sorted_parts = sorted(parts, key=lambda x: x.get('release_date', '9999-12-31') or '9999-12-31')
    for movie in sorted_parts:
        movie_id = movie.get('id')
        title = movie.get('title', addon.getLocalizedString(31112))
        year = movie.get('release_date', '')[:4]
        label = f"{title} ({year})" if year else title
        poster_path = movie.get('poster_path')
        poster = f"https://image.tmdb.org/t/p/w500{poster_path}" if poster_path else 'DefaultMovies.png'
        backdrop_path = movie.get('backdrop_path', '')
        fanart = f"https://image.tmdb.org/t/p/original{backdrop_path}" if backdrop_path else poster
        plot = movie.get('overview', '')
        listitem = xbmcgui.ListItem(label=label)
        listitem.setArt({'thumb': poster, 'poster': poster, 'icon': poster, 'fanart': fanart})
        utils.set_video_info_tag(listitem, {
            'title': title, 
            'originaltitle': movie.get('original_title', ''),
            'plot': plot, 
            'year': int(year) if year else 0,
            'genre': ", ".join([g['name'] for g in movie.get('genres', [])]),
            'rating': movie.get('vote_average', 0.0),
            'votes': movie.get('vote_count', 0),
            'mediatype': 'movie',
            'imdbnumber': movie.get('imdb_id', ''),
            'tmdb_id': movie_id
        })
        listitem.setProperty('IsPlayable', 'false')
        
        # Kontextové menu pro filmy v kolekci
        from wcs.ui.ContextMenu import create_movie_context_menu
        commands = create_movie_context_menu(
            addon=addon,
            tmdb_id=movie_id,
            title=title,
            year=year,
            plot=plot,
            poster=poster,
            original_title=title
        )
        listitem.addContextMenuItems(commands)
        
        details_url = f"plugin://{addon.getAddonInfo('id')}?action=show_wcs_details&media_type=movie&tmdb_id={movie_id}"
        xbmcplugin.addDirectoryItem(handle, details_url, listitem, False)
    xbmcplugin.endOfDirectory(handle)

def display_my_movie_collections(addon, handle, collections):
    """Zobrazí kolekce filmů."""
    if not collections:
        xbmcgui.Dialog().ok(addon.getAddonInfo('name'), addon.getLocalizedString(31829))
        xbmcplugin.endOfDirectory(handle)
        return
    xbmcplugin.setPluginCategory(handle, addon.getLocalizedString(31113))
    xbmcplugin.setContent(handle, 'movies')
    sorted_collections = sorted(collections.items(), key=lambda item: item[1]['name'])
    for coll_id, coll_data in sorted_collections:
        base_collection_name = coll_data['name']
        suffix_to_check = " (kolekce)"
        if base_collection_name.lower().endswith(suffix_to_check.lower()):
            base_collection_name = base_collection_name[:-len(suffix_to_check)]
        base_collection_name = base_collection_name.rstrip()
        label = base_collection_name
        poster_url = f"https://image.tmdb.org/t/p/w500{coll_data['poster_path']}" if coll_data['poster_path'] else ''
        fanart_url = f"https://image.tmdb.org/t/p/original{coll_data['backdrop_path']}" if coll_data['backdrop_path'] else poster_url
        art_data = {}
        if poster_url:
            art_data['thumb'] = poster_url
            art_data['poster'] = poster_url
            art_data['icon'] = poster_url
        if fanart_url:
            art_data['fanart'] = fanart_url
        listitem = xbmcgui.ListItem(label=label)
        if art_data:
            listitem.setArt(art_data)
        # --- Nově: načtení popisu kolekce s cache ---
        overview = coll_data.get('overview', '')
        log_prefix = f"[Kolekce TMDb] {label} (ID: {coll_id}): "
        if not overview:
            try:
                from wcs.metadata import TMDbCache as tmdb_cache
                import requests
                api_key = getattr(coll_data, 'tmdb_api_key', None)
                if not api_key:
                    from wcs.metadata.TMDbClient import get_tmdb_api_key
                    api_key = get_tmdb_api_key()
                endpoint = f'/collection/{coll_id}'
                params = {'language': 'cs-CZ'}
                def fetch():
                    url = f'https://api.themoviedb.org/3/collection/{coll_id}?api_key={api_key}&language=cs-CZ'
                    resp = requests.get(url, timeout=5)
                    if resp.ok:
                        xbmc.log(log_prefix + 'Popis kolekce stažen z API.', xbmc.LOGINFO)
                        return resp.json()
                    return {}
                # --- LOG: pokus o načtení z cache ---
                data = tmdb_cache.get_from_cache(endpoint, params, expire_seconds=604800)
                if data is not None:
                    xbmc.log(log_prefix + 'Popis kolekce načten z cache.', xbmc.LOGINFO)
                    overview = data.get('overview', '')
                else:
                    data = tmdb_cache.get_or_fetch(endpoint, params, fetch, expire_seconds=604800)
                    overview = data.get('overview', '') if data else ''
            except Exception:
                overview = ''
        if not overview:
            overview = addon.getLocalizedString(31115)
        utils.set_video_info_tag(listitem, {'title': label, 'plot': overview})
        url = f"plugin://{addon.getAddonInfo('id')}?action=list_collection_movies&collection_id={coll_id}&collection_name={quote_plus(label)}"
        xbmcplugin.addDirectoryItem(handle, url, listitem, True)
    xbmcplugin.endOfDirectory(handle)

def display_similar_movies(addon, handle, original_title, results):
    """Zobrazí seznam podobných filmů v Kodi UI."""
    category_name = addon.getLocalizedString(30183).replace('%s', str(original_title))
    xbmcplugin.setPluginCategory(handle, category_name)
    xbmcplugin.setContent(handle, 'movies')
    if not results:
        popinfo(addon.getLocalizedString(31116) % original_title, addon.getAddonInfo('name'))
        xbmcplugin.endOfDirectory(handle)
        return
    sorted_results = sorted(results, key=lambda x: x.get('release_date', '0000'), reverse=True)
    for movie in sorted_results:
        movie_id = movie['id']
        title = movie['title']
        year_val = movie.get('release_date', '')[:4]
        plot = movie.get('overview', '')
        poster_path = movie.get('poster_path', '')
        poster = f"https://image.tmdb.org/t/p/w500{poster_path}" if poster_path else ''
        backdrop_path = movie.get('backdrop_path', '')
        fanart = f"https://image.tmdb.org/t/p/original{backdrop_path}" if backdrop_path else poster
        label = f"{title} ({year_val})" if year_val else title
        try: info_year = int(year_val)
        except: info_year = 0
        listitem = xbmcgui.ListItem(label=label)
        if poster:
            listitem.setArt({'thumb': poster, 'poster': poster, 'icon': poster, 'fanart': fanart})
        utils.set_video_info_tag(listitem, {'title': label, 'plot': plot, 'year': info_year, 'mediatype': 'movie'})
        details_url = f"plugin://{addon.getAddonInfo('id')}?action=show_wcs_details&media_type=movie&tmdb_id={movie_id}"
        xbmcplugin.addDirectoryItem(handle, details_url, listitem, False)
    xbmcplugin.endOfDirectory(handle)

# --- Funkce pro zobrazení přidaných položek ---
def display_added_movies(addon, handle):
    xbmcplugin.setPluginCategory(handle, addon.getLocalizedString(31117))
    add_movie_item = xbmcgui.ListItem(label=addon.getLocalizedString(31118))
    add_movie_item.setArt({'icon': 'DefaultAddSource.png'})
    utils.set_video_info_tag(add_movie_item, {'title': addon.getLocalizedString(31118), 'plot': addon.getLocalizedString(31119)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=tmdb_add_movie&new=1&add_to_my_movies=1", add_movie_item, False)

    tmdb_movies = user_data.load_tmdb_movies(addon)
    if tmdb_movies:
        delete_all_item = xbmcgui.ListItem(label=f"[COLOR red]{addon.getLocalizedString(31120)}[/COLOR]")
        delete_all_item.setArt({'icon': 'none.png'})
        utils.set_video_info_tag(delete_all_item, {'title': f"[COLOR red]{addon.getLocalizedString(31120)}[/COLOR]", 'plot': addon.getLocalizedString(31121)})
        xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=tmdb_remove_all_movies", delete_all_item, False)
    ai_item = xbmcgui.ListItem(label=addon.getLocalizedString(31122))
    ai_item.setArt({'icon': 'DefaultMusicSearch.png'})
    utils.set_video_info_tag(ai_item, {'title': addon.getLocalizedString(31122), 'plot': addon.getLocalizedString(31123)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=ai_recommend_movies", ai_item, True)
    if not tmdb_movies:
        popinfo(addon.getLocalizedString(31124), addon.getLocalizedString(31125))
    for idx, movie in enumerate(tmdb_movies):
        label = f"{movie['title']} ({movie.get('year', '')})"
        plot = movie.get('overview', '')
        poster_path = movie.get('poster_path', '')
        poster = f"https://image.tmdb.org/t/p/w500{poster_path}" if poster_path else ''
        backdrop_path = movie.get('backdrop_path', '')
        fanart = f"https://image.tmdb.org/t/p/original{backdrop_path}" if backdrop_path else poster
        
        listitem = xbmcgui.ListItem(label=label)
        if poster:
            listitem.setArt({'thumb': poster, 'poster': poster, 'icon': poster, 'fanart': fanart})
        utils.set_video_info_tag(listitem, {'title': movie['title'], 'plot': plot, 'year': movie.get('year', '')})
        
        # Kontextové menu pro filmy v "Moje filmy"
        from wcs.ui.ContextMenu import create_my_movies_context_menu
        commands = create_my_movies_context_menu(
            addon=addon,
            tmdb_id=movie['id'],
            title=movie['title'],
            year=movie.get('year', ''),
            plot=plot,
            poster=poster,
            idx=idx
        )
        listitem.addContextMenuItems(commands)
        listitem.setProperty('IsPlayable', 'false')
        
        # Podle nastavení určíme, jakou akci provést při kliknutí na film
        default_action = addon.getSetting('default_movie_action')
        xbmc.log(f"[plugin.video.milionar] My Movies - Default movie action setting: '{default_action}' for movie '{movie['title']}'", level=xbmc.LOGINFO)
        
        if default_action == '1':  # 40004 - Přehrát ihned
            # Přehrát ihned - použijeme stejnou akci jako v kontextovém menu
            play_url = f"plugin://{addon.getAddonInfo('id')}?action=play_movie_from_addon&title={quote_plus(movie['title'])}&year={quote_plus(str(movie.get('year', '')))}&plot={quote_plus(plot)}&poster={quote_plus(poster)}"
            xbmc.log(f"[plugin.video.milionar] My Movies - Using PLAY action: {play_url}", level=xbmc.LOGINFO)
            xbmcplugin.addDirectoryItem(handle, play_url, listitem, False)
        else:  # 40003 - Zobrazit detaily (default)
            # Zobrazit detaily (současné chování)
            details_url = f"plugin://{addon.getAddonInfo('id')}?action=show_wcs_details&media_type=movie&tmdb_id={movie['id']}"
            xbmc.log(f"[plugin.video.milionar] My Movies - Using DETAILS action: {details_url}", level=xbmc.LOGINFO)
            xbmcplugin.addDirectoryItem(handle, details_url, listitem, False)
    xbmcplugin.endOfDirectory(handle)

def display_added_series(addon, handle):
    """Zobrazí seznam seriálů přidaných uživatelem."""
    xbmcplugin.setPluginCategory(handle, f"TMDb / {addon.getLocalizedString(30103)} / {addon.getLocalizedString(31034)}")
    add_series_item = xbmcgui.ListItem(label=addon.getLocalizedString(31035))
    add_series_item.setArt({'icon': 'DefaultAddSource.png'})
    utils.set_video_info_tag(add_series_item, {'title': addon.getLocalizedString(31035), 'plot': addon.getLocalizedString(31036)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=tmdb_add_series&new=1&add_to_my_series=1", add_series_item, False)
    tmdb_series = user_data.load_tmdb_series(addon)
    if tmdb_series:
        delete_all_item = xbmcgui.ListItem(label=f"[COLOR red]{addon.getLocalizedString(31037)}[/COLOR]")
        delete_all_item.setArt({'icon': 'none.png'})
        utils.set_video_info_tag(delete_all_item, {'title': f"[COLOR red]{addon.getLocalizedString(31037)}[/COLOR]", 'plot': addon.getLocalizedString(31038)})
        xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=tmdb_remove_all_series", delete_all_item, False)
    ai_item = xbmcgui.ListItem(label=addon.getLocalizedString(31039))
    ai_item.setArt({'icon': 'DefaultMusicSearch.png'})
    utils.set_video_info_tag(ai_item, {'title': addon.getLocalizedString(31039), 'plot': addon.getLocalizedString(31040)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=ai_recommend_series", ai_item, True)
    if not tmdb_series:
        popinfo(addon.getLocalizedString(31041), addon.getLocalizedString(31034))
        xbmcplugin.endOfDirectory(handle)
        return
    for idx, series in enumerate(tmdb_series):
        label = series.get('name', f"{addon.getLocalizedString(30103)} {idx+1}")
        plot = series.get('overview', '') or addon.getLocalizedString(31042)
        poster_path = series.get('poster_path', '')
        poster = f"https://image.tmdb.org/t/p/w500{poster_path}" if poster_path else 'DefaultTVShows.png'
        backdrop_path = series.get('backdrop_path', '')
        fanart = f"https://image.tmdb.org/t/p/original{backdrop_path}" if backdrop_path else poster
        listitem = xbmcgui.ListItem(label=label)
        listitem.setArt({'thumb': poster, 'icon': poster, 'poster': poster, 'fanart': fanart})
        utils.set_video_info_tag(listitem, {'title': label, 'plot': plot, 'year': series.get('year', '')})
        # Kontextové menu pro seriály
        tmdb_id = series['id']
        from wcs.ui.ContextMenu import create_my_series_context_menu
        commands = create_my_series_context_menu(
            addon=addon,
            tmdb_id=tmdb_id,
            name=series.get('name', ''),
            plot=series.get('overview', ''),
            poster=poster,
            idx=idx
        )
        listitem.addContextMenuItems(commands)
        url = f"plugin://{addon.getAddonInfo('id')}?action=tmdb_series_detail&series_id={series['id']}&name={quote_plus(series['name'])}"
        xbmcplugin.addDirectoryItem(handle, url, listitem, True)
    xbmcplugin.endOfDirectory(handle)

def remove_all_tmdb_series(addon):
    dialog = xbmcgui.Dialog()
    if dialog.yesno(addon.getLocalizedString(31044), addon.getLocalizedString(31045)):
        tmdb_series = user_data.load_tmdb_series(addon)
        if not tmdb_series:
            popinfo(addon.getLocalizedString(31046), addon.getLocalizedString(31034))
            return
        user_data.store_tmdb_series(addon, [])
        popinfo(addon.getLocalizedString(31047), addon.getLocalizedString(31034))
        xbmc.executebuiltin('Container.Refresh')
    else:
        popinfo(addon.getLocalizedString(31048), addon.getLocalizedString(31034))

def remove_all_tmdb_movies(addon):
    dialog = xbmcgui.Dialog()
    if dialog.yesno(addon.getLocalizedString(31127), addon.getLocalizedString(31128)):
        tmdb_movies = user_data.load_tmdb_movies(addon)
        if not tmdb_movies:
            popinfo(addon.getLocalizedString(31129), addon.getLocalizedString(31125))
            return
        user_data.store_tmdb_movies(addon, [])
        popinfo(addon.getLocalizedString(31130), addon.getLocalizedString(31125))
        xbmc.executebuiltin('Container.Refresh')
    else:
        popinfo(addon.getLocalizedString(31131), addon.getLocalizedString(31125))

def remove_all_favorite_directors(addon):
    dialog = xbmcgui.Dialog()
    if dialog.yesno(addon.getLocalizedString(31132), addon.getLocalizedString(31133)):
        favorite_directors = user_data.load_favorite_directors(addon)
        if not favorite_directors:
            popinfo(addon.getLocalizedString(31134), addon.getLocalizedString(31136))
            return
        user_data.store_favorite_directors(addon, [])
        popinfo(addon.getLocalizedString(31135), addon.getLocalizedString(31136))
        xbmc.executebuiltin('Container.Refresh')
    else:
        popinfo(addon.getLocalizedString(31131), addon.getLocalizedString(31136))

def remove_all_favorite_writers(addon):
    dialog = xbmcgui.Dialog()
    if dialog.yesno(addon.getLocalizedString(30740), addon.getLocalizedString(30741)):
        favorite_writers = user_data.load_favorite_writers(addon)
        if not favorite_writers:
            popinfo(addon.getLocalizedString(30742), addon.getLocalizedString(30744))
            return
        user_data.store_favorite_writers(addon, [])
        popinfo(addon.getLocalizedString(30743), addon.getLocalizedString(30744))
        xbmc.executebuiltin('Container.Refresh')
    else:
        popinfo(addon.getLocalizedString(30730), addon.getLocalizedString(30744))

def remove_all_favorite_actors(addon):
    dialog = xbmcgui.Dialog()
    if dialog.yesno(addon.getLocalizedString(31137), addon.getLocalizedString(31138)):
        favorite_actors = user_data.load_favorite_actors(addon)
        if not favorite_actors:
            popinfo(addon.getLocalizedString(31139), addon.getLocalizedString(31141))
            return
        user_data.store_favorite_actors(addon, [])
        popinfo(addon.getLocalizedString(31140), addon.getLocalizedString(31141))
        xbmc.executebuiltin('Container.Refresh')
    else:
        popinfo(addon.getLocalizedString(31131), addon.getLocalizedString(31141))

def add_movie_to_list(params, addon):
    """Přidá film do seznamu Moje Filmy (voláno z kontextového menu nebo detailního okna)."""
    tmdb_id = params.get('tmdb_id')
    title = params.get('title')
    add_to_my_movies = params.get('add_to_my_movies')
    if not tmdb_id:
        popinfo(addon.getLocalizedString(31142), addon.getLocalizedString(31125))
        return
    try:
        tmdb_id = int(tmdb_id)
    except ValueError:
        popinfo(addon.getLocalizedString(31143) % tmdb_id, addon.getLocalizedString(31125))
        return
    tmdb_movies = user_data.load_tmdb_movies(addon)
    if any(m['id'] == tmdb_id for m in tmdb_movies):
        title_disp = title or f"ID {tmdb_id}"
        popinfo(addon.getLocalizedString(31144) % title_disp, addon.getLocalizedString(31125))
        return
    from wcs.metadata import TMDbClient as tmdb_handler
    movie_data = tmdb_handler.get_movie_details_for_my_movies(tmdb_id, addon)
    if 'error' in movie_data:
        popinfo(addon.getLocalizedString(31145) % movie_data['error'], addon.getLocalizedString(31125))
        return
    tmdb_movies.insert(0, movie_data)
    user_data.store_tmdb_movies(addon, tmdb_movies)
    popinfo(addon.getLocalizedString(31146) % movie_data['title'], addon.getLocalizedString(31125))
    
    # Refresh pouze pokud NEJSME v hledacích seznamech
    container_path = xbmc.getInfoLabel('Container.FolderPath')
    if not any(search_action in container_path for search_action in ['tmdb_add_movie', 'tmdb_add_series', 'tmdb_universal_search']):
        xbmc.executebuiltin('Container.Refresh')

def add_series_item_to_list(addon, tmdb_id, name=None, add_to_my_series=None):
    try:
        if not tmdb_id:
            popinfo(addon.getLocalizedString(31049), addon.getLocalizedString(31034))
            return False
        try:
            tmdb_id = int(tmdb_id)
        except ValueError:
            popinfo(f"{addon.getLocalizedString(31050)} {tmdb_id}", addon.getLocalizedString(31034))
            return False
        tmdb_series = user_data.load_tmdb_series(addon)
        if any(s['id'] == tmdb_id for s in tmdb_series):
            name_disp = name or f"ID {tmdb_id}"
            popinfo(f"{addon.getLocalizedString(31051)}", addon.getLocalizedString(31034))
            return False
        from wcs.metadata import TMDbClient as tmdb_handler
        api_params = {'api_key': tmdb_handler.get_tmdb_api_key(), 'language': 'cs-CZ'}
        url = f'https://api.themoviedb.org/3/tv/{tmdb_id}'
        import requests
        try:
            response = requests.get(url, params=api_params)
            response.raise_for_status()
            selected_item = response.json()
        except Exception as e:
            popinfo(f"{addon.getLocalizedString(31052)} {e}", addon.getLocalizedString(31034))
            return False
        tmdb_series.insert(0, {
            'id': selected_item['id'],
            'name': selected_item['name'],
            'year': selected_item.get('first_air_date', '')[:4],
            'overview': selected_item.get('overview', ''),
            'poster_path': selected_item.get('poster_path', '')
        })
        user_data.store_tmdb_series(addon, tmdb_series)
        popinfo(addon.getLocalizedString(31053), addon.getLocalizedString(31034))
        
        # Refresh pouze pokud NEJSME v hledacích seznamech
        container_path = xbmc.getInfoLabel('Container.FolderPath')
        if not any(search_action in container_path for search_action in ['tmdb_add_movie', 'tmdb_add_series', 'tmdb_universal_search']):
            xbmc.executebuiltin('Container.Refresh')
        return True
    except Exception as e:
        xbmc.log(f"[plugin.video.milionar] Chyba při přidávání seriálu do Moje seriály: {e}", xbmc.LOGERROR)
        return False

def add_movie_item_to_list(addon, tmdb_id, title=None):
    try:
        params = {'tmdb_id': tmdb_id}
        if title:
            params['title'] = title
        # Kontextové menu nikdy nepředává add_to_my_movies
        add_movie_to_list(params, addon)
        return True
    except Exception as e:
        xbmc.log(f"[plugin.video.milionar] Chyba při přidávání filmu do Moje filmy: {e}", xbmc.LOGERROR)
        return False

def add_director_to_favorites(addon, director_id, director_name=None):
    from wcs.metadata.TMDbClient import add_director_to_favorites as _add
    return _add(addon, director_id, director_name)

def browse_movie_categories(addon, handle):
    """Předá seznam kategorií do UI vrstvy pro zobrazení (filmy)."""
    try:
        categories = {
            'popular': 30110,
            'top_rated': 30111,
            'now_playing': 30112,
            'upcoming': 30113
        }
        display_movie_categories(addon, handle, categories)
    except Exception as e:
        popinfo(addon.getLocalizedString(31147) % str(e), addon.getAddonInfo('name'))
        xbmcplugin.endOfDirectory(handle)

def browse_series_categories(addon, handle):
    """Předá seznam kategorií do UI vrstvy pro zobrazení (seriály)."""
    try:
        categories = {
            'popular': 30110,
            'top_rated': 30111,
            'on_the_air': 30112,
            'airing_today': 30113
        }
        display_series_categories(addon, handle, categories)
    except Exception as e:
        popinfo(addon.getLocalizedString(31148) % str(e), addon.getAddonInfo('name'))
        xbmcplugin.endOfDirectory(handle)

def display_csfd_movies_menu(addon, handle):
    """Zobrazí menu pro ČSFD filmové kategorie."""
    xbmcplugin.setPluginCategory(handle, addon.getLocalizedString(31150))
    
    # 1. ČSFD Nejlepší filmy
    listitem = xbmcgui.ListItem(label=addon.getLocalizedString(31151))
    listitem.setArt({'icon': 'DefaultMovies.png'})
    utils.set_video_info_tag(listitem, {'title': addon.getLocalizedString(31151), 'plot': addon.getLocalizedString(31152)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=csfd_top_movies", listitem, True)
    
    # 2. ČSFD Nejoblíbenější filmy
    listitem = xbmcgui.ListItem(label=addon.getLocalizedString(31153))
    listitem.setArt({'icon': 'DefaultMovies.png'})
    utils.set_video_info_tag(listitem, {'title': addon.getLocalizedString(31153), 'plot': addon.getLocalizedString(31154)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=csfd_favorite_movies", listitem, True)
    
    # 3. ČSFD Nejrozporuplnější filmy
    listitem = xbmcgui.ListItem(label=addon.getLocalizedString(31155))
    listitem.setArt({'icon': 'DefaultMovies.png'})
    utils.set_video_info_tag(listitem, {'title': addon.getLocalizedString(31155), 'plot': addon.getLocalizedString(31156)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=csfd_controversial_movies", listitem, True)
    
    # 4. ČSFD Nejhorší filmy
    listitem = xbmcgui.ListItem(label=addon.getLocalizedString(31157))
    listitem.setArt({'icon': 'DefaultMovies.png'})
    utils.set_video_info_tag(listitem, {'title': addon.getLocalizedString(31157), 'plot': addon.getLocalizedString(31158)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=csfd_worst_movies", listitem, True)
    
    xbmcplugin.endOfDirectory(handle)

def display_csfd_series_menu(addon, handle):
    """Zobrazí menu pro ČSFD seriálové kategorie."""
    xbmcplugin.setPluginCategory(handle, addon.getLocalizedString(31025))
    
    # 1. ČSFD Nejlepší seriály
    listitem = xbmcgui.ListItem(label=addon.getLocalizedString(31026))
    listitem.setArt({'icon': 'DefaultTVShows.png'})
    utils.set_video_info_tag(listitem, {'title': addon.getLocalizedString(31026), 'plot': addon.getLocalizedString(31027)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=csfd_top_series", listitem, True)
    
    # 2. ČSFD Nejoblíbenější seriály
    listitem = xbmcgui.ListItem(label=addon.getLocalizedString(31028))
    listitem.setArt({'icon': 'DefaultTVShows.png'})
    utils.set_video_info_tag(listitem, {'title': addon.getLocalizedString(31028), 'plot': addon.getLocalizedString(31029)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=csfd_favorite_series", listitem, True)
    
    # 3. ČSFD Nejrozporuplnější seriály
    listitem = xbmcgui.ListItem(label=addon.getLocalizedString(31030))
    listitem.setArt({'icon': 'DefaultTVShows.png'})
    utils.set_video_info_tag(listitem, {'title': addon.getLocalizedString(31030), 'plot': addon.getLocalizedString(31031)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=csfd_controversial_series", listitem, True)
    
    # 4. ČSFD Nejhorší seriály
    listitem = xbmcgui.ListItem(label=addon.getLocalizedString(31032))
    listitem.setArt({'icon': 'DefaultTVShows.png'})
    utils.set_video_info_tag(listitem, {'title': addon.getLocalizedString(31032), 'plot': addon.getLocalizedString(31033)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=csfd_worst_series", listitem, True)
    
    xbmcplugin.endOfDirectory(handle)

def browse_movie_genres(params, addon, handle):
    """Získá žánry filmů z TMDb a předá je do UI vrstvy."""
    from wcs.metadata.TMDbClient import fetch_tmdb_list, handle_tmdb_api_error
    try:
        genres = fetch_tmdb_list('genre/movie/list', {}, addon)
        display_movie_genres(addon, handle, genres)
    except Exception as e:
        handle_tmdb_api_error(e, addon, handle)

def browse_series_genres(params, addon, handle):
    """Získá žánry seriálů z TMDb a předá je do UI vrstvy."""
    from wcs.metadata.TMDbClient import fetch_tmdb_list, handle_tmdb_api_error
    try:
        genres = fetch_tmdb_list('genre/tv/list', {}, addon)
        display_series_genres(addon, handle, genres)
    except Exception as e:
        handle_tmdb_api_error(e, addon, handle)

def browse_movie_countries(addon, handle):
    """Zobrazí seznam zemí původu pro filmy."""
    try:
        countries = get_supported_countries(addon)
        display_movie_countries(addon, handle, countries)
    except Exception as e:
        popinfo(addon.getLocalizedString(30784).replace('%s', str(e)), addon.getAddonInfo('name'))
        xbmcplugin.endOfDirectory(handle)

def browse_series_countries(addon, handle):
    """Zobrazí seznam zemí původu pro seriály."""
    try:
        countries = get_supported_countries(addon)
        display_series_countries(addon, handle, countries)
    except Exception as e:
        popinfo(addon.getLocalizedString(30785).replace('%s', str(e)), addon.getAddonInfo('name'))
        xbmcplugin.endOfDirectory(handle)

def get_supported_countries(addon):
    """Vrací univerzální seznam podporovaných zemí pro všechny případy použití."""
    return [
        {'code': 'US', 'name': addon.getLocalizedString(30786)},
        {'code': 'GB', 'name': addon.getLocalizedString(30787)},
        {'code': 'FR', 'name': addon.getLocalizedString(30788)},
        {'code': 'DE', 'name': addon.getLocalizedString(30789)},
        {'code': 'JP', 'name': addon.getLocalizedString(30790)},
        {'code': 'KR', 'name': addon.getLocalizedString(30791)},
        {'code': 'IN', 'name': addon.getLocalizedString(30792)},
        {'code': 'ES', 'name': addon.getLocalizedString(30793)},
        {'code': 'IT', 'name': addon.getLocalizedString(30794)},
        {'code': 'CZ', 'name': addon.getLocalizedString(30795)},
    ]

def combo_select_genres(params, addon, handle):
    """Zobrazí první krok kombinovaného výběru: výběr žánru (filmy/seriály)."""
    media_type = params.get('media_type')
    if not media_type:
        popinfo(addon.getLocalizedString(30796), addon.getAddonInfo('name'))
        xbmcplugin.endOfDirectory(handle)
        return
    try:
        from wcs.metadata import TMDbClient as tmdb_handler
        genres = tmdb_handler.get_genres('tv' if media_type == 'tv' else 'movie', addon)
        media_label = addon.getLocalizedString(30103) if media_type == 'tv' else addon.getLocalizedString(30102)
        xbmcplugin.setPluginCategory(handle, f'TMDb / {media_label} / Výběr žánru')
        if not genres:
            popinfo(addon.getLocalizedString(30797).replace('%s', str(media_label)), addon.getAddonInfo('name'))
        for genre in genres:
            genre_id = genre['id']
            genre_name = genre['name']
            listitem = xbmcgui.ListItem(label=genre_name)
            listitem.setArt({'icon': 'DefaultGenre.png'})
            utils.set_video_info_tag(listitem, {'title': genre_name, 'plot': addon.getLocalizedString(30798)})
            # Odkaz na další krok: výběr země
            next_url = f"plugin://{addon.getAddonInfo('id')}?action=tmdb_combo_countries&media_type={media_type}&genre_id={genre_id}&genre_name={quote_plus(genre_name)}"
            xbmcplugin.addDirectoryItem(handle, next_url, listitem, True)
    except Exception as e:
        from wcs.metadata.TMDbClient import handle_tmdb_api_error
        handle_tmdb_api_error(e, addon, handle)
        return
    xbmcplugin.endOfDirectory(handle)

def combo_select_countries(params, addon, handle):
    """Zobrazí druhý krok kombinovaného výběru: výběr země."""
    media_type = params.get('media_type')
    genre_id = params.get('genre_id')
    genre_name = params.get('genre_name')
    
    if not all([media_type, genre_id, genre_name]):
        popinfo(addon.getLocalizedString(30799), addon.getAddonInfo('name'))
        xbmcplugin.endOfDirectory(handle)
        return
    
    media_label = addon.getLocalizedString(30103) if media_type == 'tv' else addon.getLocalizedString(30102)
    xbmcplugin.setPluginCategory(handle, f'TMDb / {media_label} / {addon.getLocalizedString(30114)} (2/3: {addon.getLocalizedString(30105)}) - {genre_name}')
    
    try:
        countries = get_supported_countries(addon)
        for country in countries:
            listitem = xbmcgui.ListItem(label=country['name'])
            listitem.setArt({'icon': 'DefaultCountry.png'})
            utils.set_video_info_tag(listitem, {'title': country['name'], 'plot': addon.getLocalizedString(30800)})
            # Odkaz na další krok: výběr roku
            next_url = f"plugin://{addon.getAddonInfo('id')}?action=tmdb_combo_years&media_type={media_type}&genre_id={genre_id}&genre_name={quote_plus(genre_name)}&country_code={country['code']}&country_name={quote_plus(country['name'])}"
            xbmcplugin.addDirectoryItem(handle, next_url, listitem, True)
    except Exception as e:
        popinfo(addon.getLocalizedString(30801).replace('%s', str(e)), addon.getAddonInfo('name'))
        import traceback
        traceback.print_exc()
    xbmcplugin.endOfDirectory(handle)

def combo_select_years(params, addon, handle):
    """Zobrazí třetí krok kombinovaného výběru: výběr roku."""
    media_type = params.get('media_type')
    genre_id = params.get('genre_id')
    genre_name = params.get('genre_name')
    country_code = params.get('country_code')
    country_name = params.get('country_name')
    
    if not all([media_type, genre_id, genre_name, country_code, country_name]):
        popinfo(addon.getLocalizedString(30802), addon.getAddonInfo('name'))
        xbmcplugin.endOfDirectory(handle)
        return
    
    media_label = addon.getLocalizedString(30103) if media_type == 'tv' else addon.getLocalizedString(30102)
    xbmcplugin.setPluginCategory(handle, f'TMDb / {media_label} / {addon.getLocalizedString(30114)} (3/3: {addon.getLocalizedString(30106)}) - {genre_name} / {country_name}')
    
    try:
        current_year = datetime.datetime.now().year
        today_str = datetime.datetime.now().strftime('%Y-%m-%d')
        # Nejprve položka "Vše"
        listitem = xbmcgui.ListItem(label=addon.getLocalizedString(30803))
        listitem.setArt({'icon': 'DefaultYear.png'})
        utils.set_video_info_tag(listitem, {'title': addon.getLocalizedString(30803), 'plot': addon.getLocalizedString(30804)})
        if media_type == 'tv':
            next_url = (
                f"plugin://{addon.getAddonInfo('id')}?action=tmdb_combo_results"
                f"&media_type={media_type}"
                f"&genre_id={genre_id}"
                f"&country_code={country_code}"
                f"&genre_name={quote_plus(genre_name)}"
                f"&country_name={quote_plus(country_name)}"
                f"&first_air_date.lte={today_str}"
                f"&first_air_date.gte=1950-01-01"
            )
        else:
            next_url = (
                f"plugin://{addon.getAddonInfo('id')}?action=tmdb_combo_results"
                f"&media_type={media_type}"
                f"&genre_id={genre_id}"
                f"&country_code={country_code}"
                f"&genre_name={quote_plus(genre_name)}"
                f"&country_name={quote_plus(country_name)}"
                f"&primary_release_date.lte={today_str}"
                f"&primary_release_date.gte=1950-01-01"
            )
        xbmcplugin.addDirectoryItem(handle, next_url, listitem, True)
        # Pak jednotlivé roky od aktuálního směrem dolů
        for y in range(current_year, 1949, -1):
            listitem = xbmcgui.ListItem(label=str(y))
            listitem.setArt({'icon': 'DefaultYear.png'})
            utils.set_video_info_tag(listitem, {'title': str(y), 'plot': addon.getLocalizedString(35092)})
            next_url = f"plugin://{addon.getAddonInfo('id')}?action=tmdb_combo_results&media_type={media_type}&genre_id={genre_id}&country_code={country_code}&year={y}&genre_name={quote_plus(genre_name)}&country_name={quote_plus(country_name)}"
            xbmcplugin.addDirectoryItem(handle, next_url, listitem, True)
    except Exception as e:
        popup_message = f"{addon.getLocalizedString(35090)} '{e}'"
        popinfo(popup_message, addon.getAddonInfo('name'))
        import traceback
        traceback.print_exc()
    xbmcplugin.endOfDirectory(handle)

def remove_added_movie(params, addon):
    idx = params.get('idx')
    if idx is None:
        popinfo(addon.getLocalizedString(30830), addon.getLocalizedString(30159))
        return False
    try:
        idx = int(idx)
        tmdb_movies = user_data.load_tmdb_movies(addon)
        if not (0 <= idx < len(tmdb_movies)):
            popinfo(addon.getLocalizedString(30831), addon.getLocalizedString(30159))
            return False
        removed = tmdb_movies[idx]
        movie_title = removed.get('title', addon.getLocalizedString(30703))
        movie_year = removed.get('year', '')
        
        # Potvrzovací dialog
        dialog = xbmcgui.Dialog()
        if not dialog.yesno(addon.getLocalizedString(30714), addon.getLocalizedString(30870).format(movie_title=movie_title)):
            popinfo(addon.getLocalizedString(30730), addon.getLocalizedString(30159))
            return False
        
        # Smazání .strm souboru z knihovny (pokud je zapnuto)
        library_deleted = False
        if addon.getSettingBool('library_auto_update'):
            movies_folder = addon.getSetting('library_movies_folder')
            if movies_folder and os.path.isdir(movies_folder):
                safe_part = utils.sanitize_filename(f"{movie_title} ({movie_year})")
                strm_filename = f"{safe_part}.strm"
                strm_filepath = os.path.join(movies_folder, strm_filename)
                if os.path.exists(strm_filepath):
                    try:
                        os.remove(strm_filepath)
                        popinfo(addon.getLocalizedString(30164).replace('%s', str(movie_title)), addon.getLocalizedString(30159))
                        library_deleted = True
                    except Exception as e:
                        popinfo(addon.getLocalizedString(30165).replace('%s', str(e)), addon.getLocalizedString(30159))
        # Mazání filmu ze seznamu
        if user_data.remove_tmdb_movie_by_index(addon, idx):
            popup_message = f"{addon.getLocalizedString(30161)} '{movie_title}' {addon.getLocalizedString(30163)}"
            popinfo(popup_message, addon.getLocalizedString(30159), sound=True)
            xbmc.executebuiltin('Container.Refresh')
            return True
        else:
            popinfo(addon.getLocalizedString(30833), addon.getLocalizedString(30159))
            return False
    except ValueError:
        popinfo(addon.getLocalizedString(30831), addon.getLocalizedString(30159))
        return False
    except Exception as e:
        popinfo(addon.getLocalizedString(30832).format(e=e), addon.getLocalizedString(30159))
        return False

def remove_added_series(params, addon):
    idx = params.get('idx')
    if idx is None:
        popinfo(addon.getLocalizedString(30834), addon.getLocalizedString(30160))
        return False
    try:
        idx = int(idx)
        tmdb_series_list = user_data.load_tmdb_series(addon)
        if not (0 <= idx < len(tmdb_series_list)):
            popinfo(addon.getLocalizedString(30835), addon.getLocalizedString(30160))
            return False
        removed = tmdb_series_list[idx]
        series_name = removed.get('name', addon.getLocalizedString(30703))
        
        # Potvrzovací dialog
        dialog = xbmcgui.Dialog()
        if not dialog.yesno(addon.getLocalizedString(30725), addon.getLocalizedString(30871).format(series_name=series_name)):
            popinfo(addon.getLocalizedString(30730), addon.getLocalizedString(30160))
            return False
        
        # Smazání složky seriálu z knihovny (pokud je zapnuto)
        library_deleted = False
        if addon.getSettingBool('library_auto_update'):
            series_folder_base = addon.getSetting('library_series_folder')
            if series_folder_base and os.path.isdir(series_folder_base):
                sanitized_series_name = utils.sanitize_filename(series_name)
                series_path = os.path.join(series_folder_base, sanitized_series_name)
                if os.path.exists(series_path):
                    try:
                        import shutil
                        shutil.rmtree(series_path)
                        popinfo(addon.getLocalizedString(30166).replace('%s', str(series_name)), addon.getLocalizedString(30160))
                        library_deleted = True
                    except Exception as e:
                        popinfo(addon.getLocalizedString(30167).replace('%s', str(e)), addon.getLocalizedString(30160))
        # Mazání seriálu ze seznamu
        if user_data.remove_tmdb_series_by_index(addon, idx):
            popup_message = f"{addon.getLocalizedString(30162)} '{series_name}' {addon.getLocalizedString(30163)}"
            popinfo(popup_message, addon.getLocalizedString(30160), sound=True)
            xbmc.executebuiltin('Container.Refresh')
            return True
        else:
            popinfo(addon.getLocalizedString(30837), addon.getLocalizedString(30160))
            return False
    except ValueError:
        popinfo(addon.getLocalizedString(31070), addon.getLocalizedString(30160))
        return False
    except Exception as e:
        popinfo(addon.getLocalizedString(31071).format(e=e), addon.getLocalizedString(30160))
        xbmc.executebuiltin('Container.Refresh')
        return False

def remove_favorite_actor(params, addon):
    idx = params.get('idx')
    if idx is None:
        popinfo(addon.getLocalizedString(30838), addon.getLocalizedString(30624), xbmcgui.NOTIFICATION_WARNING)
        return False
    try:
        idx = int(idx)
        favorite_actors = user_data.load_favorite_actors(addon)
        if 0 <= idx < len(favorite_actors):
            actor_name = favorite_actors[idx].get('name', addon.getLocalizedString(30839))
            
            # Potvrzovací dialog
            dialog = xbmcgui.Dialog()
            if not dialog.yesno(addon.getLocalizedString(30650), addon.getLocalizedString(31072).format(actor_name=actor_name)):
                popinfo(addon.getLocalizedString(31073), addon.getLocalizedString(30624))
                return False
            
            if user_data.remove_favorite_actor_by_index(addon, idx):
                popup_message = f"{addon.getLocalizedString(30169)} '{actor_name}' {addon.getLocalizedString(30170)}"
                popinfo(popup_message, addon.getLocalizedString(30624), sound=True)
                xbmc.executebuiltin('Container.Refresh')
                return True
            else:
                popinfo(addon.getLocalizedString(30841), addon.getLocalizedString(30624))
        else:
            popinfo(addon.getLocalizedString(30842), addon.getLocalizedString(30624), xbmcgui.NOTIFICATION_WARNING)
    except ValueError:
        popinfo(addon.getLocalizedString(30842), addon.getLocalizedString(30624), xbmcgui.NOTIFICATION_WARNING)
    return False

def remove_favorite_director(params, addon):
    idx = params.get('idx')
    if idx is None:
        popinfo(addon.getLocalizedString(30843), addon.getLocalizedString(30626), xbmcgui.NOTIFICATION_WARNING)
        return False
    try:
        idx = int(idx)
        favorite_directors = user_data.load_favorite_directors(addon)
        if 0 <= idx < len(favorite_directors):
            director_name = favorite_directors[idx].get('name', addon.getLocalizedString(30844))
            
            # Potvrzovací dialog
            dialog = xbmcgui.Dialog()
            if not dialog.yesno(addon.getLocalizedString(30658), addon.getLocalizedString(31074).format(director_name=director_name)):
                popinfo(addon.getLocalizedString(31075), addon.getLocalizedString(30626))
                return False
            
            if user_data.remove_favorite_director_by_index(addon, idx):
                popup_message = f"{addon.getLocalizedString(30171)} '{director_name}' {addon.getLocalizedString(30172)}"
                popinfo(popup_message, addon.getLocalizedString(30626), xbmcgui.NOTIFICATION_INFO)
                xbmc.executebuiltin('Container.Refresh')
                return True
            else:
                popinfo(addon.getLocalizedString(30846), addon.getLocalizedString(30626), xbmcgui.NOTIFICATION_WARNING)
        else:
            popinfo(addon.getLocalizedString(30847), addon.getLocalizedString(30626), xbmcgui.NOTIFICATION_WARNING)
    except ValueError:
        popinfo(addon.getLocalizedString(30847), addon.getLocalizedString(30626), xbmcgui.NOTIFICATION_WARNING)
    return False

def remove_favorite_writer(params, addon):
    idx = params.get('idx')
    if idx is None:
        popinfo(addon.getLocalizedString(30848), addon.getLocalizedString(30628), xbmcgui.NOTIFICATION_WARNING)
        return False
    try:
        idx = int(idx)
        favorite_writers = user_data.load_favorite_writers(addon)
        if 0 <= idx < len(favorite_writers):
            writer_name = favorite_writers[idx].get('name', addon.getLocalizedString(30849))
            # Potvrzovací dialog
            dialog = xbmcgui.Dialog()
            if not dialog.yesno(addon.getLocalizedString(30666), addon.getLocalizedString(31076).format(writer_name=writer_name)):
                popinfo(addon.getLocalizedString(31077), addon.getLocalizedString(30628))
                return False
            if user_data.remove_favorite_writer_by_index(addon, idx):
                popup_message = f"{addon.getLocalizedString(30173)} '{writer_name}' {addon.getLocalizedString(30174)}"
                popinfo(popup_message, addon.getLocalizedString(30628), xbmcgui.NOTIFICATION_INFO)
                xbmc.executebuiltin('Container.Refresh')
                return True
            else:
                popinfo(addon.getLocalizedString(30851), addon.getLocalizedString(30628), xbmcgui.NOTIFICATION_WARNING)
        else:
            popinfo(addon.getLocalizedString(30852), addon.getLocalizedString(30628), xbmcgui.NOTIFICATION_WARNING)
    except ValueError:
        popinfo(addon.getLocalizedString(30852), addon.getLocalizedString(30628), xbmcgui.NOTIFICATION_WARNING)
    return False

def add_movie(params, addon, handle):
    import xbmc
    xbmc.log(f"DEBUG: add_movie called, params={params}, handle={handle}", xbmc.LOGINFO)
    if handle is None:
        xbmc.log("ERROR: add_movie - handle is None!", xbmc.LOGERROR)
        xbmcgui.Dialog().notification(addon.getLocalizedString(31078), addon.getLocalizedString(31079), xbmcgui.NOTIFICATION_ERROR)
        return
    import xbmcgui, xbmcplugin, xbmcaddon
    from wcs import user_data
    from wcs.metadata.TMDbClient import fetch_tmdb_items
    from wcs.ui.ContextMenu import create_movie_context_menu
    from urllib.parse import quote_plus
    import os
    
    profile_path = xbmcaddon.Addon().getAddonInfo('profile')
    search_history_file = 'search_history_tmdb.json'
    max_history = 15

    # Smazání historie
    if params.get('clear_history'):
        confirm = xbmcgui.Dialog().yesno(
            addon.getLocalizedString(31060), 
            addon.getLocalizedString(30865)
        )
        if confirm:
            user_data.clear_search_history(profile_path, search_history_file)
            xbmc.executebuiltin(f'Container.Refresh')
        return

    history = user_data.load_search_history(profile_path, search_history_file)

    items = []
    new_search_item = xbmcgui.ListItem(label=f'[B]{addon.getLocalizedString(30861)}[/B]')
    new_search_item.setArt({'icon': 'DefaultAddonsSearch.png'})
    utils.set_video_info_tag(new_search_item, {
        'title': f'[B]{addon.getLocalizedString(30861)}[/B]', 
        'plot': addon.getLocalizedString(30864)
    })
    url = f"plugin://{addon.getAddonInfo('id')}?action=tmdb_add_movie&new=1"
    if params.get('add_to_my_movies'):
        url += "&add_to_my_movies=1"
    items.append((url, new_search_item, True))
    # Přidám položku Smazat historii pouze pokud existuje historie
    if history:
        clear_item = xbmcgui.ListItem(label=f'[COLOR red]{addon.getLocalizedString(30862)}[/COLOR]')
        clear_item.setArt({'icon': 'none.png'})
        utils.set_video_info_tag(clear_item, {
            'title': f'[COLOR red]{addon.getLocalizedString(30862)}[/COLOR]', 
            'plot': addon.getLocalizedString(30866)
        })
        url_clear = f"plugin://{addon.getAddonInfo('id')}?action=tmdb_add_movie&clear_history=1"
        if params.get('add_to_my_movies'):
            url_clear += "&add_to_my_movies=1"
        items.append((url_clear, clear_item, False))
    for q in history:
        hist_item = xbmcgui.ListItem(label=q)
        hist_item.setArt({'icon': 'DefaultSearch.png'})
        utils.set_video_info_tag(hist_item, {
            'title': q, 
            'plot': addon.getLocalizedString(30867)
        })
        url = f"plugin://{addon.getAddonInfo('id')}?action=tmdb_add_movie&query={quote_plus(q)}"
        if params.get('add_to_my_movies'):
            url += "&add_to_my_movies=1"
        items.append((url, hist_item, True))
    if not params.get('query') and not params.get('new'):
        xbmcplugin.setPluginCategory(handle, addon.getLocalizedString(30857))
        for url, li, isFolder in items:
            xbmcplugin.addDirectoryItem(handle, url, li, isFolder)
        xbmcplugin.endOfDirectory(handle)
        return
    if params.get('new'):
        search_query = xbmcgui.Dialog().input(addon.getLocalizedString(30152), type=xbmcgui.INPUT_ALPHANUM)
        if not search_query:
            return
        user_data.store_search_history(search_query, profile_path, search_history_file, max_history)
    else:
        search_query = params.get('query')
    try:
        from wcs.metadata.TMDbClient import get_tmdb_api_key, handle_tmdb_api_error
        import requests
        url = f'https://api.themoviedb.org/3/search/movie?api_key={get_tmdb_api_key()}&language=cs-CZ&query={quote_plus(search_query)}'
        response = requests.get(url)
        response.raise_for_status()
        results = response.json().get('results', [])
    except Exception as e:
        handle_tmdb_api_error(e, addon, handle)
        return
    # --- MODÁLNÍ DIALOG + PŘIDÁNÍ DO MOJE FILMY ---
    if params.get('add_to_my_movies'):
        if not results:
            xbmcgui.Dialog().notification(addon.getLocalizedString(30153), search_query, xbmcgui.NOTIFICATION_INFO)
            return
        choices = [f"{item['title']} ({item.get('release_date', '')[:4]})" for item in results]
        selected_index = xbmcgui.Dialog().select(addon.getLocalizedString(30154), choices)
        if selected_index >= 0:
            selected_item = results[selected_index]
            from wcs.metadata import TMDbClient as tmdb_handler
            params_add = {'tmdb_id': selected_item['id'], 'title': selected_item['title']}
            if params.get('add_to_my_movies'):
                params_add['add_to_my_movies'] = True
            if params.get('from_my_list'):
                params_add['from_my_list'] = True
            tmdb_handler.add_movie_to_list(params_add, addon)
        return
    # --- KLASICKÝ ITEMLIST ---
    xbmcplugin.setPluginCategory(handle, f'{addon.getLocalizedString(31063)}: {search_query}')
    xbmcplugin.setContent(handle, 'movies')
    if not results:
        xbmcgui.Dialog().notification(addon.getLocalizedString(30153), search_query, xbmcgui.NOTIFICATION_INFO)
        xbmcplugin.endOfDirectory(handle)
        return
    for movie in results:
        movie_id = movie['id']
        title = movie['title']
        year_val = movie.get('release_date', '')[:4]
        plot = movie.get('overview', '')
        poster_path = movie.get('poster_path', '')
        poster = f"https://image.tmdb.org/t/p/w500{poster_path}" if poster_path else ''
        backdrop_path = movie.get('backdrop_path', '')
        fanart = f"https://image.tmdb.org/t/p/original{backdrop_path}" if backdrop_path else poster
        label = f"{title} ({year_val})" if year_val else title
        try:
            info_year = int(year_val)
        except:
            info_year = 0
        listitem = xbmcgui.ListItem(label=label)
        if poster:
            listitem.setArt({'thumb': poster, 'poster': poster, 'icon': poster, 'fanart': fanart})
        utils.set_video_info_tag(listitem, {'title': label, 'plot': plot, 'year': info_year})
        commands = create_movie_context_menu(
            addon=addon,
            tmdb_id=movie_id,
            title=title,
            year=year_val,
            plot=plot,
            poster=poster,
            original_title=title
        )
        listitem.addContextMenuItems(commands)
        details_url = f"plugin://{addon.getAddonInfo('id')}?action=show_wcs_details&media_type=movie&tmdb_id={movie_id}"
        xbmcplugin.addDirectoryItem(handle, details_url, listitem, False)
    xbmcplugin.endOfDirectory(handle)

def add_series(params, addon, handle):
    import xbmc
    xbmc.log(f"[DEBUG] add_series called, params={params}, handle={handle}", xbmc.LOGINFO)
    import xbmcgui, xbmcplugin, xbmcaddon
    from wcs import user_data
    from urllib.parse import quote_plus
    import os
    
    profile_path = xbmcaddon.Addon().getAddonInfo('profile')
    search_history_file = 'search_history_tv.json'
    max_history = 15

    # Smazání historie
    if params.get('clear_history'):
        confirm = xbmcgui.Dialog().yesno(
            addon.getLocalizedString(31060), 
            addon.getLocalizedString(31061)
        )
        if confirm:
            user_data.clear_search_history(profile_path, search_history_file)
            xbmc.executebuiltin(f'Container.Refresh')
        return

    history = user_data.load_search_history(profile_path, search_history_file)

    items = []
    new_search_item = xbmcgui.ListItem(label=f'[B]{addon.getLocalizedString(31055)}[/B]')
    new_search_item.setArt({'icon': 'DefaultAddonsSearch.png'})
    utils.set_video_info_tag(new_search_item, {'title': f'[B]{addon.getLocalizedString(31055)}[/B]', 'plot': addon.getLocalizedString(31056)})
    url = f"plugin://{addon.getAddonInfo('id')}?action=tmdb_add_series&new=1"
    if params.get('add_to_my_series'):
        url += "&add_to_my_series=1"
    items.append((url, new_search_item, True))
    if history:
        clear_item = xbmcgui.ListItem(label=f'[COLOR red]{addon.getLocalizedString(31057)}[/COLOR]')
        clear_item.setArt({'icon': 'none.png'})
        utils.set_video_info_tag(clear_item, {'title': f'[COLOR red]{addon.getLocalizedString(31057)}[/COLOR]', 'plot': addon.getLocalizedString(31058)})
        url_clear = f"plugin://{addon.getAddonInfo('id')}?action=tmdb_add_series&clear_history=1"
        if params.get('add_to_my_series'):
            url_clear += "&add_to_my_series=1"
        items.append((url_clear, clear_item, False))
    for q in history:
        hist_item = xbmcgui.ListItem(label=q)
        hist_item.setArt({'icon': 'DefaultSearch.png'})
        utils.set_video_info_tag(hist_item, {'title': q, 'plot': addon.getLocalizedString(31059)})
        url = f"plugin://{addon.getAddonInfo('id')}?action=tmdb_add_series&query={quote_plus(q)}"
        if params.get('add_to_my_series'):
            url += "&add_to_my_series=1"
        items.append((url, hist_item, True))
    if not params.get('query') and not params.get('new'):
        xbmcplugin.setPluginCategory(handle, addon.getLocalizedString(31054))
        for url, li, isFolder in items:
            xbmcplugin.addDirectoryItem(handle, url, li, isFolder)
        xbmcplugin.endOfDirectory(handle)
        return
    if params.get('new'):
        search_query = xbmcgui.Dialog().input(addon.getLocalizedString(31062), type=xbmcgui.INPUT_ALPHANUM)
        if not search_query:
            return
        user_data.store_search_history(search_query, profile_path, search_history_file, max_history)
    else:
        search_query = params.get('query')
    try:
        from wcs.metadata.TMDbClient import get_tmdb_api_key, handle_tmdb_api_error
        import requests
        url = f'https://api.themoviedb.org/3/search/tv?api_key={get_tmdb_api_key()}&language=cs-CZ&query={quote_plus(search_query)}'
        response = requests.get(url)
        response.raise_for_status()
        results = response.json().get('results', [])
        if not results:
            popinfo(addon.getLocalizedString(30148), addon.getLocalizedString(31034)) # ID 30148: Nenalezen žádný seriál.
            return
        # --- MODÁLNÍ DIALOG + PŘIDÁNÍ DO MOJE SERIÁLY ---
        if params.get('add_to_my_series'):
            choices = [f"{item['name']} ({item.get('first_air_date', '')[:4]})" for item in results]
            selected_index = xbmcgui.Dialog().select(addon.getLocalizedString(31064), choices)
            if selected_index >= 0:
                selected_item = results[selected_index]
                tmdb_series = user_data.load_tmdb_series(addon)
                if not any(s['id'] == selected_item['id'] for s in tmdb_series):
                    tmdb_series.insert(0, {
                        'id': selected_item['id'],
                        'name': selected_item['name'],
                        'year': selected_item.get('first_air_date', '')[:4],
                        'overview': selected_item.get('overview', ''),
                        'poster_path': selected_item.get('poster_path', '')
                    })
                    user_data.store_tmdb_series(addon, tmdb_series)
                    popup_message = f"{addon.getLocalizedString(30103)} '{selected_item['name']}' {addon.getLocalizedString(30157)} '{addon.getLocalizedString(30160)}'"
                    popinfo(popup_message, addon.getLocalizedString(31034))
                else:
                    popinfo(f"{addon.getLocalizedString(30103)} '{selected_item['name']}' {addon.getLocalizedString(30151)}", addon.getLocalizedString(31034)) # ID 30151: už je v seznamu.
                xbmc.executebuiltin('Container.Refresh')
            return
        # --- KLASICKÝ ITEMLIST ---
        xbmcplugin.setPluginCategory(handle, f'{addon.getLocalizedString(31063)}: {search_query}')
        xbmcplugin.setContent(handle, 'tvshows')
        for series in results:
            series_id = series['id']
            name = series.get('name', '')
            year_val = series.get('first_air_date', '')[:4]
            plot = series.get('overview', '')
            poster_path = series.get('poster_path', '')
            poster = f"https://image.tmdb.org/t/p/w500{poster_path}" if poster_path else ''
            label = f"{name} ({year_val})" if year_val else name
            listitem = xbmcgui.ListItem(label=label)
            if poster:
                listitem.setArt({'thumb': poster, 'poster': poster, 'icon': poster, 'fanart': 'DefaultMovies.png'})
            try:
                info_year = int(year_val)
            except:
                info_year = 0
            utils.set_video_info_tag(listitem, {'title': label, 'plot': plot, 'year': info_year})
            from wcs.ui.ContextMenu import create_series_context_menu
            commands = create_series_context_menu(
                addon=addon,
                tmdb_id=series_id,
                name=name,
                year=year_val,
                plot=plot,
                poster=poster,
                is_in_my_series=False,
                original_name=name
            )
            listitem.addContextMenuItems(commands)
            detail_url = f"plugin://{addon.getAddonInfo('id')}?action=tmdb_series_detail&series_id={series_id}&name={quote_plus(name)}"
            xbmcplugin.addDirectoryItem(handle, detail_url, listitem, True)
        xbmcplugin.endOfDirectory(handle)
    except Exception as e:
        handle_tmdb_api_error(e, addon, handle)

def display_movie_list(addon, handle, results, category_name, params, current_page, total_pages):
    """Zobrazí seznam filmů v Kodi UI včetně stránkování a kontextového menu."""
    from wcs.ui.ContextMenu import create_movie_context_menu
    from urllib.parse import quote_plus
    import xbmcgui, xbmcplugin
    xbmcplugin.setPluginCategory(handle, category_name)
    xbmcplugin.setContent(handle, 'movies')
    if not results and current_page == 1:
        popinfo(addon.getLocalizedString(30168), addon.getAddonInfo('name'))
    for movie in results:
        movie_id = movie['id']
        title = movie['title']
        year_val = movie.get('release_date', '')[:4]
        plot = movie.get('overview', '')
        poster_path = movie.get('poster_path', '')
        poster = f"https://image.tmdb.org/t/p/w500{poster_path}" if poster_path else ''
        backdrop_path = movie.get('backdrop_path', '')
        fanart = f"https://image.tmdb.org/t/p/original{backdrop_path}" if backdrop_path else poster
        label = f"{title} ({year_val})" if year_val else title
        try:
            info_year = int(year_val)
        except:
            info_year = 0
        listitem = xbmcgui.ListItem(label=label)
        if poster:
            listitem.setArt({'thumb': poster, 'poster': poster, 'icon': poster, 'fanart': fanart})
        utils.set_video_info_tag(listitem, {'title': label, 'plot': plot, 'year': info_year})
        commands = create_movie_context_menu(
            addon=addon,
            tmdb_id=movie_id,
            title=title,
            year=year_val,
            plot=plot,
            poster=poster,
            original_title=title
        )
        listitem.addContextMenuItems(commands)
        # Podle nastavení určíme, jakou akci provést při kliknutí na film
        default_action = addon.getSetting('default_movie_action')
        xbmc.log(f"[plugin.video.milionar] Default movie action setting: '{default_action}' for movie '{title}'", level=xbmc.LOGINFO)
        
        if default_action == '1':  # 40004 - Přehrát ihned
            # Přehrát ihned - použijeme stejnou akci jako v kontextovém menu
            play_url = f"plugin://{addon.getAddonInfo('id')}?action=play_movie_from_addon&title={quote_plus(title)}&year={quote_plus(year_val)}&plot={quote_plus(plot)}&poster={quote_plus(poster)}"
            xbmc.log(f"[plugin.video.milionar] Using PLAY action: {play_url}", level=xbmc.LOGINFO)
            xbmcplugin.addDirectoryItem(handle, play_url, listitem, False)
        else:  # 40003 - Zobrazit detaily (default)
            # Zobrazit detaily (současné chování)
            details_url = f"plugin://{addon.getAddonInfo('id')}?action=show_wcs_details&media_type=movie&tmdb_id={movie_id}"
            xbmc.log(f"[plugin.video.milionar] Using DETAILS action: {details_url}", level=xbmc.LOGINFO)
            xbmcplugin.addDirectoryItem(handle, details_url, listitem, False)
    # Přidání položky "Další stránka"
    if current_page < total_pages:
        next_page_params = params.copy()
        next_page_params['page'] = str(current_page + 1)
        next_url = f"plugin://{addon.getAddonInfo('id')}?action=tmdb_list_movies"
        for key, value in next_page_params.items():
            if key != 'action':
                next_url += f"&{key}={quote_plus(str(value))}"
        listitem = xbmcgui.ListItem(label=f"{addon.getLocalizedString(30169)} ({current_page + 1}/{total_pages})")
        icon_path = 'DefaultFolderNext.png'
        listitem.setArt({'thumb': icon_path, 'icon': icon_path})
        xbmcplugin.addDirectoryItem(handle, next_url, listitem, True)
    xbmcplugin.endOfDirectory(handle)

def display_series_list(addon, handle, results, category_name, params, current_page, total_pages):
    """Zobrazí seznam seriálů v Kodi UI včetně stránkování a kontextového menu."""
    from wcs.ui.ContextMenu import create_series_context_menu
    from urllib.parse import quote_plus
    import xbmcgui, xbmcplugin
    xbmcplugin.setPluginCategory(handle, category_name)
    xbmcplugin.setContent(handle, 'tvshows')
    try:
        if not results and current_page == 1:
            popinfo(addon.getLocalizedString(30175), addon.getAddonInfo('name'))
        for series in results:
            series_id = series['id']
            name = series.get('name', '')
            year_val = series.get('first_air_date', '')[:4]
            plot = series.get('overview', '')
            poster_path = series.get('poster_path', '')
            poster = f"https://image.tmdb.org/t/p/w500{poster_path}" if poster_path else ''
            label = f"{name} ({year_val})" if year_val else name
            listitem = xbmcgui.ListItem(label=label)
            if poster:
                listitem.setArt({'thumb': poster, 'poster': poster, 'icon': poster, 'fanart': 'DefaultMovies.png'})
            try:
                info_year = int(year_val)
            except:
                info_year = 0
            utils.set_video_info_tag(listitem, {'title': label, 'plot': plot, 'year': info_year})
            commands = create_series_context_menu(
                addon=addon,
                tmdb_id=series_id,
                name=name,
                year=year_val,
                plot=plot,
                poster=poster,
                is_in_my_series=False,
                original_name=name
            )
            listitem.addContextMenuItems(commands)
            detail_url = f"plugin://{addon.getAddonInfo('id')}?action=tmdb_series_detail&series_id={series_id}&name={quote_plus(name)}"
            xbmcplugin.addDirectoryItem(handle, detail_url, listitem, True)
        if current_page < total_pages:
            next_page_params = params.copy()
            next_page_params['page'] = str(current_page + 1)
            next_url = f"plugin://{addon.getAddonInfo('id')}?action=tmdb_list_series"
            for key, value in next_page_params.items():
                if key != 'action':
                    next_url += f"&{key}={quote_plus(str(value))}"
            listitem = xbmcgui.ListItem(label=f"{addon.getLocalizedString(30169)} ({current_page + 1}/{total_pages})")
            icon_path = 'DefaultFolderNext.png'
            listitem.setArt({'thumb': icon_path, 'icon': icon_path})
            xbmcplugin.addDirectoryItem(handle, next_url, listitem, True)
        xbmcplugin.endOfDirectory(handle)
    except Exception as e:
        import xbmc, traceback
        xbmc.log(f"[WCS] Chyba v display_series_list: {e}\n{traceback.format_exc()}", xbmc.LOGERROR)
        popup_message = f"{addon.getLocalizedString(35091)} '{e}'"
        popinfo(popup_message, addon.getAddonInfo('name'))
        xbmcplugin.endOfDirectory(handle)

# Funkce display_my_library byla nahrazena funkcí display_my_added_items

def remove_all_my_items(addon):
    """Smazat všechny filmy a seriály z Moje přidané."""
    dialog = xbmcgui.Dialog()
    if dialog.yesno(addon.getLocalizedString(32113), addon.getLocalizedString(32112)):
        tmdb_movies = user_data.load_tmdb_movies(addon)
        tmdb_series = user_data.load_tmdb_series(addon)
        if not tmdb_movies and not tmdb_series:
            popinfo(addon.getLocalizedString(30190), addon.getLocalizedString(30621))
            return
        user_data.store_tmdb_movies(addon, [])
        user_data.store_tmdb_series(addon, [])
        popinfo(addon.getLocalizedString(35080), addon.getLocalizedString(30621))
        xbmc.executebuiltin('Container.Refresh')
    else:
        popinfo(addon.getLocalizedString(30730), addon.getLocalizedString(30621))

# display_my_library byla nahrazena display_my_added_items

def universal_search(params, addon, handle):
    """Universální vyhledávání filmů i seriálů najednou v TMDb."""
    import xbmc
    import xbmcgui, xbmcplugin, xbmcaddon
    from wcs import user_data
    from urllib.parse import quote_plus
    import os
    import requests
    from wcs.metadata.TMDbClient import get_tmdb_api_key, handle_tmdb_api_error
    from wcs.ui.ContextMenu import create_movie_context_menu, create_series_context_menu
    
    profile_path = xbmcaddon.Addon().getAddonInfo('profile')
    search_history_file = 'search_history_universal.json'
    max_history = 15

    # Smazání historie
    if params.get('clear_history'):
        confirm = xbmcgui.Dialog().yesno(
            addon.getLocalizedString(30862), 
            addon.getLocalizedString(30865)
        )
        if confirm:
            user_data.clear_search_history(profile_path, search_history_file)
            xbmc.executebuiltin(f'Container.Refresh')
        return

    history = user_data.load_search_history(profile_path, search_history_file)

    items = []
    new_search_item = xbmcgui.ListItem(label=f'[B]{addon.getLocalizedString(30861)}[/B]')
    new_search_item.setArt({'icon': 'DefaultAddonsSearch.png'})
    utils.set_video_info_tag(new_search_item, {
        'title': f'[B]{addon.getLocalizedString(30861)}[/B]', 
        'plot': addon.getLocalizedString(30864)
    })
    url = f"plugin://{addon.getAddonInfo('id')}?action=tmdb_universal_search&new=1"
    items.append((url, new_search_item, True))
    
    # NOVÉ: Manuální vyhledávání na Webshare
    manual_item = xbmcgui.ListItem(label="Manuální vyhledání na webshare")
    manual_item.setArt({'icon': 'DefaultAddonsSearch.png'})
    utils.set_video_info_tag(manual_item, {'title': "Manuální vyhledání na webshare", 'plot': "Vyhledejte soubory přímo na Webshare bez metadat."})
    url_manual = f"plugin://{addon.getAddonInfo('id')}?action=manual_webshare_search"
    items.append((url_manual, manual_item, False))
    
    # Přidám položku Smazat historii pouze pokud existuje historie
    if history:
        clear_item = xbmcgui.ListItem(label=f'[COLOR red]{addon.getLocalizedString(30862)}[/COLOR]')
        clear_item.setArt({'icon': 'none.png'})
        utils.set_video_info_tag(clear_item, {
            'title': f'[COLOR red]{addon.getLocalizedString(30862)}[/COLOR]', 
            'plot': addon.getLocalizedString(30866)
        })
        url_clear = f"plugin://{addon.getAddonInfo('id')}?action=tmdb_universal_search&clear_history=1"
        items.append((url_clear, clear_item, False))
    
    for q in history:
        hist_item = xbmcgui.ListItem(label=q)
        hist_item.setArt({'icon': 'DefaultSearch.png'})
        utils.set_video_info_tag(hist_item, {
            'title': q, 
            'plot': addon.getLocalizedString(30867)
        })
        url = f"plugin://{addon.getAddonInfo('id')}?action=search_history_select&query={quote_plus(q)}"
        items.append((url, hist_item, True))
    
    # Zobrazení historie, pokud není zadán dotaz ani požádáno o nové hledání
    if not params.get('query') and not params.get('new'):
        xbmcplugin.setPluginCategory(handle, addon.getLocalizedString(30868))
        for url, li, isFolder in items:
            xbmcplugin.addDirectoryItem(handle, url, li, isFolder)
        xbmcplugin.endOfDirectory(handle)
        return
    
    # Získání vyhledávacího dotazu
    if params.get('new'):
        search_query = xbmcgui.Dialog().input(addon.getLocalizedString(30864), type=xbmcgui.INPUT_ALPHANUM)
        if not search_query:
            return
        user_data.store_search_history(search_query, profile_path, search_history_file, max_history)
    else:
        search_query = params.get('query')
    
    if not search_query:
        return
        
    try:
        # Vyhledání filmů
        movie_url = f'https://api.themoviedb.org/3/search/movie?api_key={get_tmdb_api_key()}&language=cs-CZ&query={quote_plus(search_query)}'
        movie_response = requests.get(movie_url)
        movie_response.raise_for_status()
        movie_results = movie_response.json().get('results', [])
        
        # Vyhledání seriálů  
        tv_url = f'https://api.themoviedb.org/3/search/tv?api_key={get_tmdb_api_key()}&language=cs-CZ&query={quote_plus(search_query)}'
        tv_response = requests.get(tv_url)
        tv_response.raise_for_status()
        tv_results = tv_response.json().get('results', [])
        
    except Exception as e:
        handle_tmdb_api_error(e, addon, handle)
        return
    
    # Nastavení kategorie a obsahu
    xbmcplugin.setPluginCategory(handle, f'{addon.getLocalizedString(30868)}: {search_query}')
    xbmcplugin.setContent(handle, 'movies')
    
    # Kontrola výsledků
    total_results = len(movie_results) + len(tv_results)
    if total_results == 0:
        xbmcgui.Dialog().notification(addon.getLocalizedString(30869), search_query, xbmcgui.NOTIFICATION_INFO)
        xbmcplugin.endOfDirectory(handle)
        return
    
    # Přidání filmů do seznamu
    for movie in movie_results:
        movie_id = movie['id']
        title = movie['title']
        year_val = movie.get('release_date', '')[:4]
        plot = movie.get('overview', '')
        poster_path = movie.get('poster_path', '')
        poster = f"https://image.tmdb.org/t/p/w500{poster_path}" if poster_path else ''
        backdrop_path = movie.get('backdrop_path', '')
        fanart = f"https://image.tmdb.org/t/p/original{backdrop_path}" if backdrop_path else poster
        
        # Označení typu obsahu v názvu
        label = f"{addon.getLocalizedString(35100)} {title}"
        if year_val:
            label += f" ({year_val})"
            
        try:
            info_year = int(year_val)
        except:
            info_year = 0
            
        listitem = xbmcgui.ListItem(label=label)
        if poster:
            listitem.setArt({'thumb': poster, 'poster': poster, 'icon': poster, 'fanart': fanart})
        utils.set_video_info_tag(listitem, {'title': label, 'plot': plot, 'year': info_year, 'mediatype': 'movie'})
        
        # Kontextové menu pro filmy
        commands = create_movie_context_menu(
            addon=addon,
            tmdb_id=movie_id,
            title=title,
            year=year_val,
            plot=plot,
            poster=poster,
            original_title=title
        )
        listitem.addContextMenuItems(commands)
        
        details_url = f"plugin://{addon.getAddonInfo('id')}?action=show_wcs_details&media_type=movie&tmdb_id={movie_id}"
        xbmcplugin.addDirectoryItem(handle, details_url, listitem, False)
    
    # Přidání seriálů do seznamu
    for series in tv_results:
        series_id = series['id']
        name = series.get('name', '')
        year_val = series.get('first_air_date', '')[:4]
        plot = series.get('overview', '')
        poster_path = series.get('poster_path', '')
        poster = f"https://image.tmdb.org/t/p/w500{poster_path}" if poster_path else ''
        
        # Označení typu obsahu v názvu
        label = f"{addon.getLocalizedString(35099)} {name}"
        if year_val:
            label += f" ({year_val})"
            
        try:
            info_year = int(year_val)
        except:
            info_year = 0
            
        listitem = xbmcgui.ListItem(label=label)
        if poster:
            listitem.setArt({'thumb': poster, 'poster': poster, 'icon': poster, 'fanart': 'DefaultMovies.png'})
        utils.set_video_info_tag(listitem, {'title': label, 'plot': plot, 'year': info_year, 'mediatype': 'tvshow'})
        
        # Kontextové menu pro seriály
        commands = create_series_context_menu(
            addon=addon,
            tmdb_id=series_id,
            name=name,
            year=year_val,
            plot=plot,
            poster=poster,
            is_in_my_series=False,
            original_name=name
        )
        listitem.addContextMenuItems(commands)
        
        detail_url = f"plugin://{addon.getAddonInfo('id')}?action=tmdb_series_detail&series_id={series_id}&name={quote_plus(name)}"
        xbmcplugin.addDirectoryItem(handle, detail_url, listitem, True)
    
    xbmcplugin.endOfDirectory(handle)

# --- Funkce pro zobrazení omezeného menu (bez TMDb API klíče) ---

def display_limited_menu(addon, handle):
    """Zobrazí omezené menu pro použití bez TMDb API klíče - pouze ČSFD filmy, AI statistiky a nastavení."""
    xbmcplugin.setPluginCategory(handle, addon.getLocalizedString(35050))
    
    # První zvýrazněná položka: Zadat TMDb API klíč
    listitem = xbmcgui.ListItem(label=f"[COLOR orange]{addon.getLocalizedString(35051)}[/COLOR]")
    listitem.setArt({'icon': 'special://home/addons/plugin.video.milionar/resources/media/icons/Milionar.png', 'thumb': 'special://home/addons/plugin.video.milionar/resources/media/icons/Milionar.png', 'poster': 'special://home/addons/plugin.video.milionar/resources/media/icons/Milionar.png'})
    utils.set_video_info_tag(listitem, {
        'title': addon.getLocalizedString(35051),
        'plot': addon.getLocalizedString(35052)
    })
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=show_tmdb_login", listitem, False)
    
    # Filmy ČSFD
    listitem = xbmcgui.ListItem(label=addon.getLocalizedString(35053))
    listitem.setArt({'icon': 'DefaultMovies.png'})
    utils.set_video_info_tag(listitem, {
        'title': addon.getLocalizedString(35053),
        'plot': addon.getLocalizedString(35054)
    })
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=csfd_movies_menu", listitem, True)
    
    # Seriály ČSFD
    listitem = xbmcgui.ListItem(label=addon.getLocalizedString(35055))
    listitem.setArt({'icon': 'DefaultTVShows.png'})
    utils.set_video_info_tag(listitem, {
        'title': addon.getLocalizedString(35055),
        'plot': addon.getLocalizedString(35056)
    })
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=csfd_series_menu", listitem, True)
    
    # Nastavení
    label_settings = addon.getLocalizedString(30632)
    listitem = xbmcgui.ListItem(label=label_settings)
    listitem.setArt({'icon': 'DefaultAddonService.png'})
    utils.set_video_info_tag(listitem, {
        'title': label_settings,
        'plot': addon.getLocalizedString(35057)
    })
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=settings", listitem, False)
    
    xbmcplugin.endOfDirectory(handle)

# --- Pomocné funkce ---

def has_tmdb_api_key(addon):
    """
    Kontroluje zda je nastaven TMDb API klíč.
    Vrací True pokud je klíč nastaven, False pokud není.
    """
    try:
        from wcs.metadata.TMDbClient import get_tmdb_api_key
        get_tmdb_api_key(addon)
        return True
    except ValueError:
        # API klíč není nastaven
        return False
    except Exception:
        # Jiná chyba - považujeme to za neplatný klíč
        return False

# --- ČSFD SERIÁLY BEZ TMDb API KLÍČE ---

def display_csfd_series_seasons(addon, handle, series_csfd_id, series_name):
    """
    Zobrazí seznam sezón ČSFD seriálu.
    
    Args:
        addon: Instance addonu
        handle: Handle pro Kodi plugin
        series_csfd_id (str): ČSFD ID seriálu
        series_name (str): Název seriálu
    """
    if not series_csfd_id:
        popinfo(addon.getLocalizedString(35093), addon.getAddonInfo('name'))
        xbmcplugin.endOfDirectory(handle)
        return
    
    xbmcplugin.setPluginCategory(handle, f'ČSFD / {series_name} / Sezóny')
    xbmcplugin.setContent(handle, 'seasons')
    
    try:
        # Načtení sezón pomocí našeho ČSFD parseru
        from wcs.metadata.CSFDClient import parse_csfd_series_seasons
        seasons = parse_csfd_series_seasons(series_csfd_id, series_name)
        
        if not seasons:
            popinfo(addon.getLocalizedString(35094), addon.getAddonInfo('name'))
            xbmcplugin.endOfDirectory(handle)
            return
        
        # Zobrazení sezón
        for season in seasons:
            season_id = season.get('season_id', '')
            season_name = season.get('season_name', f'Sezóna {season_id}')
            season_url = season.get('season_url', '')
            
            # Vytvoření label
            label = season_name
            
            # Vytvoření ListItem
            listitem = xbmcgui.ListItem(label=label)
            listitem.setArt({'icon': 'DefaultTVShows.png', 'thumb': 'DefaultTVShows.png'})
            
            # Nastavení info
            plot = addon.getLocalizedString(35097).format(series_name=series_name)
            if season_url:
                plot += f"\nURL: {season_url}"
                
            utils.set_video_info_tag(listitem, {
                'title': label,
                'plot': plot,
                'mediatype': 'season'
            })
            
            # Kontextové menu
            commands = [
                ("Otevřít na ČSFD", f"RunPlugin(plugin://{addon.getAddonInfo('id')}?action=open_csfd_url&url={quote_plus(season_url)})") if season_url else None
            ]
            commands = [cmd for cmd in commands if cmd is not None]
            if commands:
                listitem.addContextMenuItems(commands)
            
            # URL pro zobrazení epizod sezóny
            next_url = f"plugin://{addon.getAddonInfo('id')}?action=csfd_series_episodes&series_csfd_id={series_csfd_id}&season_csfd_id={season_id}&season_name={quote_plus(season_name)}&series_name={quote_plus(series_name)}"
            xbmcplugin.addDirectoryItem(handle, next_url, listitem, True)
            
    except Exception as e:
        xbmc.log(f"[WCS ČSFD] Chyba při zobrazování sezón seriálu {series_name}: {e}", xbmc.LOGERROR)
        popinfo(f"Chyba při načítání sezón: {e}", addon.getAddonInfo('name'))
    
    xbmcplugin.endOfDirectory(handle)


def display_csfd_season_episodes(addon, handle, series_csfd_id, season_csfd_id, season_name, series_name):
    """
    Zobrazí seznam epizod ČSFD sezóny.
    
    Args:
        addon: Instance addonu
        handle: Handle pro Kodi plugin
        series_csfd_id (str): ČSFD ID seriálu
        season_csfd_id (str): ČSFD ID sezóny
        season_name (str): Název sezóny
        series_name (str): Název seriálu
    """
    import re  # Import regex modulu na začátek funkce
    
    if not series_csfd_id or not season_csfd_id:
        popinfo(addon.getLocalizedString(35095), addon.getAddonInfo('name'))
        xbmcplugin.endOfDirectory(handle)
        return
    
    xbmcplugin.setPluginCategory(handle, f'ČSFD / {series_name} / {season_name}')
    xbmcplugin.setContent(handle, 'episodes')
    
    try:
        # Načtení epizod pomocí našeho ČSFD parseru
        from wcs.metadata.CSFDClient import parse_csfd_season_episodes
        episodes = parse_csfd_season_episodes(series_csfd_id, season_csfd_id, season_name)
        
        if not episodes:
            popinfo(addon.getLocalizedString(35096), addon.getAddonInfo('name'))
            xbmcplugin.endOfDirectory(handle)
            return
        
        # Seřazení epizod podle čísla epizody
        def get_episode_sort_key(episode):
            try:
                episode_number = episode.get('episode_number')
                if episode_number:
                    return int(episode_number)
                else:
                    # Fallback na pořadí v seznamu
                    return 999
            except (ValueError, TypeError):
                return 999
        
        sorted_episodes = sorted(episodes, key=get_episode_sort_key)
        
        # Zobrazení epizod
        for episode in sorted_episodes:
            episode_id = episode.get('episode_id', '')
            episode_name = episode.get('episode_name', f'Epizoda {episode_id}')
            episode_number = episode.get('episode_number')
            episode_url = episode.get('episode_url', '')
            
            # Vytvoření label s číslem epizody
            if episode_number:
                label = f"E{int(episode_number):02d} - {episode_name}"
            else:
                label = episode_name
            
            # Vytvoření ListItem
            listitem = xbmcgui.ListItem(label=label)
            listitem.setArt({'icon': 'DefaultTVShows.png', 'thumb': 'DefaultTVShows.png'})
            listitem.setProperty('IsPlayable', 'true')  # Epizoda je přehratelná
            
            # Nastavení info
            plot = addon.getLocalizedString(35098).format(series_name=series_name, season_name=season_name)
            if episode_url:
                plot += f"\nURL: {episode_url}"
                
            info_dict = {
                'title': label,
                'plot': plot,
                'mediatype': 'episode'
            }
            
            # Přidání čísla epizody do info pokud je k dispozici
            if episode_number:
                try:
                    info_dict['episode'] = int(episode_number)
                except (ValueError, TypeError):
                    pass
            
            utils.set_video_info_tag(listitem, info_dict)
            
            # Kontextové menu
            commands = [
                ("Otevřít na ČSFD", f"RunPlugin(plugin://{addon.getAddonInfo('id')}?action=open_csfd_url&url={quote_plus(episode_url)})") if episode_url else None
            ]
            commands = [cmd for cmd in commands if cmd is not None]
            if commands:
                listitem.addContextMenuItems(commands)
            
            # URL pro přehrání epizody - správný formát jako u TMDb epizod
            if episode_number:
                # Vytvoříme standardní formát S01E01 pro vyhledávání
                try:
                    # Extrahuj číslo sezóny ze season_name pokud je možné
                    season_num_match = re.search(r'(\d+)', season_name)
                    if season_num_match:
                        season_num = int(season_num_match.group(1))
                    else:
                        season_num = 1  # Fallback na sezónu 1
                    
                    episode_num = int(episode_number)
                    
                    # Použijeme tmdb_episode_search akci pro konzistentní vyhledávání
                    # Předáme také fanart pro lepší zobrazení v dialogu
                    fanart = item.getProperty("fanart") or ""
                    play_url = f"plugin://{addon.getAddonInfo('id')}?action=tmdb_episode_search&series_name={quote_plus(series_name)}&season={season_num}&episode={episode_num}&ep_name={quote_plus(episode_name)}&tmdb_fanart={quote_plus(fanart)}"
                    
                except (ValueError, TypeError):
                    # Fallback na obyčejné vyhledávání pokud selže parsování čísel
                    search_query = f"{series_name} {season_name} epizoda {episode_number}"
                    play_url = f"plugin://{addon.getAddonInfo('id')}?action=search&what={quote_plus(search_query)}"
            else:
                # Pokusíme se vytáhnout číslo z názvu epizody
                episode_num_match = re.search(r'(\d+)', episode_name)
                if episode_num_match:
                    try:
                        # Extrahuj číslo sezóny ze season_name pokud je možné
                        season_num_match = re.search(r'(\d+)', season_name)
                        if season_num_match:
                            season_num = int(season_num_match.group(1))
                        else:
                            season_num = 1  # Fallback na sezónu 1
                        
                        episode_num = int(episode_num_match.group(1))
                        
                        # Použijeme tmdb_episode_search akci pro konzistentní vyhledávání
                        # Předáme také fanart pro lepší zobrazení v dialogu
                        fanart = item.getProperty("fanart") or ""
                        play_url = f"plugin://{addon.getAddonInfo('id')}?action=tmdb_episode_search&series_name={quote_plus(series_name)}&season={season_num}&episode={episode_num}&ep_name={quote_plus(episode_name)}&tmdb_fanart={quote_plus(fanart)}"
                        
                    except (ValueError, TypeError):
                        # Fallback na obyčejné vyhledávání
                        search_query = f"{series_name} {episode_name}"
                        play_url = f"plugin://{addon.getAddonInfo('id')}?action=search&what={quote_plus(search_query)}"
                else:
                    # Úplný fallback
                    search_query = f"{series_name} {episode_name}"
                    play_url = f"plugin://{addon.getAddonInfo('id')}?action=search&what={quote_plus(search_query)}"
            xbmcplugin.addDirectoryItem(handle, play_url, listitem, False)
            
    except Exception as e:
        xbmc.log(f"[WCS ČSFD] Chyba při zobrazování epizod sezóny {season_name}: {e}", xbmc.LOGERROR)
        popinfo(f"Chyba při načítání epizod: {e}", addon.getAddonInfo('name'))
    
    xbmcplugin.endOfDirectory(handle)

def display_my_added_items(addon, handle):
    """Zobrazí sloučené 'Moje přidané' obsahující jak filmy, tak seriály."""
    xbmcplugin.setPluginCategory(handle, addon.getLocalizedString(30621))
    
    # Načtení dat
    tmdb_movies = user_data.load_tmdb_movies(addon)
    tmdb_series = user_data.load_tmdb_series(addon)
    
    # Přidání položky "Detailní zobrazení seznamu" na začátek
    my_list_item = xbmcgui.ListItem(label=addon.getLocalizedString(32163))
    my_list_item.setArt({'icon': 'DefaultFavourites.png'})
    utils.set_video_info_tag(my_list_item, {'title': addon.getLocalizedString(32163), 'plot': addon.getLocalizedString(32164)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=my_list_dialog", my_list_item, False)
    
    # Přidání položek pro přidání nového obsahu
    add_movie_item = xbmcgui.ListItem(label=addon.getLocalizedString(30707))
    add_movie_item.setArt({'icon': 'DefaultAddSource.png'})
    utils.set_video_info_tag(add_movie_item, {'title': addon.getLocalizedString(30707), 'plot': addon.getLocalizedString(30708)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=tmdb_add_movie&new=1&add_to_my_movies=1", add_movie_item, False)
    
    add_series_item = xbmcgui.ListItem(label=addon.getLocalizedString(30716))
    add_series_item.setArt({'icon': 'DefaultAddSource.png'})
    utils.set_video_info_tag(add_series_item, {'title': addon.getLocalizedString(30716), 'plot': addon.getLocalizedString(30717)})
    xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=tmdb_add_series&new=1&add_to_my_series=1", add_series_item, False)
    
    # Smazání všech položek (pokud existují)
    if tmdb_movies or tmdb_series:
        delete_all_item = xbmcgui.ListItem(label=f"[COLOR red]{addon.getLocalizedString(32113)}[/COLOR]")
        delete_all_item.setArt({'icon': 'none.png'})
        utils.set_video_info_tag(delete_all_item, {'title': addon.getLocalizedString(32113), 'plot': addon.getLocalizedString(32112)})
        xbmcplugin.addDirectoryItem(handle, f"plugin://{addon.getAddonInfo('id')}?action=remove_all_my_items", delete_all_item, False)
    
    # Kontrola, zda máme nějaký obsah
    if not tmdb_movies and not tmdb_series:
        popinfo(addon.getLocalizedString(30190), addon.getLocalizedString(30621))
        xbmcplugin.endOfDirectory(handle)
        return
    
    # Přidání filmů
    for idx, movie in enumerate(tmdb_movies):
        label = f"{addon.getLocalizedString(35100)} {movie['title']} ({movie.get('year', '')})"
        plot = movie.get('overview', '')
        poster_path = movie.get('poster_path', '')
        poster = f"https://image.tmdb.org/t/p/w500{poster_path}" if poster_path else ''
        backdrop_path = movie.get('backdrop_path', '')
        fanart = f"https://image.tmdb.org/t/p/original{backdrop_path}" if backdrop_path else poster
        
        listitem = xbmcgui.ListItem(label=label)
        if poster:
            listitem.setArt({'thumb': poster, 'poster': poster, 'icon': poster, 'fanart': fanart})
        utils.set_video_info_tag(listitem, {'title': movie['title'], 'plot': plot, 'year': movie.get('year', ''), 'mediatype': 'movie'})
        
        # Kontextové menu pro filmy v "Moje přidané"
        from wcs.ui.ContextMenu import create_my_movies_context_menu
        commands = create_my_movies_context_menu(
            addon=addon,
            tmdb_id=movie['id'],
            title=movie['title'],
            year=movie.get('year', ''),
            plot=plot,
            poster=poster,
            idx=idx
        )
        listitem.addContextMenuItems(commands)
        listitem.setProperty('IsPlayable', 'false')
        
        # Podle nastavení určíme, jakou akci provést při kliknutí na film
        default_action = addon.getSetting('default_movie_action')
        xbmc.log(f"[plugin.video.milionar] My Added Items - Default movie action setting: '{default_action}' for movie '{movie['title']}'", level=xbmc.LOGINFO)
        
        if default_action == '1':  # 40004 - Přehrát ihned
            # Přehrát ihned - použijeme stejnou akci jako v kontextovém menu
            play_url = f"plugin://{addon.getAddonInfo('id')}?action=play_movie_from_addon&title={quote_plus(movie['title'])}&year={quote_plus(str(movie.get('year', '')))}&plot={quote_plus(plot)}&poster={quote_plus(poster)}"
            xbmc.log(f"[plugin.video.milionar] My Added Items - Using PLAY action: {play_url}", level=xbmc.LOGINFO)
            xbmcplugin.addDirectoryItem(handle, play_url, listitem, False)
        else:  # 40003 - Zobrazit detaily (default)
            # Zobrazit detaily (současné chování)
            details_url = f"plugin://{addon.getAddonInfo('id')}?action=show_wcs_details&media_type=movie&tmdb_id={movie['id']}"
            xbmc.log(f"[plugin.video.milionar] My Added Items - Using DETAILS action: {details_url}", level=xbmc.LOGINFO)
            xbmcplugin.addDirectoryItem(handle, details_url, listitem, False)
    
    # Přidání seriálů
    for idx, series in enumerate(tmdb_series):
        label = f"{addon.getLocalizedString(35099)} {series.get('name', f'Seriál {idx+1}')}"
        plot = series.get('overview', '') or addon.getLocalizedString(31042)
        poster_path = series.get('poster_path', '')
        poster = f"https://image.tmdb.org/t/p/w500{poster_path}" if poster_path else 'DefaultTVShows.png'
        backdrop_path = series.get('backdrop_path', '')
        fanart = f"https://image.tmdb.org/t/p/original{backdrop_path}" if backdrop_path else poster
        
        listitem = xbmcgui.ListItem(label=label)
        listitem.setArt({'thumb': poster, 'icon': poster, 'poster': poster, 'fanart': fanart})
        utils.set_video_info_tag(listitem, {'title': series.get('name', ''), 'plot': plot, 'year': series.get('year', ''), 'mediatype': 'tv'})
        
        # Kontextové menu pro seriály v "Moje přidané"
        tmdb_id = series['id']
        from wcs.ui.ContextMenu import create_my_series_context_menu
        commands = create_my_series_context_menu(
            addon=addon,
            tmdb_id=tmdb_id,
            name=series.get('name', ''),
            plot=series.get('overview', ''),
            poster=poster,
            idx=idx
        )
        listitem.addContextMenuItems(commands)
        url = f"plugin://{addon.getAddonInfo('id')}?action=tmdb_series_detail&series_id={series['id']}&name={quote_plus(series['name'])}"
        xbmcplugin.addDirectoryItem(handle, url, listitem, True)
    
    xbmcplugin.endOfDirectory(handle)
