/**
 * Display Mobile JavaScript
 * Optimized for mobile viewing with auto-refresh
 */

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

// 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 refreshInterval = null;

// 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';
  }
}

// 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',
    second: '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;
  }
}

// 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) {
  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;
}

// 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);

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

  currentPositions.forEach((positionName, index) => {
    const status = statuses[index] || STATUS.ABSENT;

    const item = document.createElement('div');
    item.className = 'attendance-item';
    item.style.animationDelay = `${index * 0.05}s`;

    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);

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

// Show refresh indicator
function showRefreshIndicator() {
  const indicator = document.getElementById('refresh-indicator');
  indicator.style.display = 'flex';
  
  setTimeout(() => {
    indicator.style.display = 'none';
  }, 1000);
}

// Auto-refresh data
async function autoRefresh() {
  showRefreshIndicator();
  await loadDataFromAPI();
  renderAttendanceList();
}

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

  // Update date time
  updateDateTime();
  setInterval(updateDateTime, 1000);

  // Load initial data
  await loadDataFromAPI();
  renderAttendanceList();

  // Auto-refresh every 5 seconds if API mode
  if (isApiMode) {
    refreshInterval = setInterval(autoRefresh, 5000);
  }

  console.log('Display mobile initialized');
}

// Cleanup on page unload
window.addEventListener('beforeunload', () => {
  if (refreshInterval) {
    clearInterval(refreshInterval);
  }
});

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