// ==========================================
// athlete.js - مدیریت کلاینت ها و برنامه‌ها
// هماهنگ با gym-program-bundle.js (a.js)
// Desktop App Version - Minimal & Clean
// ==========================================

// کلیدهای localStorage - هماهنگ با a.js
const STUDENTS_KEY = "gym-students-v2";
const CATEGORIES_KEY = "gym-categories-v2";
const SETTINGS_KEY = "gym-settings-v2";
const THEME_KEY = "gym-theme-v2";
const ACTIVE_PROGRAM_KEY = "gym-active-program-v2";
const PROGRAM_META_PREFIX = "gym-program-meta::";
const PROGRAM_DAYS_PREFIX = "gym-program-days::";

// ============================
// توابع ذخیره و بازیابی
// ============================
function loadStudents() {
    try {
        return JSON.parse(localStorage.getItem(STUDENTS_KEY)) || [];
    } catch (e) {
        return [];
    }
}

function saveStudents(s) {
    localStorage.setItem(STUDENTS_KEY, JSON.stringify(s));
}

function loadCategories() {
    try {
        const r = localStorage.getItem(CATEGORIES_KEY);
        if (r) return JSON.parse(r);
    } catch (e) {}
    const d = [
        { id: 'default-recovery', name: 'بازیابی' },
        { id: 'default-bulk', name: 'حجم‌گیری' },
        { id: 'default-archive', name: 'آرشیو' }
    ];
    saveCategories(d);
    return d;
}

function saveCategories(c) {
    localStorage.setItem(CATEGORIES_KEY, JSON.stringify(c));
}

function uid() {
    return Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
}

function loadSettings() {
    try {
        return JSON.parse(localStorage.getItem(SETTINGS_KEY)) || {};
    } catch (e) {
        return {};
    }
}

function saveSettingsData(d) {
    localStorage.setItem(SETTINGS_KEY, JSON.stringify(d));
}

// ==========================================
// IndexedDB - Photos & Logo Storage
// ==========================================

const PHOTO_DB_NAME = "gym-photo-db";
const PHOTO_STORE = "photos";
const LOGO_STORE = "logo";
const PHOTO_DB_VERSION = 2;

let photoDb = null;
let logoDb = null;

async function openPhotoDB() {
    if (photoDb) return photoDb;

    return new Promise((resolve, reject) => {
        const request = indexedDB.open(PHOTO_DB_NAME, PHOTO_DB_VERSION);

        request.onupgradeneeded = event => {
            const db = event.target.result;
            if (!db.objectStoreNames.contains(PHOTO_STORE)) {
                db.createObjectStore(PHOTO_STORE, { keyPath: "id" });
            }
            if (!db.objectStoreNames.contains(LOGO_STORE)) {
                db.createObjectStore(LOGO_STORE, { keyPath: "id" });
            }
        };

        request.onsuccess = () => {
            photoDb = request.result;
            resolve(photoDb);
        };

        request.onerror = () => reject(request.error);

        request.onblocked = () => {
            console.warn('Database blocked, retrying...');
            setTimeout(() => {
                const retryRequest = indexedDB.open(PHOTO_DB_NAME, PHOTO_DB_VERSION);
                retryRequest.onsuccess = () => {
                    photoDb = retryRequest.result;
                    resolve(photoDb);
                };
                retryRequest.onerror = () => reject(retryRequest.error);
            }, 500);
        };
    });
}

async function openLogoDB() {
    return openPhotoDB();
}

async function savePhoto(file) {
    const db = await openPhotoDB();
    const id = "photo_" + Date.now() + "_" + Math.random().toString(36).substring(2, 10);

    return new Promise((resolve, reject) => {
        try {
            const tx = db.transaction(PHOTO_STORE, "readwrite");
            tx.objectStore(PHOTO_STORE).put({ id, blob: file });
            tx.oncomplete = () => resolve(id);
            tx.onerror = () => reject(tx.error);
        } catch (error) {
            reject(error);
        }
    });
}

async function loadPhoto(id) {
    const db = await openPhotoDB();

    return new Promise((resolve, reject) => {
        try {
            const tx = db.transaction(PHOTO_STORE, "readonly");
            const request = tx.objectStore(PHOTO_STORE).get(id);

            request.onsuccess = () => {
                if (!request.result) {
                    resolve(null);
                    return;
                }
                resolve(request.result.blob);
            };

            request.onerror = () => reject(request.error);
        } catch (error) {
            resolve(null);
        }
    });
}

async function deletePhoto(id) {
    const db = await openPhotoDB();

    return new Promise((resolve, reject) => {
        try {
            const tx = db.transaction(PHOTO_STORE, "readwrite");
            tx.objectStore(PHOTO_STORE).delete(id);
            tx.oncomplete = () => resolve();
            tx.onerror = () => reject(tx.error);
        } catch (error) {
            reject(error);
        }
    });
}

async function getPhotoUrl(id) {
    try {
        const blob = await loadPhoto(id);
        if (!blob) return null;
        return URL.createObjectURL(blob);
    } catch (error) {
        console.error('Error getting photo URL:', error);
        return null;
    }
}

async function saveLogo(file) {
    const db = await openLogoDB();

    return new Promise((resolve, reject) => {
        try {
            const tx = db.transaction(LOGO_STORE, "readwrite");
            const store = tx.objectStore(LOGO_STORE);
            store.clear();
            store.put({ id: "gym-logo", blob: file });
            tx.oncomplete = () => resolve("gym-logo");
            tx.onerror = () => reject(tx.error);
        } catch (error) {
            reject(error);
        }
    });
}

async function loadLogo() {
    const db = await openLogoDB();

    return new Promise((resolve, reject) => {
        try {
            const tx = db.transaction(LOGO_STORE, "readonly");
            const request = tx.objectStore(LOGO_STORE).get("gym-logo");

            request.onsuccess = () => {
                if (!request.result) {
                    resolve(null);
                    return;
                }
                resolve(request.result.blob);
            };

            request.onerror = () => reject(request.error);
        } catch (error) {
            resolve(null);
        }
    });
}

async function deleteLogo() {
    const db = await openLogoDB();

    return new Promise((resolve, reject) => {
        try {
            const tx = db.transaction(LOGO_STORE, "readwrite");
            tx.objectStore(LOGO_STORE).delete("gym-logo");
            tx.oncomplete = () => resolve();
            tx.onerror = () => reject(tx.error);
        } catch (error) {
            reject(error);
        }
    });
}

async function getLogoUrl() {
    try {
        const blob = await loadLogo();
        if (!blob) return null;
        return URL.createObjectURL(blob);
    } catch (error) {
        return null;
    }
}

// ============================
// توابع کمکی برای برنامه‌ها
// ============================
function createDefaultDays() {
    return [
        { name: "جلسه ۱", items: [] },
        { name: "جلسه ۲", items: [] },
        { name: "جلسه ۳", items: [] }
    ];
}

function createEmptyProgramData(studentName = "") {
    return {
        days: createDefaultDays(),
        clipboard: null,
        studentName: studentName || ""
    };
}

function getProgramStorageKey(studentId, programId, type) {
    const prefix = type === 'meta' ? PROGRAM_META_PREFIX : PROGRAM_DAYS_PREFIX;
    return `${prefix}${studentId}::${programId}`;
}

// ============================
// State
// ============================
let students = loadStudents();
let categories = loadCategories();
let activeCategory = 'all';
let searchQuery = '';
let editingStudentId = null;
let selectedStudent = null;
let tempPhotos = [];
let tempPhotoUrls = new Map();
let currentLogoUrl = null;

// ============================
// DOM Elements
// ============================
const studentsGrid = document.getElementById('studentsGrid');
const searchInput = document.getElementById('searchInput');
const categoriesRow = document.getElementById('categoriesRow');
const studentModal = document.getElementById('studentModal');
const detailPanel = document.getElementById('detailPanel');
const photoInput = document.getElementById('photoInput');

// ============================
// رندر دسته‌بندی‌ها
// ============================
function renderCategories() {
    if (!categoriesRow) return;

    // حذف فقط category-chip ها و wrapper های قبلی
    const existingChips = categoriesRow.querySelectorAll('.category-chip');
    existingChips.forEach(c => c.remove());

    const existingWrappers = categoriesRow.querySelectorAll('div[style*="position: relative"]');
    existingWrappers.forEach(w => w.remove());

    const addBtn = document.getElementById('addCategoryBtn');
    if (!addBtn) return;

    // دکمه همه
    const allChip = document.createElement('button');
    allChip.className = 'category-chip' + (activeCategory === 'all' ? ' active' : '');
    allChip.dataset.category = 'all';
    allChip.textContent = 'همه';
    allChip.addEventListener('click', () => {
        activeCategory = 'all';
        renderCategories();
        renderStudents();
    });
    categoriesRow.insertBefore(allChip, addBtn);

    // دسته‌بندی‌ها
    categories.forEach(cat => {
        const wrapper = document.createElement('div');
        wrapper.style.cssText = 'position:relative;display:inline-flex;align-items:center;';

        const chip = document.createElement('button');
        chip.className = 'category-chip' + (activeCategory === cat.id ? ' active' : '');
        chip.dataset.category = cat.id;
        chip.textContent = cat.name;
        chip.addEventListener('click', () => {
            activeCategory = cat.id;
            renderCategories();
            renderStudents();
        });
        wrapper.appendChild(chip);

        const delBtn = document.createElement('button');
        delBtn.textContent = '✕';
        delBtn.style.cssText = 'position:absolute;top:-4px;right:-4px;width:16px;height:16px;border-radius:50%;border:1px solid #e5e7eb;background:#fff;color:#6b7280;cursor:pointer;font-size:8px;display:flex;align-items:center;justify-content:center;opacity:0;transition:all 0.2s ease;padding:0;';
        delBtn.addEventListener('click', e => {
            e.stopPropagation();
            if (confirm(`دسته‌بندی "${cat.name}" حذف شود؟`)) {
                categories = categories.filter(c => c.id !== cat.id);
                saveCategories(categories);
                if (activeCategory === cat.id) activeCategory = 'all';
                renderCategories();
                renderStudents();
            }
        });
        wrapper.addEventListener('mouseenter', () => {
            delBtn.style.opacity = '1';
        });
        wrapper.addEventListener('mouseleave', () => {
            delBtn.style.opacity = '0';
        });
        wrapper.appendChild(delBtn);
        categoriesRow.insertBefore(wrapper, addBtn);
    });

    // آپدیت select دسته‌بندی توی مودال
    const select = document.getElementById('studentCategory');
    if (select) {
        select.innerHTML = '<option value="">بدون دسته‌بندی</option>';
        categories.forEach(c => select.innerHTML += `<option value="${c.id}">${c.name}</option>`);
    }
}

// ============================
// رندر کلاینت ها
// ============================
function renderStudents() {
    if (!studentsGrid) return;

    const filtered = students.filter(s =>
        (activeCategory === 'all' || s.category === activeCategory) &&
        (!searchQuery || (s.name && s.name.includes(searchQuery)) || (s.phone && s.phone.includes(searchQuery)))
    );

    if (!filtered.length) {
        studentsGrid.innerHTML = '<div class="empty-state"><div class="empty-state-icon">👥</div><h3>هیچ کلاینتی پیدا نشد</h3><p>برای شروع اولین کلاینت خود را اضافه کنید</p></div>';
        return;
    }

    studentsGrid.innerHTML = filtered.map(s => `
        <div class="student-card" onclick="openStudentDetail('${s.id}')">
            <div class="student-card-top">
                <div class="student-avatar">
                    <img class="student-photo" data-photo-id="${s.photos?.[0] ?? ''}" style="${!s.photos?.length ? 'display:none' : ''}" />
                    <span class="student-avatar-fallback" style="${s.photos?.length ? 'display:none' : ''}">👤</span>
                </div>
                <div class="student-info">
                    <h3>${s.name || 'بدون نام'}</h3>
                    <span class="student-meta">${s.programs && s.programs.length ? s.programs.length + ' برنامه' : 'بدون برنامه'}</span>
                </div>
            </div>
        </div>
    `).join('');

    // با تاخیر کم عکس‌ها رو لود کن تا DOM آماده بشه
    setTimeout(() => {
        loadStudentCardPhotos();
    }, 50);
}

async function loadStudentCardPhotos() {
    const images = document.querySelectorAll(".student-photo");

    for (const img of images) {
        const id = img.dataset.photoId;
        if (!id) continue;

        try {
            const url = await getPhotoUrl(id);
            if (url && img) {
                img.src = url;
                img.style.display = '';
                const fallback = img.parentElement?.querySelector('.student-avatar-fallback');
                if (fallback) {
                    fallback.style.display = 'none';
                }
            }
        } catch (error) {
            console.error('Error loading photo:', error);
            if (img) {
                img.style.display = 'none';
                const fallback = img.parentElement?.querySelector('.student-avatar-fallback');
                if (fallback) {
                    fallback.style.display = '';
                }
            }
        }
    }
}

// ============================
// Navigation - Desktop App
// ============================
function navigateTo(pageName) {
    const pages = document.querySelectorAll('.page');
    const sidebarLinks = document.querySelectorAll('.sidebar-link');

    // مخفی کردن همه صفحات
    pages.forEach(p => p.classList.remove('active'));

    // غیرفعال کردن همه لینک‌ها
    sidebarLinks.forEach(l => l.classList.remove('active'));

    // نمایش صفحه مورد نظر
    const pageMap = {
        'welcome': 'welcomeSection',
        'students': 'studentsSection',
        'settings': 'settingsSection'
    };

    const targetId = pageMap[pageName] || 'welcomeSection';
    const targetPage = document.getElementById(targetId);
    if (targetPage) {
        targetPage.classList.add('active');
    }

    // فعال کردن لینک مربوطه
    const activeLink = document.querySelector(`.sidebar-link[data-page="${pageName}"]`);
    if (activeLink) {
        activeLink.classList.add('active');
    }
}

// مودال افزودن/ویرایش کلاینت
function openModal(student = null) {
    editingStudentId = student ? student.id : null;
    tempPhotos = student?.photos ? [...student.photos] : [];
    tempPhotoUrls.clear();

    document.getElementById('modalTitle').textContent = student ? 'ویرایش کلاینت' : 'افزودن کلاینت جدید';
    document.getElementById('studentName').value = student ? student.name || '' : '';
    document.getElementById('studentPhone').value = student ? student.phone || '' : '';
    document.getElementById('studentHeight').value = student ? student.height || '' : '';
    document.getElementById('studentWeight').value = student ? student.weight || '' : '';
    document.getElementById('studentArm').value = student ? student.arm || '' : '';
    document.getElementById('studentThigh').value = student ? student.thigh || '' : '';
    document.getElementById('studentWaist').value = student ? student.waist || '' : '';
    document.getElementById('studentNotes').value = student ? student.notes || '' : '';
    document.getElementById('studentCategory').value = student ? student.category || '' : '';
    document.getElementById('studentId').value = student ? student.id : '';

    renderPhotos();
    studentModal.classList.add('active');
}

function closeModal() {
    studentModal.classList.remove('active');
    editingStudentId = null;
    for (const url of tempPhotoUrls.values()) {
        URL.revokeObjectURL(url);
    }
    tempPhotoUrls.clear();
    tempPhotos = [];
}

async function renderPhotos() {
    const container = document.getElementById("photosContainer");
    if (!container) return;

    container.innerHTML = "";

    for (let i = 0; i < tempPhotos.length; i++) {
        const id = tempPhotos[i];
        let url = tempPhotoUrls.get(id);
        if (!url) {
            url = await getPhotoUrl(id);
            if (url) tempPhotoUrls.set(id, url);
        }

        const div = document.createElement("div");
        div.className = "photo-upload";
        div.innerHTML = `<img src="${url}"><button class="remove-photo">✕</button>`;

        div.querySelector(".remove-photo").addEventListener("click", async e => {
            e.stopPropagation();
            await deletePhoto(id);
            const objectUrl = tempPhotoUrls.get(id);
            if (objectUrl) {
                URL.revokeObjectURL(objectUrl);
                tempPhotoUrls.delete(id);
            }
            tempPhotos.splice(i, 1);
            renderPhotos();
        });

        container.appendChild(div);
    }

    if (tempPhotos.length < 5) {
        const add = document.createElement("div");
        add.className = "photo-upload";
        add.textContent = "+";
        add.onclick = () => photoInput.click();
        container.appendChild(add);
    }
}

// ============================
// Event Listeners
// ============================

// Navigation
document.querySelectorAll('.sidebar-link').forEach(link => {
    link.addEventListener('click', () => {
        const page = link.dataset.page;
        navigateTo(page);
    });
});

// Title bar settings button
const goToSettingsBtn = document.getElementById('goToSettings');
if (goToSettingsBtn) {
    goToSettingsBtn.addEventListener('click', () => navigateTo('settings'));
}

// Back to students button (in settings page)
const backToStudentsBtn = document.getElementById('backToStudents');
if (backToStudentsBtn) {
    backToStudentsBtn.addEventListener('click', () => navigateTo('students'));
}

// Add student from nav
const navAddStudentBtn = document.getElementById('navAddStudent');
if (navAddStudentBtn) {
    navAddStudentBtn.addEventListener('click', () => {
        navigateTo('students');
        setTimeout(() => openModal(), 100);
    });
}

// Welcome page CTA button
const goToStudentsFromWelcome = document.getElementById('goToStudentsFromWelcome');
if (goToStudentsFromWelcome) {
    goToStudentsFromWelcome.addEventListener('click', () => {
        navigateTo('students');
    });
}

// Modal events
const addPhotoBtn = document.getElementById('addPhotoBtn');
if (addPhotoBtn) {
    addPhotoBtn.addEventListener('click', () => photoInput.click());
}

if (photoInput) {
    photoInput.addEventListener("change", async e => {
        const files = Array.from(e.target.files).slice(0, 5 - tempPhotos.length);
        for (const file of files) {
            const photoId = await savePhoto(file);
            tempPhotos.push(photoId);
            tempPhotoUrls.set(photoId, URL.createObjectURL(file));
        }
        photoInput.value = "";
        renderPhotos();
    });
}

const studentForm = document.getElementById('studentForm');
if (studentForm) {
    studentForm.addEventListener('submit', e => {
        e.preventDefault();
        const d = {
            id: editingStudentId || uid(),
            name: document.getElementById('studentName').value.trim(),
            phone: document.getElementById('studentPhone').value.trim(),
            height: document.getElementById('studentHeight').value,
            weight: document.getElementById('studentWeight').value,
            arm: document.getElementById('studentArm').value,
            thigh: document.getElementById('studentThigh').value,
            waist: document.getElementById('studentWaist').value,
            notes: document.getElementById('studentNotes').value.trim(),
            category: document.getElementById('studentCategory').value,
            photos: [...tempPhotos],
            programs: editingStudentId ? (students.find(s => s.id === editingStudentId)?.programs || []) : [],
            createdAt: editingStudentId ? (students.find(s => s.id === editingStudentId)?.createdAt || new Date().toISOString()) : new Date().toISOString()
        };
        students = editingStudentId ? students.map(s => s.id === editingStudentId ? d : s) : [...students, d];
        saveStudents(students);
        closeModal();
        renderStudents();
    });
}

const cancelModalBtn = document.getElementById('cancelModal');
if (cancelModalBtn) {
    cancelModalBtn.addEventListener('click', closeModal);
}

const addStudentBtn = document.getElementById('addStudentBtn');
if (addStudentBtn) {
    addStudentBtn.addEventListener('click', () => openModal());
}

const addCategoryBtn = document.getElementById('addCategoryBtn');
if (addCategoryBtn) {
    addCategoryBtn.addEventListener('click', () => {
        const n = prompt('نام دسته‌بندی جدید:');
        if (n && n.trim()) {
            categories.push({ id: uid(), name: n.trim() });
            saveCategories(categories);
            renderCategories();
        }
    });
}

if (studentModal) {
    studentModal.addEventListener('click', e => {
        if (e.target === studentModal) closeModal();
    });
}

// ============================
// پنل جزئیات کلاینت
// ============================
async function openStudentDetail(id) {
    selectedStudent = students.find(s => s.id === id);
    if (!selectedStudent) return;

    const avatar = document.getElementById("detailAvatar");
    if (avatar) {
        avatar.innerHTML = "👤";
        if (selectedStudent.photos?.length) {
            const url = await getPhotoUrl(selectedStudent.photos[0]);
            if (url) {
                avatar.innerHTML = `<img src="${url}">`;
            }
        }
    }

    const detailName = document.getElementById('detailName');
    if (detailName) {
        detailName.textContent = selectedStudent.name || 'بدون نام';
    }

    renderPrograms();
    if (detailPanel) detailPanel.classList.add('active');
}

function renderPrograms() {
    const l = document.getElementById('programsList');
    if (!l) return;

    const p = selectedStudent.programs || [];
    if (!p.length) {
        l.innerHTML = '<div class="no-programs">هنوز برنامه‌ای ایجاد نشده</div>';
        return;
    }

    l.innerHTML = p.map(x => {
        const goalInfo = x.goal ? `<span style="color:#2563eb;font-size:11px;margin-top:1px;display:block;">🎯 ${x.goal}</span>` : '';
        return `
        <div class="program-item">
            <div class="program-item-info">
                <h4>${x.name || 'بدون عنوان'}${goalInfo}</h4>
                <span>${new Date(x.createdAt).toLocaleDateString('fa-IR')}</span>
            </div>
            <div class="program-item-actions">
                <button class="program-open-btn" onclick="event.stopPropagation();openProgram('${selectedStudent.id}','${x.id}')">باز کردن →</button>
                <button class="icon-btn" onclick="event.stopPropagation();renameProgram('${x.id}')">✎</button>
                <button class="icon-btn delete" onclick="event.stopPropagation();deleteProgram('${x.id}')">✕</button>
            </div>
        </div>
        `;
    }).join('');
}

function addProgram() {
    const overlay = document.createElement('div');
    overlay.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);z-index:300;display:flex;align-items:center;justify-content:center;';

    const dialog = document.createElement('div');
    dialog.style.cssText = 'background:#fff;border-radius:12px;padding:24px;width:90%;max-width:420px;box-shadow:0 20px 60px rgba(0,0,0,0.3);';
    dialog.innerHTML = `
        <h3 style="margin:0 0 20px 0;color:#1a1a1a;font-size:18px;font-weight:700;">افزودن برنامه جدید</h3>
        <div style="display:flex;flex-direction:column;gap:14px;">
            <div>
                <label style="display:block;margin-bottom:6px;color:#6b7280;font-size:12px;font-weight:600;">نام برنامه</label>
                <input type="text" id="progNameInput" placeholder="مثلاً برنامه حجم‌گیری" style="width:100%;padding:10px 12px;border:1px solid #e5e7eb;border-radius:8px;background:#fafbfc;color:#1a1a1a;font-size:13px;box-sizing:border-box;font-family:inherit;">
            </div>
            <div>
                <label style="display:block;margin-bottom:6px;color:#6b7280;font-size:12px;font-weight:600;">روزهای استراحت</label>
                <input type="text" id="progRestInput" placeholder="مثلاً شنبه و سه‌شنبه" style="width:100%;padding:10px 12px;border:1px solid #e5e7eb;border-radius:8px;background:#fafbfc;color:#1a1a1a;font-size:13px;box-sizing:border-box;font-family:inherit;">
            </div>
            <div>
                <label style="display:block;margin-bottom:6px;color:#6b7280;font-size:12px;font-weight:600;">هدف برنامه</label>
                <input type="text" id="progGoalInput" placeholder="مثلاً افزایش حجم عضلات بالاتنه" style="width:100%;padding:10px 12px;border:1px solid #e5e7eb;border-radius:8px;background:#fafbfc;color:#1a1a1a;font-size:13px;box-sizing:border-box;font-family:inherit;">
            </div>
        </div>
        <div style="display:flex;gap:10px;justify-content:flex-end;margin-top:24px;">
            <button id="progCancelBtn" style="padding:8px 16px;border:1px solid #e5e7eb;border-radius:8px;background:transparent;color:#6b7280;cursor:pointer;font-size:13px;font-family:inherit;">انصراف</button>
            <button id="progSaveBtn" style="padding:8px 20px;border:none;border-radius:8px;background:#2563eb;color:#fff;cursor:pointer;font-size:13px;font-weight:600;font-family:inherit;">ذخیره</button>
        </div>
    `;

    overlay.appendChild(dialog);
    document.body.appendChild(overlay);

    const nameInput = dialog.querySelector('#progNameInput');
    const close = () => overlay.remove();

    overlay.addEventListener('click', (e) => {
        if (e.target === overlay) close();
    });
    dialog.querySelector('#progCancelBtn').addEventListener('click', close);
    dialog.querySelector('#progSaveBtn').addEventListener('click', () => {
        const n = nameInput.value.trim();
        if (!n) {
            nameInput.style.borderColor = '#dc2626';
            nameInput.focus();
            return;
        }
        if (!selectedStudent.programs) selectedStudent.programs = [];
        const programId = uid();
        selectedStudent.programs.push({
            id: programId,
            name: n,
            restDays: dialog.querySelector('#progRestInput').value.trim(),
            goal: dialog.querySelector('#progGoalInput').value.trim(),
            createdAt: new Date().toISOString()
        });
        students = students.map(s => s.id === selectedStudent.id ? selectedStudent : s);
        saveStudents(students);

        const metaKey = getProgramStorageKey(selectedStudent.id, programId, 'meta');
        const daysKey = getProgramStorageKey(selectedStudent.id, programId, 'days');
        const emptyData = createEmptyProgramData(selectedStudent.name);
        localStorage.setItem(metaKey, JSON.stringify({
            name: n,
            restDays: dialog.querySelector('#progRestInput').value.trim(),
            goal: dialog.querySelector('#progGoalInput').value.trim(),
            studentName: selectedStudent.name,
            dayCount: 3,
            totalExercises: 0
        }));
        localStorage.setItem(daysKey, JSON.stringify(emptyData));
        close();
        renderPrograms();
    });

    nameInput.focus();
}

function renameProgram(pid) {
    const p = selectedStudent.programs.find(x => x.id === pid);
    if (!p) return;

    const overlay = document.createElement('div');
    overlay.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);z-index:300;display:flex;align-items:center;justify-content:center;';

    const dialog = document.createElement('div');
    dialog.style.cssText = 'background:#fff;border-radius:12px;padding:24px;width:90%;max-width:420px;box-shadow:0 20px 60px rgba(0,0,0,0.3);';
    dialog.innerHTML = `
        <h3 style="margin:0 0 20px 0;color:#1a1a1a;font-size:18px;font-weight:700;">ویرایش برنامه</h3>
        <div style="display:flex;flex-direction:column;gap:14px;">
            <div>
                <label style="display:block;margin-bottom:6px;color:#6b7280;font-size:12px;font-weight:600;">نام برنامه</label>
                <input type="text" id="editProgNameInput" value="${p.name || ''}" style="width:100%;padding:10px 12px;border:1px solid #e5e7eb;border-radius:8px;background:#fafbfc;color:#1a1a1a;font-size:13px;box-sizing:border-box;font-family:inherit;">
            </div>
            <div>
                <label style="display:block;margin-bottom:6px;color:#6b7280;font-size:12px;font-weight:600;">روزهای استراحت</label>
                <input type="text" id="editProgRestInput" value="${p.restDays || ''}" style="width:100%;padding:10px 12px;border:1px solid #e5e7eb;border-radius:8px;background:#fafbfc;color:#1a1a1a;font-size:13px;box-sizing:border-box;font-family:inherit;">
            </div>
            <div>
                <label style="display:block;margin-bottom:6px;color:#6b7280;font-size:12px;font-weight:600;">هدف برنامه</label>
                <input type="text" id="editProgGoalInput" value="${p.goal || ''}" style="width:100%;padding:10px 12px;border:1px solid #e5e7eb;border-radius:8px;background:#fafbfc;color:#1a1a1a;font-size:13px;box-sizing:border-box;font-family:inherit;">
            </div>
        </div>
        <div style="display:flex;gap:10px;justify-content:flex-end;margin-top:24px;">
            <button id="editProgCancelBtn" style="padding:8px 16px;border:1px solid #e5e7eb;border-radius:8px;background:transparent;color:#6b7280;cursor:pointer;font-size:13px;font-family:inherit;">انصراف</button>
            <button id="editProgSaveBtn" style="padding:8px 20px;border:none;border-radius:8px;background:#2563eb;color:#fff;cursor:pointer;font-size:13px;font-weight:600;font-family:inherit;">ذخیره</button>
        </div>
    `;

    overlay.appendChild(dialog);
    document.body.appendChild(overlay);

    const nameInput = dialog.querySelector('#editProgNameInput');
    const close = () => overlay.remove();

    overlay.addEventListener('click', (e) => {
        if (e.target === overlay) close();
    });
    dialog.querySelector('#editProgCancelBtn').addEventListener('click', close);
    dialog.querySelector('#editProgSaveBtn').addEventListener('click', () => {
        const n = nameInput.value.trim();
        if (!n) {
            nameInput.style.borderColor = '#dc2626';
            nameInput.focus();
            return;
        }
        p.name = n;
        p.restDays = dialog.querySelector('#editProgRestInput').value.trim();
        p.goal = dialog.querySelector('#editProgGoalInput').value.trim();
        students = students.map(s => s.id === selectedStudent.id ? selectedStudent : s);
        saveStudents(students);

        const metaKey = getProgramStorageKey(selectedStudent.id, pid, 'meta');
        const meta = JSON.parse(localStorage.getItem(metaKey) || '{}');
        meta.name = n;
        meta.restDays = dialog.querySelector('#editProgRestInput').value.trim();
        meta.goal = dialog.querySelector('#editProgGoalInput').value.trim();
        localStorage.setItem(metaKey, JSON.stringify(meta));
        close();
        renderPrograms();
    });

    nameInput.focus();
    nameInput.select();
}

function deleteProgram(pid) {
    if (!confirm('حذف شود؟')) return;
    selectedStudent.programs = selectedStudent.programs.filter(x => x.id !== pid);
    students = students.map(s => s.id === selectedStudent.id ? selectedStudent : s);
    saveStudents(students);
    localStorage.removeItem(getProgramStorageKey(selectedStudent.id, pid, 'meta'));
    localStorage.removeItem(getProgramStorageKey(selectedStudent.id, pid, 'days'));
    renderPrograms();
}

function openProgram(sid, pid) {
    localStorage.setItem(ACTIVE_PROGRAM_KEY, JSON.stringify({ studentId: sid, programId: pid }));
    window.location.href = 'editor.html';
}

// Detail panel events
const addProgramBtn = document.getElementById('addProgramBtn');
if (addProgramBtn) addProgramBtn.addEventListener('click', addProgram);

const closeDetailBtn = document.getElementById('closeDetail');
if (closeDetailBtn) {
    closeDetailBtn.addEventListener('click', () => {
        if (detailPanel) detailPanel.classList.remove('active');
    });
}

if (detailPanel) {
    detailPanel.addEventListener('click', e => {
        if (e.target === detailPanel) detailPanel.classList.remove('active');
    });
}

// ============================
// پنل اطلاعات
// ============================
const infoPanel = document.getElementById('infoPanel');
const viewInfoLink = document.getElementById('viewInfoLink');

if (viewInfoLink) {
    viewInfoLink.addEventListener('click', async () => {
        if (!selectedStudent) return;
        const s = selectedStudent;
        const cn = categories.find(c => c.id === s.category)?.name || '—';

        const photosDiv = document.getElementById("infoPanelPhotos");
        if (photosDiv) {
            photosDiv.innerHTML = "";
            if (!s.photos?.length) {
                photosDiv.innerHTML = '<span class="no-photo">👤</span>';
            } else {
                for (let i = 0; i < s.photos.length; i++) {
                    const url = await getPhotoUrl(s.photos[i]);
                    if (!url) continue;
                    photosDiv.innerHTML += `<img src="${url}" class="${i===0?'active':''}" data-index="${i}">`;
                }
            }
        }

        const dd = document.getElementById('infoPanelDots');
        const pb = document.getElementById('photoPrevBtn');
        const nb = document.getElementById('photoNextBtn');
        const ps = s.photos || [];
        let cp = 0;

        if (dd) {
            if (ps.length <= 1) {
                dd.innerHTML = '';
                if (pb) pb.style.visibility = 'hidden';
                if (nb) nb.style.visibility = 'hidden';
            } else {
                dd.innerHTML = ps.map((_, i) => `<span class="info-panel-dot${i === 0 ? ' active' : ''}" data-index="${i}"></span>`).join('');
                if (pb) pb.style.visibility = 'visible';
                if (nb) nb.style.visibility = 'visible';

                const ai = document.getElementById('infoPanelPhotos')?.querySelectorAll('img');
                const ad = dd.querySelectorAll('.info-panel-dot');

                function sp(i) {
                    cp = i;
                    if (ai) ai.forEach((img, x) => img.classList.toggle('active', x === i));
                    ad.forEach((dot, x) => dot.classList.toggle('active', x === i));
                    if (pb) pb.disabled = i === 0;
                    if (nb) nb.disabled = i === ps.length - 1;
                }

                ad.forEach(dot => dot.addEventListener('click', e => sp(parseInt(e.target.dataset.index))));

                if (pb) {
                    pb.onclick = () => {
                        if (cp > 0) sp(cp - 1);
                    };
                }

                if (nb) {
                    nb.onclick = () => {
                        if (cp < ps.length - 1) sp(cp + 1);
                    };
                }

                sp(0);
            }
        }

        const infoFields = document.getElementById('infoPanelFields');
        if (infoFields) {
            infoFields.innerHTML = [
                    { l: 'نام', v: s.name || '—' },
                    { l: 'تلفن', v: s.phone || '—' },
                    { l: 'قد', v: s.height ? s.height + ' سانتی‌متر' : '—' },
                    { l: 'وزن', v: s.weight ? s.weight + ' کیلوگرم' : '—' },
                    { l: 'دور بازو', v: s.arm ? s.arm + ' سانتی‌متر' : '—' },
                    { l: 'دور ران', v: s.thigh ? s.thigh + ' سانتی‌متر' : '—' },
                    { l: 'دور شکم', v: s.waist ? s.waist + ' سانتی‌متر' : '—' },
                    { l: 'دسته‌بندی', v: cn },
                    { l: 'تاریخ ثبت', v: new Date(s.createdAt).toLocaleDateString('fa-IR') }
                ].map(f => `<div class="info-field"><span class="info-field-label">${f.l}</span><span class="info-field-value">${f.v}</span></div>`).join('') +
                (s.notes ? `<div class="info-notes"><strong>توضیحات</strong>${s.notes}</div>` : '');
        }

        const editBtn = document.getElementById('editStudentFromInfo');
        if (editBtn) {
            editBtn.onclick = () => {
                if (infoPanel) infoPanel.classList.remove('active');
                openModal(s);
            };
        }

        const deleteBtn = document.getElementById('deleteStudentFromInfo');
        if (deleteBtn) {
            deleteBtn.onclick = () => {
                if (confirm(`حذف "${s.name || 'این کلاینت'}"؟`)) {
                    if (s.programs) {
                        s.programs.forEach(p => {
                            localStorage.removeItem(getProgramStorageKey(s.id, p.id, 'meta'));
                            localStorage.removeItem(getProgramStorageKey(s.id, p.id, 'days'));
                        });
                    }
                    students = students.filter(st => st.id !== s.id);
                    saveStudents(students);
                    if (infoPanel) infoPanel.classList.remove('active');
                    if (detailPanel) detailPanel.classList.remove('active');
                    selectedStudent = null;
                    renderStudents();
                }
            };
        }

        if (infoPanel) infoPanel.classList.add('active');
    });
}

const closeInfoPanelBtn = document.getElementById('closeInfoPanel');
if (closeInfoPanelBtn) {
    closeInfoPanelBtn.addEventListener('click', () => {
        if (infoPanel) infoPanel.classList.remove('active');
    });
}

if (infoPanel) {
    infoPanel.addEventListener('click', e => {
        if (e.target === infoPanel) infoPanel.classList.remove('active');
    });
}

// ============================
// لایت‌باکس تصاویر
// ============================
let lightboxPhotos = [];
let lightboxIndex = 0;

function openLightbox(photos, index) {
    lightboxPhotos = photos;
    lightboxIndex = index;
    showLightboxImage();
    const lightboxOverlay = document.getElementById('lightboxOverlay');
    if (lightboxOverlay) lightboxOverlay.classList.add('active');
}

function showLightboxImage() {
    const lbImg = document.getElementById('lightboxImage');
    if (!lbImg) return;

    lbImg.style.opacity = '0';
    setTimeout(() => {
        lbImg.src = lightboxPhotos[lightboxIndex];
        const tempImg = new Image();
        tempImg.onload = () => {
            lbImg.style.opacity = '1';
        };
        tempImg.onerror = () => {
            lbImg.style.opacity = '1';
        };
        tempImg.src = lightboxPhotos[lightboxIndex];

        const prevBtn = document.getElementById('lightboxPrevBtn');
        const nextBtn = document.getElementById('lightboxNextBtn');
        if (prevBtn) prevBtn.style.visibility = lightboxIndex === 0 ? 'hidden' : 'visible';
        if (nextBtn) nextBtn.style.visibility = lightboxIndex === lightboxPhotos.length - 1 ? 'hidden' : 'visible';
    }, 150);
}

const infoPhotosDiv = document.getElementById('infoPanelPhotos');
if (infoPhotosDiv) {
    infoPhotosDiv.addEventListener('click', e => {
        const img = e.target.closest('img');
        if (!img || !img.src) return;
        const allImgs = [...infoPhotosDiv.querySelectorAll('img')];
        const photos = allImgs.map(i => i.src);
        const index = allImgs.indexOf(img);
        openLightbox(photos, index);
    });
}

const lightboxPrevBtn = document.getElementById('lightboxPrevBtn');
if (lightboxPrevBtn) {
    lightboxPrevBtn.addEventListener('click', () => {
        if (lightboxIndex > 0) {
            lightboxIndex--;
            showLightboxImage();
        }
    });
}

const lightboxNextBtn = document.getElementById('lightboxNextBtn');
if (lightboxNextBtn) {
    lightboxNextBtn.addEventListener('click', () => {
        if (lightboxIndex < lightboxPhotos.length - 1) {
            lightboxIndex++;
            showLightboxImage();
        }
    });
}

const closeLightboxBtn = document.getElementById('closeLightbox');
if (closeLightboxBtn) {
    closeLightboxBtn.addEventListener('click', () => {
        const lightboxOverlay = document.getElementById('lightboxOverlay');
        if (lightboxOverlay) lightboxOverlay.classList.remove('active');
    });
}

const lightboxOverlay = document.getElementById('lightboxOverlay');
if (lightboxOverlay) {
    lightboxOverlay.addEventListener('click', e => {
        if (e.target === e.currentTarget) e.currentTarget.classList.remove('active');
    });
}

// ============================
// تم‌ها
// ============================
const THEMES = {
    "clean-light": {
        bg: "#e8ecf1",
        appBg: "#ffffff",
        sidebarBg: "#fafbfc",
        sidebarBorder: "#e5e7eb",
        sidebarLinkHover: "#f0f1f3",
        sidebarActiveBg: "#eff6ff",
        accent: "#2563eb",
        accentHover: "#1d4ed8",
        accentLight: "#eff6ff",
        accentGlow: "rgba(37,99,235,0.1)",
        titleBarBg: "#f8f9fa",
        titleBarBorder: "#e5e7eb",
        text: "#1a1a1a",
        textSecondary: "#6b7280",
        textMuted: "#9ca3af",
        border: "#e5e7eb",
        borderLight: "#f3f4f6",
        cardBg: "#fafbfc",
        cardHoverBorder: "#2563eb",
        inputBg: "#fafbfc",
        inputBorder: "#e5e7eb",
        dotColor: "#e5e7eb"
    },
    "clean-sand": {
        bg: "#f5f0e8",
        appBg: "#fffdf8",
        sidebarBg: "#faf7f2",
        sidebarBorder: "#e8e3da",
        sidebarLinkHover: "#f0ebe0",
        sidebarActiveBg: "#fef3e0",
        accent: "#b7791f",
        accentHover: "#975a16",
        accentLight: "#fef3e0",
        accentGlow: "rgba(183,121,31,0.1)",
        titleBarBg: "#faf6f0",
        titleBarBorder: "#e8e3da",
        text: "#2f332d",
        textSecondary: "#747a70",
        textMuted: "#9a9e94",
        border: "#e8e3da",
        borderLight: "#f0ebe0",
        cardBg: "#faf7f2",
        cardHoverBorder: "#b7791f",
        inputBg: "#faf7f2",
        inputBorder: "#e8e3da",
        dotColor: "#e8e3da"
    },
    "nord-frost": {
        bg: "#d8e3ec",
        appBg: "#ffffff",
        sidebarBg: "#f0f4f8",
        sidebarBorder: "#d8e3ec",
        sidebarLinkHover: "#e5edf4",
        sidebarActiveBg: "#e8eff8",
        accent: "#5e81ac",
        accentHover: "#4c6f98",
        accentLight: "#e8eff8",
        accentGlow: "rgba(94,129,172,0.1)",
        titleBarBg: "#f0f4f8",
        titleBarBorder: "#d8e3ec",
        text: "#263445",
        textSecondary: "#66788c",
        textMuted: "#8a9bb0",
        border: "#d8e3ec",
        borderLight: "#e5edf4",
        cardBg: "#f0f4f8",
        cardHoverBorder: "#5e81ac",
        inputBg: "#f0f4f8",
        inputBorder: "#d8e3ec",
        dotColor: "#d8e3ec"
    },
    "midnight-blue": {
        bg: "#0a0f18",
        appBg: "#101a2b",
        sidebarBg: "#0d1625",
        sidebarBorder: "#1e2d45",
        sidebarLinkHover: "#162136",
        sidebarActiveBg: "#1a3050",
        accent: "#5098f0",
        accentHover: "#3878d0",
        accentLight: "#1a3050",
        accentGlow: "rgba(80,152,240,0.15)",
        titleBarBg: "#0d1625",
        titleBarBorder: "#1e2d45",
        text: "#e6f0ff",
        textSecondary: "#8fa8cc",
        textMuted: "#5a7099",
        border: "#1e2d45",
        borderLight: "#162136",
        cardBg: "#162136",
        cardHoverBorder: "#5098f0",
        inputBg: "#0d1625",
        inputBorder: "#1e2d45",
        dotColor: "#1e2d45"
    },
    "tokyo-night": {
        bg: "#111522",
        appBg: "#1a1f30",
        sidebarBg: "#161b2a",
        sidebarBorder: "#2a3045",
        sidebarLinkHover: "#20273a",
        sidebarActiveBg: "#252d48",
        accent: "#6e94f0",
        accentHover: "#5a80d8",
        accentLight: "#252d48",
        accentGlow: "rgba(110,148,240,0.15)",
        titleBarBg: "#161b2a",
        titleBarBorder: "#2a3045",
        text: "#dce4ff",
        textSecondary: "#8896c8",
        textMuted: "#5a6590",
        border: "#2a3045",
        borderLight: "#20273a",
        cardBg: "#20273a",
        cardHoverBorder: "#6e94f0",
        inputBg: "#161b2a",
        inputBorder: "#2a3045",
        dotColor: "#2a3045"
    },
    "soft-peach": {
        bg: "#f8ebe4",
        appBg: "#fffaf7",
        sidebarBg: "#fdf5f0",
        sidebarBorder: "#f0ddd4",
        sidebarLinkHover: "#fae8dc",
        sidebarActiveBg: "#fef0e8",
        accent: "#e76f51",
        accentHover: "#c9553d",
        accentLight: "#fef0e8",
        accentGlow: "rgba(231,111,81,0.1)",
        titleBarBg: "#fdf5f0",
        titleBarBorder: "#f0ddd4",
        text: "#3b302d",
        textSecondary: "#806f68",
        textMuted: "#a09088",
        border: "#f0ddd4",
        borderLight: "#fae8dc",
        cardBg: "#fdf5f0",
        cardHoverBorder: "#e76f51",
        inputBg: "#fdf5f0",
        inputBorder: "#f0ddd4",
        dotColor: "#f0ddd4"
    },
    "emerald-glass": {
        bg: "#06120e",
        appBg: "#0a1c16",
        sidebarBg: "#081812",
        sidebarBorder: "#1a382e",
        sidebarLinkHover: "#0f2a20",
        sidebarActiveBg: "#153828",
        accent: "#30d090",
        accentHover: "#18b878",
        accentLight: "#153828",
        accentGlow: "rgba(48,208,144,0.15)",
        titleBarBg: "#081812",
        titleBarBorder: "#1a382e",
        text: "#dcf8ed",
        textSecondary: "#8ab8a5",
        textMuted: "#4a8070",
        border: "#1a382e",
        borderLight: "#0f2a20",
        cardBg: "#0f2a20",
        cardHoverBorder: "#30d090",
        inputBg: "#081812",
        inputBorder: "#1a382e",
        dotColor: "#1a382e"
    },
    "monochrome-pro": {
        bg: "#0d0d0d",
        appBg: "#1a1a1a",
        sidebarBg: "#141414",
        sidebarBorder: "#2a2a2a",
        sidebarLinkHover: "#222222",
        sidebarActiveBg: "#2a2a2a",
        accent: "#e8e8e8",
        accentHover: "#c8c8c8",
        accentLight: "#2a2a2a",
        accentGlow: "rgba(255,255,255,0.08)",
        titleBarBg: "#141414",
        titleBarBorder: "#2a2a2a",
        text: "#f0f0f0",
        textSecondary: "#a0a0a0",
        textMuted: "#606060",
        border: "#2a2a2a",
        borderLight: "#222222",
        cardBg: "#222222",
        cardHoverBorder: "#e8e8e8",
        inputBg: "#141414",
        inputBorder: "#2a2a2a",
        dotColor: "#2a2a2a"
    },
    "royal-purple": {
        bg: "#100818",
        appBg: "#1d1430",
        sidebarBg: "#160e24",
        sidebarBorder: "#2e2048",
        sidebarLinkHover: "#261b3e",
        sidebarActiveBg: "#302850",
        accent: "#9b80f0",
        accentHover: "#7540e8",
        accentLight: "#302850",
        accentGlow: "rgba(155,128,240,0.15)",
        titleBarBg: "#160e24",
        titleBarBorder: "#2e2048",
        text: "#eee5ff",
        textSecondary: "#a890d0",
        textMuted: "#6a5098",
        border: "#2e2048",
        borderLight: "#261b3e",
        cardBg: "#261b3e",
        cardHoverBorder: "#9b80f0",
        inputBg: "#160e24",
        inputBorder: "#2e2048",
        dotColor: "#2e2048"
    },
    "neo-gym": {
        bg: "#0a100c",
        appBg: "#121c17",
        sidebarBg: "#0e1612",
        sidebarBorder: "#1e3028",
        sidebarLinkHover: "#18231d",
        sidebarActiveBg: "#1e3828",
        accent: "#5ce68c",
        accentHover: "#3cc96a",
        accentLight: "#1e3828",
        accentGlow: "rgba(92,230,140,0.12)",
        titleBarBg: "#0e1612",
        titleBarBorder: "#1e3028",
        text: "#e6f5ec",
        textSecondary: "#8aaa94",
        textMuted: "#4a7060",
        border: "#1e3028",
        borderLight: "#18231d",
        cardBg: "#18231d",
        cardHoverBorder: "#5ce68c",
        inputBg: "#0e1612",
        inputBorder: "#1e3028",
        dotColor: "#1e3028"
    }
};

function applyTheme(themeName) {
    const theme = THEMES[themeName] || THEMES['clean-light'];

    const root = document.documentElement;

    root.style.setProperty('--bg', theme.bg);
    root.style.setProperty('--app-bg', theme.appBg);
    root.style.setProperty('--sidebar-bg', theme.sidebarBg);
    root.style.setProperty('--sidebar-border', theme.sidebarBorder);
    root.style.setProperty('--sidebar-link-hover', theme.sidebarLinkHover);
    root.style.setProperty('--sidebar-active-bg', theme.sidebarActiveBg);
    root.style.setProperty('--accent', theme.accent);
    root.style.setProperty('--accent-hover', theme.accentHover);
    root.style.setProperty('--accent-light', theme.accentLight);
    root.style.setProperty('--accent-glow', theme.accentGlow);
    root.style.setProperty('--titlebar-bg', theme.titleBarBg);
    root.style.setProperty('--titlebar-border', theme.titleBarBorder);
    root.style.setProperty('--text', theme.text);
    root.style.setProperty('--text-secondary', theme.textSecondary);
    root.style.setProperty('--text-muted', theme.textMuted);
    root.style.setProperty('--border', theme.border);
    root.style.setProperty('--border-light', theme.borderLight);
    root.style.setProperty('--card-bg', theme.cardBg);
    root.style.setProperty('--card-hover-border', theme.cardHoverBorder);
    root.style.setProperty('--input-bg', theme.inputBg);
    root.style.setProperty('--input-border', theme.inputBorder);
    root.style.setProperty('--dot-color', theme.dotColor);

    localStorage.setItem(THEME_KEY, themeName);
}

// تنظیم تم پیش‌فرض
const savedTheme = localStorage.getItem(THEME_KEY) || 'clean-light';
const themeSelect = document.getElementById('settingsTheme');
if (themeSelect) {
    themeSelect.value = savedTheme;
    themeSelect.addEventListener('change', function() {
        applyTheme(this.value);
    });
}
applyTheme(savedTheme);

// ============================
// مدیریت لوگو
// ============================
async function loadAndDisplayLogo() {
    const logoPreview = document.getElementById('gymLogoPreview');
    const logoPlaceholder = document.getElementById('gymLogoPlaceholder');
    const removeBtn = document.getElementById('removeGymLogo');

    if (currentLogoUrl) {
        URL.revokeObjectURL(currentLogoUrl);
    }

    currentLogoUrl = await getLogoUrl();

    if (currentLogoUrl) {
        if (logoPreview) {
            logoPreview.src = currentLogoUrl;
            logoPreview.style.display = 'block';
        }
        if (logoPlaceholder) logoPlaceholder.style.display = 'none';
        if (removeBtn) removeBtn.style.display = 'block';
    } else {
        if (logoPreview) logoPreview.style.display = 'none';
        if (logoPlaceholder) logoPlaceholder.style.display = 'flex';
        if (removeBtn) removeBtn.style.display = 'none';
    }
}

const selectGymLogoBtn = document.getElementById('selectGymLogo');
if (selectGymLogoBtn) {
    selectGymLogoBtn.addEventListener('click', () => {
        const gymLogoInput = document.getElementById('gymLogoInput');
        if (gymLogoInput) gymLogoInput.click();
    });
}

const gymLogoInput = document.getElementById('gymLogoInput');
if (gymLogoInput) {
    gymLogoInput.addEventListener('change', async (e) => {
        const file = e.target.files[0];
        if (!file) return;

        try {
            await saveLogo(file);

            const logoPreview = document.getElementById('gymLogoPreview');
            const logoPlaceholder = document.getElementById('gymLogoPlaceholder');
            const removeBtn = document.getElementById('removeGymLogo');

            if (currentLogoUrl) {
                URL.revokeObjectURL(currentLogoUrl);
            }

            currentLogoUrl = URL.createObjectURL(file);
            if (logoPreview) {
                logoPreview.src = currentLogoUrl;
                logoPreview.style.display = 'block';
            }
            if (logoPlaceholder) logoPlaceholder.style.display = 'none';
            if (removeBtn) removeBtn.style.display = 'block';

        } catch (error) {
            console.error('خطا در ذخیره لوگو:', error);
            alert('خطا در ذخیره لوگو. لطفاً دوباره تلاش کنید.');
        }

        e.target.value = '';
    });
}

const removeGymLogoBtn = document.getElementById('removeGymLogo');
if (removeGymLogoBtn) {
    removeGymLogoBtn.addEventListener('click', async () => {
        if (!confirm('آیا از حذف لوگو مطمئن هستید؟')) return;

        try {
            await deleteLogo();

            if (currentLogoUrl) {
                URL.revokeObjectURL(currentLogoUrl);
                currentLogoUrl = null;
            }

            const logoPreview = document.getElementById('gymLogoPreview');
            const logoPlaceholder = document.getElementById('gymLogoPlaceholder');

            if (logoPreview) logoPreview.style.display = 'none';
            if (logoPlaceholder) logoPlaceholder.style.display = 'flex';
            if (removeGymLogoBtn) removeGymLogoBtn.style.display = 'none';

        } catch (error) {
            console.error('خطا در حذف لوگو:', error);
            alert('خطا در حذف لوگو. لطفاً دوباره تلاش کنید.');
        }
    });
}

// ============================
// تنظیمات
// ============================
function populateSettings() {
    const s = loadSettings();
    const gymNameInput = document.getElementById('settingsGymName');
    const phoneInput = document.getElementById('settingsPhone');
    if (gymNameInput) gymNameInput.value = s.gymName || '';
    if (phoneInput) phoneInput.value = s.phone || '';
}

populateSettings();
loadAndDisplayLogo();

const settingsGymNameInput = document.getElementById('settingsGymName');
if (settingsGymNameInput) {
    settingsGymNameInput.addEventListener('input', function() {
        const s = loadSettings();
        s.gymName = this.value.trim();
        saveSettingsData(s);
    });
}

const settingsPhoneInput = document.getElementById('settingsPhone');
if (settingsPhoneInput) {
    settingsPhoneInput.addEventListener('input', function() {
        const s = loadSettings();
        s.phone = this.value.trim();
        saveSettingsData(s);
    });
}

// ============================
// پشتیبان‌گیری و بازیابی
// ============================
const backupDataBtn = document.getElementById('backupData');
if (backupDataBtn) {
    backupDataBtn.addEventListener('click', () => {
        const b = {
            students: loadStudents(),
            categories: loadCategories(),
            settings: loadSettings(),
            date: new Date().toISOString()
        };
        const blob = new Blob([JSON.stringify(b)], { type: 'application/json' });
        const a = document.createElement('a');
        a.href = URL.createObjectURL(blob);
        a.download = `backup-${new Date().toISOString().slice(0, 10)}.json`;
        a.click();
    });
}

const restoreDataBtn = document.getElementById('restoreData');
if (restoreDataBtn) {
    restoreDataBtn.addEventListener('click', () => {
        const inp = document.createElement('input');
        inp.type = 'file';
        inp.accept = '.json';
        inp.onchange = e => {
            const f = e.target.files[0];
            if (!f) return;
            const r = new FileReader();
            r.onload = ev => {
                try {
                    const b = JSON.parse(ev.target.result);
                    if (b.students) saveStudents(b.students);
                    if (b.categories) saveCategories(b.categories);
                    if (b.settings) saveSettingsData(b.settings);
                    alert('بازیابی شد.');
                    location.reload();
                } catch {
                    alert('فایل نامعتبر');
                }
            };
            r.readAsText(f);
        };
        inp.click();
    });
}

// ============================
// Search
// ============================
if (searchInput) {
    searchInput.addEventListener('input', () => {
        searchQuery = searchInput.value.trim();
        renderStudents();
    });
}

// ============================
// Testimonials Slider
// ============================
function initTestimonialsSlider() {
    const slides = document.querySelectorAll('.testimonials-slide');
    const dotsContainer = document.getElementById('testimonialsDots');
    const prevBtn = document.getElementById('testimonialPrev');
    const nextBtn = document.getElementById('testimonialNext');

    if (!slides.length || !dotsContainer) return;

    const totalSlides = slides.length;
    let currentSlide = 0;

    dotsContainer.innerHTML = '';
    for (let i = 0; i < totalSlides; i++) {
        const dot = document.createElement('span');
        dot.className = 'testimonials-dot' + (i === 0 ? ' active' : '');
        dot.addEventListener('click', () => goToSlide(i));
        dotsContainer.appendChild(dot);
    }

    function goToSlide(index) {
        slides[currentSlide].classList.remove('active');
        currentSlide = index;
        slides[currentSlide].classList.add('active');

        const dots = dotsContainer.querySelectorAll('.testimonials-dot');
        dots.forEach((dot, i) => {
            dot.classList.toggle('active', i === currentSlide);
        });

        if (prevBtn) prevBtn.disabled = currentSlide === 0;
        if (nextBtn) nextBtn.disabled = currentSlide === totalSlides - 1;
    }

    if (prevBtn) {
        prevBtn.addEventListener('click', () => {
            if (currentSlide > 0) goToSlide(currentSlide - 1);
        });
    }

    if (nextBtn) {
        nextBtn.addEventListener('click', () => {
            if (currentSlide < totalSlides - 1) goToSlide(currentSlide + 1);
        });
    }

    goToSlide(0);
}

// ============================
// راه‌اندازی اولیه
// ============================
function init() {
    renderCategories();
    renderStudents();
    navigateTo('welcome');
    initTestimonialsSlider();

    setTimeout(() => {
        loadStudentCardPhotos();
    }, 100);
}

// در دسترس قرار دادن توابع در scope گلوبال
window.openStudentDetail = openStudentDetail;
window.openProgram = openProgram;
window.renameProgram = renameProgram;
window.deleteProgram = deleteProgram;

// ============================
// Cleanup
// ============================
window.addEventListener('beforeunload', () => {
    if (currentLogoUrl) {
        URL.revokeObjectURL(currentLogoUrl);
    }
});

// استارت برنامه
init();