/**
 * Mobile Dashboard JavaScript
 * Optimized for touch interactions and mobile devices
 */

// Status constants
const STATUS = {
  PRESENT: 'present',
  ABSENT: 'absent',
  CUTI: 'cuti',
  TUGAS_LUAR: 'tugas_luar'
};

const STATUS_CYCLE = [STATUS.PRESENT, STATUS.CUTI, STATUS.TUGAS_LUAR, STATUS.ABSENT];

// Fallback positions
const FALLBACK_POSITIONS = [
  'Kepala Dinas',
  'Sekretaris',
  'Kabid Pembinaan Pendidikan Dasar',
  'Kabid Pembinaan PAUD dan Pendidikan Non Formal',
  'Kabid Kelembagaan dan Sarana Prasarana Pendidikan',
  'Kabid Kebudayaan',
  'Kasubag Umum dan Kepegawaian',
  'Kasubag Perencanaan dan Pelaporan',
  'Kasubag Keuangan'
];

// Global state
let positions = [];
let attendanceData = [];
let isApiMode = false;
let currentUser = null;
let isUpdating = false;

// Session key
const SESSION_KEY = 'info-hadir-session';

// Get badge class
function getBadgeClass(status) {
  switch(status) {
    case STATUS.PRESENT: return 'success';
    case STATUS.CUTI: return 'warning';
    case STATUS.TUGAS_LUAR: return 'info';
    case STATUS.ABSENT: return 'danger';
    default: return 'danger';
  }
}

// Get badge text
function getBadgeText(status) {
  switch(status) {
    case STATUS.PRESENT: return 'ADA';
    case STATUS.CUTI: return 'CUTI';
    case STATUS.TUGAS_LUAR: return 'TUGAS LUAR';
    case STATUS.ABSENT: return 'TIDAK ADA';
    default: return 'TIDAK ADA';
  }
}

// Get next status
function getNextStatus(currentStatus) {
  const currentIndex = STATUS_CYCLE.indexOf(currentStatus);
  const nextIndex = (currentIndex + 1) % STATUS_CYCLE.length;
  return STATUS_CYCLE[nextIndex];
}

// Get current user
function getCurrentUser() {
  const session = sessionStorage.getItem(SESSION_KEY);
  console.log('getCurrentUser called, session:', session);
  try {
    const user = session ? JSON.parse(session) : null;
    console.log('Parsed user:', user);
    return user;
  } catch (error) {
    console.error('Error parsing session:', error);
    return null;
  }
}

// Update date time
function updateDateTime() {
  const now = new Date();
  const options = { 
    weekday: 'long', 
    year: 'numeric', 
    month: 'long', 
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  };
  const formatted = now.toLocaleDateString('id-ID', options);
  document.getElementById('date-time').textContent = formatted;
}

// Load data from API
async function loadDataFromAPI() {
  try {
    const positionsResponse = await positionsAPI.getPositions();
    if (positionsResponse.success) {
      positions = positionsResponse.data.map(p => p.name);
      isApiMode = true;
    }

    const attendanceResponse = await attendanceAPI.getAttendance();
    if (attendanceResponse.success) {
      attendanceData = attendanceResponse.data;
    }

    return true;
  } catch (error) {
    console.log('API not available, using fallback:', error.message);
    positions = [...FALLBACK_POSITIONS];
    isApiMode = false;
    return false;
  }
}

// Update attendance via API
async function updateAttendanceAPI(positionId, status) {
  if (!currentUser || !currentUser.id) {
    showToast('Anda harus login untuk mengubah status', 'error');
    return false;
  }

  try {
    const response = await attendanceAPI.updateAttendance(positionId, status, currentUser.id);
    if (response.success) {
      return true;
    }
    return false;
  } catch (error) {
    console.error('Failed to update attendance:', error);
    return false;
  }
}

// Calculate stats
function calculateStats(statuses) {
  const stats = {
    present: 0,
    cuti: 0,
    tugas_luar: 0,
    absent: 0
  };

  statuses.forEach(status => {
    if (status === STATUS.PRESENT) stats.present++;
    else if (status === STATUS.CUTI) stats.cuti++;
    else if (status === STATUS.TUGAS_LUAR) stats.tugas_luar++;
    else stats.absent++;
  });

  return stats;
}

// Update stats display
function updateStats(statuses) {
  // Check if user is non-admin
  const isAdmin = currentUser && currentUser.isAdmin;
  const userPositionIndex = currentUser ? currentUser.positionIndex : -1;
  
  console.log('updateStats called:', { 
    hasCurrentUser: !!currentUser, 
    isAdmin, 
    userPositionIndex,
    currentUser 
  });
  
  if (currentUser && !isAdmin && userPositionIndex >= 0) {
    console.log('User mode: showing checkmarks only');
    // For non-admin users, make stats cards clickable
    const userStatus = statuses[userPositionIndex] || STATUS.ABSENT;
    console.log('User status:', userStatus);
    
    // Show checkmark on active status FIRST
    document.getElementById('stat-present').textContent = userStatus === STATUS.PRESENT ? '✓' : '';
    document.getElementById('stat-cuti').textContent = userStatus === STATUS.CUTI ? '✓' : '';
    document.getElementById('stat-tugas').textContent = userStatus === STATUS.TUGAS_LUAR ? '✓' : '';
    document.getElementById('stat-absent').textContent = userStatus === STATUS.ABSENT ? '✓' : '';
    
    // Get all stat cards
    const statCards = document.querySelectorAll('.stat-card');
    
    // Make cards clickable and highlight active status
    statCards.forEach((card, index) => {
      card.style.cursor = 'pointer';
      
      // Determine which status this card represents
      let cardStatus;
      if (index === 0) cardStatus = STATUS.PRESENT;
      else if (index === 1) cardStatus = STATUS.CUTI;
      else if (index === 2) cardStatus = STATUS.TUGAS_LUAR;
      else cardStatus = STATUS.ABSENT;
      
      // Add/remove active class
      if (cardStatus === userStatus) {
        card.classList.add('active');
      } else {
        card.classList.remove('active');
      }
      
      // Remove old event listeners by cloning
      const newCard = card.cloneNode(true);
      card.parentNode.replaceChild(newCard, card);
      
      // Add click handler
      newCard.addEventListener('click', async () => {
        if (isUpdating) return;
        
        // Don't do anything if already this status
        if (cardStatus === userStatus) {
          showToast('Status sudah ' + getBadgeText(cardStatus), 'info');
          return;
        }
        
        isUpdating = true;
        
        // Visual feedback
        newCard.style.opacity = '0.5';
        
        if (isApiMode && attendanceData[userPositionIndex]) {
          const positionId = attendanceData[userPositionIndex].position_id;
          const success = await updateAttendanceAPI(positionId, cardStatus);
          
          if (success) {
            showToast('Status diubah ke ' + getBadgeText(cardStatus), 'success');
            await loadDataFromAPI();
            renderAttendanceList();
          } else {
            showToast('Gagal mengubah status', 'error');
            newCard.style.opacity = '1';
          }
        }
        
        isUpdating = false;
      });
    });
    
  } else {
    console.log('Admin/Guest mode: showing totals');
    // For admin or guest, show all stats (not clickable)
    const stats = calculateStats(statuses);
    document.getElementById('stat-present').textContent = stats.present;
    document.getElementById('stat-cuti').textContent = stats.cuti;
    document.getElementById('stat-tugas').textContent = stats.tugas_luar;
    document.getElementById('stat-absent').textContent = stats.absent;
    
    // Remove active class and reset cursor
    const statCards = document.querySelectorAll('.stat-card');
    statCards.forEach(card => {
      card.style.cursor = 'default';
      card.classList.remove('active');
    });
  }
}

// Render attendance list
function renderAttendanceList() {
  const container = document.getElementById('attendance-list');
  container.innerHTML = '';

  const currentPositions = positions.length > 0 ? positions : FALLBACK_POSITIONS;
  const statuses = isApiMode ? 
    attendanceData.map(item => item.status || STATUS.ABSENT) :
    Array(currentPositions.length).fill(STATUS.ABSENT);

  // Update stats
  updateStats(statuses);

  // Check user permissions
  const isAdmin = currentUser && currentUser.isAdmin;
  const userPositionIndex = currentUser ? currentUser.positionIndex : -1;

  // Always show section title and list for all users
  const sectionTitle = document.getElementById('section-title');
  if (sectionTitle) sectionTitle.style.display = 'flex';
  container.style.display = 'flex';
  
  currentPositions.forEach((positionName, index) => {
    const status = statuses[index] || STATUS.ABSENT;
    const canEdit = !currentUser || isAdmin || userPositionIndex === index;

    const item = document.createElement('div');
    item.className = 'attendance-item';

    const number = document.createElement('div');
    number.className = 'item-number';
    number.textContent = index + 1;

    const info = document.createElement('div');
    info.className = 'item-info';

    const name = document.createElement('div');
    name.className = 'item-name';
    name.textContent = positionName;

    info.appendChild(name);

    const badge = document.createElement('div');
    badge.className = `status-badge ${getBadgeClass(status)}`;
    badge.textContent = getBadgeText(status);
    badge.dataset.index = index;
    badge.dataset.status = status;

    if (canEdit && !isUpdating) {
      badge.style.cursor = 'pointer';
      badge.addEventListener('click', async (e) => {
        e.preventDefault();
        e.stopPropagation();

        if (isUpdating) return;

        const newStatus = getNextStatus(status);
        isUpdating = true;

        // Visual feedback
        badge.style.opacity = '0.5';
        badge.textContent = '...';

        if (isApiMode && attendanceData[index]) {
          const positionId = attendanceData[index].position_id;
          const success = await updateAttendanceAPI(positionId, newStatus);

          if (success) {
            showToast('Status berhasil diubah', 'success');
            await loadDataFromAPI();
            renderAttendanceList();
          } else {
            showToast('Gagal mengubah status', 'error');
            badge.style.opacity = '1';
            badge.className = `status-badge ${getBadgeClass(status)}`;
            badge.textContent = getBadgeText(status);
          }
        }

        isUpdating = false;
      });
    } else {
      badge.style.opacity = '0.7';
    }

    item.appendChild(number);
    item.appendChild(info);
    item.appendChild(badge);
    container.appendChild(item);
  });

  if (currentPositions.length === 0) {
    container.innerHTML = `
      <div class="empty-state">
        <div class="empty-icon">📭</div>
        <div>Tidak ada data</div>
      </div>
    `;
  }
}

// Show toast notification
function showToast(message, type = 'info') {
  // Remove existing toast
  const existingToast = document.querySelector('.toast');
  if (existingToast) {
    existingToast.remove();
  }

  const toast = document.createElement('div');
  toast.className = 'toast';
  toast.style.cssText = `
    position: fixed;
    top: 80px;
    left: 50%;
    transform: translateX(-50%);
    background: ${type === 'success' ? 'rgba(16, 185, 129, 0.95)' : 'rgba(239, 68, 68, 0.95)'};
    color: white;
    padding: 12px 20px;
    border-radius: 12px;
    font-size: 14px;
    font-weight: 600;
    z-index: 1000;
    animation: slideDown 0.3s ease;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  `;
  toast.textContent = message;

  document.body.appendChild(toast);

  setTimeout(() => {
    toast.style.animation = 'slideUp 0.3s ease';
    setTimeout(() => toast.remove(), 300);
  }, 2000);
}

// Setup user interface
function setupUserInterface() {
  currentUser = getCurrentUser();
  
  console.log('setupUserInterface called, currentUser:', currentUser);

  if (currentUser) {
    const userCard = document.getElementById('user-card');
    const userAvatar = document.getElementById('user-avatar');
    const userName = document.getElementById('user-name');
    const userRole = document.getElementById('user-role');
    const userBadge = document.getElementById('user-badge');
    const adminMenu = document.getElementById('admin-menu');
    const desktopMenu = document.getElementById('desktop-menu');
    const logoutMenu = document.getElementById('logout-menu');
    const loginMenu = document.getElementById('login-menu');

    userCard.style.display = 'flex';
    userName.textContent = currentUser.fullName || currentUser.username;
    userRole.textContent = currentUser.positionName || currentUser.position || 'User';
    
    // Avatar initial
    const initial = (currentUser.fullName || currentUser.username || 'U').charAt(0).toUpperCase();
    userAvatar.textContent = initial;

    // Badge
    if (currentUser.isAdmin) {
      userBadge.textContent = 'Admin';
      userBadge.style.background = 'rgba(47, 107, 255, 0.2)';
      userBadge.style.borderColor = 'rgba(47, 107, 255, 0.3)';
      userBadge.style.color = '#93c5fd';
      if (adminMenu) adminMenu.style.display = 'flex';
      if (desktopMenu) desktopMenu.style.display = 'flex';
    } else {
      userBadge.textContent = 'User';
      // Hide desktop menu for non-admin users
      if (desktopMenu) desktopMenu.style.display = 'none';
    }

    if (logoutMenu) logoutMenu.style.display = 'flex';
    if (loginMenu) loginMenu.style.display = 'none';
  }
}

// Menu toggle
function setupMenu() {
  const menuBtn = document.getElementById('menu-btn');
  const sideMenu = document.getElementById('side-menu');
  const menuOverlay = document.getElementById('menu-overlay');
  const closeMenu = document.getElementById('close-menu');

  function openMenu() {
    sideMenu.classList.add('open');
    menuOverlay.classList.add('show');
  }

  function closeMenuFn() {
    sideMenu.classList.remove('open');
    menuOverlay.classList.remove('show');
  }

  menuBtn.addEventListener('click', openMenu);
  closeMenu.addEventListener('click', closeMenuFn);
  menuOverlay.addEventListener('click', closeMenuFn);

  // Logout handler
  const logoutMenu = document.getElementById('logout-menu');
  if (logoutMenu) {
    logoutMenu.addEventListener('click', (e) => {
      e.preventDefault();
      if (confirm('Apakah Anda yakin ingin keluar?')) {
        sessionStorage.removeItem(SESSION_KEY);
        window.location.href = 'logout.php';
      }
    });
  }
}

// Refresh button
function setupRefresh() {
  const refreshBtn = document.getElementById('refresh-btn');
  refreshBtn.addEventListener('click', async (e) => {
    e.preventDefault();
    
    const icon = refreshBtn.querySelector('.nav-icon');
    icon.style.animation = 'spin 1s linear';
    
    await loadDataFromAPI();
    renderAttendanceList();
    
    setTimeout(() => {
      icon.style.animation = '';
    }, 1000);
    
    showToast('Data berhasil diperbarui', 'success');
  });
}

// Initialize app
async function initializeApp() {
  console.log('Initializing mobile dashboard...');

  updateDateTime();
  setInterval(updateDateTime, 1000);

  setupUserInterface();
  setupMenu();
  setupRefresh();

  await loadDataFromAPI();
  renderAttendanceList();

  // Auto-refresh every 5 seconds if API mode
  if (isApiMode) {
    setInterval(async () => {
      if (!isUpdating) {
        await loadDataFromAPI();
        renderAttendanceList();
      }
    }, 5000);
  }

  console.log('Mobile dashboard initialized');
}

// Add CSS animations
const style = document.createElement('style');
style.textContent = `
  @keyframes slideDown {
    from { transform: translate(-50%, -20px); opacity: 0; }
    to { transform: translate(-50%, 0); opacity: 1; }
  }
  @keyframes slideUp {
    from { transform: translate(-50%, 0); opacity: 1; }
    to { transform: translate(-50%, -20px); opacity: 0; }
  }
`;
document.head.appendChild(style);

// Start app
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', initializeApp);
} else {
  initializeApp();
}
