/* ===== 서비스 워커 해제 (push-sw.js 제외) ===== */
if ('serviceWorker' in navigator) {
    navigator.serviceWorker.getRegistrations().then(function(regs) { regs.forEach(function(r) {
        if (!r.active || !r.active.scriptURL.includes('push-sw.js')) { r.unregister(); }
    }); });
    if (typeof caches !== 'undefined') { caches.keys().then(function(ns) { ns.forEach(function(n) { caches.delete(n); }); }); }
}

/* ===== Config ===== */
const API_BASE = '/api';

/* ===== Token ===== */
function _cookieGet(n) { const m = document.cookie.match(new RegExp('(?:^|; )' + n + '=([^;]*)')); return m ? decodeURIComponent(m[1]) : null; }
function _cookieRemove(n) { let c = n + '=; path=/; max-age=0'; if (location.hostname.includes('technicalkorea.net')) c += '; domain=.technicalkorea.net; secure; samesite=lax'; document.cookie = c; }
function getToken() { return _cookieGet('sso_token'); }
function getLoginUrl() {
    const h = location.hostname;
    const t = Date.now();
    if (h.includes('technicalkorea.net')) return location.protocol + '//tkds.technicalkorea.net/dashboard?redirect=' + encodeURIComponent(location.href) + '&_t=' + t;
    return location.protocol + '//' + h + ':30780/dashboard?redirect=' + encodeURIComponent(location.href) + '&_t=' + t;
}
function decodeToken(t) { try { const b = atob(t.split('.')[1].replace(/-/g,'+').replace(/_/g,'/')); return JSON.parse(new TextDecoder().decode(Uint8Array.from(b, c => c.charCodeAt(0)))); } catch { return null; } }

/* ===== 리다이렉트 루프 방지 ===== */
const _REDIRECT_KEY = '_sso_redirect_ts';
function _safeRedirect() {
    const last = parseInt(sessionStorage.getItem(_REDIRECT_KEY) || '0', 10);
    if (Date.now() - last < 5000) { console.warn('[tksupport] 리다이렉트 루프 감지'); return; }
    sessionStorage.setItem(_REDIRECT_KEY, String(Date.now()));
    location.href = getLoginUrl();
}

/* ===== API ===== */
async function api(path, opts = {}) {
    const token = getToken();
    const headers = { 'Authorization': token ? `Bearer ${token}` : '', ...(opts.headers||{}) };
    if (!(opts.body instanceof FormData)) headers['Content-Type'] = 'application/json';
    const res = await fetch(API_BASE + path, { ...opts, headers });
    if (res.status === 401) { _safeRedirect(); throw new Error('인증 만료'); }
    const data = await res.json();
    if (!res.ok) throw new Error(data.error || '요청 실패');
    return data;
}

/* ===== Toast ===== */
function showToast(msg, type = 'success') {
    document.querySelector('.toast-message')?.remove();
    const el = document.createElement('div');
    el.className = `toast-message fixed bottom-4 right-4 px-4 py-3 rounded-lg text-white z-[10000] shadow-lg ${type==='success'?'bg-purple-500':'bg-red-500'}`;
    el.innerHTML = `<i class="fas ${type==='success'?'fa-check-circle':'fa-exclamation-circle'} mr-2"></i>${escapeHtml(msg)}`;
    document.body.appendChild(el);
    setTimeout(() => { el.classList.add('opacity-0'); setTimeout(() => el.remove(), 300); }, 3000);
}

/* ===== Escape ===== */
function escapeHtml(str) { if (!str) return ''; const d = document.createElement('div'); d.textContent = str; return d.innerHTML; }

/* ===== Helpers ===== */
function formatDate(d) { if (!d) return ''; return String(d).substring(0, 10); }
function formatDateTime(d) { if (!d) return ''; return String(d).substring(0, 16).replace('T', ' '); }

function statusBadge(s) {
    const m = {
        pending: ['badge-amber', '대기'],
        approved: ['badge-green', '승인'],
        rejected: ['badge-red', '반려'],
        cancelled: ['badge-gray', '취소']
    };
    const [cls, label] = m[s] || ['badge-gray', s];
    return `<span class="badge ${cls}">${label}</span>`;
}

/* ===== Logout ===== */
function doLogout() {
    if (!confirm('로그아웃?')) return;
    _cookieRemove('sso_token'); _cookieRemove('sso_user'); _cookieRemove('sso_refresh_token');
    ['sso_token','sso_user','sso_refresh_token','token','user','access_token','currentUser','current_user','userInfo','userPageAccess'].forEach(k => localStorage.removeItem(k));
    location.href = getLoginUrl() + '&logout=1';
}

/* ===== Mobile Menu ===== */
function toggleMobileMenu() {
    const nav = document.getElementById('sideNav');
    const overlay = document.getElementById('mobileOverlay');
    if (!overlay) {
        const o = document.createElement('div');
        o.id = 'mobileOverlay';
        o.className = 'fixed inset-0 bg-black bg-opacity-30 hidden';
        o.style.zIndex = '30';
        o.onclick = toggleMobileMenu;
        document.body.appendChild(o);
        toggleMobileMenu();
        return;
    }
    const open = nav.classList.toggle('mobile-open');
    overlay.classList.toggle('hidden', !open);
    document.body.style.overflow = open ? 'hidden' : '';
}

/* ===== Navbar ===== */
let currentUserPermissions = {};

function renderNavbar() {
    const currentPage = location.pathname.replace(/\//g, '') || 'index.html';
    const isAdmin = currentUser && ['admin','system'].includes(currentUser.role);
    const links = [
        { href: '/', icon: 'fa-home', label: '대시보드', match: ['index.html'] },
        { href: '/vacation-request.html', icon: 'fa-paper-plane', label: '휴가 신청', match: ['vacation-request.html'] },
        { href: '/vacation-status.html', icon: 'fa-calendar-check', label: '내 휴가 현황', match: ['vacation-status.html'] },
        { href: '/vacation-approval.html', icon: 'fa-clipboard-check', label: '휴가 승인', match: ['vacation-approval.html'], page: 'support_vacation_approval' },
        { href: '/company-holidays.html', icon: 'fa-calendar-day', label: '전사 휴가 관리', match: ['company-holidays.html'], page: 'support_company_holidays' },
        { href: '/vacation-dashboard.html', icon: 'fa-chart-bar', label: '전체 휴가관리', match: ['vacation-dashboard.html'], page: 'support_vacation_dashboard' },
        { href: '/vacation-admin.html', icon: 'fa-user-edit', label: '휴가 보정', match: ['vacation-admin.html'], page: 'support_vacation_admin' },
    ];
    const nav = document.getElementById('sideNav');
    if (!nav) return;
    nav.innerHTML = links.filter(l => {
        if (l.page) {
            if (isAdmin) return true;
            return currentUserPermissions[l.page]?.can_access === true;
        }
        return true;
    }).map(l => {
        const active = l.match.some(m => currentPage === m || currentPage.endsWith(m));
        return `<a href="${l.href}" class="nav-link flex items-center gap-3 px-4 py-2.5 rounded-lg text-sm transition-colors ${active ? 'active' : 'text-gray-600 hover:bg-gray-100'}">
            <i class="fas ${l.icon} w-5 text-center"></i><span>${l.label}</span></a>`;
    }).join('');
    // 모바일: nav-link 클릭 시 메뉴 닫기
    nav.querySelectorAll('.nav-link').forEach(a => {
        a.addEventListener('click', () => {
            if (nav.classList.contains('mobile-open')) toggleMobileMenu();
        });
    });
}

/* ===== State ===== */
let currentUser = null;

/* ===== Init ===== */
function initAuth() {
    const cookieToken = _cookieGet('sso_token');
    const localToken = localStorage.getItem('sso_token');
    if (!cookieToken && localToken) {
        ['sso_token','sso_user','sso_refresh_token','token','user','access_token',
         'currentUser','current_user','userInfo','userPageAccess'].forEach(k => localStorage.removeItem(k));
        _safeRedirect();
        return false;
    }

    const token = getToken();
    if (!token) { _safeRedirect(); return false; }
    const decoded = decodeToken(token);
    if (!decoded) { _safeRedirect(); return false; }
    sessionStorage.removeItem(_REDIRECT_KEY);
    currentUser = {
        id: decoded.user_id || decoded.id,
        username: decoded.username || decoded.sub,
        name: decoded.name || decoded.full_name,
        role: (decoded.role || decoded.access_level || '').toLowerCase()
    };
    const dn = currentUser.name || currentUser.username;
    const nameEl = document.getElementById('headerUserName');
    const avatarEl = document.getElementById('headerUserAvatar');
    if (nameEl) nameEl.textContent = dn;
    if (avatarEl) avatarEl.textContent = dn.charAt(0).toUpperCase();

    // 권한 로드 후 네비게이션 렌더링
    const isAdmin = ['admin','system'].includes(currentUser.role);
    if (!isAdmin) {
        _loadPermissions(currentUser.id).then(() => renderNavbar());
    }
    renderNavbar();

    // 알림 벨 로드
    _loadNotificationBell();

    setTimeout(() => document.querySelectorAll('.fade-in').forEach(el => el.classList.add('visible')), 50);
    return true;
}

/* ===== 권한 로드 (tkuser API) ===== */
async function _loadPermissions(userId) {
    try {
        const tkuserBase = location.hostname.includes('technicalkorea.net')
            ? 'https://tkuser.technicalkorea.net/api'
            : location.protocol + '//' + location.hostname + ':30300/api';
        const token = getToken();
        const res = await fetch(`${tkuserBase}/permissions/users/${userId}/effective-permissions`, {
            headers: { 'Authorization': `Bearer ${token}` }
        });
        if (res.ok) {
            const data = await res.json();
            currentUserPermissions = data.permissions || {};
        }
    } catch (e) { /* 실패 시 빈 객체 유지 — 권한 메뉴 안 보임 */ }
}

/* ===== 알림 벨 ===== */
function _loadNotificationBell() {
    const s = document.createElement('script');
    s.src = (location.hostname.includes('technicalkorea.net') ? 'https://tkds.technicalkorea.net' : location.protocol + '//' + location.hostname + ':30000') + '/shared/notification-bell.js?v=4';
    document.head.appendChild(s);
}

/* ===== Modal ESC 닫기 ===== */
document.addEventListener('keydown', e => {
    if (e.key === 'Escape') {
        document.querySelectorAll('.modal-overlay:not(.hidden)')
            .forEach(m => m.classList.add('hidden'));
    }
});
