<script setup lang="ts">
import { resolveMediaUrl } from '@/lib/utils';
import employee from '@/routes/employee';
import { Link, usePage } from '@inertiajs/vue3';
import {
    CalendarClock,
    CalendarRange,
    CheckCircle,
    CheckSquare,
    ChevronLeft,
    Files,
    FileText,
    LayoutDashboard,
    LifeBuoy,
    Package,
    User,
    Users,
    Wallet,
    Zap,
} from 'lucide-vue-next';
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';

defineProps<{
    isCollapsed: boolean;
}>();

const emit = defineEmits(['toggleCollapse', 'update:activeSection']);

const page = usePage();

// Initialize active section based on current URL
const getInitialSection = () => {
    const url = page.url;

    if (url.startsWith('/employee/profile')) {
        return 'profile';
    }

    if (url.startsWith('/employee/attendance')) {
        return 'attendance';
    }

    if (url.startsWith('/employee/manager')) {
        return 'manager';
    }

    if (url.startsWith('/employee/my-team')) {
        return 'manager';
    }

    if (url.startsWith('/employee/leave')) {
        return 'leave';
    }

    if (url.startsWith('/employee/assets')) {
        return 'assets';
    }

    if (url.startsWith('/employee/loans')) {
        return 'finance';
    }

    if (url.startsWith('/employee/salary-certificates')) {
        return 'finance';
    }

    if (url.startsWith('/employee/dashboard') || url === '/employee') {
        return 'dashboard';
    }
    // Default fallback
    return 'dashboard';
};

const activeSection = ref(getInitialSection());

const switchSection = (section: string) => {
    activeSection.value = section;
    emit('update:activeSection', section);
};

// Branding helper
const t = (key: string) => {
    if (key === 'tier_title') return page.props.branding?.employee?.sidebar?.tier_title || 'employee_tier_title';
    if (key === 'tier_subtitle') return page.props.branding?.employee?.sidebar?.tier_subtitle || 'employee_tier_subtitle';
    return page.props.branding?.employee?.sidebar?.[key] || key;
};

const logoUrl = computed(() => resolveMediaUrl((page.props as any).branding?.business_settings?.logo_url));
const liveLogoUrl = ref('');
const displayLogoUrl = computed(() => liveLogoUrl.value || logoUrl.value);

const handleLogoPreview = (event: Event) => {
    const customEvent = event as CustomEvent<string>;
    liveLogoUrl.value = customEvent.detail || '';
};

onMounted(() => {
    window.addEventListener('branding-logo-preview', handleLogoPreview);
});

onBeforeUnmount(() => {
    window.removeEventListener('branding-logo-preview', handleLogoPreview);
});
</script>

<template>
    <aside
        id="employee-sidebar"
        class="fixed inset-y-0 start-0 top-0 z-50 flex h-screen border-e border-admin-sidebar-border bg-admin-sidebar transition-all duration-300 ease-in-out lg:sticky dark:border-admin-sidebar-border-dark dark:bg-admin-sidebar-dark"
        :class="{ 'w-18': isCollapsed, 'w-75': !isCollapsed }"
    >
        <!-- TIER 1: Command Rail -->
        <div class="z-20 flex w-18 shrink-0 flex-col items-center space-y-6 bg-admin-sidebar-rail py-4 dark:bg-admin-sidebar-rail-dark">
            <Link
                :href="employee.dashboard.url()"
                class="flex h-14 w-14 cursor-pointer items-center justify-center overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-lg transition-colors hover:brightness-110 dark:border-slate-700 dark:bg-slate-800"
            >
                <img v-if="displayLogoUrl" :src="displayLogoUrl" class="h-full w-full object-cover" />
                <Zap v-else :size="20" fill="currentColor" class="text-(--brand-primary)" />
            </Link>

            <div class="flex w-full flex-1 flex-col items-center space-y-2">
                <!-- Dashboard -->
                <button
                    @click="switchSection('dashboard')"
                    class="admin-rail-btn group relative flex w-full flex-col items-center py-3 transition-all"
                    :class="activeSection === 'dashboard' ? 'active-rail' : 'rail-icon hover:brightness-110'"
                >
                    <LayoutDashboard :size="20" class="mb-1" />
                    <span
                        class="rail-label pointer-events-none absolute left-17.5 z-50 rounded-lg bg-slate-800 px-3 py-1.5 text-xs font-bold whitespace-nowrap text-white opacity-0 shadow-xl transition-opacity group-hover:pointer-events-auto group-hover:opacity-100"
                        >{{ __(t('dashboard')) }}</span
                    >
                </button>

                <!-- Attendance -->
                <button
                    @click="switchSection('attendance')"
                    class="admin-rail-btn group relative flex w-full flex-col items-center py-3 transition-all"
                    :class="activeSection === 'attendance' ? 'active-rail' : 'rail-icon hover:brightness-110'"
                >
                    <CalendarClock :size="20" class="mb-1" />
                    <span
                        class="rail-label pointer-events-none absolute left-17.5 z-50 rounded-lg bg-slate-800 px-3 py-1.5 text-xs font-bold whitespace-nowrap text-white opacity-0 shadow-xl transition-opacity group-hover:pointer-events-auto group-hover:opacity-100"
                        >{{ __(t('attendance')) }}</span
                    >
                </button>

                <!-- Leave -->
                <button
                    @click="switchSection('leave')"
                    class="admin-rail-btn group relative flex w-full flex-col items-center py-3 transition-all"
                    :class="activeSection === 'leave' ? 'active-rail' : 'rail-icon hover:brightness-110'"
                >
                    <CalendarRange :size="20" class="mb-1" />
                    <span
                        class="rail-label pointer-events-none absolute left-17.5 z-50 rounded-lg bg-slate-800 px-3 py-1.5 text-xs font-bold whitespace-nowrap text-white opacity-0 shadow-xl transition-opacity group-hover:pointer-events-auto group-hover:opacity-100"
                        >{{ __(t('leave')) }}</span
                    >
                </button>

                <!-- Assets -->
                <button
                    @click="switchSection('assets')"
                    class="admin-rail-btn group relative flex w-full flex-col items-center py-3 transition-all"
                    :class="activeSection === 'assets' ? 'active-rail' : 'rail-icon hover:brightness-110'"
                >
                    <Package :size="20" class="mb-1" />
                    <span
                        class="rail-label pointer-events-none absolute left-17.5 z-50 rounded-lg bg-slate-800 px-3 py-1.5 text-xs font-bold whitespace-nowrap text-white opacity-0 shadow-xl transition-opacity group-hover:pointer-events-auto group-hover:opacity-100"
                        >{{ __(t('assets')) }}</span
                    >
                </button>

                <!-- Finance -->
                <button
                    @click="switchSection('finance')"
                    class="admin-rail-btn group relative flex w-full flex-col items-center py-3 transition-all"
                    :class="activeSection === 'finance' ? 'active-rail' : 'rail-icon hover:brightness-110'"
                >
                    <Wallet :size="20" class="mb-1" />
                    <span
                        class="rail-label pointer-events-none absolute left-17.5 z-50 rounded-lg bg-slate-800 px-3 py-1.5 text-xs font-bold whitespace-nowrap text-white opacity-0 shadow-xl transition-opacity group-hover:pointer-events-auto group-hover:opacity-100"
                        >{{ __(t('finance')) }}</span
                    >
                </button>

                <!-- Profile -->
                <button
                    @click="switchSection('profile')"
                    class="admin-rail-btn group relative flex w-full flex-col items-center py-3 transition-all"
                    :class="activeSection === 'profile' ? 'active-rail' : 'rail-icon hover:brightness-110'"
                >
                    <User :size="20" class="mb-1" />
                    <span
                        class="rail-label pointer-events-none absolute left-17.5 z-50 rounded-lg bg-slate-800 px-3 py-1.5 text-xs font-bold whitespace-nowrap text-white opacity-0 shadow-xl transition-opacity group-hover:pointer-events-auto group-hover:opacity-100"
                        >{{ __(t('profile')) }}</span
                    >
                </button>

                <!-- Manager Section (only if user is a manager) -->
                <button
                    v-if="$page.props.auth?.user?.is_manager"
                    @click="switchSection('manager')"
                    class="admin-rail-btn group relative flex w-full flex-col items-center py-3 transition-all"
                    :class="activeSection === 'manager' ? 'active-rail' : 'rail-icon hover:brightness-110'"
                >
                    <CheckCircle :size="20" class="mb-1" />
                    <span
                        class="rail-label pointer-events-none absolute left-17.5 z-50 rounded-lg bg-slate-800 px-3 py-1.5 text-xs font-bold whitespace-nowrap text-white opacity-0 shadow-xl transition-opacity group-hover:pointer-events-auto group-hover:opacity-100"
                        >{{ __(t('manager')) }}</span
                    >
                </button>
            </div>

            <div class="flex w-full flex-col items-center space-y-4 border-t border-slate-800/50 px-4 pt-4">
                <button
                    @click="emit('toggleCollapse')"
                    class="rail-icon group relative hidden h-10 w-10 items-center justify-center rounded-xl transition-all hover:bg-slate-800 hover:text-sky-400 lg:flex"
                >
                    <ChevronLeft :size="20" :class="{ 'rotate-180': isCollapsed }" />
                    <span
                        class="rail-label pointer-events-none absolute left-17.5 z-50 rounded-lg bg-slate-800 px-3 py-1.5 text-xs font-bold whitespace-nowrap text-white opacity-0 shadow-xl transition-opacity group-hover:pointer-events-auto group-hover:opacity-100"
                        >{{ __(t('collapse')) }}</span
                    >
                </button>
                <button
                    class="rail-icon group relative flex h-10 w-10 items-center justify-center rounded-xl transition-all hover:bg-slate-800 hover:text-sky-400"
                >
                    <LifeBuoy :size="20" />
                    <span
                        class="rail-label pointer-events-none absolute left-17.5 z-50 rounded-lg bg-slate-800 px-3 py-1.5 text-xs font-bold whitespace-nowrap text-white opacity-0 shadow-xl transition-opacity group-hover:pointer-events-auto group-hover:opacity-100"
                        >{{ __(t('support')) }}</span
                    >
                </button>
            </div>
        </div>

        <!-- TIER 2: Sub-menu -->
        <div
            id="tier-2-container"
            class="flex h-full shrink-0 flex-col overflow-hidden bg-admin-sidebar transition-all duration-300 ease-in-out dark:bg-admin-sidebar-dark"
            :class="isCollapsed ? 'pointer-events-none w-0 opacity-0' : 'w-57 opacity-100'"
        >
            <div class="border-sidebar-border dark:border-sidebar-border-dark border-b p-5">
                <h2
                    class="line-clamp-1 text-xl font-extrabold tracking-tight text-slate-900 dark:text-white"
                    :title="$page.props.branding.business_settings?.business_name"
                >
                    {{ $page.props.branding.business_settings?.business_name || __(t('tier_title')) }}
                </h2>
                <p class="mt-1.5 text-xs leading-snug font-semibold text-slate-500">
                    {{ $page.props.branding.business_settings?.tagline || __(t('tier_subtitle')) }}
                </p>
            </div>

            <div class="flex-1 space-y-1 overflow-y-auto p-4">
                <!-- Dashboard Section -->
                <div v-if="activeSection === 'dashboard'" class="animate-fade-in">
                    <div class="mb-3 px-4 text-[11px] font-bold tracking-widest text-slate-400 uppercase">{{ __(t('main_menu')) }}</div>
                    <Link
                        :href="employee.dashboard.url()"
                        class="flex items-center space-x-3 rounded-lg px-3 py-2.5 text-sm whitespace-nowrap transition-all"
                        :class="
                            $page.url === employee.dashboard.url()
                                ? 'nav-link-active bg-admin-active font-bold text-admin-active-text'
                                : 'text-slate-500 hover:bg-slate-50 dark:text-slate-400 dark:hover:bg-slate-800'
                        "
                    >
                        <LayoutDashboard :size="16" />
                        <span>{{ __(t('dashboard')) }}</span>
                    </Link>
                </div>

                <!-- Attendance Section -->
                <div v-if="activeSection === 'attendance'" class="animate-fade-in">
                    <div class="mb-3 px-4 text-[11px] font-bold tracking-widest text-slate-400 uppercase">{{ __(t('attendance')) }}</div>
                    <Link
                        :href="employee.attendance.index.url()"
                        class="flex items-center space-x-3 rounded-lg px-3 py-2.5 text-sm whitespace-nowrap transition-all"
                        :class="
                            $page.url.startsWith(employee.attendance.index.definition.url)
                                ? 'nav-link-active bg-admin-active font-bold text-admin-active-text'
                                : 'text-slate-500 hover:bg-slate-50 dark:text-slate-400 dark:hover:bg-slate-800'
                        "
                    >
                        <CalendarClock :size="16" />
                        <span>{{ __(t('my_attendance')) }}</span>
                    </Link>
                </div>

                <!-- Leave Section -->
                <div v-if="activeSection === 'leave'" class="animate-fade-in">
                    <div class="mb-3 px-4 text-[11px] font-bold tracking-widest text-slate-400 uppercase">{{ __(t('leave_management')) }}</div>
                    <Link
                        :href="employee.leave.index.url()"
                        class="flex items-center space-x-3 rounded-lg px-3 py-2.5 text-sm whitespace-nowrap transition-all"
                        :class="
                            $page.url.startsWith(employee.leave.index.definition.url)
                                ? 'nav-link-active bg-admin-active font-bold text-admin-active-text'
                                : 'text-slate-500 hover:bg-slate-50 dark:text-slate-400 dark:hover:bg-slate-800'
                        "
                    >
                        <Files :size="16" />
                        <span>{{ __(t('my_leave_requests')) }}</span>
                    </Link>
                </div>

                <!-- Asset Section -->
                <div v-if="activeSection === 'assets'" class="animate-fade-in">
                    <div class="mb-3 px-4 text-[11px] font-bold tracking-widest text-slate-400 uppercase">{{ __(t('asset_management')) }}</div>
                    <Link
                        :href="employee.assets.index.url()"
                        class="flex items-center space-x-3 rounded-lg px-3 py-2.5 text-sm whitespace-nowrap transition-all"
                        :class="
                            $page.url.startsWith(employee.assets.index.definition.url)
                                ? 'nav-link-active bg-admin-active font-bold text-admin-active-text'
                                : 'text-slate-500 hover:bg-slate-50 dark:text-slate-400 dark:hover:bg-slate-800'
                        "
                    >
                        <Package :size="16" />
                        <span>{{ __(t('my_assets')) }}</span>
                    </Link>
                </div>

                <!-- Finance Section -->
                <div v-if="activeSection === 'finance'" class="animate-fade-in">
                    <div class="mb-3 px-4 text-[11px] font-bold tracking-widest text-slate-400 uppercase">{{ __(t('finance')) }}</div>
                    <Link
                        href="/employee/loans"
                        class="flex items-center space-x-3 rounded-lg px-3 py-2.5 text-sm whitespace-nowrap transition-all"
                        :class="
                            $page.url.startsWith('/employee/loans')
                                ? 'nav-link-active bg-admin-active font-bold text-admin-active-text'
                                : 'text-slate-500 hover:bg-slate-50 dark:text-slate-400 dark:hover:bg-slate-800'
                        "
                    >
                        <Wallet :size="16" />
                        <span>{{ __(t('my_loans')) }}</span>
                    </Link>
                    <Link
                        :href="employee.salaryCertificates.index.url()"
                        class="flex items-center space-x-3 rounded-lg px-3 py-2.5 text-sm whitespace-nowrap transition-all"
                        :class="
                            $page.url.startsWith(employee.salaryCertificates.index.definition.url)
                                ? 'nav-link-active bg-admin-active font-bold text-admin-active-text'
                                : 'text-slate-500 hover:bg-slate-50 dark:text-slate-400 dark:hover:bg-slate-800'
                        "
                    >
                        <FileText :size="16" />
                        <span>{{ __(t('salary_certificates')) }}</span>
                    </Link>
                </div>

                <!-- Profile Section -->
                <div v-if="activeSection === 'profile'" class="animate-fade-in space-y-1">
                    <div class="mb-3 px-4">
                        <h2 class="text-sm font-extrabold tracking-tight text-slate-900 dark:text-white">{{ __(t('account_settings')) }}</h2>
                        <p class="mt-1 text-[10px] font-bold tracking-[0.2em] text-slate-400 uppercase">{{ __(t('manage_profile')) }}</p>
                    </div>

                    <Link
                        :href="employee.profile.edit.url()"
                        class="flex items-center space-x-3 rounded-lg px-3 py-2.5 text-sm whitespace-nowrap transition-all"
                        :class="
                            $page.url.startsWith(employee.profile.edit.definition.url)
                                ? 'nav-link-active bg-admin-active font-bold text-admin-active-text'
                                : 'text-slate-500 hover:bg-slate-50 dark:text-slate-400 dark:hover:bg-slate-800'
                        "
                    >
                        <User :size="16" class="opacity-70" />
                        <span class="text-sm">{{ __(t('my_profile')) }}</span>
                    </Link>
                </div>

                <div v-if="activeSection === 'manager'" class="animate-fade-in">
                    <div class="mb-3 px-4 text-[11px] font-bold tracking-widest text-slate-400 uppercase">{{ __(t('manager')) }}</div>
                    <Link
                        :href="employee.myTeam.index.url()"
                        class="flex items-center space-x-3 rounded-lg px-3 py-2.5 text-sm whitespace-nowrap transition-all"
                        :class="
                            $page.url.startsWith(employee.myTeam.index.definition.url)
                                ? 'nav-link-active bg-admin-active font-bold text-admin-active-text'
                                : 'text-slate-500 hover:bg-slate-50 dark:text-slate-400 dark:hover:bg-slate-800'
                        "
                    >
                        <Users :size="16" />
                        <span>My Team</span>
                    </Link>
                    <Link
                        :href="employee.manager.attendance.approvals.url()"
                        class="flex items-center space-x-3 rounded-lg px-3 py-2.5 text-sm whitespace-nowrap transition-all"
                        :class="
                            $page.url.startsWith(employee.manager.attendance.approvals.definition.url)
                                ? 'nav-link-active bg-admin-active font-bold text-admin-active-text'
                                : 'text-slate-500 hover:bg-slate-50 dark:text-slate-400 dark:hover:bg-slate-800'
                        "
                    >
                        <CheckCircle :size="16" />
                        <span>{{ __(t('attendance_approvals')) }}</span>
                    </Link>
                    <Link
                        :href="employee.manager.leave.approvals.url()"
                        class="flex items-center space-x-3 rounded-lg px-3 py-2.5 text-sm whitespace-nowrap transition-all"
                        :class="
                            $page.url.startsWith(employee.manager.leave.approvals.definition.url)
                                ? 'nav-link-active bg-admin-active font-bold text-admin-active-text'
                                : 'text-slate-500 hover:bg-slate-50 dark:text-slate-400 dark:hover:bg-slate-800'
                        "
                    >
                        <CheckSquare :size="16" />
                        <span>{{ __(t('leave_approvals')) }}</span>
                    </Link>
                </div>
            </div>
        </div>
    </aside>
</template>

<style scoped>
.active-rail {
    background-color: var(--admin-active-item-bg);
    color: var(--admin-active-item-text) !important;
    border-right: 4px solid var(--admin-active-item-border);
}
:global(.dark) .active-rail {
    background-color: var(--admin-active-item-bg-dark);
    color: var(--admin-active-item-text-dark) !important;
    border-right: 4px solid var(--admin-active-item-border-dark);
}

[dir='rtl'] .active-rail {
    border-right: none;
    border-left: 4px solid var(--admin-active-item-border);
}
[dir='rtl'] :global(.dark) .active-rail {
    border-left: 4px solid var(--admin-active-item-border-dark);
}

.nav-link-active {
    background-color: var(--admin-active-item-bg);
    color: var(--admin-active-item-text);
    font-weight: 700;
}
:global(.dark) .nav-link-active {
    background-color: var(--admin-active-item-bg-dark);
    color: var(--admin-active-item-text-dark);
}

.animate-fade-in {
    animation: fadeIn 0.4s ease-out;
}
@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.rail-icon {
    color: var(--admin-sidebar-icon);
}
:global(.dark) .rail-icon {
    color: var(--admin-sidebar-icon-dark);
}
</style>
