{extends file="layout.tpl"}

{block name="styles"}
<style>
.btn-xs {
    padding: 0.15rem 0.4rem;
    font-size: 0.75rem;
    line-height: 1.3;
    border-radius: 0.2rem;
}
</style>
{/block}

{block name="content"}
<div class="container-fluid">
    <div class="row justify-content-center">
        <div class="col-lg-10 col-xl-8">
            <!-- Header -->
            <div class="d-flex align-items-center mb-4">
                <div class="stat-icon bg-primary bg-opacity-10 text-primary me-3" style="width: 48px; height: 48px; border-radius: 12px; display: flex; align-items: center; justify-content: center;">
                    <i class="bi bi-broadcast fs-4"></i>
                </div>
                <div>
                    <h4 class="mb-1">Xtream Check</h4>
                    <p class="text-muted mb-0">Sprawdź status i szczegóły konta Xtream Codes</p>
                </div>
            </div>

            {if $error|default:false}
            <div class="alert alert-danger">
                <i class="bi bi-exclamation-circle me-2"></i>{$error}
            </div>
            {/if}

            <!-- Formularz -->
            <div class="card mb-4">
                <div class="card-header">
                    <ul class="nav nav-tabs card-header-tabs" role="tablist">
                        <li class="nav-item">
                            <button class="nav-link {if (!$inputData|default:false || $inputData.input_type == 'url') && !$prefillData|default:false}active{/if}" 
                                    data-bs-toggle="tab" data-bs-target="#tab-url" type="button">
                                <i class="bi bi-link-45deg me-1"></i>Link URL
                            </button>
                        </li>
                        <li class="nav-item">
                            <button class="nav-link {if ($inputData|default:false && $inputData.input_type == 'manual') || $prefillData|default:false}active{/if}" 
                                    data-bs-toggle="tab" data-bs-target="#tab-manual" type="button">
                                <i class="bi bi-input-cursor-text me-1"></i>Ręcznie
                            </button>
                        </li>
                    </ul>
                </div>
                <div class="card-body">
                    <form method="post" action="{$baseUrl}/xtream-check/check" id="xtreamCheckForm">
                        <input type="hidden" name="csrf_token" value="{$csrfToken}">
                        <input type="hidden" name="input_type" id="inputType" value="{if $prefillData|default:false}manual{else}{$inputData.input_type|default:'url'}{/if}">
                        
                        <div class="tab-content">
                            <!-- Tab: Link URL -->
                            <div class="tab-pane fade {if (!$inputData|default:false || $inputData.input_type == 'url') && !$prefillData|default:false}show active{/if}" id="tab-url">
                                <div class="mb-3">
                                    <label class="form-label">Link do API Xtream</label>
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="bi bi-link-45deg"></i></span>
                                        <input type="text" 
                                               name="xtream_link" 
                                               id="xtreamLink"
                                               class="form-control" 
                                               value="{$inputData.url|default:''}"
                                               placeholder="http://server.com:port/player_api.php?username=xxx&password=yyy"
                                               autocomplete="off"
                                               data-lpignore="true"
                                               data-form-type="other">
                                    </div>
                                    <small class="text-muted">
                                        Obsługiwane formaty:<br>
                                        • <code>http://server:port/player_api.php?username=xxx&password=yyy</code><br>
                                        • <code>http://server:port/get.php?username=xxx&password=yyy&type=m3u_plus</code><br>
                                        • <code>http://server:port/live/username/password/...</code>
                                    </small>
                                </div>
                            </div>
                            
                            <!-- Tab: Ręcznie -->
                            <div class="tab-pane fade {if ($inputData|default:false && $inputData.input_type == 'manual') || $prefillData|default:false}show active{/if}" id="tab-manual">
                                <div class="row">
                                    <div class="col-md-12 mb-3">
                                        <label class="form-label">Adres serwera</label>
                                        <div class="input-group">
                                            <span class="input-group-text"><i class="bi bi-hdd-network"></i></span>
                                            <input type="text" 
                                                   name="xc_host_addr" 
                                                   id="xtreamServer"
                                                   class="form-control" 
                                                   value="{$prefillData.server|default:$inputData.server|default:''}"
                                                   placeholder="http://server.com:port"
                                                   autocomplete="new-password"
                                                   data-lpignore="true"
                                                   data-1p-ignore="true"
                                                   data-bwignore="true"
                                                   data-form-type="other">
                                        </div>
                                        <small class="text-muted">np. http://iptv.example.com:8080</small>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Nazwa użytkownika</label>
                                        <div class="input-group">
                                            <span class="input-group-text"><i class="bi bi-person"></i></span>
                                            <input type="text" 
                                                   name="xc_api_login" 
                                                   id="xtreamUser"
                                                   class="form-control" 
                                                   value="{$prefillData.username|default:$inputData.username|default:''}"
                                                   placeholder="username"
                                                   autocomplete="new-password"
                                                   data-lpignore="true"
                                                   data-1p-ignore="true"
                                                   data-bwignore="true"
                                                   data-form-type="other">
                                        </div>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Hasło</label>
                                        <div class="input-group">
                                            <span class="input-group-text"><i class="bi bi-key"></i></span>
                                            <input type="text" 
                                                   name="xc_api_key" 
                                                   id="xtreamPass"
                                                   class="form-control" 
                                                   value="{$prefillData.password|default:''}"
                                                   placeholder="password"
                                                   autocomplete="new-password"
                                                   data-lpignore="true"
                                                   data-1p-ignore="true"
                                                   data-bwignore="true"
                                                   data-form-type="other">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-primary" id="checkBtn">
                                <i class="bi bi-search me-1"></i>Sprawdź konto
                            </button>
                            <button type="button" class="btn btn-outline-secondary" id="clearBtn">
                                <i class="bi bi-x-lg me-1"></i>Wyczyść
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            {if $result|default:false}
            <!-- Wyniki -->
            {if $result.success}
            
            <!-- Status konta -->
            <div class="card mb-4">
                <div class="card-header bg-success text-white">
                    <h5 class="mb-0"><i class="bi bi-check-circle me-2"></i>Konto aktywne</h5>
                </div>
                <div class="card-body">
                    <div class="row g-4">
                        <!-- Informacje o koncie -->
                        <div class="col-md-6">
                            <h6 class="text-muted mb-3"><i class="bi bi-person-badge me-2"></i>Informacje o koncie</h6>
                            <table class="table table-sm table-borderless mb-0">
                                <tr>
                                    <td class="text-muted" style="width: 140px;">Użytkownik:</td>
                                    <td><strong>{$result.user_info.username|default:'-'}</strong></td>
                                </tr>
                                <tr>
                                    <td class="text-muted">Status:</td>
                                    <td>
                                        {if $result.user_info.status == 'Active'}
                                        <span class="badge bg-success">Aktywny</span>
                                        {else}
                                        <span class="badge bg-danger">{$result.user_info.status|default:'Nieznany'}</span>
                                        {/if}
                                    </td>
                                </tr>
                                <tr>
                                    <td class="text-muted">Wygasa:</td>
                                    <td>
                                        {if $result.user_info.exp_date}
                                            <strong>{$result.user_info.exp_date_formatted}</strong>
                                            {if $result.user_info.days_left > 30}
                                                <span class="badge bg-success ms-2">{$result.user_info.days_left} dni</span>
                                            {elseif $result.user_info.days_left > 7}
                                                <span class="badge bg-warning ms-2">{$result.user_info.days_left} dni</span>
                                            {elseif $result.user_info.days_left > 0}
                                                <span class="badge bg-danger ms-2">{$result.user_info.days_left} dni</span>
                                            {else}
                                                <span class="badge bg-danger ms-2">Wygasło!</span>
                                            {/if}
                                        {else}
                                            <span class="badge bg-info">Bez limitu</span>
                                        {/if}
                                    </td>
                                </tr>
                                <tr>
                                    <td class="text-muted">Połączenia:</td>
                                    <td>
                                        {if $result.user_info.max_connections}
                                            <strong>{$result.user_info.active_cons|default:0}</strong> / {$result.user_info.max_connections}
                                            <div class="progress mt-1" style="height: 6px; width: 100px;">
                                                <div class="progress-bar {if $result.user_info.conn_percent > 80}bg-danger{elseif $result.user_info.conn_percent > 50}bg-warning{else}bg-success{/if}" 
                                                     style="width: {$result.user_info.conn_percent}%"></div>
                                            </div>
                                        {else}
                                            <span class="badge bg-info">Bez limitu</span>
                                        {/if}
                                    </td>
                                </tr>
                                <tr>
                                    <td class="text-muted">Utworzone:</td>
                                    <td>
                                        {if $result.user_info.created_at}
                                            {$result.user_info.created_at|date_format:"%d.%m.%Y %H:%M"}
                                        {else}
                                            -
                                        {/if}
                                    </td>
                                </tr>
                                {if $result.user_info.is_trial}
                                <tr>
                                    <td class="text-muted">Trial:</td>
                                    <td><span class="badge bg-warning">Konto testowe</span></td>
                                </tr>
                                {/if}
                            </table>
                        </div>
                        
                        <!-- Informacje o serwerze -->
                        <div class="col-md-6">
                            <h6 class="text-muted mb-3"><i class="bi bi-hdd-rack me-2"></i>Informacje o serwerze</h6>
                            <table class="table table-sm table-borderless mb-0">
                                <tr>
                                    <td class="text-muted" style="width: 140px;">URL:</td>
                                    <td><code class="small">{$result.server_info.url|default:$result.server}</code></td>
                                </tr>
                                <tr>
                                    <td class="text-muted">Port:</td>
                                    <td>{$result.server_info.port|default:'-'}</td>
                                </tr>
                                <tr>
                                    <td class="text-muted">HTTPS Port:</td>
                                    <td>{$result.server_info.https_port|default:'-'}</td>
                                </tr>
                                <tr>
                                    <td class="text-muted">Protokół:</td>
                                    <td>{$result.server_info.server_protocol|default:'-'}</td>
                                </tr>
                                <tr>
                                    <td class="text-muted">Strefa czasowa:</td>
                                    <td>{$result.server_info.timezone|default:'-'}</td>
                                </tr>
                                <tr>
                                    <td class="text-muted">Czas serwera:</td>
                                    <td>
                                        {if $result.server_info.time_now}
                                            {$result.server_info.time_now}
                                        {else}
                                            -
                                        {/if}
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Statystyki kategorii -->
            <div class="row g-4 mb-4">
                <div class="col-md-4">
                    <div class="card h-100 border-primary">
                        <div class="card-body text-center">
                            <i class="bi bi-broadcast display-4 text-primary mb-2"></i>
                            <h2 class="mb-1">{$result.stats.live_categories}</h2>
                            <p class="text-muted mb-0">Kategorie Live TV</p>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card h-100 border-success">
                        <div class="card-body text-center">
                            <i class="bi bi-film display-4 text-success mb-2"></i>
                            <h2 class="mb-1">{$result.stats.vod_categories}</h2>
                            <p class="text-muted mb-0">Kategorie VOD</p>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card h-100 border-warning">
                        <div class="card-body text-center">
                            <i class="bi bi-collection-play display-4 text-warning mb-2"></i>
                            <h2 class="mb-1">{$result.stats.series_categories}</h2>
                            <p class="text-muted mb-0">Kategorie Seriali</p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Polskie kategorie -->
            <div class="card mb-4">
                <div class="card-header {if $result.stats.has_polish}bg-success text-white{else}bg-secondary text-white{/if}">
                    <h5 class="mb-0">
                        {if $result.stats.has_polish}
                        <i class="bi bi-check-circle me-2"></i>Znaleziono polskie kategorie
                        {else}
                        <i class="bi bi-x-circle me-2"></i>Brak polskich kategorii
                        {/if}
                    </h5>
                </div>
                {if $result.stats.has_polish}
                <div class="card-body">
                    <div class="row g-4">
                        {if $result.polish_categories.live|@count > 0}
                        <div class="col-md-4">
                            <h6 class="text-primary"><i class="bi bi-broadcast me-1"></i>Live TV ({$result.polish_categories.live|@count})</h6>
                            <ul class="list-unstyled mb-0">
                                {foreach $result.polish_categories.live as $cat}
                                <li class="mb-1">
                                    <i class="bi bi-check text-success me-1"></i>
                                    {$cat.category_name}
                                </li>
                                {/foreach}
                            </ul>
                        </div>
                        {/if}
                        
                        {if $result.polish_categories.vod|@count > 0}
                        <div class="col-md-4">
                            <h6 class="text-success"><i class="bi bi-film me-1"></i>VOD ({$result.polish_categories.vod|@count})</h6>
                            <ul class="list-unstyled mb-0">
                                {foreach $result.polish_categories.vod as $cat}
                                <li class="mb-1">
                                    <i class="bi bi-check text-success me-1"></i>
                                    {$cat.category_name}
                                </li>
                                {/foreach}
                            </ul>
                        </div>
                        {/if}
                        
                        {if $result.polish_categories.series|@count > 0}
                        <div class="col-md-4">
                            <h6 class="text-warning"><i class="bi bi-collection-play me-1"></i>Seriale ({$result.polish_categories.series|@count})</h6>
                            <ul class="list-unstyled mb-0">
                                {foreach $result.polish_categories.series as $cat}
                                <li class="mb-1">
                                    <i class="bi bi-check text-success me-1"></i>
                                    {$cat.category_name}
                                </li>
                                {/foreach}
                            </ul>
                        </div>
                        {/if}
                    </div>
                </div>
                {/if}
            </div>

            <!-- Generator M3U - zintegrowany z kategoriami -->
            <form method="post" action="{$baseUrl}/xtream-check/generate" id="m3uGeneratorForm">
                <input type="hidden" name="csrf_token" value="{$csrfToken}">
                <input type="hidden" name="server" value="{$result.server}">
                <input type="hidden" name="username" value="{$result.username}">
                <input type="hidden" name="password" value="{$inputData.password|default:''}">
                
                <div class="card mb-4">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">
                            <i class="bi bi-list-check me-2"></i>Wybierz kategorie do playlisty M3U
                        </h5>
                        <div class="btn-group btn-group-sm">
                            <button type="button" class="btn btn-outline-primary" id="selectAllBtn">
                                <i class="bi bi-check-all me-1"></i>Zaznacz wszystkie
                            </button>
                            <button type="button" class="btn btn-outline-secondary" id="deselectAllBtn">
                                <i class="bi bi-x-lg me-1"></i>Odznacz wszystkie
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <!-- Live TV -->
                            {if $result.categories.live|@count > 0}
                            <div class="col-lg-4 mb-4">
                                <div class="border-bottom pb-2 mb-2">
                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                        <h6 class="text-primary mb-0">
                                            <i class="bi bi-broadcast me-1"></i>Live TV <span class="badge bg-primary">{$result.categories.live|@count}</span>
                                        </h6>
                                    </div>
                                    <div class="d-flex gap-1">
                                        {if $result.polish_categories.live|@count > 0}
                                        <button type="button" class="btn btn-xs btn-outline-danger select-polish-btn" data-type="live">
                                            🇵🇱 {$result.polish_categories.live|@count}
                                        </button>
                                        {/if}
                                        <button type="button" class="btn btn-xs btn-outline-secondary select-all-type-btn" data-type="live">
                                            Wszystkie
                                        </button>
                                    </div>
                                </div>
                                <div style="max-height: 280px; overflow-y: auto;">
                                    {foreach $result.categories.live as $cat}
                                    {assign var="isPolish" value=false}
                                    {foreach $result.polish_categories.live as $polCat}
                                        {if $polCat.category_id == $cat.category_id}{assign var="isPolish" value=true}{/if}
                                    {/foreach}
                                    <div class="form-check py-1">
                                        <input type="checkbox" name="categories[live][]" value="{$cat.category_id}" 
                                               id="live_{$cat.category_id}" class="form-check-input cat-checkbox cat-live{if $isPolish} polish-cat polish-live{/if}">
                                        <label class="form-check-label small{if $isPolish} text-danger{/if}" for="live_{$cat.category_id}">
                                            {$cat.category_name}
                                        </label>
                                    </div>
                                    {/foreach}
                                </div>
                            </div>
                            {/if}
                            
                            <!-- VOD -->
                            {if $result.categories.vod|@count > 0}
                            <div class="col-lg-4 mb-4">
                                <div class="border-bottom pb-2 mb-2">
                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                        <h6 class="text-success mb-0">
                                            <i class="bi bi-film me-1"></i>VOD <span class="badge bg-success">{$result.categories.vod|@count}</span>
                                        </h6>
                                    </div>
                                    <div class="d-flex gap-1">
                                        {if $result.polish_categories.vod|@count > 0}
                                        <button type="button" class="btn btn-xs btn-outline-danger select-polish-btn" data-type="vod">
                                            🇵🇱 {$result.polish_categories.vod|@count}
                                        </button>
                                        {/if}
                                        <button type="button" class="btn btn-xs btn-outline-secondary select-all-type-btn" data-type="vod">
                                            Wszystkie
                                        </button>
                                    </div>
                                </div>
                                <div style="max-height: 280px; overflow-y: auto;">
                                    {foreach $result.categories.vod as $cat}
                                    {assign var="isPolish" value=false}
                                    {foreach $result.polish_categories.vod as $polCat}
                                        {if $polCat.category_id == $cat.category_id}{assign var="isPolish" value=true}{/if}
                                    {/foreach}
                                    <div class="form-check py-1">
                                        <input type="checkbox" name="categories[vod][]" value="{$cat.category_id}" 
                                               id="vod_{$cat.category_id}" class="form-check-input cat-checkbox cat-vod{if $isPolish} polish-cat polish-vod{/if}">
                                        <label class="form-check-label small{if $isPolish} text-danger{/if}" for="vod_{$cat.category_id}">
                                            {$cat.category_name}
                                        </label>
                                    </div>
                                    {/foreach}
                                </div>
                            </div>
                            {/if}
                            
                            <!-- Seriale -->
                            {if $result.categories.series|@count > 0}
                            <div class="col-lg-4 mb-4">
                                <div class="border-bottom pb-2 mb-2">
                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                        <h6 class="text-warning mb-0">
                                            <i class="bi bi-collection-play me-1"></i>Seriale <span class="badge bg-warning text-dark">{$result.categories.series|@count}</span>
                                        </h6>
                                    </div>
                                    <div class="d-flex gap-1">
                                        {if $result.polish_categories.series|@count > 0}
                                        <button type="button" class="btn btn-xs btn-outline-danger select-polish-btn" data-type="series">
                                            🇵🇱 {$result.polish_categories.series|@count}
                                        </button>
                                        {/if}
                                        <button type="button" class="btn btn-xs btn-outline-secondary select-all-type-btn" data-type="series">
                                            Wszystkie
                                        </button>
                                    </div>
                                </div>
                                <div style="max-height: 280px; overflow-y: auto;">
                                    {foreach $result.categories.series as $cat}
                                    {assign var="isPolish" value=false}
                                    {foreach $result.polish_categories.series as $polCat}
                                        {if $polCat.category_id == $cat.category_id}{assign var="isPolish" value=true}{/if}
                                    {/foreach}
                                    <div class="form-check py-1">
                                        <input type="checkbox" name="categories[series][]" value="{$cat.category_id}" 
                                               id="series_{$cat.category_id}" class="form-check-input cat-checkbox cat-series{if $isPolish} polish-cat polish-series{/if}">
                                        <label class="form-check-label small{if $isPolish} text-danger{/if}" for="series_{$cat.category_id}">
                                            {$cat.category_name}
                                        </label>
                                    </div>
                                    {/foreach}
                                </div>
                            </div>
                            {/if}
                        </div>
                        
                        <!-- Podsumowanie i przycisk -->
                        <div class="border-top pt-3 mt-2">
                            <div class="d-flex justify-content-between align-items-center flex-wrap gap-3">
                                <div class="text-muted">
                                    <i class="bi bi-info-circle me-1"></i>
                                    Zaznaczono: <strong><span id="selectedCount">0</span></strong> kategorii
                                    <span id="selectedTypes" class="ms-2"></span>
                                </div>
                                <button type="submit" class="btn btn-primary btn-lg" id="generateBtn">
                                    <i class="bi bi-download me-2"></i>Generuj M3U
                                </button>
                            </div>
                            
                            <!-- Progress bar -->
                            <div id="generateProgress" class="mt-3" style="display: none;">
                                <div class="d-flex align-items-center mb-2">
                                    <div class="spinner-border spinner-border-sm text-primary me-2"></div>
                                    <span id="progressText">Generowanie playlisty...</span>
                                </div>
                                <div class="progress" style="height: 8px;">
                                    <div id="progressBar" class="progress-bar progress-bar-striped progress-bar-animated" 
                                         role="progressbar" style="width: 0%"></div>
                                </div>
                                <small class="text-muted mt-1 d-block" id="progressDetails"></small>
                            </div>
                        </div>
                    </div>
                </div>
            </form>

            {else}
            <!-- Błąd -->
            <div class="card border-danger">
                <div class="card-header bg-danger text-white">
                    <h5 class="mb-0"><i class="bi bi-x-circle me-2"></i>Błąd sprawdzania konta</h5>
                </div>
                <div class="card-body">
                    <p class="mb-0">{$result.error}</p>
                </div>
            </div>
            {/if}
            
            {/if}
        </div>
    </div>
</div>
{/block}

{block name="scripts"}
<script>
document.addEventListener('DOMContentLoaded', function() {
    var form = document.getElementById('xtreamCheckForm');
    var inputTypeField = document.getElementById('inputType');
    var checkBtn = document.getElementById('checkBtn');
    var clearBtn = document.getElementById('clearBtn');
    
    // Zmiana taba - aktualizuj input_type
    document.querySelectorAll('[data-bs-toggle="tab"]').forEach(function(tab) {
        tab.addEventListener('shown.bs.tab', function(e) {
            if (e.target.getAttribute('data-bs-target') === '#tab-url') {
                inputTypeField.value = 'url';
            } else {
                inputTypeField.value = 'manual';
            }
        });
    });
    
    // Loading state
    if (form) {
        form.addEventListener('submit', function() {
            if (checkBtn) {
                checkBtn.disabled = true;
                checkBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Sprawdzanie...';
            }
        });
    }
    
    // Wyczyść formularz
    if (clearBtn) {
        clearBtn.addEventListener('click', function() {
            document.getElementById('xtreamLink').value = '';
            document.getElementById('xtreamServer').value = '';
            document.getElementById('xtreamUser').value = '';
            document.getElementById('xtreamPass').value = '';
        });
    }
    
    // ============ GENERATOR M3U ============
    
    var catCheckboxes = document.querySelectorAll('.cat-checkbox');
    var selectedCountEl = document.getElementById('selectedCount');
    var selectedTypesEl = document.getElementById('selectedTypes');
    
    // Funkcja aktualizacji licznika
    function updateSelectedCount() {
        var liveCount = document.querySelectorAll('.cat-live:checked').length;
        var vodCount = document.querySelectorAll('.cat-vod:checked').length;
        var seriesCount = document.querySelectorAll('.cat-series:checked').length;
        var total = liveCount + vodCount + seriesCount;
        
        if (selectedCountEl) {
            selectedCountEl.textContent = total;
        }
        
        if (selectedTypesEl) {
            var types = [];
            if (liveCount > 0) types.push('<span class="badge bg-primary">' + liveCount + ' Live</span>');
            if (vodCount > 0) types.push('<span class="badge bg-success">' + vodCount + ' VOD</span>');
            if (seriesCount > 0) types.push('<span class="badge bg-warning text-dark">' + seriesCount + ' Seriale</span>');
            selectedTypesEl.innerHTML = types.join(' ');
        }
        
        // Aktualizuj stany przycisków
        updateButtonStates();
    }
    
    // Funkcja aktualizacji stanów przycisków
    function updateButtonStates() {
        ['live', 'vod', 'series'].forEach(function(type) {
            var allBtn = document.querySelector('.select-all-type-btn[data-type="' + type + '"]');
            var plBtn = document.querySelector('.select-polish-btn[data-type="' + type + '"]');
            
            var allCheckboxes = document.querySelectorAll('.cat-' + type);
            var polishCheckboxes = document.querySelectorAll('.polish-' + type);
            
            var allChecked = allCheckboxes.length > 0 && Array.from(allCheckboxes).every(function(cb) { return cb.checked; });
            var allPolishChecked = polishCheckboxes.length > 0 && Array.from(polishCheckboxes).every(function(cb) { return cb.checked; });
            
            // Przycisk "Wszystkie" - szary outline / pełny secondary
            if (allBtn) {
                if (allChecked) {
                    allBtn.classList.remove('btn-outline-secondary');
                    allBtn.classList.add('btn-secondary');
                } else {
                    allBtn.classList.remove('btn-secondary');
                    allBtn.classList.add('btn-outline-secondary');
                }
            }
            
            // Przycisk "PL" - czerwony outline / pełny czerwony
            if (plBtn) {
                if (allPolishChecked) {
                    plBtn.classList.remove('btn-outline-danger');
                    plBtn.classList.add('btn-danger');
                } else {
                    plBtn.classList.remove('btn-danger');
                    plBtn.classList.add('btn-outline-danger');
                }
            }
        });
    }
    
    // Nasłuchuj zmian w checkboxach kategorii
    catCheckboxes.forEach(function(cb) {
        cb.addEventListener('change', updateSelectedCount);
    });
    
    // Przycisk "Wszystkie" dla danego typu (toggle)
    document.querySelectorAll('.select-all-type-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            var type = this.dataset.type;
            var checkboxes = document.querySelectorAll('.cat-' + type);
            var allChecked = Array.from(checkboxes).every(function(cb) { return cb.checked; });
            
            // Toggle - jeśli wszystkie zaznaczone to odznacz, w przeciwnym razie zaznacz wszystkie
            checkboxes.forEach(function(cb) {
                cb.checked = !allChecked;
            });
            updateSelectedCount();
        });
    });
    
    // Zaznacz/Odznacz wszystkie (globalne)
    var selectAllBtn = document.getElementById('selectAllBtn');
    var deselectAllBtn = document.getElementById('deselectAllBtn');
    
    if (selectAllBtn) {
        selectAllBtn.addEventListener('click', function() {
            catCheckboxes.forEach(function(cb) { cb.checked = true; });
            updateSelectedCount();
        });
    }
    
    if (deselectAllBtn) {
        deselectAllBtn.addEventListener('click', function() {
            catCheckboxes.forEach(function(cb) { cb.checked = false; });
            updateSelectedCount();
        });
    }
    
    // Przycisk "PL" dla danego typu (toggle)
    document.querySelectorAll('.select-polish-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            var type = this.dataset.type;
            var polishCheckboxes = document.querySelectorAll('.polish-' + type);
            var allPolishChecked = Array.from(polishCheckboxes).every(function(cb) { return cb.checked; });
            
            // Toggle - jeśli wszystkie polskie zaznaczone to odznacz, w przeciwnym razie zaznacz
            polishCheckboxes.forEach(function(cb) {
                cb.checked = !allPolishChecked;
            });
            updateSelectedCount();
        });
    });
    
    // Generator M3U z progress barem
    var generatorForm = document.getElementById('m3uGeneratorForm');
    if (generatorForm) {
        generatorForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            var anySelected = document.querySelectorAll('.cat-checkbox:checked').length > 0;
            if (!anySelected) {
                alert('Zaznacz przynajmniej jedną kategorię do wygenerowania playlisty M3U');
                return false;
            }
            
            var generateBtn = document.getElementById('generateBtn');
            var progressDiv = document.getElementById('generateProgress');
            var progressBar = document.getElementById('progressBar');
            var progressText = document.getElementById('progressText');
            var progressDetails = document.getElementById('progressDetails');
            
            // Zlicz wybrane typy
            var liveCount = document.querySelectorAll('.cat-live:checked').length;
            var vodCount = document.querySelectorAll('.cat-vod:checked').length;
            var seriesCount = document.querySelectorAll('.cat-series:checked').length;
            var totalCats = liveCount + vodCount + seriesCount;
            
            // Pokaż progress
            generateBtn.disabled = true;
            generateBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Generowanie...';
            progressDiv.style.display = 'block';
            progressBar.style.width = '5%';
            progressBar.classList.remove('bg-danger', 'bg-success');
            progressBar.classList.add('progress-bar-animated');
            
            // Timer pokazujący ile czasu minęło
            var startTime = Date.now();
            var timerInterval = setInterval(function() {
                var elapsed = Math.floor((Date.now() - startTime) / 1000);
                var mins = Math.floor(elapsed / 60);
                var secs = elapsed % 60;
                var timeStr = mins > 0 ? mins + 'm ' + secs + 's' : secs + 's';
                document.getElementById('elapsedTime').textContent = timeStr;
            }, 1000);
            
            // Informacje o zadaniu
            var taskInfo = [];
            if (liveCount > 0) taskInfo.push(liveCount + ' kat. Live');
            if (vodCount > 0) taskInfo.push(vodCount + ' kat. VOD');
            if (seriesCount > 0) taskInfo.push(seriesCount + ' kat. Seriali');
            
            progressText.innerHTML = '<i class="bi bi-hourglass-split me-1"></i>Generowanie playlisty M3U...';
            progressDetails.innerHTML = '<span class="me-3">' + taskInfo.join(', ') + '</span><span class="badge bg-secondary">Czas: <span id="elapsedTime">0s</span></span>';
            
            // Symulacja postępu - wolniejsza, bardziej realistyczna
            var progressValue = 5;
            var progressInterval = setInterval(function() {
                if (progressValue < 95) {
                    // Wolniejszy postęp dla seriali
                    var increment = seriesCount > 0 ? Math.random() * 2 : Math.random() * 4;
                    progressValue += increment;
                    progressBar.style.width = Math.min(progressValue, 95) + '%';
                    
                    // Aktualizuj tekst w zależności od postępu
                    if (progressValue < 20) {
                        progressText.innerHTML = '<i class="bi bi-cloud-download me-1"></i>Pobieranie listy strumieni...';
                    } else if (progressValue < 50) {
                        if (seriesCount > 0) {
                            progressText.innerHTML = '<i class="bi bi-collection-play me-1"></i>Pobieranie informacji o serialach (równolegle)...';
                        } else {
                            progressText.innerHTML = '<i class="bi bi-film me-1"></i>Przetwarzanie strumieni...';
                        }
                    } else if (progressValue < 80) {
                        progressText.innerHTML = '<i class="bi bi-file-earmark-text me-1"></i>Budowanie pliku M3U...';
                    } else {
                        progressText.innerHTML = '<i class="bi bi-check2-circle me-1"></i>Finalizowanie...';
                    }
                }
            }, 800);
            
            // Wyślij formularz przez AJAX z długim timeout (10 minut)
            var formData = new FormData(generatorForm);
            var controller = new AbortController();
            var timeoutId = setTimeout(function() {
                controller.abort();
            }, 600000); // 10 minut timeout
            
            fetch(generatorForm.action, {
                method: 'POST',
                body: formData,
                signal: controller.signal
            })
            .then(function(response) {
                clearTimeout(timeoutId);
                clearInterval(progressInterval);
                clearInterval(timerInterval);
                
                if (response.redirected) {
                    // Błąd - przekierowanie
                    window.location.href = response.url;
                    return null;
                }
                
                // Sprawdź czy to plik M3U
                var contentType = response.headers.get('Content-Type');
                if (contentType && contentType.includes('mpegurl')) {
                    // Sukces - pobierz plik
                    var elapsed = Math.floor((Date.now() - startTime) / 1000);
                    progressBar.style.width = '100%';
                    progressBar.classList.remove('progress-bar-animated');
                    progressBar.classList.add('bg-success');
                    progressText.innerHTML = '<i class="bi bi-check-circle-fill me-1"></i>Gotowe! Pobieranie pliku...';
                    progressDetails.innerHTML = '<span class="text-success">Wygenerowano w ' + elapsed + ' sekund</span>';
                    
                    // Pobierz nazwę pliku z headers
                    var disposition = response.headers.get('Content-Disposition');
                    var filename = 'playlist.m3u';
                    if (disposition) {
                        var match = disposition.match(/filename="(.+)"/);
                        if (match) filename = match[1];
                    }
                    
                    return response.blob().then(function(blob) {
                        return { blob: blob, filename: filename };
                    });
                } else {
                    // Prawdopodobnie błąd HTML
                    window.location.href = '{$baseUrl}/xtream-check';
                    return null;
                }
            })
            .then(function(data) {
                if (data && data.blob) {
                    // Utwórz link do pobrania
                    var url = window.URL.createObjectURL(data.blob);
                    var a = document.createElement('a');
                    a.href = url;
                    a.download = data.filename;
                    document.body.appendChild(a);
                    a.click();
                    window.URL.revokeObjectURL(url);
                    a.remove();
                    
                    // Reset UI po 2 sekundach
                    setTimeout(function() {
                        generateBtn.disabled = false;
                        generateBtn.innerHTML = '<i class="bi bi-download me-2"></i>Generuj M3U';
                        progressDiv.style.display = 'none';
                        progressBar.style.width = '0%';
                        progressBar.classList.add('progress-bar-animated');
                        progressBar.classList.remove('bg-success');
                    }, 2000);
                }
            })
            .catch(function(error) {
                clearTimeout(timeoutId);
                clearInterval(progressInterval);
                clearInterval(timerInterval);
                console.error('Błąd:', error);
                
                var elapsed = Math.floor((Date.now() - startTime) / 1000);
                progressBar.classList.remove('progress-bar-animated');
                progressBar.classList.add('bg-danger');
                
                // Lepsze komunikaty błędów
                if (error.name === 'AbortError') {
                    progressText.innerHTML = '<i class="bi bi-exclamation-triangle me-1"></i>Przekroczono limit czasu (10 minut)';
                    progressDetails.innerHTML = 'Spróbuj wybrać mniej kategorii seriali';
                } else if (error.message === 'Failed to fetch') {
                    progressText.innerHTML = '<i class="bi bi-wifi-off me-1"></i>Utracono połączenie z serwerem';
                    progressDetails.innerHTML = 'Serwer mógł być przeciążony (po ' + elapsed + 's) - spróbuj ponownie';
                } else {
                    progressText.innerHTML = '<i class="bi bi-x-circle me-1"></i>Wystąpił błąd';
                    progressDetails.innerHTML = error.message || 'Spróbuj ponownie';
                }
                
                setTimeout(function() {
                    generateBtn.disabled = false;
                    generateBtn.innerHTML = '<i class="bi bi-download me-2"></i>Generuj M3U';
                    progressDiv.style.display = 'none';
                    progressBar.style.width = '0%';
                    progressBar.classList.add('progress-bar-animated');
                    progressBar.classList.remove('bg-danger');
                }, 5000);
            });
        });
    }
    
    // Auto-submit jeśli przekazano dane z playlisty
    {if $prefillData|default:false}
    if (form && document.getElementById('xtreamServer').value && document.getElementById('xtreamUser').value && document.getElementById('xtreamPass').value) {
        // Krótkie opóźnienie żeby strona się wyrenderowała
        setTimeout(function() {
            form.submit();
        }, 300);
    }
    {/if}
});
</script>
{/block}
