<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Akkurtcast - Müzik Listesi</title>
    <link rel="icon" type="image/png" href="/static/img/icon.png">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <style>
        :root { --sidebar-bg: #1a1d21; --sidebar-hover: #2a2e35; --sidebar-text: #a8b2c0; --accent: #0d6efd; --page-bg: #f0f2f5; --card-bg: #fff; --card-border: #e2e8f0; --green: #16a34a; }
        * { box-sizing: border-box; }
        body { background: var(--page-bg); margin: 0; font-family: system-ui, -apple-system, sans-serif; }
        .sidebar { min-height: 100vh; background: var(--sidebar-bg); display: flex; flex-direction: column; position: sticky; top: 0; height: 100vh; overflow-y: auto; }
        .brand { display: flex; align-items: center; gap: 10px; padding: 20px 18px 16px; color: #fff; font-weight: 800; font-size: 1.05rem; border-bottom: 1px solid #2a2e35; flex-shrink: 0; }
        .brand img { width: 46px; height: 46px; object-fit: contain; border-radius: 8px; }
        .brand-mark { display: flex; flex-direction: column; min-width: 0; line-height: 1.05; }
        .brand-name { color: #f8fafc; font-size: 1.18rem; font-weight: 850; letter-spacing: .2px; text-shadow: 0 1px 0 rgba(0,0,0,.25); }
        .brand-subtitle { margin-top: 4px; color: #7dd3fc; font-size: .63rem; font-weight: 700; letter-spacing: 1.25px; text-transform: uppercase; }
        .nav-section-label { font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: 1px; color: #4a5568; padding: 14px 18px 4px; }
        .sidebar a { color: var(--sidebar-text); display: flex; align-items: center; gap: 8px; padding: 9px 18px; text-decoration: none; font-size: 0.875rem; font-weight: 500; border-left: 3px solid transparent; transition: all 0.15s; }
        .sidebar a:hover { background: var(--sidebar-hover); color: #fff; }
        .sidebar a.active { background: rgba(13,110,253,0.12); color: #4d9fff; border-left-color: var(--accent); }
        .sidebar a .nav-icon { width: 22px; height: 22px; min-width: 22px; border-radius: 7px; display: inline-flex; align-items: center; justify-content: center; color: #fff; font-size: .78rem; line-height: 1; box-shadow: inset 0 1px 0 rgba(255,255,255,.18), 0 6px 14px rgba(0,0,0,.18); }
.nav-icon-panel { background: linear-gradient(135deg,#2563eb,#38bdf8); }
.nav-icon-music { background: linear-gradient(135deg,#7c3aed,#ec4899); }
.nav-icon-jingle { background: linear-gradient(135deg,#f59e0b,#f97316); }
.nav-icon-library { background: linear-gradient(135deg,#0f766e,#22c55e); }
.nav-icon-calendar { background: linear-gradient(135deg,#dc2626,#fb7185); }
.nav-icon-automation { background: linear-gradient(135deg,#475569,#94a3b8); }
.nav-icon-news { background: linear-gradient(135deg,#0891b2,#06b6d4); }
.nav-icon-broadcast { background: linear-gradient(135deg,#4338ca,#818cf8); }
.nav-icon-dj { background: linear-gradient(135deg,#111827,#64748b); }
.nav-icon-mobile { background: linear-gradient(135deg,#0e7490,#14b8a6); }
.nav-icon-reports { background: linear-gradient(135deg,#16a34a,#84cc16); }
.nav-icon-widget { background: linear-gradient(135deg,#9333ea,#22d3ee); }
.nav-icon-backup { background: linear-gradient(135deg,#6b7280,#d97706); }
.nav-icon-settings { background: linear-gradient(135deg,#334155,#0ea5e9); }
.nav-icon-logout { background: linear-gradient(135deg,#7f1d1d,#ef4444); }
.sidebar a:hover .nav-icon, .sidebar a.active .nav-icon { transform: translateY(-1px); box-shadow: inset 0 1px 0 rgba(255,255,255,.22), 0 8px 18px rgba(13,110,253,.25); }
        .sidebar-footer { margin-top: auto; border-top: 1px solid #2a2e35; padding: 8px 0; }
        .topbar { background: #fff; border-bottom: 1px solid var(--card-border); padding: 12px 24px; display: flex; align-items: center; justify-content: space-between; gap: 12px; position: sticky; top: 0; z-index: 100; }
        .topbar-title { font-weight: 700; font-size: 0.95rem; color: #1a202c; }
        .topbar-status { display: inline-flex; align-items: center; gap: 6px; font-size: 0.8rem; font-weight: 600; padding: 4px 10px; border-radius: 20px; }
        .topbar-status.on { background: #dcfce7; color: #15803d; }
        .topbar-status.off { background: #fee2e2; color: #b91c1c; }
        .topbar-status::before { content: ''; width: 7px; height: 7px; border-radius: 50%; background: currentColor; }
        .card-panel { background: var(--card-bg); border: 1px solid var(--card-border); border-radius: 12px; overflow: hidden; }
        .card-panel-header { padding: 14px 20px; border-bottom: 1px solid var(--card-border); display: flex; align-items: center; justify-content: space-between; gap: 12px; }
        .card-panel-header .title { font-weight: 700; font-size: 0.9rem; color: #1a202c; }
        .card-panel-header .subtitle { font-size: 0.78rem; color: #64748b; margin-top: 2px; }
        .card-panel-body { padding: 20px; }
        .action-btn { border-radius: 8px; font-weight: 600; font-size: 0.875rem; }
        .now-badge { display: inline-flex; align-items: center; gap: 4px; background: #dcfce7; color: #15803d; font-size: 0.7rem; font-weight: 700; padding: 2px 8px; border-radius: 20px; margin-left: 8px; }
        .stat-pill { background: var(--page-bg); border: 1px solid var(--card-border); border-radius: 8px; padding: 10px 14px; }
        .stat-pill .label { font-size: 0.7rem; color: #64748b; font-weight: 600; text-transform: uppercase; letter-spacing: .5px; margin-bottom: 2px; }
        .stat-pill .value { font-size: 1.2rem; font-weight: 700; color: #1a202c; }
        .playlist-modal .modal-dialog { max-width: 820px; }
        .playlist-modal .modal-body { max-height: 70vh; overflow-y: auto; }
        .playlist-section { border: 1px solid var(--card-border); border-radius: 8px; overflow: hidden; margin-bottom: 14px; }
        .playlist-section-title { background: #0d6efd; color: #fff; font-weight: 700; padding: 10px 14px; }
        .playlist-section-body { padding: 14px; }
        .option-help { font-size: .72rem; color: #64748b; margin-top: 2px; }
        .playlist-meta { display: inline-flex; gap: 6px; flex-wrap: wrap; margin-top: 6px; }
        .playlist-meta .badge { font-size: .68rem; font-weight: 600; }
        .playlist-row { cursor: grab; border-left: 4px solid transparent; }
        .playlist-row.playlist-active { background: #f0fdf4; border-left-color: #22c55e; }
        .playlist-row.playlist-passive { background: #f8fafc; opacity: .72; }
        .playlist-row.playlist-normal { border-left-color: #0ea5e9; }
        .playlist-row.playlist-saat { border-left-color: #f59e0b; }
        .last-played-note { margin-top: 6px; color: #64748b; font-size: .74rem; }
        .health-strip { border-radius: 8px; border: 1px solid #bfdbfe; background: #eff6ff; padding: 12px 14px; }
        .health-strip.warning { border-color: #fbbf24; background: #fffbeb; }
        .health-pill { display: inline-flex; align-items: center; gap: 6px; border-radius: 999px; padding: 4px 9px; background: #fff; border: 1px solid #e2e8f0; font-size: .78rem; font-weight: 700; }
        .health-dot { width: 8px; height: 8px; border-radius: 99px; display: inline-block; }
        .health-dot.danger { background: #ef4444; }
        .health-dot.warning { background: #f59e0b; }
        .health-dot.info { background: #3b82f6; }
        .playlist-row.dragging { opacity: .45; }
        .playlist-dropzone.drag-over td { outline: 2px dashed #0d6efd; outline-offset: -6px; background: #eff6ff; }
        .category-row td { border-top: 2px solid transparent; }
        .category-panel { border-radius: 8px; padding: 12px 14px; display: flex; align-items: center; justify-content: space-between; gap: 12px; }
        .category-panel .category-title { display: flex; align-items: center; gap: 10px; min-width: 0; }
        .category-panel .category-dot { width: 34px; height: 34px; border-radius: 10px; display: inline-flex; align-items: center; justify-content: center; color: #fff; font-weight: 800; box-shadow: inset 0 1px 0 rgba(255,255,255,.25); }
        .category-panel.normal { background: #e0f2fe; border: 1px solid #7dd3fc; }
        .category-panel.normal .category-dot { background: linear-gradient(135deg,#0284c7,#22d3ee); }
        .category-panel.saat { background: #fef3c7; border: 1px solid #fbbf24; }
        .category-panel.saat .category-dot { background: linear-gradient(135deg,#d97706,#f59e0b); }
        .category-panel.open { box-shadow: 0 8px 22px rgba(15, 23, 42, .12); }
        .category-toggle .state-open { display: none; }
        .category-toggle[aria-expanded="true"] .state-open { display: inline; }
        .category-toggle[aria-expanded="true"] .state-closed { display: none; }
        .category-toggle[aria-expanded="true"] .chevron { transform: rotate(180deg); }
        .category-toggle .chevron { display: inline-block; transition: transform .15s ease; }
        @media (max-width: 767px) {
            .sidebar { min-height: auto; height: auto; position: static; flex-direction: row; overflow-x: auto; overflow-y: hidden; white-space: nowrap; }
            .brand { border-bottom: none; border-right: 1px solid #2a2e35; padding: 12px 14px; }
            .nav-section-label { display: none; }
            .sidebar a { padding: 12px 14px; border-left: none; border-bottom: 3px solid transparent; }
            .sidebar a.active { border-left-color: transparent; border-bottom-color: var(--accent); }
            .sidebar-footer { margin-top: 0; border-top: none; }
            .topbar { padding: 10px 16px; }
            .card-panel-body { padding: 14px; }
        }
    
        /* Mobile shell fix: keep the sidebar from squeezing content on phones. */
        @media (max-width: 767px) {
            html, body { width: 100%; max-width: 100%; overflow-x: hidden; }
            .container-fluid > .row.g-0 { display: block; width: 100%; margin: 0; }
            aside.sidebar,
            .sidebar {
                width: 100% !important;
                min-width: 0 !important;
                max-width: 100% !important;
                min-height: auto !important;
                height: auto !important;
                position: relative !important;
                top: auto !important;
                flex-direction: row !important;
                align-items: stretch;
                overflow-x: auto;
                overflow-y: hidden;
                white-space: nowrap;
                -webkit-overflow-scrolling: touch;
            }
            .brand { min-width: 188px; padding: 10px 12px !important; }
            .brand img { width: 40px !important; height: 40px !important; }
            .brand-name { font-size: 1rem !important; }
            .brand-subtitle { font-size: .55rem !important; letter-spacing: .9px !important; }
            .sidebar a { flex: 0 0 auto; padding: 12px 10px !important; }
            .sidebar a .nav-icon { width: 28px; height: 28px; min-width: 28px; }
            .sidebar-footer { display: flex; flex: 0 0 auto; }
            main.col,
            main[class*="col"] {
                display: block;
                width: 100% !important;
                max-width: 100% !important;
                flex: 0 0 100% !important;
                min-width: 0 !important;
            }
            .topbar { position: sticky; top: 0; z-index: 50; padding: 10px 14px !important; }
            .topbar-title { font-size: 1rem; }
            .topbar-status { font-size: .75rem; padding: 4px 9px; }
            main > .p-4 { padding: 14px !important; }
            .card-panel { border-radius: 10px; }
            .card-panel-header { align-items: flex-start; flex-direction: column; padding: 14px !important; }
            .card-panel-header > .d-flex,
            .card-panel-header .d-flex { flex-wrap: wrap; }
            .card-panel-body { padding: 14px !important; }
            .broadcast-controls { display: grid !important; grid-template-columns: 1fr; gap: 10px; }
            .broadcast-controls .action-btn { width: 100%; min-height: 44px; }
            .stream-row,
            .stream-actions { flex-direction: column !important; align-items: stretch !important; gap: 10px !important; }
            .stream-url,
            .stream-row a { max-width: 100%; overflow-wrap: anywhere; word-break: break-word; }
            .history-item { align-items: flex-start; }
            .history-time { margin-left: 0; white-space: normal; }
            .now-playing-card { padding: 16px !important; }
            .next-track-box .next-path { white-space: normal; overflow-wrap: anywhere; }
        }
    </style>
</head>
<body>
<div class="container-fluid p-0">
    <div class="row g-0">
        <aside class="col-12 col-md-auto sidebar p-0" style="width: 220px; min-width: 220px;">
            <div class="brand">
                <img src="/static/img/akkurtcast-badge.png" alt="Akkurtcast">
                <span class="brand-mark"><span class="brand-name">Akkurtcast</span><span class="brand-subtitle">Broadcast Panel</span></span>
            </div>
            <div class="nav-section-label">Yayın</div>
            <a href="/"><span class="nav-icon nav-icon-panel"><i class="bi bi-house-door-fill"></i></span> Panel</a>
            <a class="active" href="/muzik"><span class="nav-icon nav-icon-music"><i class="bi bi-music-note-beamed"></i></span> Müzik listesi</a>
            <a href="/jingle"><span class="nav-icon nav-icon-jingle"><i class="bi bi-bell-fill"></i></span> Jingle listesi</a>
            <a href="/kutuphane"><span class="nav-icon nav-icon-library"><i class="bi bi-folder-fill"></i></span> Kütüphane</a>
            <div class="nav-section-label">Planlama</div>
            <a href="/takvim"><span class="nav-icon nav-icon-calendar"><i class="bi bi-calendar-week-fill"></i></span> Takvim</a>
            <a href="/otomasyon"><span class="nav-icon nav-icon-automation"><i class="bi bi-sliders"></i></span> Otomasyon</a>
            <a href="/haber-bulteni"><span class="nav-icon nav-icon-news"><i class="bi bi-newspaper"></i></span> Haber Bülteni</a>
            <div class="nav-section-label">Yayın Araçları</div>
            <a href="/naklen-yayin"><span class="nav-icon nav-icon-broadcast"><i class="bi bi-broadcast-pin"></i></span> Naklen Yayın</a>
            <a href="/dj"><span class="nav-icon nav-icon-dj"><i class="bi bi-headphones"></i></span> DJ</a>
            <a href="/mobil"><span class="nav-icon nav-icon-mobile"><i class="bi bi-phone-fill"></i></span> Mobil</a>
            <div class="nav-section-label">Sistem</div>
            <a href="/raporlar"><span class="nav-icon nav-icon-reports"><i class="bi bi-bar-chart-fill"></i></span> Raporlar</a>
            <a href="/widgetler"><span class="nav-icon nav-icon-widget"><i class="bi bi-puzzle-fill"></i></span> Widget</a>
            <a href="/yedek"><span class="nav-icon nav-icon-backup"><i class="bi bi-device-hdd-fill"></i></span> Yedek</a>
            <a href="/ayarlar"><span class="nav-icon nav-icon-settings"><i class="bi bi-gear-fill"></i></span> Ayarlar</a>
            <a href="/akis"><span class="nav-icon nav-icon-calendar"><i class="bi bi-list-check"></i></span> Yayın Akışı</a>
            <div class="sidebar-footer">
                <a href="/logout"><span class="nav-icon nav-icon-logout"><i class="bi bi-box-arrow-right"></i></span> Çıkış</a>
            </div>
        </aside>
        <main class="col p-0" style="min-width: 0;">
            <div class="topbar">
                <div class="topbar-title">Müzik Listesi</div>
                <span class="topbar-status {{ 'on' if durum == 'YAYINDA' else 'off' }}">{{ durum }}</span>
            </div>
            <div class="p-4">
                {% if playlist_health %}
                <div class="health-strip warning mb-3">
                    <div class="d-flex flex-wrap align-items-center justify-content-between gap-2">
                        <div>
                            <div class="fw-bold">Playlist Sağlık Kontrolü</div>
                            <div class="small text-muted">Boş liste, eksik dosya veya kategori önerilerini hızlıca gör.</div>
                        </div>
                        <a class="btn btn-outline-dark btn-sm action-btn" href="/takvim">Detaylı kontrol</a>
                    </div>
                    <div class="d-flex flex-wrap gap-2 mt-2">
                        {% for issue in playlist_health[:4] %}
                        <span class="health-pill"><span class="health-dot {{ issue.level }}"></span>{{ issue.title }}</span>
                        {% endfor %}
                    </div>
                </div>
                {% else %}
                <div class="health-strip mb-3">
                    <div class="fw-bold">Playlist Sağlık Kontrolü</div>
                    <div class="small text-muted">Aktif listelerde görünen bir sorun yok.</div>
                </div>
                {% endif %}

                <!-- Çalma Ayarları -->
                <div class="card-panel mb-4">
                    <div class="card-panel-header">
                        <div>
                            <div class="title">Çalma Ayarları</div>
                            <div class="subtitle">Sıralama, tekrar ve zamanlı liste değiştirme</div>
                        </div>
                    </div>
                    <div class="card-panel-body">
                        <form method="post" action="/muzik-ayarlari" class="row g-3 align-items-end">
                            <div class="col-md-3 col-6">
                                <label class="form-label small fw-semibold">Çalma modu</label>
                                <select name="playlist_mode" class="form-select form-select-sm">
                                    <option value="shuffle" {% if ayarlar.playlist_mode == 'shuffle' %}selected{% endif %}>Karışık</option>
                                    <option value="ordered" {% if ayarlar.playlist_mode == 'ordered' %}selected{% endif %}>Sıralı</option>
                                </select>
                            </div>
                            <div class="col-md-3 col-6">
                                <label class="form-label small fw-semibold">Sanatçı tekrar aralığı</label>
                                <input type="number" class="form-control form-control-sm" name="artist_gap" min="0" max="20" value="{{ ayarlar.artist_gap }}">
                            </div>
                            <div class="col-md-3 col-6">
                                <label class="form-label small fw-semibold">Şarkı tekrar etmesin (saat)</label>
                                <input type="number" class="form-control form-control-sm" name="track_repeat_hours" min="0" max="48" value="{{ ayarlar.track_repeat_hours }}">
                            </div>
                            <div class="col-md-3 col-6">
                                <div class="form-check mt-3 mt-md-0" style="padding-top:8px;">
                                    <input class="form-check-input" type="checkbox" name="auto_restart" id="autoRestart" {% if ayarlar.auto_restart %}checked{% endif %}>
                                    <label class="form-check-label small" for="autoRestart">Otomatik toparla</label>
                                </div>
                            </div>
                            <div class="col-md-3 col-6">
                                <label class="form-label small fw-semibold">Gündüz listesi</label>
                                <select name="day_playlist" class="form-select form-select-sm">
                                    <option value="">Kapalı</option>
                                    {% for liste in listeler %}
                                    <option value="{{ liste.key }}" {% if ayarlar.day_playlist == liste.key %}selected{% endif %}>{{ liste.name }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                            <div class="col-md-3 col-6">
                                <label class="form-label small fw-semibold">Gece listesi</label>
                                <select name="night_playlist" class="form-select form-select-sm">
                                    <option value="">Kapalı</option>
                                    {% for liste in listeler %}
                                    <option value="{{ liste.key }}" {% if ayarlar.night_playlist == liste.key %}selected{% endif %}>{{ liste.name }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                            <div class="col-md-2 col-6">
                                <label class="form-label small fw-semibold">Gündüz başlar</label>
                                <input type="time" class="form-control form-control-sm" name="day_start" value="{{ ayarlar.day_start }}">
                            </div>
                            <div class="col-md-2 col-6">
                                <label class="form-label small fw-semibold">Gece başlar</label>
                                <input type="time" class="form-control form-control-sm" name="night_start" value="{{ ayarlar.night_start }}">
                            </div>
                            <div class="col-md-2">
                                <button class="btn btn-primary btn-sm w-100 action-btn">Kaydet</button>
                            </div>
                        </form>
                    </div>
                </div>

                {% macro playlist_row(liste, row_no, modal_id, active_playlist, available_media) %}
                <tr class="playlist-row {{ 'playlist-active' if liste.active else 'playlist-passive' }} {{ 'playlist-normal' if liste.resolved_group == 'normal' else '' }} {{ 'playlist-saat' if liste.resolved_group == 'saat' else '' }} {{ 'table-primary' if liste.key == active_playlist else '' }}" draggable="{{ 'false' if liste.key == 'all' else 'true' }}" data-playlist-key="{{ liste.key }}">
                    <td class="ps-4 py-3">
                        <span class="badge text-bg-light text-dark border">#{{ row_no }}</span>
                    </td>
                    <td class="py-3">
                        <div class="fw-semibold">{{ liste.name }}</div>
                        {% if liste.description %}<div class="small text-muted">{{ liste.description }}</div>{% endif %}
                        <div class="playlist-meta">
                            {% if not liste.active %}<span class="badge text-bg-secondary">Pasif</span>{% endif %}
                            {% if liste.source == 'remote' %}<span class="badge text-bg-warning">Uzak URL</span>{% else %}<span class="badge text-bg-light text-dark border">Şarkı tabanlı</span>{% endif %}
                            {% if liste.key != 'all' %}
                                {% if liste.resolved_group == 'normal' %}<span class="badge text-bg-info">Normal anons</span>{% elif liste.resolved_group == 'saat' %}<span class="badge text-bg-warning">Saat anonsu</span>{% endif %}
                            {% endif %}
                        </div>
                        {% if liste.key == active_playlist %}
                            <span class="now-badge">▶ Şimdi çalıyor</span>
                        {% endif %}
                        <div class="last-played-note">
                            Son çaldı:
                            {% if liste.last_played and liste.last_played.time %}
                                <strong>{{ liste.last_played.time }}</strong>{% if liste.last_played.title %} · {{ liste.last_played.title }}{% endif %}
                            {% else %}
                                Henüz yok
                            {% endif %}
                        </div>
                    </td>
                    <td class="py-3">
                        {% if liste.duration != '-' %}<div>{{ liste.duration }}</div>{% endif %}
                        <button type="button" class="btn btn-link btn-sm p-0 small text-decoration-none playlist-track-count" data-playlist-key="{{ liste.key }}" data-playlist-name="{{ liste.name }}" data-bs-toggle="modal" data-bs-target="#playlistTracksModal">{{ liste.count }} şarkı</button>
                    </td>
                    <td class="py-3">
                        <div class="fw-semibold small">
                            {% if liste.playback_type == 'once_per_x_songs' %}Her {{ liste.interval_value or 1 }} şarkı{% elif liste.playback_type == 'once_per_x_minutes' %}Her {{ liste.interval_value or 1 }} dakika{% elif liste.playback_type == 'once_per_hour' %}Saatin {{ liste.interval_value or 0 }}. dakikası{% elif liste.playback_type == 'advanced' %}Gelişmiş{% else %}Genel Oynatma{% endif %}
                        </div>
                        <div class="small text-muted">
                            {% if liste.playback_order == 'sequential' %}Sıralı{% elif liste.playback_order == 'random' %}Rastgele{% else %}Karışık{% endif %}
                        </div>
                    </td>
                    <td class="py-3">
                        <form method="post" action="/playlist-karistir/{{ liste.key }}">
                            <div class="form-check mb-0">
                                <input class="form-check-input" type="checkbox" name="shuffle" value="on" {% if liste.shuffle %}checked{% endif %} onchange="this.form.submit()">
                                <label class="form-check-label small">Karışık</label>
                            </div>
                        </form>
                    </td>
                    <td class="py-3 text-end pe-4">
                        <div class="d-flex flex-wrap justify-content-end gap-1">
                            {% if liste.key != 'all' %}
                            <form method="post" action="/playlist-sira/{{ liste.key }}/up">
                                <button class="btn btn-outline-secondary btn-sm action-btn" title="Yukarı taşı">↑</button>
                            </form>
                            <form method="post" action="/playlist-sira/{{ liste.key }}/down">
                                <button class="btn btn-outline-secondary btn-sm action-btn" title="Aşağı taşı">↓</button>
                            </form>
                            <button class="btn btn-outline-secondary btn-sm action-btn" data-playlist-edit data-playlist='{{ liste|tojson }}' data-bs-toggle="modal" data-bs-target="#playlistAddModal">Düzenle</button>
                            <button class="btn btn-outline-success btn-sm action-btn" data-bs-toggle="modal" data-bs-target="#playlistUploadModal{{ modal_id }}">Şarkı Ekle</button>
                            <form method="post" action="/playlist-grup/{{ liste.key }}">
                                <select class="form-select form-select-sm" name="display_group" onchange="this.form.submit()" style="width:150px;">
                                    <option value="auto" {% if liste.display_group == 'auto' %}selected{% endif %}>Otomatik</option>
                                    <option value="main" {% if liste.resolved_group == 'main' and liste.display_group == 'main' %}selected{% endif %}>Ana liste</option>
                                    <option value="normal" {% if liste.resolved_group == 'normal' %}selected{% endif %}>Normal anons</option>
                                    <option value="saat" {% if liste.resolved_group == 'saat' %}selected{% endif %}>Saat anonsu</option>
                                </select>
                            </form>
                            <form method="post" action="/playlist-durum/{{ liste.key }}">
                                <button class="btn btn-sm action-btn {% if liste.active %}btn-outline-secondary{% else %}btn-success{% endif %}">
                                    {% if liste.active %}Pasifleştir{% else %}Aktifleştir{% endif %}
                                </button>
                            </form>
                            <form method="post" action="/playlist-sil/{{ liste.key }}" onsubmit="return confirm('{{ liste.name }} çalma listesini ve içindeki dosyaları silmek istiyor musun?');">
                                <button class="btn btn-outline-danger btn-sm action-btn">Sil</button>
                            </form>
                            <form method="post" action="/playlist-test/{{ liste.key }}">
                                <button class="btn btn-outline-dark btn-sm action-btn" {% if not liste.active %}disabled{% endif %}>Test et</button>
                            </form>
                            {% endif %}
                            <form method="post" action="/playlist-sec/{{ liste.key }}">
                                <button class="btn btn-outline-primary btn-sm action-btn" {% if not liste.active %}disabled{% endif %}>▶ Yayına al</button>
                            </form>
                        </div>

                        {% if liste.key != 'all' %}
                        <div class="modal fade" id="playlistUploadModal{{ modal_id }}" tabindex="-1" aria-hidden="true">
                            <div class="modal-dialog modal-dialog-centered modal-lg">
                                <div class="modal-content text-start">
                                    <form method="post" action="/playlist-dosya-ekle/{{ liste.key }}" enctype="multipart/form-data">
                                        <div class="modal-header">
                                            <h5 class="modal-title">{{ liste.name }} - Şarkı/Jingle Ekle</h5>
                                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Kapat"></button>
                                        </div>
                                        <div class="modal-body">
                                            <label class="form-label small fw-semibold">Mevcut müzik/jingle havuzu</label>
                                            <select class="form-select" name="selected_media" multiple size="12">
                                                {% for media in available_media %}
                                                    <option value="{{ media.path }}" {% if media.path in liste.manual_tracks %}selected{% endif %}>{{ media.name }}</option>
                                                {% endfor %}
                                            </select>
                                            <div class="form-text">Ctrl tuşuyla birden fazla dosya seçebilirsin. Seçilenler kopyalanmaz; bu çalma listesine bağlanır.</div>
                                            <hr>
                                            <label class="form-label small fw-semibold">İstersen yeni dosya da yükle</label>
                                            <input class="form-control" type="file" name="files" accept=".mp3,.wav,.ogg,.flac,.m4a,.aac,audio/*" multiple>
                                        </div>
                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Kapat</button>
                                            <button class="btn btn-success">Listeye Ekle</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                        {% endif %}
                    </td>
                </tr>
                {% endmacro %}

                <!-- Listeler tablosu -->
                <div class="card-panel">
                    <div class="card-panel-header">
                        <div>
                            <div class="title">Oynatma Listeleri</div>
                            <div class="subtitle">Klasör bazlı çalma listeleri ve zamanlı akışlar</div>
                        </div>
                        <button class="btn btn-primary btn-sm action-btn" data-playlist-new data-bs-toggle="modal" data-bs-target="#playlistAddModal">+ Çalma Listesi Ekle</button>
                    </div>
                    <div class="table-responsive">
                        <table class="table align-middle mb-0" style="font-size:.875rem;">
                            <thead style="background:#f8fafc;">
                                <tr>
                                    <th class="ps-4 py-3" style="width:70px;">No</th>
                                    <th class="py-3">Liste</th>
                                    <th class="py-3">Süre / Şarkı</th>
                                    <th class="py-3">Mod</th>
                                    <th class="py-3">Karıştır</th>
                                    <th class="py-3 text-end pe-4">İşlemler</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr class="table-light playlist-dropzone" data-group="main">
                                    <td class="ps-4 py-2"><span class="badge text-bg-primary">Ana</span></td>
                                    <td class="py-2" colspan="5">
                                        <div class="fw-semibold">Ana Listeler</div>
                                        <div class="small text-muted">Bir çalma listesini buraya sürükleyip ana listelere taşıyabilirsin.</div>
                                    </td>
                                </tr>
                            {% for liste in oynatma_listeleri %}
                                {{ playlist_row(liste, loop.index, 'main' ~ loop.index, active_playlist, available_media) }}
                            {% endfor %}

                            
                                <tr class="category-row playlist-dropzone" data-group="normal">
                                    <td colspan="6" class="p-3">
                                        <div class="category-panel normal" data-category-panel="normal">
                                            <div class="category-title">
                                                <span class="category-dot">{{ normal_anonslar|length }}</span>
                                                <div>
                                                    <form method="post" action="/playlist-grup-baslik" class="d-flex flex-wrap gap-2 align-items-center">
                                                        <input type="hidden" name="saat_name" value="{{ playlist_group_names.saat }}">
                                                        <input class="form-control form-control-sm fw-semibold" name="normal_name" value="{{ playlist_group_names.normal }}" style="max-width:260px;">
                                                        <button class="btn btn-outline-secondary btn-sm action-btn">İsmi kaydet</button>
                                                    </form>
                                                    <div class="small text-muted">Jingle/spot grupları burada toplanır. Buraya sürükleyip bırakabilirsin.</div>
                                                </div>
                                            </div>
                                            <button class="btn btn-info btn-sm action-btn category-toggle" type="button" data-bs-toggle="collapse" data-bs-target="#normalAnonsRows" aria-expanded="false">
                                                <span class="state-closed">Kapalı</span><span class="state-open">Açık</span> <span class="chevron">⌄</span>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                <tr class="collapse" id="normalAnonsRows">
                                    <td colspan="6" class="p-0">
                                        <table class="table align-middle mb-0" style="font-size:.875rem;">
                                            <tbody>
                                            {% for liste in normal_anonslar %}
                                                {{ playlist_row(liste, 'N' ~ loop.index, 'normal' ~ loop.index, active_playlist, available_media) }}
                                            {% endfor %}
                                            </tbody>
                                        </table>
                                    </td>
                                </tr>
                                <tr class="category-row playlist-dropzone" data-group="saat">
                                    <td colspan="6" class="p-3">
                                        <div class="category-panel saat" data-category-panel="saat">
                                            <div class="category-title">
                                                <span class="category-dot">{{ saat_anonslari|length }}</span>
                                                <div>
                                                    <form method="post" action="/playlist-grup-baslik" class="d-flex flex-wrap gap-2 align-items-center">
                                                        <input type="hidden" name="normal_name" value="{{ playlist_group_names.normal }}">
                                                        <input class="form-control form-control-sm fw-semibold" name="saat_name" value="{{ playlist_group_names.saat }}" style="max-width:260px;">
                                                        <button class="btn btn-outline-secondary btn-sm action-btn">İsmi kaydet</button>
                                                    </form>
                                                    <div class="small text-muted">Saatlik anons listeleri burada toplanır. Buraya sürükleyip bırakabilirsin.</div>
                                                </div>
                                            </div>
                                            <button class="btn btn-warning btn-sm action-btn category-toggle" type="button" data-bs-toggle="collapse" data-bs-target="#saatAnonsRows" aria-expanded="false">
                                                <span class="state-closed">Kapalı</span><span class="state-open">Açık</span> <span class="chevron">⌄</span>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                <tr class="collapse" id="saatAnonsRows">
                                    <td colspan="6" class="p-0">
                                        <table class="table align-middle mb-0" style="font-size:.875rem;">
                                            <tbody>
                                            {% for liste in saat_anonslari %}
                                                {{ playlist_row(liste, 'S' ~ loop.index, 'saat' ~ loop.index, active_playlist, available_media) }}
                                            {% endfor %}
                                            </tbody>
                                        </table>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

            </div>
        </main>
    </div>
</div>

<div class="modal fade" id="playlistTracksModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <div>
                    <h5 class="modal-title" id="playlistTracksTitle">Çalma Listesi</h5>
                    <div class="small text-muted" id="playlistTracksCount">Yükleniyor...</div>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Kapat"></button>
            </div>
            <div class="modal-body p-0">
                <div class="table-responsive" style="max-height: 60vh; overflow:auto;">
                    <table class="table table-sm align-middle mb-0">
                        <thead style="background:#f8fafc; position:sticky; top:0;">
                            <tr>
                                <th class="ps-3" style="width:64px;">No</th>
                                <th>Şarkı</th>
                                <th>Konum</th>
                            </tr>
                        </thead>
                        <tbody id="playlistTracksBody">
                            <tr><td colspan="3" class="text-muted p-3">Yükleniyor...</td></tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade playlist-modal" id="playlistAddModal" tabindex="-1" aria-labelledby="playlistAddModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
            <form method="post" action="/playlist-ekle" id="playlistForm">
                <div class="modal-header">
                    <h5 class="modal-title" id="playlistAddModalLabel">Çalma Listesi Ekle</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Kapat"></button>
                </div>
                <div class="modal-body">
                    <ul class="nav nav-tabs mb-3" role="tablist">
                        <li class="nav-item" role="presentation"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#playlistBasicTab" type="button" role="tab">Temel Bilgiler</button></li>
                        <li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#playlistScheduleTab" type="button" role="tab">Zamanla</button></li>
                        <li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#playlistAdvancedTab" type="button" role="tab">Gelişmiş</button></li>
                    </ul>

                    <div class="tab-content">
                        <div class="tab-pane fade show active" id="playlistBasicTab" role="tabpanel">
                            <div class="row g-3 mb-3">
                                <div class="col-lg-6">
                                    <label class="form-label small fw-semibold">Çalma Listesi İsmi</label>
                                    <input class="form-control" name="name" required>
                                </div>
                                <div class="col-lg-6 d-flex align-items-end">
                                    <div class="form-check form-switch mb-2">
                                        <input class="form-check-input" type="checkbox" name="active" id="playlistActive" checked>
                                        <label class="form-check-label" for="playlistActive">Etkin</label>
                                        <div class="option-help">Kapalı listeler otomatik yayına alınmaz.</div>
                                    </div>
                                </div>
                                <div class="col-12">
                                    <label class="form-label small fw-semibold">Açıklama</label>
                                    <textarea class="form-control" name="description" rows="2"></textarea>
                                </div>
                            </div>

                            <div class="mb-3">
                                <label class="form-label small fw-semibold">Kaynak</label>
                                <div class="row g-2">
                                    <div class="col-md-6">
                                        <label class="border rounded p-3 d-block h-100">
                                            <input class="form-check-input me-2" type="radio" name="source" value="songs" checked data-source-radio>
                                            <span class="fw-semibold">Şarkı Tabanlı</span>
                                            <div class="option-help">Yeni bir müzik klasörü oluşturur; dosyaları bu klasöre yüklersin.</div>
                                        </label>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="border rounded p-3 d-block h-100">
                                            <input class="form-check-input me-2" type="radio" name="source" value="remote" data-source-radio>
                                            <span class="fw-semibold">Uzak Çalma Listesi URL'si</span>
                                            <div class="option-help">URL kaydedilir; yayın motoruna bağlama için ayrıca özel akış gerekir.</div>
                                        </label>
                                    </div>
                                </div>
                                <input class="form-control mt-2 d-none" name="remote_url" id="remoteUrlInput" placeholder="https://.../playlist.m3u">
                            </div>

                            <div class="playlist-section">
                                <div class="playlist-section-title">Çalma Listesinden Çal</div>
                                <div class="playlist-section-body">
                                    <div class="row g-3">
                                        <div class="col-md-6">
                                            <div class="form-check form-switch">
                                                <input class="form-check-input" type="checkbox" name="avoid_duplicates" id="avoidDuplicates" checked>
                                                <label class="form-check-label fw-semibold" for="avoidDuplicates">Yinelenen Sanatçılardan/Şarkılardan Kaçının</label>
                                                <div class="option-help">Sanatçı ve şarkı tekrarlarını azaltmak için mevcut tekrar korumasını kullanır.</div>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-check form-switch">
                                                <input class="form-check-input" type="checkbox" name="include_requests" id="includeRequests">
                                                <label class="form-check-label fw-semibold" for="includeRequests">İsteğe Bağlı Oynatıcıya Dahil Et</label>
                                                <div class="option-help">Şimdilik ayar olarak saklanır.</div>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-check form-switch">
                                                <input class="form-check-input" type="checkbox" name="show_on_public" id="showOnPublic" checked>
                                                <label class="form-check-label fw-semibold" for="showOnPublic">Çalma Listesinde İstekleri Etkinleştir</label>
                                                <div class="option-help">Liste görünürlüğü için saklanır.</div>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-check form-switch">
                                                <input class="form-check-input" type="checkbox" name="hide_metadata" id="hideMetadata">
                                                <label class="form-check-label fw-semibold" for="hideMetadata">Meta Verilerini Gizle</label>
                                                <div class="option-help">Jingle mode benzeri gizleme tercihi olarak saklanır.</div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="row g-3 mt-1">
                                        <div class="col-md-6">
                                            <label class="form-label small fw-semibold">Çalma Listesi Türü</label>
                                            <div class="vstack gap-2">
                                                <label><input class="form-check-input me-2" type="radio" name="playback_type" value="general" checked data-playback-type>Genel Oynatma</label>
                                                <label><input class="form-check-input me-2" type="radio" name="playback_type" value="once_per_x_songs" data-playback-type>x Şarkıda Bir Çal</label>
                                                <label><input class="form-check-input me-2" type="radio" name="playback_type" value="once_per_x_minutes" data-playback-type>x Dakikada Bir Çal</label>
                                                <label><input class="form-check-input me-2" type="radio" name="playback_type" value="once_per_hour" data-playback-type>Saatte Bir Çal</label>
                                                <label><input class="form-check-input me-2" type="radio" name="playback_type" value="advanced" data-playback-type>Gelişmiş</label>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label small fw-semibold">Şarkı Çalma Sırası</label>
                                            <div class="vstack gap-2">
                                                <label><input class="form-check-input me-2" type="radio" name="playback_order" value="shuffle" checked>Karışık</label>
                                                <label><input class="form-check-input me-2" type="radio" name="playback_order" value="random">Rastgele</label>
                                                <label><input class="form-check-input me-2" type="radio" name="playback_order" value="sequential">Sıralı</label>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="mt-3" id="generalOptions">
                                        <label class="form-label small fw-semibold">Çalma Listesi Önceliği</label>
                                        <select class="form-select" name="weight">
                                            {% for i in range(1, 26) %}
                                            <option value="{{ i }}" {% if i == 3 %}selected{% endif %}>{{ i }}</option>
                                            {% endfor %}
                                        </select>
                                        <div class="option-help">Büyük değer daha sık çalınacak liste anlamına gelir; mevcut motorda bilgi olarak saklanır.</div>
                                    </div>
                                    <div class="mt-3 d-none" id="intervalOptions">
                                        <label class="form-label small fw-semibold" id="intervalLabel">Kaç aralıkta bir çalınsın?</label>
                                        <input class="form-control" type="number" min="1" max="240" name="interval_value" value="1">
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="tab-pane fade" id="playlistScheduleTab" role="tabpanel">
                            <div class="playlist-section">
                                <div class="playlist-section-title d-flex justify-content-between align-items-center">
                                    <span>Planlanan Zaman #1</span>
                                </div>
                                <div class="playlist-section-body">
                                    <div class="row g-3">
                                        <div class="col-md-6">
                                            <label class="form-label small fw-semibold">Başlama Zamanı</label>
                                            <input class="form-control" type="time" name="start_time">
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label small fw-semibold">Bitiş Zamanı</label>
                                            <input class="form-control" type="time" name="end_time">
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label small fw-semibold">Başlangıç Tarihi</label>
                                            <input class="form-control" type="date" name="start_date">
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label small fw-semibold">Bitiş Tarihi</label>
                                            <input class="form-control" type="date" name="end_date">
                                        </div>
                                        <div class="col-md-8">
                                            <label class="form-label small fw-semibold">Haftalık Zamanlama</label>
                                            <div class="d-flex flex-wrap gap-2">
                                                {% for value, label in [('0','Pazartesi'),('1','Salı'),('2','Çarşamba'),('3','Perşembe'),('4','Cuma'),('5','Cumartesi'),('6','Pazar')] %}
                                                <label class="form-check-label small"><input class="form-check-input" type="checkbox" name="days" value="{{ value }}"> {{ label }}</label>
                                                {% endfor %}
                                            </div>
                                            <div class="option-help">Gün seçmezsen her gün çalışır.</div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-check form-switch mt-md-4">
                                                <input class="form-check-input" type="checkbox" name="once" id="onceOnly">
                                                <label class="form-check-label" for="onceOnly">Bir Kez Oynat</label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="tab-pane fade" id="playlistAdvancedTab" role="tabpanel">
                            <div class="vstack gap-2">
                                <label><input class="form-check-input me-2" type="checkbox" name="interrupt_other">Planlanan saatte çalmak için diğer şarkıları yarıda kesin.</label>
                                <label><input class="form-check-input me-2" type="checkbox" name="scheduled_single_track">Planlanan zamanda sadece bir parça çalın.</label>
                                <label><input class="form-check-input me-2" type="checkbox" name="merge">Merge playlist to play as a single track.</label>
                                <label><input class="form-check-input me-2" type="checkbox" name="prioritize_requests">Prioritize over listener requests.</label>
                            </div>
                            <div class="alert alert-light border small mt-3 mb-0">Bu gelişmiş seçenekler kaydedilir; yayın motoruna özel davranış eklemek istersen sonraki adımda Liquidsoap tarafına bağlanabilir.</div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Kapat</button>
                    <button class="btn btn-danger">Kaydet</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
const playlistModal = document.getElementById('playlistAddModal');
const playlistForm = document.getElementById('playlistForm');
const playlistTitle = document.getElementById('playlistAddModalLabel');

function setChecked(name, value) {
    const field = playlistForm.querySelector(`[name="${name}"][value="${value}"]`);
    if (field) field.checked = true;
}

function setSwitch(name, value) {
    const field = playlistForm.querySelector(`[name="${name}"]`);
    if (field) field.checked = Boolean(value);
}

function updateSourceFields() {
    const remote = playlistForm.querySelector('[name="source"][value="remote"]').checked;
    document.getElementById('remoteUrlInput').classList.toggle('d-none', !remote);
}

function updatePlaybackFields() {
    const type = playlistForm.querySelector('[name="playback_type"]:checked').value;
    const interval = document.getElementById('intervalOptions');
    const general = document.getElementById('generalOptions');
    const label = document.getElementById('intervalLabel');
    const input = interval.querySelector('[name="interval_value"]');
    const needsInterval = type === 'once_per_x_songs' || type === 'once_per_x_minutes' || type === 'once_per_hour';
    interval.classList.toggle('d-none', !needsInterval);
    general.classList.toggle('d-none', type !== 'general');
    if (type === 'once_per_x_songs') label.textContent = 'Kaç şarkıda bir çalınsın?';
    if (type === 'once_per_x_minutes') label.textContent = 'Kaç dakikada bir çalınsın?';
    if (type === 'once_per_hour') label.textContent = 'Saatin hangi dakikasında çalınsın?';
    if (input) {
        input.min = type === 'once_per_hour' ? '0' : '1';
        input.max = type === 'once_per_hour' ? '59' : '240';
        if (type === 'once_per_hour' && Number(input.value || 0) > 59) input.value = '0';
    }
}

function resetPlaylistForm() {
    playlistForm.reset();
    playlistForm.action = '/playlist-ekle';
    playlistTitle.textContent = 'Çalma Listesi Ekle';
    playlistForm.querySelector('[name="name"]').readOnly = false;
    setChecked('source', 'songs');
    setChecked('playback_type', 'general');
    setChecked('playback_order', 'shuffle');
    setSwitch('active', true);
    setSwitch('avoid_duplicates', true);
    setSwitch('show_on_public', true);
    playlistForm.querySelectorAll('[name="days"]').forEach((field) => field.checked = false);
    updateSourceFields();
    updatePlaybackFields();
}

function fillPlaylistForm(config) {
    resetPlaylistForm();
    playlistForm.action = `/playlist-duzenle/${encodeURIComponent(config.key)}`;
    playlistTitle.textContent = 'Çalma Listesi Düzenle';
    playlistForm.querySelector('[name="name"]').value = config.name || config.key || '';
    playlistForm.querySelector('[name="description"]').value = config.description || '';
    playlistForm.querySelector('[name="remote_url"]').value = config.remote_url || '';
    playlistForm.querySelector('[name="weight"]').value = config.weight || '3';
    playlistForm.querySelector('[name="interval_value"]').value = config.interval_value || '1';
    setSwitch('active', config.active !== false);
    setSwitch('include_requests', config.include_requests);
    setSwitch('avoid_duplicates', config.avoid_duplicates !== false);
    setSwitch('show_on_public', config.show_on_public !== false);
    setSwitch('hide_metadata', config.hide_metadata);
    setSwitch('interrupt_other', config.interrupt_other);
    setSwitch('scheduled_single_track', config.scheduled_single_track);
    setSwitch('merge', config.merge);
    setSwitch('prioritize_requests', config.prioritize_requests);
    setChecked('source', config.source || 'songs');
    setChecked('playback_type', config.playback_type || 'general');
    setChecked('playback_order', config.playback_order || 'shuffle');

    const schedule = config.schedule || {};
    playlistForm.querySelector('[name="start_time"]').value = schedule.start_time || '';
    playlistForm.querySelector('[name="end_time"]').value = schedule.end_time || '';
    playlistForm.querySelector('[name="start_date"]').value = schedule.start_date || '';
    playlistForm.querySelector('[name="end_date"]').value = schedule.end_date || '';
    setSwitch('once', schedule.once);
    const days = (schedule.days || []).map(String);
    playlistForm.querySelectorAll('[name="days"]').forEach((field) => {
        field.checked = days.includes(field.value);
    });
    updateSourceFields();
    updatePlaybackFields();
}

document.querySelectorAll('[data-source-radio]').forEach((radio) => radio.addEventListener('change', updateSourceFields));
document.querySelectorAll('[data-playback-type]').forEach((radio) => radio.addEventListener('change', updatePlaybackFields));
document.querySelectorAll('[data-playlist-new]').forEach((button) => button.addEventListener('click', resetPlaylistForm));
document.querySelectorAll('[data-playlist-edit]').forEach((button) => {
    button.addEventListener('click', () => fillPlaylistForm(JSON.parse(button.dataset.playlist || '{}')));
});

let draggedPlaylistKey = '';
document.querySelectorAll('.playlist-row[draggable="true"]').forEach((row) => {
    row.addEventListener('dragstart', (event) => {
        draggedPlaylistKey = row.dataset.playlistKey || '';
        row.classList.add('dragging');
        event.dataTransfer.effectAllowed = 'move';
        event.dataTransfer.setData('text/plain', draggedPlaylistKey);
    });
    row.addEventListener('dragend', () => {
        row.classList.remove('dragging');
        draggedPlaylistKey = '';
    });
});

document.querySelectorAll('.playlist-dropzone').forEach((zone) => {
    zone.addEventListener('dragover', (event) => {
        event.preventDefault();
        zone.classList.add('drag-over');
    });
    zone.addEventListener('dragleave', () => zone.classList.remove('drag-over'));
    zone.addEventListener('drop', async (event) => {
        event.preventDefault();
        zone.classList.remove('drag-over');
        const key = draggedPlaylistKey || event.dataTransfer.getData('text/plain');
        const group = zone.dataset.group;
        if (!key || !group || key === 'all') return;
        const form = new FormData();
        form.append('display_group', group);
        await fetch(`/playlist-grup/${encodeURIComponent(key)}`, {
            method: 'POST',
            headers: {'X-Requested-With': 'fetch'},
            body: form
        });
        window.location.reload();
    });
});

const playlistTracksTitle = document.getElementById('playlistTracksTitle');
const playlistTracksCount = document.getElementById('playlistTracksCount');
const playlistTracksBody = document.getElementById('playlistTracksBody');
document.querySelectorAll('.playlist-track-count').forEach((button) => {
    button.addEventListener('click', async () => {
        const key = button.dataset.playlistKey;
        playlistTracksTitle.textContent = button.dataset.playlistName || 'Çalma Listesi';
        playlistTracksCount.textContent = 'Yükleniyor...';
        playlistTracksBody.innerHTML = '<tr><td colspan="3" class="text-muted p-3">Yükleniyor...</td></tr>';
        try {
            const response = await fetch(`/api/playlist-parcalari/${encodeURIComponent(key)}`);
            const data = await response.json();
            playlistTracksTitle.textContent = data.name || button.dataset.playlistName || 'Çalma Listesi';
            playlistTracksCount.textContent = `${data.total || 0} şarkı`;
            if (!data.tracks || data.tracks.length === 0) {
                playlistTracksBody.innerHTML = '<tr><td colspan="3" class="text-muted p-3">Bu listede dosya yok.</td></tr>';
                return;
            }
            playlistTracksBody.innerHTML = data.tracks.map((track) => `
                <tr>
                    <td class="ps-3 text-muted">#${track.no}</td>
                    <td>
                        <div class="fw-semibold">${escapeHtml(track.name || '')}</div>
                        ${track.artist ? `<div class="small text-muted">${escapeHtml(track.artist)}</div>` : ''}
                    </td>
                    <td class="small text-muted">${escapeHtml(track.relative || track.path || '')}</td>
                </tr>
            `).join('');
        } catch (error) {
            playlistTracksCount.textContent = 'Açılamadı';
            playlistTracksBody.innerHTML = '<tr><td colspan="3" class="text-danger p-3">Şarkı listesi yüklenemedi.</td></tr>';
        }
    });
});

function escapeHtml(value) {
    return String(value).replace(/[&<>"']/g, (char) => ({
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
    }[char]));
}

document.querySelectorAll('.collapse[id$="AnonsRows"]').forEach((collapseEl) => {
    const group = collapseEl.id === 'normalAnonsRows' ? 'normal' : 'saat';
    const panel = document.querySelector(`[data-category-panel="${group}"]`);
    if (!panel) return;
    collapseEl.addEventListener('shown.bs.collapse', () => panel.classList.add('open'));
    collapseEl.addEventListener('hidden.bs.collapse', () => panel.classList.remove('open'));
});
playlistModal.addEventListener('hidden.bs.modal', resetPlaylistForm);
resetPlaylistForm();
</script>
<script src="/static/js/mobile-nav.js"></script>
</body>
</html>











