// ===== MOBILE MENU =====
const mobileMenuBtn = document.querySelector('.mobile-menu-btn');
const navMenu = document.querySelector('.nav-menu');

if (mobileMenuBtn && navMenu) {
    mobileMenuBtn.setAttribute('role', 'button');
    mobileMenuBtn.setAttribute('aria-label', 'Abrir menú');
    mobileMenuBtn.setAttribute('aria-expanded', 'false');

    mobileMenuBtn.addEventListener('click', () => {
        const isOpen = navMenu.classList.toggle('mobile-active');
        document.body.classList.toggle('menu-open', isOpen);
        mobileMenuBtn.classList.toggle('active', isOpen);
        mobileMenuBtn.setAttribute('aria-expanded', String(isOpen));
    });
}

// ===== STREAMING VIDEO =====
const video = document.getElementById('mainStream');
const overlay = document.getElementById('streamOverlay');

if (overlay && video) {
    overlay.addEventListener('click', () => {
        video.play();
        overlay.classList.add('hidden');
    });

    video.addEventListener('pause', () => {
        overlay.classList.remove('hidden');
    });

    video.addEventListener('play', () => {
        overlay.classList.add('hidden');
    });
}

// ===== FULLSCREEN =====
function toggleFullscreen() {
    const videoWrapper = document.querySelector('.video-wrapper');

    if (!document.fullscreenElement) {
        if (videoWrapper.requestFullscreen) {
            videoWrapper.requestFullscreen();
        } else if (videoWrapper.webkitRequestFullscreen) {
            videoWrapper.webkitRequestFullscreen();
        } else if (videoWrapper.msRequestFullscreen) {
            videoWrapper.msRequestFullscreen();
        }
    } else {
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
        } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        }
    }
}

// ===== LIVE STATS SIMULATION =====
function updateStats() {
    const viewers = document.getElementById('viewers');
    const uptime = document.getElementById('uptime');

    if (viewers) {
        const currentViewers = parseInt(viewers.textContent.replace(',', ''));
        const change = Math.floor(Math.random() * 20) - 10;
        const newViewers = Math.max(500, currentViewers + change);
        viewers.textContent = newViewers.toLocaleString();
    }

    if (uptime) {
        // Keep uptime static for now, or implement real timer
    }
}

setInterval(updateStats, 5000);

// ===== SMOOTH SCROLL =====
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();
        const target = document.querySelector(this.getAttribute('href'));
        if (target) {
            target.scrollIntoView({
                behavior: 'smooth',
                block: 'start'
            });
        }
    });
});

// ===== LIKE BUTTONS =====
document.querySelectorAll('.action-btn.like, .post-buttons button:first-child').forEach(btn => {
    btn.addEventListener('click', function() {
        this.classList.toggle('liked');
        if (this.classList.contains('liked')) {
            this.style.color = 'var(--gold)';
        } else {
            this.style.color = '';
        }
    });
});

// ===== ACTIVE NAV ITEM =====
const currentPage = window.location.pathname.split('/').pop() || 'index.html';
document.querySelectorAll('.nav-item a').forEach(link => {
    if (link.getAttribute('href').includes(currentPage)) {
        link.parentElement.classList.add('active');
    } else {
        link.parentElement.classList.remove('active');
    }
});

// ===== DROPDOWNS =====
document.querySelectorAll('.nav-item.has-dropdown > a').forEach(dropdown => {
    dropdown.addEventListener('click', (e) => {
        if (window.innerWidth <= 768) {
            e.preventDefault();
            const parent = dropdown.parentElement;
            document.querySelectorAll('.nav-item.mobile-open').forEach(item => {
                if (item !== parent) item.classList.remove('mobile-open');
            });
            parent.classList.toggle('mobile-open');
        }
    });
});

document.querySelectorAll('.dropdown-menu a').forEach(link => {
    link.addEventListener('click', () => {
        if (window.innerWidth <= 768 && navMenu) {
            navMenu.classList.remove('mobile-active');
            document.body.classList.remove('menu-open');
            mobileMenuBtn?.classList.remove('active');
            mobileMenuBtn?.setAttribute('aria-expanded', 'false');
        }
    });
});

// ===== WINDOW RESIZE =====
window.addEventListener('resize', () => {
    if (window.innerWidth > 768) {
        navMenu.classList.remove('mobile-active');
    }
});

console.log('CEGIC Website loaded successfully!');

// ===== COMMITTEE LOGIN & POSTS =====
const committeeAccounts = {
    admin: { name: 'Administrador General', icon: 'fa-user-shield' },
    cultura: { name: 'Cultura Ministerial CEGIC', icon: 'fa-church' },
    educacion: { name: 'Educación Cristiana', icon: 'fa-graduation-cap' },
    conajuve: { name: 'Conajuve - Juventud CEGIC', icon: 'fa-users' },
    conafem: { name: 'Conafem', icon: 'fa-female' },
    amic: { name: 'Agencia AMIC', icon: 'fa-hand-holding-heart' },
    tv: { name: 'TV/Radio CEGIC', icon: 'fa-tv' },
    social: { name: 'Proyección Social', icon: 'fa-hands-helping' },
    doctrina: { name: 'Nuestra Doctrina', icon: 'fa-book-bible' },
    consejos: { name: 'Consejos Regionales', icon: 'fa-map-marked-alt' },
    datos: { name: 'Datos Estadísticos', icon: 'fa-chart-bar' },
    contactos: { name: 'Contactos', icon: 'fa-envelope' }
};

const postsKey = 'cegic_committee_posts';
const sessionKey = 'cegic_committee_session';
const apiBase = `${window.location.pathname.includes('/pages/') ? '../' : ''}api`;
let serverMode = false;

function getCommitteePosts() {
    try {
        return JSON.parse(localStorage.getItem(postsKey)) || [];
    } catch (error) {
        return [];
    }
}

function saveCommitteePosts(posts) {
    localStorage.setItem(postsKey, JSON.stringify(posts));
}

async function fetchServerPosts() {
    try {
        const response = await fetch(`${apiBase}/posts.php`, { credentials: 'include' });
        if (!response.ok) return null;
        const data = await response.json();
        if (!data.ok || !Array.isArray(data.posts)) return null;
        serverMode = true;
        saveCommitteePosts(data.posts);
        return data.posts;
    } catch (error) {
        return null;
    }
}

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

function renderPostCard(post, editable = false) {
    const image = post.image ? `<div class="post-image"><img src="${post.image}" alt="${escapeHtml(post.title)}"></div>` : '';
    const canDelete = editable && (!post.committeeKey || post.committeeKey === localStorage.getItem(sessionKey));
    const deleteButton = canDelete ? `<button class="delete-post-btn" data-delete-post="${post.id}"><i class="fas fa-trash"></i> Eliminar</button>` : '';
    return `
        <article class="post-card committee-post">
            <div class="post-header">
                <div class="post-avatar"><i class="fas ${post.icon || 'fa-newspaper'}"></i></div>
                <div class="post-meta">
                    <h4>${escapeHtml(post.committee)}</h4>
                    <span>${escapeHtml(post.date)} · <i class="fas fa-globe-americas"></i></span>
                </div>
            </div>
            <div class="post-content">
                <h4>${escapeHtml(post.title)}</h4>
                <p>${escapeHtml(post.text)}</p>
                ${image}
            </div>
            <div class="post-stats">
                <span><i class="fas fa-thumbs-up"></i> 0</span>
                <span><i class="fas fa-comment"></i> 0 comentarios</span>
                <span><i class="fas fa-share"></i> 0 compartidos</span>
            </div>
            <div class="post-buttons">
                <button><i class="fas fa-thumbs-up"></i> Me gusta</button>
                <button><i class="fas fa-comment"></i> Comentar</button>
                <button><i class="fas fa-share"></i> Compartir</button>
            </div>
            ${deleteButton}
        </article>`;
}

function renderPublicCommitteeFeed() {
    const feed = document.getElementById('committeePostsFeed');
    if (!feed) return;
    const posts = getCommitteePosts();
    feed.innerHTML = posts.length ? posts.map(post => renderPostCard(post)).join('') : '';
}

function renderSectionCommitteeFeed() {
    const feed = document.getElementById('committeeSectionFeed');
    if (!feed) return;
    const committeeKey = feed.dataset.committee;
    const account = committeeAccounts[committeeKey];
    const posts = getCommitteePosts().filter(post => post.committeeKey === committeeKey || (!post.committeeKey && account && post.committee === account.name));
    feed.innerHTML = posts.length
        ? posts.map(post => renderPostCard(post)).join('')
        : '<div class="committee-admin-empty">Aún no hay publicaciones en esta sección.</div>';
}

function renderAdminPosts() {
    const target = document.getElementById('committeeAdminPosts');
    if (!target) return;
    const activeUser = localStorage.getItem(sessionKey);
    const posts = getCommitteePosts().filter(post => !activeUser || post.committeeKey === activeUser || !post.committeeKey);
    target.innerHTML = posts.length
        ? posts.map(post => renderPostCard(post, true)).join('')
        : '<div class="committee-admin-empty">Aún no hay publicaciones guardadas.</div>';

    target.querySelectorAll('[data-delete-post]').forEach(button => {
        button.addEventListener('click', async () => {
            if (serverMode) {
                try {
                    await fetch(`${apiBase}/posts.php?id=${encodeURIComponent(button.dataset.deletePost)}`, {
                        method: 'DELETE',
                        credentials: 'include'
                    });
                    await fetchServerPosts();
                } catch (error) {}
            } else {
                const nextPosts = getCommitteePosts().filter(post => post.id !== button.dataset.deletePost);
                saveCommitteePosts(nextPosts);
            }
            renderAdminPosts();
            renderPublicCommitteeFeed();
            renderSectionCommitteeFeed();
        });
    });
}

async function loginOnServer(username, password) {
    try {
        const response = await fetch(`${apiBase}/login.php`, {
            method: 'POST',
            credentials: 'include',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ user: username, password })
        });
        const data = await response.json();
        if (!response.ok || !data.ok) return false;
        serverMode = true;
        return true;
    } catch (error) {
        return false;
    }
}

function initCommitteePublishing() {
    const loginPanel = document.getElementById('committeeLoginPanel');
    const composerPanel = document.getElementById('committeeComposerPanel');
    const loginForm = document.getElementById('committeeLoginForm');
    const postForm = document.getElementById('committeePostForm');
    const loginMessage = document.getElementById('loginMessage');
    const postMessage = document.getElementById('postMessage');
    const loggedCommitteeName = document.getElementById('loggedCommitteeName');
    const logoutButton = document.getElementById('logoutCommittee');
    const imageInput = document.getElementById('postImage');
    const preview = document.getElementById('postPreview');
    let selectedImage = '';
    let selectedFile = null;

    if (!loginPanel || !composerPanel) return;

    function setSession(username) {
        const account = committeeAccounts[username];
        if (!account) return;
        localStorage.setItem(sessionKey, username);
        loginPanel.classList.add('hidden');
        composerPanel.classList.remove('hidden');
        loggedCommitteeName.textContent = `${account.name}${serverMode ? ' · conectado al servidor' : ' · modo prueba local'}`;
        renderAdminPosts();
    }

    const activeUser = localStorage.getItem(sessionKey);
    if (activeUser && committeeAccounts[activeUser]) {
        setSession(activeUser);
    }

    loginForm.addEventListener('submit', async event => {
        event.preventDefault();
        const username = document.getElementById('committeeUser').value.trim().toLowerCase();
        const password = document.getElementById('committeePass').value;
        const account = committeeAccounts[username];

        loginMessage.textContent = 'Verificando acceso...';
        loginMessage.style.color = 'var(--text-muted)';

        if (!account) {
            loginMessage.textContent = 'Usuario o contraseña incorrectos.';
            loginMessage.style.color = '#ff6b57';
            return;
        }

        const isHosted = window.location.protocol === 'http:' || window.location.protocol === 'https:';
        const serverLoginOk = await loginOnServer(username, password);

        if (isHosted && !serverLoginOk) {
            loginMessage.textContent = 'Usuario o contraseña incorrectos.';
            loginMessage.style.color = '#ff6b57';
            return;
        }

        await fetchServerPosts();
        loginMessage.textContent = '';
        setSession(username);
    });

    logoutButton.addEventListener('click', async () => {
        if (serverMode) {
            try { await fetch(`${apiBase}/logout.php`, { credentials: 'include' }); } catch (error) {}
        }
        localStorage.removeItem(sessionKey);
        composerPanel.classList.add('hidden');
        loginPanel.classList.remove('hidden');
    });

    imageInput.addEventListener('change', () => {
        const file = imageInput.files[0];
        selectedFile = file || null;
        if (!file) {
            selectedImage = '';
            preview.classList.add('hidden');
            return;
        }
        const reader = new FileReader();
        reader.onload = () => {
            selectedImage = reader.result;
            preview.src = selectedImage;
            preview.classList.remove('hidden');
        };
        reader.readAsDataURL(file);
    });

    postForm.addEventListener('submit', async event => {
        event.preventDefault();
        const username = localStorage.getItem(sessionKey);
        const account = committeeAccounts[username];
        if (!account) return;

        const title = document.getElementById('postTitle').value.trim();
        const text = document.getElementById('postText').value.trim();
        postMessage.textContent = 'Guardando publicación...';
        postMessage.style.color = 'var(--text-muted)';

        if (serverMode) {
            try {
                const formData = new FormData();
                formData.append('title', title);
                formData.append('text', text);
                if (selectedFile) formData.append('image', selectedFile);
                const response = await fetch(`${apiBase}/posts.php`, {
                    method: 'POST',
                    credentials: 'include',
                    body: formData
                });
                const data = await response.json();
                if (!response.ok || !data.ok) throw new Error(data.message || 'No se pudo guardar.');
                saveCommitteePosts(data.posts || []);
            } catch (error) {
                postMessage.textContent = 'No se pudo guardar en servidor. Revisa PHP/permisos del hosting.';
                postMessage.style.color = '#ff6b57';
                return;
            }
        } else {
            const post = {
                id: String(Date.now()),
                committeeKey: username,
                committee: account.name,
                icon: account.icon,
                title,
                text,
                image: selectedImage,
                date: new Date().toLocaleString('es-GT', { dateStyle: 'medium', timeStyle: 'short' })
            };
            const posts = [post, ...getCommitteePosts()].slice(0, 60);
            saveCommitteePosts(posts);
        }

        postForm.reset();
        selectedImage = '';
        selectedFile = null;
        preview.classList.add('hidden');
        postMessage.textContent = 'Publicación guardada. Aparecerá en el inicio y en la sección correspondiente.';
        postMessage.style.color = 'var(--secondary)';
        renderAdminPosts();
        renderPublicCommitteeFeed();
        renderSectionCommitteeFeed();
    });

    renderAdminPosts();
}

renderPublicCommitteeFeed();
renderSectionCommitteeFeed();
fetchServerPosts().then(() => {
    renderPublicCommitteeFeed();
    renderSectionCommitteeFeed();
    renderAdminPosts();
});
initCommitteePublishing();




