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

// Status cycle: present -> cuti -> tugas_luar -> absent -> present
const STATUS_CYCLE = [STATUS.PRESENT, STATUS.CUTI, STATUS.TUGAS_LUAR, STATUS.ABSENT];

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

const STORAGE_KEY = 'info-hadir-statuses-v2';

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

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

function readSavedStatuses(count) {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return Array(count).fill(STATUS.ABSENT);
    const parsed = JSON.parse(raw);
    if (!Array.isArray(parsed)) return Array(count).fill(STATUS.ABSENT);
    return parsed.map(s => s || STATUS.ABSENT);
  } catch (_) {
    return Array(count).fill(STATUS.ABSENT);
  }
}

function saveStatuses(statuses) {
  try { localStorage.setItem(STORAGE_KEY, JSON.stringify(statuses)); } catch (_) {}
}

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

    // Load attendance
    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;
  }
}

// Update attendance via API
async function updateAttendanceAPI(positionId, status) {
  try {
    const currentUser = getCurrentUser();
    if (!currentUser || !currentUser.id) {
      throw new Error('User not logged in');
    }

    console.log('Dashboard: Updating attendance via API:', { positionId, status, userId: currentUser.id });
    const response = await attendanceAPI.updateAttendance(positionId, status, currentUser.id);
    console.log('Dashboard: API response:', response);
    
    if (response.success) {
      console.log('Dashboard: Attendance updated successfully in database:', response.data);
      return true;
    } else {
      console.log('Dashboard: Failed to update attendance in database');
    }
    return false;
  } catch (error) {
    console.error('Failed to update attendance via API:', error.message);
    console.error('Error details:', error);
    return false;
  }
}

// Get statuses from API data
function getStatusesFromAPI() {
  if (!attendanceData || attendanceData.length === 0) {
    return Array(FALLBACK_POSITIONS.length).fill(STATUS.ABSENT);
  }
  
  return attendanceData.map(item => item.status || STATUS.ABSENT);
}

// Render table for display mode (read-only)
function renderTableForDisplay(container, statuses) {
  const currentPositions = positions.length > 0 ? positions : FALLBACK_POSITIONS;
  
  currentPositions.forEach((name, index) => {
    const row = document.createElement('div');
    row.className = 'row';

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

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

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

    const status = statuses[index] || STATUS.ABSENT;
    const badge = document.createElement('span');
    badge.className = 'badge ' + getBadgeClass(status);
    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);
  });
}

function renderTable() {
  const container = document.getElementById('table-body');
  container.innerHTML = '';

  const currentPositions = positions.length > 0 ? positions : FALLBACK_POSITIONS;
  const statuses = isApiMode ? getStatusesFromAPI() : readSavedStatuses(currentPositions.length);
  const currentUser = getCurrentUser();

  // In display mode, don't require authentication
  if (isDisplayMode()) {
    renderTableForDisplay(container, statuses);
    return;
  }

  // Handle fallback mode when no user session
  if (!currentUser) {
    console.log('No user session found, using fallback display mode');
    renderTableForDisplay(container, statuses);
    return;
  }

  // For admin users, positionIndex can be -1 (no specific position)
  const isAdminUser = Boolean(currentUser.isAdmin);
  if (!isAdminUser && typeof currentUser.positionIndex !== 'number') {
    console.log('Invalid user session (no position), using fallback display mode');
    renderTableForDisplay(container, statuses);
    return;
  }

  if (isAdminUser) {
    // Admin mode: render semua jabatan dan izinkan update semuanya
    currentPositions.forEach((positionName, index) => {
      const row = document.createElement('div');
      row.className = 'row';

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

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

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

      const currentStatus = statuses[index] || STATUS.ABSENT;
      const badge = document.createElement('span');
      badge.className = 'badge ' + getBadgeClass(currentStatus);
      badge.textContent = getBadgeText(currentStatus);
      badge.setAttribute('data-index', String(index));
      badge.style.cursor = 'pointer';

      badge.addEventListener('click', (e) => {
        e.preventDefault();
        e.stopPropagation();

        const newStatus = getNextStatus(currentStatus);

        if (isApiMode && attendanceData[index]) {
          const positionId = attendanceData[index].position_id;
          updateAttendanceAPI(positionId, newStatus).then(success => {
            if (success) {
              statuses[index] = newStatus;
              badge.className = 'badge ' + getBadgeClass(newStatus);
              badge.textContent = getBadgeText(newStatus);
              badge.classList.remove('anim-success', 'anim-warning', 'anim-danger', 'loading');
              void badge.offsetWidth;
              const animClass = newStatus === STATUS.PRESENT ? 'anim-success' : 
                               newStatus === STATUS.CUTI ? 'anim-warning' : 'anim-danger';
              badge.classList.add(animClass, 'loading');
              setTimeout(() => badge.classList.remove('loading'), 2000);
              console.log(`Dashboard(Admin): Status updated for ${positionName} to ${newStatus}`);
              loadDataFromAPI().then(() => {
                console.log('Dashboard(Admin): Data refreshed after update');
              });
            } else {
              console.log('Dashboard(Admin): Failed to update status via API');
              alert('Gagal mengupdate status. Silakan coba lagi.');
            }
          });
        } else {
          // Fallback localStorage
          statuses[index] = newStatus;
          badge.className = 'badge ' + getBadgeClass(newStatus);
          badge.textContent = getBadgeText(newStatus);
          badge.classList.remove('anim-success', 'anim-warning', 'anim-danger', 'loading');
          void badge.offsetWidth;
          const animClass = newStatus === STATUS.PRESENT ? 'anim-success' : 
                           newStatus === STATUS.CUTI ? 'anim-warning' : 'anim-danger';
          badge.classList.add(animClass, 'loading');
          setTimeout(() => badge.classList.remove('loading'), 2000);
          saveStatuses(statuses);
          console.log(`Dashboard(Admin): Status updated for ${positionName} to ${newStatus} via localStorage`);
        }
      });

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

  // Non-admin: hanya tampilkan status user yang login
  const userPositionIndex = currentUser.positionIndex;
  const userPositionName = currentPositions[userPositionIndex] || 'Unknown Position';

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

  const no = document.createElement('div');
  no.className = 'cell';
  no.textContent = String(userPositionIndex + 1);

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

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

  const currentStatus = statuses[userPositionIndex] || STATUS.ABSENT;
  const badge = document.createElement('span');
  badge.className = 'badge ' + getBadgeClass(currentStatus);
  badge.textContent = getBadgeText(currentStatus);
  badge.setAttribute('data-index', String(userPositionIndex));
  badge.style.cursor = 'pointer';

  badge.addEventListener('click', (e) => {
    e.preventDefault();
    e.stopPropagation();

    const newStatus = getNextStatus(currentStatus);

    if (isApiMode && attendanceData[userPositionIndex]) {
      const positionId = attendanceData[userPositionIndex].position_id;
      updateAttendanceAPI(positionId, newStatus).then(success => {
        if (success) {
          statuses[userPositionIndex] = newStatus;
          badge.className = 'badge ' + getBadgeClass(newStatus);
          badge.textContent = getBadgeText(newStatus);
          badge.classList.remove('anim-success', 'anim-warning', 'anim-danger', 'loading');
          void badge.offsetWidth;
          const animClass = newStatus === STATUS.PRESENT ? 'anim-success' : 
                           newStatus === STATUS.CUTI ? 'anim-warning' : 'anim-danger';
          badge.classList.add(animClass, 'loading');
          setTimeout(() => badge.classList.remove('loading'), 2000);
          console.log(`Dashboard: Status updated for ${userPositionName} to ${newStatus}`);
          loadDataFromAPI().then(() => {
            console.log('Dashboard: Data refreshed after update');
          });
        } else {
          console.log('Dashboard: Failed to update status via API');
          alert('Gagal mengupdate status. Silakan coba lagi.');
        }
      });
    } else {
      statuses[userPositionIndex] = newStatus;
      badge.className = 'badge ' + getBadgeClass(newStatus);
      badge.textContent = getBadgeText(newStatus);
      badge.classList.remove('anim-success', 'anim-warning', 'anim-danger', 'loading');
      void badge.offsetWidth;
      const animClass = newStatus === STATUS.PRESENT ? 'anim-success' : 
                       newStatus === STATUS.CUTI ? 'anim-warning' : 'anim-danger';
      badge.classList.add(animClass, 'loading');
      setTimeout(() => badge.classList.remove('loading'), 2000);
      saveStatuses(statuses);
      console.log(`Status updated for ${userPositionName} to ${newStatus} via localStorage`);
    }
  });

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

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

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

// Get current user info
function getCurrentUser() {
  const session = sessionStorage.getItem(SESSION_KEY);
  try {
    const user = session ? JSON.parse(session) : null;
    if (user && typeof user.positionIndex === 'number') {
      return user;
    }
    return null;
  } catch {
    return null;
  }
}

// Validate user session
function validateUserSession() {
  const user = getCurrentUser();
  if (!user) {
    sessionStorage.removeItem(SESSION_KEY);
    return false;
  }
  
  if (typeof user.positionIndex !== 'number') {
    sessionStorage.removeItem(SESSION_KEY);
    return false;
  }
  
  return true;
}

// Check if user is logged in
function checkLoginStatus() {
  return getCurrentUser() !== null;
}

// Check if we're in display mode
function isDisplayMode() {
  const urlParams = new URLSearchParams(window.location.search);
  const displayMode = urlParams.get('display') === 'true' || localStorage.getItem('display-mode') === 'true';
  return displayMode;
}

// Check authentication
function checkAuthentication() {
  if (isDisplayMode()) {
    return true;
  }
  
  if (!validateUserSession()) {
    console.log('No valid session found, using fallback mode');
    return true;
  }
  return true;
}

// Show user info and setup logout
function setupUserInterface() {
  if (isDisplayMode()) {
    const userInfo = document.getElementById('user-info');
    const displayModeInfo = document.getElementById('display-mode-info');
    const backToLoginBtn = document.getElementById('back-to-login-btn');
    
    if (userInfo) userInfo.style.display = 'none';
    if (displayModeInfo) displayModeInfo.style.display = 'flex';
    if (backToLoginBtn) {
      backToLoginBtn.addEventListener('click', () => {
        localStorage.removeItem('display-mode');
        window.location.href = 'login.php';
      });
    }
    return;
  }
  
  const currentUser = getCurrentUser();
  if (currentUser) {
    const userInfo = document.getElementById('user-info');
    const displayModeInfo = document.getElementById('display-mode-info');
    const userPosition = document.getElementById('user-position');
    const userName = document.getElementById('user-name');
    const logoutBtn = document.getElementById('logout-btn');
    const authBtn = document.getElementById('auth-btn');

    if (displayModeInfo) displayModeInfo.style.display = 'none';
    if (userInfo) userInfo.style.display = 'block';
    if (userPosition) userPosition.textContent = currentUser.positionName || currentUser.position || 'Unknown Position';
    if (userName) userName.textContent = currentUser.fullName || currentUser.username || 'Unknown User';
    if (authBtn) authBtn.style.display = 'none';
    if (logoutBtn) {
      logoutBtn.style.display = 'inline-block';
      logoutBtn.replaceWith(logoutBtn.cloneNode(true));
      const newLogoutBtn = document.getElementById('logout-btn');
      if (newLogoutBtn) newLogoutBtn.addEventListener('click', handleLogout);
    }

    setInterval(() => {
      if (!validateUserSession()) {
        alert('Session telah expired. Silakan login kembali.');
        window.location.href = 'login.php';
      }
    }, 30000);
  } else {
    const authBtn = document.getElementById('auth-btn');
    const logoutBtn = document.getElementById('logout-btn');
    const userInfo = document.getElementById('user-info');
    
    if (authBtn) authBtn.style.display = 'inline-block';
    if (logoutBtn) logoutBtn.style.display = 'none';
    if (userInfo) userInfo.style.display = 'none';
  }
}

// Update user info display
function updateUserInfo() {
  const currentUser = getCurrentUser();
  if (!currentUser) {
    console.log('No user session found');
    return;
  }
  
  const userPositionElement = document.getElementById('user-position');
  const userNameElement = document.getElementById('user-name');
  const userInfoElement = document.getElementById('user-info');
  
  if (userPositionElement) userPositionElement.textContent = currentUser.position || 'Unknown Position';
  if (userNameElement) userNameElement.textContent = currentUser.username || 'Unknown User';
  if (userInfoElement) userInfoElement.style.display = 'flex';
  
  console.log('User info updated:', {
    username: currentUser.username,
    position: currentUser.position
  });
}

// Handle logout
function handleLogout() {
  if (confirm('Apakah Anda yakin ingin keluar?')) {
    try {
      sessionStorage.removeItem(SESSION_KEY);
      localStorage.removeItem('display-mode');
      console.log('User logged out, session cleared');
      window.location.href = 'logout.php';
      setTimeout(() => {
        if (window.location.href.includes('dashboard.html')) {
          window.location.replace('logout.php');
        }
      }, 1000);
    } catch (error) {
      console.error('Error during logout:', error);
      window.location.href = 'login.php';
    }
  }
}

// Initialize app function
async function initializeApp() {
  console.log('Initializing app...');
  
  if (!checkAuthentication()) {
    console.log('Authentication failed, using fallback mode');
  }

  const currentUser = getCurrentUser();
  console.log('Dashboard loaded for user:', currentUser);
  console.log('Display mode:', isDisplayMode());
  
  updateUserInfo();
  const roleEl = document.getElementById('current-user-role');
  if (roleEl) {
    if (currentUser) {
      roleEl.textContent = currentUser.positionName || currentUser.position || 'Tidak diketahui';
    } else {
      roleEl.textContent = 'Tidak ada session';
    }
  }

  const adminBtn = document.getElementById('admin-btn');
  if (adminBtn && currentUser && currentUser.isAdmin) {
    adminBtn.style.display = 'inline-block';
    adminBtn.style.visibility = 'visible';
  }
  
  if (currentUser && currentUser.isAdmin) {
    setTimeout(() => {
      const adminBtnRetry = document.getElementById('admin-btn');
      if (adminBtnRetry) {
        adminBtnRetry.style.display = 'inline-block';
        adminBtnRetry.style.visibility = 'visible';
      }
    }, 100);
  }

  await loadDataFromAPI();
  setupUserInterface();

  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);
    }
  }
  renderTable();
  updateClock();
  setInterval(updateClock, 1000);
  
  if (isApiMode) {
    setInterval(async () => {
      try {
        await loadDataFromAPI();
        renderTable();
        console.log('Data refreshed from API');
      } catch (error) {
        console.log('Auto-refresh failed:', error.message);
      }
    }, 5000);
  }
}

// Auto-initialize when script loads
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', initializeApp);
} else {
  initializeApp();
}

window.initializeApp = initializeApp;
