/* STREAMING_CHUNK:Alap CSS és Plex Theme Változók */
/* ALAP CSS VÁLTOZÓK ÉS PLEX THEME (Javított: Eredeti Sötét Palaszürke és Narancs/Arany) */
:root, body.theme-plex {
--th-bg: #191a1c;       /* Plex Dark Slate */
--th-panel: #282a2d;    /* Plex Lighter Slate */
--th-border: #3e4247;   /* Plex Border */
--th-primary: #e5a00d;  /* Plex Orange/Gold (Gamboge) */
--th-primary-hover: #cc8e0b;
--th-text-light: #f8fafc;
}

/* STREAMING_CHUNK:Netflix és HBO Max Téma Változók */
/* NETFLIX THEME */
body.theme-netflix {
--th-bg: #141414;       /* Netflix Black */
--th-panel: #1f1f1f;
--th-border: #2b2b2b;
--th-primary: #e50914;  /* Netflix Red */
--th-primary-hover: #b81d24;
}

/* HBO MAX THEME */
body.theme-hbomax {
--th-bg: #090211;       /* HBO Max Dark Purple */
--th-panel: #150529;
--th-border: #30195e;
--th-primary: #9d25d0;  /* Ripe Plum */
--th-primary-hover: #7b1fa2;
}

/* STREAMING_CHUNK:Disney+, SkyShowtime és Amazon Téma Változók */
/* DISNEY+ THEME */
body.theme-disney {
--th-bg: #040714;       /* Disney+ Dark Blue */
--th-panel: #1a1d29;
--th-border: #31343e;
--th-primary: #00e5ff;  /* Disney+ Genoa/Cyan */
--th-primary-hover: #00b8cc;
}

/* SKYSHOWTIME THEME */
body.theme-skyshowtime {
--th-bg: #000a1f;       /* SkyShowtime Dark Navy */
--th-panel: #00133d;
--th-border: #002266;
--th-primary: #00b0ff;  /* Medium Purple / Light Blue */
--th-primary-hover: #0088cc;
}

/* AMAZON PRIME VIDEO THEME */
body.theme-amazon {
--th-bg: #0f171e;       /* Prime Video Black/Navy */
--th-panel: #1a242f;
--th-border: #252f39;
--th-primary: #00a8e1;  /* Spanish Sky Blue */
--th-primary-hover: #0089b8;
}

/* STREAMING_CHUNK:Tailwind osztályok felülírása a témákhoz */
/* TÉMA ALKALMAZÁSA A TAILWIND OSZTÁLYOKRA */
body { background-color: var(--th-bg) !important; color: var(--th-text-light); font-family: ui-sans-serif, system-ui, -apple-system, sans-serif; }
.bg-slate-900, .bg-slate-900\/90, .bg-slate-900\/50, .bg-slate-950 { background-color: var(--th-bg) !important; }
.bg-slate-800 { background-color: var(--th-panel) !important; }
.border-slate-800, .border-slate-700, .border-slate-700\/50 { border-color: var(--th-border) !important; }

/* Bár Tailwindben fuchsia-ként vannak hivatkozva, a CSS felülírja a tényleges színt a var(--th-primary) értékre */
.text-fuchsia-500, .text-fuchsia-400 { color: var(--th-primary) !important; }
.bg-fuchsia-600 { background-color: var(--th-primary) !important; }
.bg-fuchsia-600:hover { background-color: var(--th-primary-hover) !important; }
.border-fuchsia-500 { border-color: var(--th-primary) !important; }
.focus\:border-fuchsia-500:focus { border-color: var(--th-primary) !important; }
.focus\:ring-fuchsia-500:focus { --tw-ring-color: var(--th-primary) !important; }
.tab-btn.active { border-bottom: 2px solid var(--th-primary) !important; color: var(--th-primary) !important; }

/* STREAMING_CHUNK:Egyéb stílusok, Grid, Scrollbar, Animációk */
/* SPECIÁLIS KÁRTYA STÍLUSOK (Éppen játszott) */
.tech-grid { display: grid; grid-template-columns: 85px 1fr; gap: 2px 10px; font-size: 11px; line-height: 1.3; }
.tech-label { color: #9ca3af; text-transform: uppercase; text-align: right; letter-spacing: 0.5px; }
.tech-value { color: #f3f4f6; font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

.hide { display: none !important; }
::-webkit-scrollbar { width: 8px; }
::-webkit-scrollbar-track { background: var(--th-bg); }
::-webkit-scrollbar-thumb { background: var(--th-border); border-radius: 4px; }
::-webkit-scrollbar-thumb:hover { background: #64748b; }

.modal-enter { animation: modalFadeIn 0.2s ease-out forwards; }
@keyframes modalFadeIn {
from { opacity: 0; transform: scale(0.95) translateY(-10px); }
to { opacity: 1; transform: scale(1) translateY(0); }
}

/* STREAMING_CHUNK:User Manager Specifikus stílusok és Üveggombok */
/* USER MANAGER SPECIFIKUS STÍLUSOK */
.modal-overlay { background-color: rgba(0, 0, 0, 0.75); backdrop-filter: blur(4px); }

/* --- ÜVEG GOMB ALAPSTÍLUS (Biztonság fülhöz) --- */
.glass-btn {
position: relative; display: inline-flex; align-items: center; justify-content: center;
border: 1px solid rgba(0, 0, 0, 0.8); border-radius: 999px;
color: #ffffff; font-weight: 700; text-shadow: 0px -1px 1px rgba(0,0,0,0.9), 0px 2px 4px rgba(0,0,0,0.8);
box-shadow: inset 0px -8px 20px rgba(255, 255, 255, 0.25), inset 0px 5px 15px rgba(0, 0, 0, 0.6), 0px 5px 15px rgba(0, 0, 0, 0.6);
transition: all 0.2s ease-in-out; overflow: hidden; cursor: pointer; text-decoration: none; z-index: 1;
}
.glass-btn::after {
content: ''; position: absolute; top: 2px; left: 3%; width: 94%; height: 45%;
background: linear-gradient(180deg, rgba(255,255,255,0.85) 0%, rgba(255,255,255,0.05) 100%);
border-radius: 999px 999px 150px 150px / 999px 999px 40px 40px; pointer-events: none; z-index: 2;
}
.glass-btn > * { position: relative; z-index: 3; }
.glass-btn-red { background: radial-gradient(circle at 50% 110%, #ff4d4d 0%, #590000 80%); box-shadow: inset 0px -8px 20px rgba(255, 100, 100, 0.4), inset 0px 5px 15px rgba(0, 0, 0, 0.8), 0px 5px 15px rgba(200, 0, 0, 0.5); }
.glass-btn-green { background: radial-gradient(circle at 50% 110%, #4dff4d 0%, #004d00 80%); box-shadow: inset 0px -8px 20px rgba(100, 255, 100, 0.4), inset 0px 5px 15px rgba(0, 0, 0, 0.8), 0px 5px 15px rgba(0, 150, 0, 0.5); }
.glass-btn-blue { background: radial-gradient(circle at 50% 110%, #66b3ff 0%, #00264d 80%); box-shadow: inset 0px -8px 20px rgba(100, 180, 255, 0.4), inset 0px 5px 15px rgba(0, 0, 0, 0.8), 0px 5px 15px rgba(0, 100, 200, 0.5); }
.glass-btn-amber { background: radial-gradient(circle at 50% 110%, #ffcc00 0%, #663300 80%); box-shadow: inset 0px -8px 20px rgba(255, 200, 100, 0.4), inset 0px 5px 15px rgba(0, 0, 0, 0.8), 0px 5px 15px rgba(200, 100, 0, 0.5); }
.glass-btn-gray { background: radial-gradient(circle at 50% 110%, #8c8c8c 0%, #1a1a1a 80%); box-shadow: inset 0px -8px 20px rgba(255, 255, 255, 0.2), inset 0px 5px 15px rgba(0, 0, 0, 0.9), 0px 5px 15px rgba(0, 0, 0, 0.6); }
.glass-btn-purple { background: radial-gradient(circle at 50% 110%, #a855f7 0%, #3b0764 80%); box-shadow: inset 0px -8px 20px rgba(168, 85, 247, 0.4), inset 0px 5px 15px rgba(0, 0, 0, 0.8), 0px 5px 15px rgba(107, 33, 168, 0.5); }
.glass-btn:hover { filter: brightness(1.2) contrast(1.1); transform: scale(1.02); }
.glass-btn:active { transform: scale(0.95); filter: brightness(0.8); }
.glass-btn-inactive { opacity: 0.6; transform: scale(0.98); }
.glass-btn-inactive:hover { opacity: 1; transform: scale(1.02); }
```eof

### 3. A `main.js` (Témaváltó logika és grafikon színezése kiegészítve)

```javascript:main.js
/* STREAMING_CHUNK:Globális állapotváltozók és Környezet ellenőrzése */
// --- GLOBAL STATE ---
let localDB = { users: {}, servers: [], system: {} };
let userManagerDB = { users: [] }; 
let currentUser = null; 

let allHistoryData = [];
let nowPlayingData = [];
let plexAccountNames = {}; 
let customUserNames = {}; 

let chartInstance = null;
let selectedUserId = null;

let nowPlayingInterval = null; 
let historyInterval = null;    

let isSyncingNowPlaying = false;
let isSyncingHistory = false;

// --- 0 LEJÁTSZÁS VÁLTOZÓK ---
let cachedUnplayedMovies = [];
let cachedUnplayedShows = [];
let visibleMoviesLimit = 60;
let visibleShowsLimit = 60;
const RENDER_CHUNK = 60;
let isFetchingUnplayed = false;

// --- USER MANAGER ÁLLAPOTVÁLTOZÓK ---
let umExpirationQueue = [];
let umCurrentExpiredUser = null;
let umIsRevenueVisible = true;

// --- PROFIT ÁLLAPOTVÁLTOZÓK ---
let profitDB = { expenses: {} };
const expenseGroups = ['Google 1', 'Google 2', 'OneDrive', 'Szerverek', 'Egyéb bevétel'];
let exchangeRates = { HUF: 1, EUR: 0.0025, USD: 0.0027, GBP: 0.0021, CHF: 0.0024, RON: 0.012, PLN: 0.011 };

// Környezet ellenőrzése
function isPreviewEnv() {
    return window.location.protocol === 'blob:' || window.location.protocol === 'data:' || window.location.protocol === 'file:' || (window.self !== window.top && window.location.hostname !== 'localhost' && window.location.hostname !== '127.0.0.1');
}

/* STREAMING_CHUNK:Téma kezelő rendszer */
// --- THEME SYSTEM ---
function applyTheme(theme) {
    document.getElementById('app-body').className = `min-h-screen ${theme}`;
    localStorage.setItem('mp_theme', theme);
    
    const headerSel = document.getElementById('theme-selector');
    const adminSel = document.getElementById('theme-selector-admin');
    if(headerSel) headerSel.value = theme;
    if(adminSel) adminSel.value = theme;

    if(chartInstance) {
        // Dinamikus grafikon szín beállítása a kiválasztott téma alapján
        let color = '#e5a00d'; // Plex default (Gamboge)
        if(theme === 'theme-netflix') color = '#e50914';
        else if(theme === 'theme-hbomax') color = '#9d25d0';
        else if(theme === 'theme-disney') color = '#00e5ff';
        else if(theme === 'theme-skyshowtime') color = '#00b0ff';
        else if(theme === 'theme-amazon') color = '#00a8e1';
        
        chartInstance.data.datasets[0].backgroundColor = color;
        chartInstance.update();
    }
}

/* STREAMING_CHUNK:Segédfüggvények (fetch, titkosítás, jelszó, adatbázis) */
async function fetchWithTimeout(resource, options = {}, timeout = 10000) {
    const controller = new AbortController();
    const id = setTimeout(() => controller.abort(), timeout);
    const response = await fetch(resource, { ...options, signal: controller.signal });
    clearTimeout(id);
    return response;
}

const OBF_KEY = "PlexMon";
function obfuscate(text) {
    let result = ''; for(let i=0; i<text.length; i++) result += String.fromCharCode(text.charCodeAt(i) ^ OBF_KEY.charCodeAt(i % OBF_KEY.length)); return btoa(result);
}
function deobfuscate(encoded) {
    try { const text = atob(encoded); let result = ''; for(let i=0; i<text.length; i++) result += String.fromCharCode(text.charCodeAt(i) ^ OBF_KEY.charCodeAt(i % OBF_KEY.length)); return result; } catch(e) { return encoded; } 
}

function getValidServerAuth(savedObj) {
    if (!localDB.servers || localDB.servers.length === 0) return savedObj || { url: '', token: '' };
    let match = localDB.servers.find(s => s.id === savedObj?.id);
    if (!match) match = localDB.servers.find(s => s.url === savedObj?.url);
    if (!match && localDB.servers.length === 1) match = localDB.servers[0];
    if (!match) match = localDB.servers[0];
    return { url: match.url, token: deobfuscate(match.token) };
}

async function hashPassword(username, password) {
    const msgBuffer = new TextEncoder().encode(username.toLowerCase() + password);
    const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
    const hashArray = Array.from(new Uint8Array(hashBuffer));
    return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}

async function fetchDB() {
    if(isPreviewEnv()) return false;
    try {
        const res = await fetch('/api/db?_t=' + Date.now());
        if (res.ok) {
            const data = await res.json();
            localDB = { users: data.users || {}, servers: Array.isArray(data.servers) ? data.servers : [], system: data.system || {} };
            
            if(localDB.system.history_backup) {
                try {
                    const parsedHist = JSON.parse(localDB.system.history_backup);
                    allHistoryData = Array.isArray(parsedHist) ? parsedHist.filter(i => i && i.serverObj && i.serverObj.url) : [];
                } catch(e) { allHistoryData = []; }
            }
            
            if(localDB.system.custom_names) try { customUserNames = JSON.parse(localDB.system.custom_names); } catch(e) {}
            if(localDB.system.plex_accounts) try { plexAccountNames = JSON.parse(localDB.system.plex_accounts); } catch(e) {}
            
            if(localDB.system.unplayed_cache) {
                try {
                    const parsed = JSON.parse(localDB.system.unplayed_cache);
                    
                    const uniqueM = new Map();
                    parsed.m.forEach(x => {
                        const key = x.rK || x.t;
                        if (!uniqueM.has(key)) uniqueM.set(key, { title: x.t, year: x.y, thumb: x.th, addedAt: x.a || 0, genres: x.g || [], countries: x.c || [], libraryName: x.lN, serverObj: {url: x.sU, token: x.sT}, ratingKey: x.rK });
                    });
                    cachedUnplayedMovies = Array.from(uniqueM.values());
                    
                    const uniqueS = new Map();
                    parsed.s.forEach(x => {
                        const key = x.rK || x.t;
                        if (!uniqueS.has(key)) uniqueS.set(key, { title: x.t, year: x.y, thumb: x.th, addedAt: x.a || 0, genres: x.g || [], countries: x.c || [], libraryName: x.lN, serverObj: {url: x.sU, token: x.sT}, ratingKey: x.rK });
                    });
                    cachedUnplayedShows = Array.from(uniqueS.values());
                    
                    if (typeof window.populateUnplayedDropdowns === 'function') {
                        window.populateUnplayedDropdowns();
                    }
                } catch(e) { cachedUnplayedMovies = []; cachedUnplayedShows = []; }
            }
            return true;
        }
    } catch(e) { return false; }
}

async function saveDB() {
    if(isPreviewEnv()) return;
    try {
        localDB.system.history_backup = JSON.stringify(allHistoryData.slice(0, 15000));
        localDB.system.custom_names = JSON.stringify(customUserNames);
        localDB.system.plex_accounts = JSON.stringify(plexAccountNames);
        
        const slimUnplayed = { 
            m: cachedUnplayedMovies.map(m => ({ t: m.title, y: m.year, th: m.thumb, a: m.addedAt, g: m.genres, c: m.countries, lN: m.libraryName, sU: m.serverObj.url, sT: m.serverObj.token, rK: m.ratingKey })), 
            s: cachedUnplayedShows.map(s => ({ t: s.title, y: s.year, th: s.thumb, a: s.addedAt, g: s.genres, c: s.countries, lN: s.libraryName, sU: s.serverObj.url, sT: s.serverObj.token, rK: s.ratingKey })) 
        };
        localDB.system.unplayed_cache = JSON.stringify(slimUnplayed);

        document.getElementById('sync-indicator').classList.remove('hide');
        await fetch('/api/db', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(localDB)
        });
        setTimeout(() => document.getElementById('sync-indicator').classList.add('hide'), 1500);
    } catch(e) {}
}

/* STREAMING_CHUNK:Modális és Riasztás kezelők */
window.showAlert = (title, message, isError = false) => {
    document.getElementById('alert-title').textContent = title;
    document.getElementById('alert-msg').textContent = message;
    document.getElementById('alert-icon').className = `ph text-4xl mb-3 ${isError ? 'ph-warning-circle text-red-500' : 'ph-check-circle text-emerald-500'}`;
    document.getElementById('modal-alert').classList.remove('hide');
}
window.closeAlert = () => document.getElementById('modal-alert').classList.add('hide');

window.openPasswordModal = () => { ['pwd-old', 'pwd-new'].forEach(id => document.getElementById(id).value = ''); document.getElementById('pwd-msg').classList.add('hide'); document.getElementById('modal-password').classList.remove('hide'); }
window.closePasswordModal = () => document.getElementById('modal-password').classList.add('hide');

window.saveNewPassword = async () => {
    const oldP = document.getElementById('pwd-old').value, newP = document.getElementById('pwd-new').value, msgBox = document.getElementById('pwd-msg');
    if(!oldP || !newP) return;
    const oldHash = await hashPassword(currentUser.name, oldP);
    if (oldHash !== currentUser.password) { msgBox.textContent = "A régi jelszó helytelen!"; msgBox.className = "text-sm p-2 rounded mb-3 bg-red-900/50 text-red-200 border border-red-500"; msgBox.classList.remove('hide'); return; }
    if(newP.length < 4) { msgBox.textContent = "Az új jelszó túl rövid!"; msgBox.className = "text-sm p-2 rounded mb-3 bg-amber-900/50 text-amber-200 border border-amber-500"; msgBox.classList.remove('hide'); return; }
    
    currentUser.password = await hashPassword(currentUser.name, newP); 
    localDB.users[currentUser.id] = currentUser;
    if(localStorage.getItem('mp_currentUser')) localStorage.setItem('mp_currentUser', JSON.stringify(currentUser)); else sessionStorage.setItem('mp_currentUser', JSON.stringify(currentUser));
    await saveDB(); closePasswordModal(); showAlert("Siker", "A jelszavad megváltozott!");
}

window.openRenameModal = (uid) => { document.getElementById('rename-uid').value = uid; document.getElementById('rename-input').value = customUserNames[uid] || plexAccountNames[uid] || ''; document.getElementById('modal-rename').classList.remove('hide'); }
window.closeRenameModal = () => document.getElementById('modal-rename').classList.add('hide');
window.saveRenamedUser = async () => {
    const uid = document.getElementById('rename-uid').value, newName = document.getElementById('rename-input').value.trim();
    if(newName) { customUserNames[uid] = newName; await saveDB(); closeRenameModal(); if (typeof window.processDataAndRender === 'function') window.processDataAndRender(); }
}

window.generateId = () => Math.random().toString(36).substr(2, 9);
window.getTodayStr = () => new Date().toISOString().split('T')[0];
window.addMonthsToDate = (dateStr, months) => {
    const date = new Date(dateStr);
    date.setMonth(date.getMonth() + parseInt(months));
    return date.toISOString().split('T')[0];
};
window.formatDateHu = (dateStr) => {
    if (!dateStr) return '';
    return new Date(dateStr).toLocaleDateString('hu-HU');
};
window.showNotif = (msg, isError = false) => {
    let container = document.getElementById('notif-container');
    if (!container) {
        container = document.createElement('div');
        container.id = 'notif-container';
        container.className = 'fixed bottom-4 right-4 z-[70] flex flex-col gap-2 pointer-events-none';
        document.body.appendChild(container);
    }
    const notif = document.createElement('div');
    notif.className = `border px-4 py-3 rounded shadow-lg flex items-center justify-between gap-4 transform transition-all duration-300 translate-y-10 opacity-0 pointer-events-auto ${isError ? 'bg-red-900 border-red-700 text-red-100' : 'bg-slate-800 border-slate-600 text-white'}`;
    notif.innerHTML = `<span>${msg}</span><button onclick="this.parentElement.remove()" class="text-slate-400 hover:text-white"><i class="fas fa-times"></i></button>`;
    container.appendChild(notif);
    setTimeout(() => notif.classList.remove('translate-y-10', 'opacity-0'), 10);
    setTimeout(() => {
        notif.classList.add('translate-y-10', 'opacity-0');
        setTimeout(() => notif.remove(), 300);
    }, 4000);
};

/* STREAMING_CHUNK:Bejelentkezési logika és Nézet váltások */
function showView(view) {
    ['view-login', 'view-pending', 'view-app'].forEach(id => document.getElementById(id).classList.add('hide'));
    if (view === 'login') document.getElementById('view-login').classList.remove('hide');
    if (view === 'pending') document.getElementById('view-pending').classList.remove('hide');
    if (view === 'app') {
        document.getElementById('view-app').classList.remove('hide');
        document.getElementById('user-name-display').textContent = currentUser.name;
        document.getElementById('user-avatar').textContent = currentUser.name.charAt(0).toUpperCase();
        
        const isAdmin = currentUser.role === 'admin';
        document.getElementById('tab-admin').classList.toggle('hide', !isAdmin);
        document.getElementById('tab-usermanager').classList.toggle('hide', !isAdmin); 
        document.getElementById('tab-profit').classList.toggle('hide', !isAdmin); 
        document.getElementById('tab-security').classList.toggle('hide', !isAdmin); 
    }
}

function logout() {
    localStorage.removeItem('mp_currentUser'); sessionStorage.removeItem('mp_currentUser');
    currentUser = null;
    if(nowPlayingInterval) clearInterval(nowPlayingInterval); 
    if(historyInterval) clearInterval(historyInterval); 
    showView('login');
}

async function handleLogin(e) {
    e.preventDefault();
    const nameInput = document.getElementById('login-name').value.trim(), passInput = document.getElementById('login-password').value;
    const rememberMe = document.getElementById('login-remember').checked;
    document.getElementById('login-error').classList.add('hide');
    if (!nameInput || !passInput) return;
    
    await fetchDB();
    const userId = nameInput.toLowerCase().replace(/[^a-z0-9]/g, '');
    const passHash = await hashPassword(nameInput, passInput);
    
    if (localDB.users[userId]) {
        const user = localDB.users[userId];
        if (!user.password) { user.password = passHash; currentUser = user; localDB.users[userId] = user; await saveDB(); } 
        else if (user.password !== passHash) { const err = document.getElementById('login-error'); err.textContent = "Hibás jelszó!"; err.classList.remove('hide'); return; } 
        else currentUser = user;
    } else {
        const newUser = { id: userId, name: nameInput, role: Object.keys(localDB.users).length === 0 ? 'admin' : 'pending', password: passHash, createdAt: new Date().toISOString() };
        localDB.users[userId] = newUser; currentUser = newUser; await saveDB();
    }
    
    if(rememberMe) localStorage.setItem('mp_currentUser', JSON.stringify(currentUser)); else sessionStorage.setItem('mp_currentUser', JSON.stringify(currentUser));

    if (currentUser.role === 'pending') showView('pending'); 
    else {
        showView('app'); document.getElementById('loading-overlay').classList.add('hide'); document.getElementById('content-area').classList.remove('hide');
        if (currentUser.role === 'admin') { 
            if (typeof window.renderAdminUsers === 'function') window.renderAdminUsers(); 
            if (typeof window.renderAdminServers === 'function') window.renderAdminServers(); 
            if (typeof window.fetchUserManagerDB === 'function') window.fetchUserManagerDB();
            if (typeof window.fetchRates === 'function') window.fetchRates();
            if (typeof window.fetchProfitDB === 'function') window.fetchProfitDB();
        }
        if (allHistoryData.length > 0 && typeof window.processDataAndRender === 'function') window.processDataAndRender();
        if (typeof window.syncNowPlaying === 'function') {
            window.syncNowPlaying(); 
            if(!nowPlayingInterval) nowPlayingInterval = setInterval(window.syncNowPlaying, 5000); 
        }
        if (typeof window.syncHistory === 'function') {
            window.syncHistory();
            if(!historyInterval) historyInterval = setInterval(window.syncHistory, 60000);
        }
    }
    e.target.reset();
}

/* STREAMING_CHUNK:Alkalmazás Inicializálása (Init) */
async function init() {
    document.getElementById('theme-selector').addEventListener('change', (e) => applyTheme(e.target.value));
    document.getElementById('theme-selector-admin').addEventListener('change', (e) => applyTheme(e.target.value));
    const savedTheme = localStorage.getItem('mp_theme') || 'theme-plex';
    applyTheme(savedTheme);

    await fetchDB(); 

    const savedUser = localStorage.getItem('mp_currentUser') || sessionStorage.getItem('mp_currentUser');

    if (savedUser) { 
        currentUser = JSON.parse(savedUser); 
        
        if(Object.keys(localDB.users).length > 0 && !localDB.users[currentUser.id]) { logout(); return; } 
        else if(Object.keys(localDB.users).length === 0) localDB.users[currentUser.id] = currentUser; 

        if (currentUser.role === 'pending') { showView('pending'); } 
        else {
            showView('app');
            document.getElementById('loading-overlay').classList.add('hide');
            document.getElementById('content-area').classList.remove('hide');
            
            if (currentUser.role === 'admin') { 
                if (typeof window.renderAdminUsers === 'function') window.renderAdminUsers(); 
                if (typeof window.renderAdminServers === 'function') window.renderAdminServers(); 
                if (typeof window.fetchUserManagerDB === 'function') window.fetchUserManagerDB(); 
                if (typeof window.fetchRates === 'function') window.fetchRates();
                if (typeof window.fetchProfitDB === 'function') window.fetchProfitDB();
            }
            if (allHistoryData.length > 0 && typeof window.processDataAndRender === 'function') window.processDataAndRender();

            if (typeof window.syncNowPlaying === 'function') {
                window.syncNowPlaying(); 
                if(!nowPlayingInterval) nowPlayingInterval = setInterval(window.syncNowPlaying, 5000); 
            }
            if (typeof window.syncHistory === 'function') {
                window.syncHistory();
                if(!historyInterval) historyInterval = setInterval(window.syncHistory, 60000);       
            }
        }
    } else showView('login');

    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.addEventListener('click', async (e) => {
            document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
            const targetBtn = e.target.closest('.tab-btn');
            targetBtn.classList.add('active');
            const targetId = targetBtn.getAttribute('data-target');
            
            document.querySelectorAll('[id^="tab-content-"]').forEach(c => c.classList.add('hide'));
            document.getElementById('tab-content-' + targetId).classList.remove('hide');
            
            if(targetId === 'dashboard' && chartInstance) chartInstance.update();
            if(targetId === 'unplayed' && (cachedUnplayedMovies.length > 0 || cachedUnplayedShows.length > 0)) {
                document.getElementById('unplayed-loading').classList.add('hide'); 
                document.getElementById('unplayed-filters').classList.remove('hide'); 
                document.getElementById('unplayed-content').classList.remove('hide'); 
                if (typeof window.renderUnplayed === 'function') window.renderUnplayed(true);
            }
        });
    });

    const timeFilter = document.getElementById('time-filter');
    if(timeFilter) timeFilter.addEventListener('change', () => { if (typeof window.processDataAndRender === 'function') window.processDataAndRender(); });
    
    const mediaSearch = document.getElementById('media-search');
    if(mediaSearch) mediaSearch.addEventListener('input', () => { if (typeof window.renderMedia === 'function') window.renderMedia(); });
    
    const mediaSort = document.getElementById('media-sort');
    if(mediaSort) mediaSort.addEventListener('change', () => { if (typeof window.renderMedia === 'function') window.renderMedia(); });
    
    const mediaType = document.getElementById('media-type');
    if(mediaType) mediaType.addEventListener('change', () => { if (typeof window.renderMedia === 'function') window.renderMedia(); });
    
    document.getElementById('btn-logout').addEventListener('click', logout);
    document.getElementById('btn-logout-pending').addEventListener('click', logout);
    
    const btnAddServer = document.getElementById('btn-add-server');
    if (btnAddServer) btnAddServer.addEventListener('click', (e) => { if (typeof window.handleAddServer === 'function') window.handleAddServer(e); });
    
    document.getElementById('login-form').addEventListener('submit', handleLogin);
}

window.addEventListener('DOMContentLoaded', init);
```eof
