// Portal Website dan Aplikasi By lurredev

document.addEventListener('DOMContentLoaded', function() {
    // Elements
    const mainMenu = document.querySelector('.main-menu');
    const sections = document.querySelectorAll('section');
    const addAppForm = document.getElementById('add-app-form');
    const iconOptions = document.querySelectorAll('.icon-option');
    const appsGrid = document.getElementById('apps-grid');
    const themeSelector = document.getElementById('theme-selector');
    const saveSettingsBtn = document.getElementById('save-settings');
  
    // State
    let userApps = [];
    let userSettings = {
      theme: 'light',
      openBehavior: 'new-tab',
      sessionTimeout: 60
    };
  
    // Initialize
    initializeExtension();
  
    // Menu Navigation
    mainMenu.addEventListener('click', function(e) {
      const menuItem = e.target.closest('li');
      if (!menuItem) return;
  
      // Update active menu
      document.querySelector('.main-menu li.active').classList.remove('active');
      menuItem.classList.add('active');
  
      // Show corresponding section
      const targetSection = menuItem.getAttribute('data-menu');
      sections.forEach(section => {
        section.classList.remove('active');
        if (section.id === targetSection) {
          section.classList.add('active');
        }
      });
    });
  
    // Icon Selection
    iconOptions.forEach(icon => {
      icon.addEventListener('click', function() {
        // Remove selected class from all icons
        iconOptions.forEach(i => i.classList.remove('selected'));
        // Add selected class to clicked icon
        this.classList.add('selected');
        // Update icon input
        document.getElementById('app-icon').value = this.getAttribute('data-icon');
      });
    });
  
    // Add App Form Submit
    addAppForm.addEventListener('submit', function(e) {
      e.preventDefault();
      const name = document.getElementById('app-name').value;
      const url = document.getElementById('app-url').value;
      const icon = document.getElementById('app-icon').value || 'fa-globe';
  
      addApp(name, url, icon);
      this.reset();
      iconOptions.forEach(i => i.classList.remove('selected'));
  
      // Switch to Apps view
      document.querySelector('[data-menu="apps"]').click();
    });
  
    // Theme Selector
    themeSelector.addEventListener('change', function() {
      applyTheme(this.value);
      userSettings.theme = this.value;
    });
  
    // Save Settings
    saveSettingsBtn.addEventListener('click', function() {
      userSettings = {
        theme: themeSelector.value,
        openBehavior: document.getElementById('open-behavior').value,
        sessionTimeout: parseInt(document.getElementById('session-timeout').value) || 60
      };
  
      saveUserSettings();
      alert('Pengaturan disimpan!');
    });
  
    // Initialize Extension
    function initializeExtension() {
      loadUserData();
      loadUserSettings();
      refreshAppsList();
    }
  
    // Load User Data
    function loadUserData() {
      userApps = JSON.parse(localStorage.getItem('portalApps') || '[]');
    }
  
    // Load User Settings
    function loadUserSettings() {
      const settings = JSON.parse(localStorage.getItem('portalSettings') || 'null');
      if (settings) {
        userSettings = {...userSettings, ...settings};
      }
  
      // Apply saved settings to UI
      themeSelector.value = userSettings.theme;
      document.getElementById('open-behavior').value = userSettings.openBehavior;
      document.getElementById('session-timeout').value = userSettings.sessionTimeout;
  
      // Apply theme
      applyTheme(userSettings.theme);
    }
  
    // Save User Data
    function saveUserData() {
      localStorage.setItem('portalApps', JSON.stringify(userApps));
    }
  
    // Save User Settings
    function saveUserSettings() {
      localStorage.setItem('portalSettings', JSON.stringify(userSettings));
    }
  
    // Add App Function
    function addApp(name, url, icon) {
      // Ensure URL has protocol
      if (!/^https?:\/\//i.test(url)) {
        url = 'https://' + url;
      }
      
      // Create new app object
      const newApp = {
        id: Date.now().toString(),
        name,
        url,
        icon,
        dateAdded: new Date().toISOString()
      };
      
      // Add to apps array
      userApps.push(newApp);
      
      // Save to localStorage
      saveUserData();
      
      // Refresh apps list
      refreshAppsList();
    }
  
    // Refresh Apps List
    function refreshAppsList() {
      // Clear current list
      appsGrid.innerHTML = '';
      
      // Check if user has apps
      if (userApps.length === 0) {
        appsGrid.innerHTML = '<p class="no-apps">Belum ada aplikasi. Pergi ke "Tambah Aplikasi" untuk memulai.</p>';
        return;
      }
      
      // Add each app to the grid
      userApps.forEach(app => {
        const appTile = document.createElement('div');
        appTile.className = 'app-tile';
        appTile.setAttribute('data-app-id', app.id);
        appTile.innerHTML = `
          <div class="app-icon">
            <i class="fas ${app.icon}"></i>
          </div>
          <div class="app-name">${app.name}</div>
        `;
        
        // Add click handler
        appTile.addEventListener('click', function() {
          openApp(app);
        });
        
        // Add context menu for removal
        appTile.addEventListener('contextmenu', function(e) {
          e.preventDefault();
          if (confirm(`Hapus ${app.name} dari dasbor Anda?`)) {
            removeApp(app.id);
          }
        });
        
        appsGrid.appendChild(appTile);
      });
    }
  
    // Open App Function
    function openApp(app) {
      // Determine how to open the app based on settings
      const openInNewTab = userSettings.openBehavior === 'new-tab';
      
      // Open the app URL
      if (openInNewTab) {
        chrome.tabs.create({ url: app.url });
      } else {
        chrome.tabs.update({ url: app.url });
      }
      
      // Record last opened timestamp
      const appIndex = userApps.findIndex(a => a.id === app.id);
      if (appIndex !== -1) {
        userApps[appIndex].lastOpened = new Date().toISOString();
        saveUserData();
      }
    }
  
    // Remove App Function
    function removeApp(id) {
      userApps = userApps.filter(app => app.id !== id);
      saveUserData();
      refreshAppsList();
    }
  
    // Apply Theme Function
    function applyTheme(theme) {
      if (theme === 'system') {
        // Check system preference
        if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
          document.body.classList.add('dark-theme');
        } else {
          document.body.classList.remove('dark-theme');
        }
      } else if (theme === 'dark') {
        document.body.classList.add('dark-theme');
      } else {
        document.body.classList.remove('dark-theme');
      }
    }
  
    // Setup default apps for new users
    function setupDefaultApps() {
      if (userApps.length === 0) {
        const defaultApps = [
          {
            id: 'default1',
            name: 'Gmail',
            url: 'https://mail.google.com',
            icon: 'fa-envelope',
            dateAdded: new Date().toISOString()
          },
          {
            id: 'default2',
            name: 'Google Drive',
            url: 'https://drive.google.com',
            icon: 'fa-cloud',
            dateAdded: new Date().toISOString()
          },
          {
            id: 'default3',
            name: 'Unhasy',
            url: 'https://unhasy.ac.id',
            icon: 'fa-graduation-cap',
            dateAdded: new Date().toISOString()
          }
        ];
        
        userApps = defaultApps;
        saveUserData();
        refreshAppsList();
      }
    }
  
    // Run setup for default apps if user is new
    if (!localStorage.getItem('portalApps')) {
      setupDefaultApps();
    }
});