/**
 * URAIO Community Hub - Main Script
 * Handles navigation, state management, and simulations
 */

const app = {
    // State
    state: {
        theme: localStorage.getItem('theme') || 'light',
        user: {
            name: 'User #' + Math.floor(Math.random() * 1000),
            id: 'u_' + Date.now(),
            houseNumber: localStorage.getItem('houseNumber') || 'Not Set'
        },
        battery: 85,
        solar: 120,
        onlineUsers: 42,
        temp: 28,
        posts: [
            {
                id: 1,
                author: 'Community Admin',
                time: '10 mins ago',
                content: '📢 Weekly community meeting is starting in 30 minutes at the main hall.',
                image: null,
                likes: 12,
                comments: 4
            },
            {
                id: 2,
                author: 'Sarah J.',
                time: '1 hour ago',
                content: 'Just shared some new educational resources in the File Sharing hub. Check them out! 📚',
                image: null,
                likes: 8,
                comments: 1
            },
            {
                id: 3,
                author: 'Dave M.',
                time: '3 hours ago',
                content: 'Anyone have a spare charging cable? Mine just broke.',
                image: 'https://via.placeholder.com/600x300?text=Broken+Cable',
                likes: 2,
                comments: 6
            }
        ],
        messages: [
            { id: 1, text: 'Hello everyone!', sender: 'other', time: '10:00' },
            { id: 2, text: 'Hi! How is the connection today?', sender: 'me', time: '10:01' },
            { id: 3, text: 'Signal is strong near the north node.', sender: 'other', time: '10:02' }
        ]
    },

    // Initialization
    init() {
        this.applyTheme();
        this.setupEventListeners();
        this.renderFeed();
        this.renderChat();
        this.startSimulation();
        this.updateStatusUI();
        this.updateProfileUI();
    },

    // Theme Management
    toggleTheme() {
        this.state.theme = this.state.theme === 'light' ? 'dark' : 'light';
        localStorage.setItem('theme', this.state.theme);
        this.applyTheme();
    },

    applyTheme() {
        document.documentElement.setAttribute('data-theme', this.state.theme);
        const icon = document.querySelector('#theme-toggle i');
        if (this.state.theme === 'dark') {
            icon.classList.remove('fa-moon');
            icon.classList.add('fa-sun');
        } else {
            icon.classList.remove('fa-sun');
            icon.classList.add('fa-moon');
        }
    },

    // Navigation
    navigateTo(viewId) {
        // Hide all views
        document.querySelectorAll('.view').forEach(el => el.classList.remove('active'));
        // Show target view
        document.getElementById(`view-${viewId}`).classList.add('active');

        // Update Bottom Nav
        document.querySelectorAll('.nav-item').forEach(el => el.classList.remove('active'));
        document.querySelector(`.nav-item[data-target="${viewId}"]`)?.classList.add('active');

        // Handle FAB visibility
        const fab = document.querySelector('.fab');
        if (viewId === 'home') {
            fab.style.display = 'flex';
        } else {
            fab.style.display = 'none';
        }
    },

    // Modal Management
    openModal(modalType) {
        const overlay = document.getElementById('modal-overlay');
        overlay.classList.remove('hidden');

        if (modalType === 'new-post') {
            document.getElementById('modal-new-post').classList.remove('hidden');
        } else if (modalType === 'emergency') {
            document.getElementById('modal-emergency').classList.remove('hidden');
        } else {
            // Generic Modal handling
            const modal = document.getElementById('modal-generic');
            const title = document.getElementById('generic-modal-title');
            const content = document.getElementById('generic-modal-content');

            modal.classList.remove('hidden');

            // Set content based on type
            switch (modalType) {
                case 'files':
                    title.textContent = 'File Sharing';
                    content.innerHTML = '<p class="text-center text-muted">Local P2P file sharing active.<br>Scanning for peers...</p>';
                    break;
                case 'wiki':
                    title.textContent = 'Offline Wikipedia';
                    content.innerHTML = '<p class="text-center text-muted">Accessing local knowledge base...<br>3.2GB available offline.</p>';
                    break;
                case 'maps':
                    title.textContent = 'Community Maps';
                    content.innerHTML = '<div style="height:200px; background:#e5e7eb; display:flex; align-items:center; justify-content:center;">Map Placeholder</div>';
                    break;
                case 'health':
                    title.textContent = 'Health Resources';
                    content.innerHTML = '<ul class="list-group"><li class="list-item">First Aid Guide</li><li class="list-item">Local Clinics</li></ul>';
                    break;
                case 'ticket':
                    title.textContent = 'Community Tickets';
                    content.innerHTML = `
                        <ul class="list-group">
                            <li class="list-item">
                                <i class="fas fa-calendar-alt list-icon text-primary"></i>
                                <div>
                                    <strong>Weekly Meeting</strong><br>
                                    <small class="text-muted">Today, 18:00 - Main Hall</small>
                                </div>
                                <button class="btn-sm btn-primary" style="margin-left:auto">RSVP</button>
                            </li>
                            <li class="list-item">
                                <i class="fas fa-music list-icon text-secondary"></i>
                                <div>
                                    <strong>Music Night</strong><br>
                                    <small class="text-muted">Sat, 20:00 - Park</small>
                                </div>
                                <button class="btn-sm btn-primary" style="margin-left:auto">Buy</button>
                            </li>
                        </ul>`;
                    break;
                case 'shop':
                    title.textContent = 'Community Shop';
                    content.innerHTML = `
                        <div style="display:grid; grid-template-columns:1fr 1fr; gap:10px;">
                            <div style="background:var(--bg-body); padding:10px; border-radius:8px; text-align:center;">
                                <i class="fas fa-apple-alt fa-2x text-success" style="margin-bottom:8px;"></i>
                                <div>Fresh Apples</div>
                                <div class="text-primary font-bold">$2.00/kg</div>
                            </div>
                            <div style="background:var(--bg-body); padding:10px; border-radius:8px; text-align:center;">
                                <i class="fas fa-bread-slice fa-2x text-warning" style="margin-bottom:8px;"></i>
                                <div>Homemade Bread</div>
                                <div class="text-primary font-bold">$3.50</div>
                            </div>
                        </div>`;
                    break;
                case 'kitchen':
                    title.textContent = 'Community Kitchen';
                    content.innerHTML = `
                        <div style="text-align:center; margin-bottom:15px;">
                            <span class="badge badge-success">Open Now</span>
                        </div>
                        <h4 style="margin-bottom:10px;">Today's Menu</h4>
                        <ul class="list-group">
                            <li class="list-item">
                                <div>
                                    <strong>Vegetable Stew</strong><br>
                                    <small class="text-muted">Served with rice</small>
                                </div>
                                <span style="margin-left:auto; font-weight:bold;">$5.00</span>
                            </li>
                            <li class="list-item">
                                <div>
                                    <strong>Grilled Chicken</strong><br>
                                    <small class="text-muted">Local herbs</small>
                                </div>
                                <span style="margin-left:auto; font-weight:bold;">$7.50</span>
                            </li>
                        </ul>`;
                    break;
                case 'drive':
                    title.textContent = 'My Drive';
                    content.innerHTML = `
                        <ul class="list-group">
                            <li class="list-item">
                                <i class="fas fa-folder list-icon text-warning"></i>
                                <span>Documents</span>
                            </li>
                            <li class="list-item">
                                <i class="fas fa-folder list-icon text-warning"></i>
                                <span>Photos</span>
                            </li>
                            <li class="list-item">
                                <i class="fas fa-file-pdf list-icon text-danger"></i>
                                <span>Manual.pdf</span>
                                <small class="text-muted" style="margin-left:auto">2.4MB</small>
                            </li>
                        </ul>`;
                    break;
                default:
                    title.textContent = 'Info';
                    content.textContent = 'Feature coming soon.';
            }
        }
    },

    closeModals() {
        document.getElementById('modal-overlay').classList.add('hidden');
        document.querySelectorAll('.modal').forEach(el => el.classList.add('hidden'));
    },

    // Feed Logic
    renderFeed() {
        const container = document.getElementById('feed-container');
        container.innerHTML = this.state.posts.map(post => `
            <div class="feed-item">
                <div class="feed-header">
                    <div class="avatar">${post.author.charAt(0)}</div>
                    <div class="feed-meta">
                        <span class="feed-author">${post.author}</span>
                        <span class="feed-time">${post.time}</span>
                    </div>
                </div>
                <div class="feed-content">
                    <p>${post.content}</p>
                </div>
                ${post.image ? `<img src="${post.image}" class="feed-image" alt="Post image">` : ''}
                <div class="feed-actions">
                    <button class="action-btn"><i class="far fa-heart"></i> ${post.likes}</button>
                    <button class="action-btn"><i class="far fa-comment"></i> ${post.comments}</button>
                    <button class="action-btn"><i class="far fa-share-square"></i> Share</button>
                </div>
            </div>
        `).join('');
    },

    createPost() {
        const content = document.getElementById('post-content').value;
        if (!content.trim()) return;

        const newPost = {
            id: Date.now(),
            author: 'You',
            time: 'Just now',
            content: content,
            image: null,
            likes: 0,
            comments: 0
        };

        this.state.posts.unshift(newPost);
        this.renderFeed();
        this.closeModals();
        document.getElementById('post-content').value = '';
    },

    // Chat Logic
    renderChat() {
        const container = document.getElementById('chat-messages');
        container.innerHTML = this.state.messages.map(msg => `
            <div class="message ${msg.sender === 'me' ? 'sent' : 'received'}">
                ${msg.text}
            </div>
        `).join('');
        container.scrollTop = container.scrollHeight;
    },

    sendMessage() {
        const input = document.getElementById('message-input');
        const text = input.value.trim();
        if (!text) return;

        // Add user message
        this.state.messages.push({
            id: Date.now(),
            text: text,
            sender: 'me',
            time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
        });

        this.renderChat();
        input.value = '';

        // Simulate reply
        setTimeout(() => {
            this.state.messages.push({
                id: Date.now() + 1,
                text: 'Received loud and clear! 👍',
                sender: 'other',
                time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
            });
            this.renderChat();
        }, 1500);
    },

    // Simulation Logic
    startSimulation() {
        setInterval(() => {
            // Fluctuate values slightly
            this.state.battery = Math.max(0, Math.min(100, this.state.battery + (Math.random() > 0.5 ? -1 : 0)));
            this.state.solar = Math.max(0, Math.floor(this.state.solar + (Math.random() * 10 - 5)));
            this.state.onlineUsers = Math.max(0, Math.floor(this.state.onlineUsers + (Math.random() * 4 - 2)));

            this.updateStatusUI();
        }, 5000);
    },

    updateStatusUI() {
        document.getElementById('battery-level').textContent = `${this.state.battery}%`;
        document.getElementById('solar-input').textContent = `${this.state.solar}W`;
        document.getElementById('online-users').textContent = this.state.onlineUsers;
        document.getElementById('temperature').textContent = `${this.state.temp}°C`;
    },

    updateProfileUI() {
        document.getElementById('house-number-display').textContent = this.state.user.houseNumber;
    },

    editHouseNumber() {
        const newHouse = prompt('Enter your House Number:', this.state.user.houseNumber === 'Not Set' ? '' : this.state.user.houseNumber);
        if (newHouse !== null && newHouse.trim() !== '') {
            this.state.user.houseNumber = newHouse.trim();
            localStorage.setItem('houseNumber', this.state.user.houseNumber);
            this.updateProfileUI();
        }
    },

    setupEventListeners() {
        document.getElementById('theme-toggle').addEventListener('click', () => this.toggleTheme());
        document.getElementById('modal-overlay').addEventListener('click', () => this.closeModals());

        // Chat enter key
        document.getElementById('message-input').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') this.sendMessage();
        });
    }
};

// Initialize App
document.addEventListener('DOMContentLoaded', () => {
    app.init();
});
