/**
 * JavaScript untuk halaman Display - Version 3 (4 Status)
 * Menampilkan semua status kehadiran dalam mode read-only
 * Support: ADA, CUTI, TUGAS LUAR, TIDAK ADA
 */

// Data: daftar jabatan (fallback jika API tidak tersedia)
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'
];

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

// Global variables untuk data dari API
let positions = [];
let attendanceData = [];
let isApiMode = false;
let previousStatuses = [];
let loadingUntilByIndex = {};

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

// Get badge text based on status
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';
  }
}

// Load data dari API
async function loadDataFromAPI() {
  try {
    console.log('Loading data from API...');
    
    const positionsResponse = await positionsAPI.getPositions();
    if (positionsResponse.success) {
      positions = positionsResponse.data.map(p => p.name);
      isApiMode = true;
      console.log('Positions loaded from API:', positions);
    }

    const attendanceResponse = await attendanceAPI.getAttendance();
    if (attendanceResponse.success) {
      attendanceData = attendanceResponse.data;
      console.log('Attendance loaded from API:', attendanceData);
    }

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

// Get statuses from API data
function getStatusesFromAPI() {
  console.log('Getting statuses from API data:', attendanceData);
  
  const currentPositions = positions.length > 0 ? positions : FALLBACK_POSITIONS;
  
  if (!attendanceData || attendanceData.length === 0) {
    console.log('No attendance data available, returning default absent array');
    return Array(currentPositions.length).fill(STATUS.ABSENT);
  }
  
  let statuses;
  if (positions.length > 0 && positions.length === attendanceData.length) {
    statuses = attendanceData.map(item => item.status || STATUS.ABSENT);
  } else {
    statuses = Array(currentPositions.length).fill(STATUS.ABSENT);
    attendanceData.forEach((item, index) => {
      if (index < statuses.length) {
        statuses[index] = item.status || STATUS.ABSENT;
      }
    });
  }
  
  console.log('Statuses from API:', statuses);
  return statuses;
}

// Get statuses from localStorage (fallback)
function getStatusesFromLocalStorage() {
  try {
    const raw = localStorage.getItem('info-hadir-statuses-v2');
    if (!raw) return Array(FALLBACK_POSITIONS.length).fill(STATUS.ABSENT);
    const parsed = JSON.parse(raw);
    if (!Array.isArray(parsed)) return Array(FALLBACK_POSITIONS.length).fill(STATUS.ABSENT);
    return parsed.map(status => status || STATUS.ABSENT);
  } catch (_) {
    return Array(FALLBACK_POSITIONS.length).fill(STATUS.ABSENT);
  }
}

// Helper function to render a single row
function renderRow(container, positionName, index, status, loadingUntilByIndex) {
  if (!container || !positionName) {
    console.error('renderRow: Invalid parameters', { container: !!container, positionName });
    return;
  }

  const row = document.createElement('div');
  row.className = 'row';

  const no = document.createElement('div');
  no.className = 'cell';
  no.textContent = String(index);

  const jabatan = document.createElement('div');
  jabatan.className = 'cell';
  jabatan.textContent = positionName;

  const statusCell = document.createElement('div');
  statusCell.className = 'cell center';

  const badge = document.createElement('span');
  const badgeClass = getBadgeClass(status);
  const shouldShowLoading = loadingUntilByIndex && Date.now() < loadingUntilByIndex;
  const animClass = shouldShowLoading ? (' anim-' + badgeClass) : '';
  badge.className = shouldShowLoading ? ('badge ' + badgeClass + ' loading' + animClass) : ('badge ' + badgeClass);
  badge.textContent = getBadgeText(status);
  badge.style.cursor = 'default';
  badge.style.opacity = '1';
  
  // Make badges brighter in display mode
  if (status === STATUS.PRESENT) {
    badge.style.background = 'rgba(32, 201, 151, 0.3)';
    badge.style.color = '#4ae8c7';
    badge.style.boxShadow = 'inset 0 0 0 2px rgba(32,201,151,0.6)';
  } else if (status === STATUS.CUTI) {
    badge.style.background = 'rgba(255, 193, 7, 0.3)';
    badge.style.color = '#ffd54f';
    badge.style.boxShadow = 'inset 0 0 0 2px rgba(255,193,7,0.6)';
  } else {
    badge.style.background = 'rgba(255, 92, 92, 0.3)';
    badge.style.color = '#ffb3b3';
    badge.style.boxShadow = 'inset 0 0 0 2px rgba(255,92,92,0.6)';
  }

  statusCell.appendChild(badge);
  row.appendChild(no);
  row.appendChild(jabatan);
  row.appendChild(statusCell);
  container.appendChild(row);
}

// Render table untuk display mode (read-only) - 2 columns
function renderTable() {
  console.log('=== renderTable called ===');
  
  const leftContainer = document.getElementById('table-body-left');
  const rightContainer = document.getElementById('table-body-right');
  const container = document.getElementById('table-body');
  
  if (!leftContainer && !rightContainer && !container) {
    console.error('CRITICAL: No containers found!');
    return;
  }
  
  const useTwoColumns = leftContainer && rightContainer;

  const currentPositions = positions.length > 0 ? positions : FALLBACK_POSITIONS;
  let statuses = isApiMode ? getStatusesFromAPI() : getStatusesFromLocalStorage();

  if (!statuses || !Array.isArray(statuses)) {
    statuses = Array(currentPositions.length).fill(STATUS.ABSENT);
  }

  if (statuses.length !== currentPositions.length) {
    while (statuses.length < currentPositions.length) {
      statuses.push(STATUS.ABSENT);
    }
    statuses = statuses.slice(0, currentPositions.length);
  }

  // Detect changes and mark for loading animation
  if (previousStatuses.length === statuses.length) {
    statuses.forEach((status, index) => {
      if (previousStatuses[index] !== status) {
        loadingUntilByIndex[index] = Date.now() + 2000;
      }
    });
  }

  // Clear containers
  if (useTwoColumns) {
    if (leftContainer) leftContainer.innerHTML = '';
    if (rightContainer) rightContainer.innerHTML = '';
  } else if (container) {
    container.innerHTML = '';
  }

  if (useTwoColumns) {
    const leftPositions = currentPositions.slice(0, 5);
    const rightPositions = currentPositions.slice(5, 10);
    
    if (leftContainer && leftPositions.length > 0) {
      leftPositions.forEach((name, localIndex) => {
        const globalIndex = localIndex;
        const loadingTime = loadingUntilByIndex[globalIndex];
        const status = statuses[globalIndex] || STATUS.ABSENT;
        renderRow(leftContainer, name, globalIndex + 1, status, loadingTime);
      });
    }
    
    if (rightContainer && rightPositions.length > 0) {
      rightPositions.forEach((name, localIndex) => {
        const globalIndex = localIndex + 5;
        const loadingTime = loadingUntilByIndex[globalIndex];
        const status = statuses[globalIndex] || STATUS.ABSENT;
        renderRow(rightContainer, name, globalIndex + 1, status, loadingTime);
      });
    }
  } else {
    const targetContainer = container || leftContainer || rightContainer;
    if (targetContainer) {
      currentPositions.forEach((name, index) => {
        const loadingTime = loadingUntilByIndex[index];
        const status = statuses[index] || STATUS.ABSENT;
        renderRow(targetContainer, name, index + 1, status, loadingTime);
      });
    }
  }

  previousStatuses = statuses.slice();
  console.log('=== Table render completed ===');
}

// Clock
function updateClock() {
  const now = new Date();
  const seconds = now.getSeconds();
  const minutes = now.getMinutes();
  const hours = now.getHours();

  const secondDeg = seconds * 6;
  const minuteDeg = minutes * 6 + seconds * 0.1;
  const hourDeg = (hours % 12) * 30 + minutes * 0.5;

  const offset = -90;
  document.getElementById('second-hand').style.transform = `translate(-0%, -50%) rotate(${secondDeg + offset}deg)`;
  document.getElementById('minute-hand').style.transform = `translate(-0%, -50%) rotate(${minuteDeg + offset}deg)`;
  document.getElementById('hour-hand').style.transform   = `translate(-0%, -50%) rotate(${hourDeg + offset}deg)`;

  const dateText = document.getElementById('date-text');
  const locale = 'id-ID';
  const formatted = now.toLocaleDateString(locale, { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
  const time = now.toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit', second: '2-digit' });
  dateText.textContent = `${formatted} • ${time} WITA`;
}

// Check if user is logged in
function isLoggedIn() {
  const session = sessionStorage.getItem('info-hadir-session');
  return session !== null;
}

// Get current user from session
function getCurrentUser() {
  const session = sessionStorage.getItem('info-hadir-session');
  if (!session) return null;
  
  try {
    return JSON.parse(session);
  } catch (error) {
    console.error('Error parsing session:', error);
    return null;
  }
}

// Update login button based on session
function updateLoginButton() {
  const loginBtn = document.getElementById('login-btn');
  if (!loginBtn) return;
  
  const btnIcon = loginBtn.querySelector('.btn-icon');
  
  if (isLoggedIn()) {
    loginBtn.classList.add('logout');
    loginBtn.setAttribute('title', 'Kembali ke Dashboard');
    if (btnIcon) {
      btnIcon.innerHTML = `
        <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
        <polyline points="9 22 9 12 15 12 15 22" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
      `;
    }
  } else {
    loginBtn.classList.remove('logout');
    loginBtn.setAttribute('title', 'Login');
    if (btnIcon) {
      btnIcon.innerHTML = `
        <path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4M10 17l5-5-5-5M15 12H3" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
      `;
    }
  }
}

// Handle login button click
function handleLoginClick() {
  if (isLoggedIn()) {
    window.location.href = 'dashboard.html';
  } else {
    window.location.href = 'login.php';
  }
}

// Fullscreen detection
function checkFullscreen() {
  const apiFullscreen = !!(document.fullscreenElement || 
                         document.webkitFullscreenElement || 
                         document.mozFullScreenElement || 
                         document.msFullscreenElement);
  const sw = window.screen ? window.screen.width : 0;
  const sh = window.screen ? window.screen.height : 0;
  const aw = window.screen ? (window.screen.availWidth || sw) : sw;
  const ah = window.screen ? (window.screen.availHeight || sh) : sh;
  const iw = window.innerWidth;
  const ih = window.innerHeight;
  const near = (a, b, tol) => Math.abs(a - b) <= tol;
  const mediaFullscreen = window.matchMedia && window.matchMedia('(display-mode: fullscreen)').matches;
  const topNearZero = Math.abs((window.screenTop ?? window.screenY ?? 0)) <= 1;
  const leftNearZero = Math.abs((window.screenLeft ?? window.screenX ?? 0)) <= 1;
  const condExactScreen = sw && sh && near(iw, sw, 2) && near(ih, sh, 2) && topNearZero && leftNearZero;
  const condAvailScreen = aw && ah && near(iw, aw, 2) && near(ih, ah, 2) && topNearZero && leftNearZero;
  const f11Fullscreen = !apiFullscreen && (condExactScreen || condAvailScreen);
  const isFullscreen = apiFullscreen || mediaFullscreen || f11Fullscreen;
  
  if (isFullscreen) {
    document.body.classList.add('fullscreen');
  } else {
    document.body.classList.remove('fullscreen');
  }
}

// Setup fullscreen listener
function setupFullscreenListener() {
  const events = [
    'fullscreenchange',
    'webkitfullscreenchange', 
    'mozfullscreenchange',
    'MSFullscreenChange'
  ];
  
  events.forEach(event => {
    document.addEventListener(event, checkFullscreen);
  });
  window.addEventListener('resize', checkFullscreen);
  window.addEventListener('orientationchange', checkFullscreen);
  setInterval(checkFullscreen, 1000);
  
  checkFullscreen();
}

// Initialize display page
document.addEventListener('DOMContentLoaded', async () => {
  console.log('Display page loaded');
  document.documentElement.classList.add('portrait-mode');
  document.body.classList.add('portrait-mode');
  
  const loginBtn = document.getElementById('login-btn');
  if (loginBtn) {
    loginBtn.addEventListener('click', handleLoginClick);
    updateLoginButton();
  }
  
  setupFullscreenListener();

  try {
    await loadDataFromAPI();
  } catch (error) {
    console.error('Error loading data:', error);
  }

  const face = document.querySelector('.clock-face');
  if (face && face.querySelectorAll('.number').length === 0) {
    for (let n = 1; n <= 12; n++) {
      const el = document.createElement('div');
      el.className = 'number';
      el.textContent = String(n);
      const angle = (n - 3) * (Math.PI * 2) / 12;
      const radiusPercent = 42;
      el.style.left = `calc(50% + ${radiusPercent}% * cos(${angle}))`;
      el.style.top  = `calc(50% + ${radiusPercent}% * sin(${angle}))`;
      face.appendChild(el);
    }
  }
  
  setTimeout(() => {
    renderTable();
  }, 100);
  
  updateClock();
  setInterval(updateClock, 1000);
  
  if (isApiMode) {
    setInterval(async () => {
      try {
        await loadDataFromAPI();
        renderTable();
        console.log('Display data refreshed from API');
      } catch (error) {
        console.log('Auto-refresh failed:', error.message);
      }
    }, 3000);
  }
  
  setTimeout(() => {
    renderTable();
  }, 500);
});
