<script lang="ts" setup>
import type { NavLink } from '@bagelink/vue'
import { Btn, Icon } from '@bagelink/vue'
import { inject, computed, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { resolveI18n } from '../../i18n'

// Extended interface for links with active route tracking
interface LinkWithAction extends NavLink {
	activeRoutes?: string[] // נתיבים שצריכים להיות מסומנים כאקטיביים עבור הלינק הזה
}

interface Props {
	navLinks: LinkWithAction[]
	footerLinks?: LinkWithAction[]
	logo?: string
	logoAlt?: string
	card?: boolean
	bgColor?: string
	textColor?: string
	activeColor?: string
	logoHeight?: string
	name?: string
	frame?: boolean
	activeRoutes?: string[]
}

const props = withDefaults(defineProps<Props>(), {
	card: true,
	bgColor: 'var(--bgl-white)',
	textColor: 'var(--bgl-black)',
	activeColor: 'var(--bgl-black)',
	logoAlt: 'Logo',
	logoHeight: '2rem',
	name: 'App Name',
	footerLinks: () => [],
})

const route = useRoute()
const isTransitioning = ref(false)

// Inject menu state from parent
const menuState = inject('menuState', {
	isOpen: { value: true },
	isMobile: { value: false },
	closeOnMobile: () => void 0,
	sidebarWidth: '260px',
	sidebarCollapsedWidth: '66px',
}) as {
	isOpen: { value: boolean }
	isMobile: { value: boolean }
	closeOnMobile: () => void
	sidebarWidth: string
	sidebarCollapsedWidth: string
}

// Watch for changes in menu state to handle transitioning
watch(
	() => menuState.isOpen.value,
	() => {
		if (!menuState.isMobile.value) {
			isTransitioning.value = true
			// Reset after transition completes
			setTimeout(() => {
				isTransitioning.value = false
			}, 300) // Match the CSS transition duration
		}
	}
)

// Check if a route is active (exact match, parent route, or custom activeRoutes)
function isActiveRoute(link: LinkWithAction): boolean {
	const linkPath = link.to

	if (linkPath == null || linkPath === '') {
		return false
	}

	// אם יש activeRoutes מותאמים אישית, השתמש בהם בלבד
	if (link.activeRoutes && link.activeRoutes.length > 0) {
		return link.activeRoutes.some((activePath) => {
			if (activePath === '/') {
				return route.path === activePath
			}
			return route.path === activePath || route.path.startsWith(`${activePath}/`)
		})
	}

	// אחרת, השתמש בלוגיקה האוטומטית הרגילה
	if (linkPath === '/') {
		return route.path === linkPath
	}

	// Exact match
	if (route.path === linkPath) {
		return true
	}

	// Check if current path starts with link path followed by a slash
	// This handles nested routes like /organizations/id/settings
	if (route.path.startsWith(`${linkPath}/`)) {
		return true
	}

	// Handle dynamic routes - if linkPath has multiple segments and current path matches the pattern
	const linkSegments = linkPath.split('/').filter(Boolean)
	const routeSegments = route.path.split('/').filter(Boolean)

	// If link has fewer segments than current route, check if the beginning matches
	if (linkSegments.length <= routeSegments.length) {
		return linkSegments.every((segment, index) => {
			// Allow UUID-like patterns to match
			if (segment.match(/^[a-f0-9-]{36}$/i) && routeSegments[index]?.match(/^[a-f0-9-]{36}$/i)) {
				return true
			}
			return segment === routeSegments[index]
		})
	}

	return false
}

// Computed styles
const sidebarStyles = computed(() => {
	let width = '280px'

	if (!menuState.isMobile.value) {
		const collapsedWidth = props.card ? '82px' : '68px'
		width = menuState.isOpen.value ? menuState.sidebarWidth : collapsedWidth
	}

	return {
		width,
	}
})
</script>

<template>
	<aside
		class="app-sidebar transition-400 fixed start top bottom h-100vh z-99" :class="{
			'sidebar-mobile-open': menuState.isMobile.value && menuState.isOpen.value,
			'sidebar-mobile-closed':
				menuState.isMobile.value && !menuState.isOpen.value,
			'transitioning': isTransitioning,
			'p-05': props.card,
			'sidebar-collapsed': !menuState.isMobile.value && !menuState.isOpen.value,
		}" :style="sidebarStyles"
	>
		<div
			:style="{
				backgroundColor: props.bgColor,
				color: props.textColor,
				...(props.card && { borderRadius: 'var(--card-border-radius)' }),
			}" :class="{
				'card cardWrapSide': props.card,
				'ps-05': !menuState.isOpen.value,
				'scrollbar-gutter-both': menuState.isOpen.value,
				'aside_frame': props.frame,
			}" class="overflow-hidden flex column flex-stretch gap-1 w100p pt-1 pb-05 h-100p"
		>
			<!-- Logo/Brand -->
			<router-link
				to="/" class="decoration-none flex px-05" :class="{
					'gap-05': menuState.isOpen.value,
					'gap-0': !menuState.isOpen.value,
				}"
			>
				<img
					v-if="props.logo" :src="props.logo" :alt="props.logoAlt" class="contain"
					:style="{ height: props.logoHeight }"
				>
				<span class="nav-text">
					{{ props.name }}
				</span>
			</router-link>

			<!-- Navigation Links -->
			<nav class="sidebar-nav flex column flex-stretch gap-025 align-items-start scrollbar-gutter-stable">
				<Btn
					v-for="link in props.navLinks" :key="link.to"
					:title="!menuState.isOpen.value && !menuState.isMobile.value ? resolveI18n(link.label) : ''" fullWidth
					alignTxt="start" class="flex-shrink-0 px-1" :class="{ 'nav-btn-active': isActiveRoute(link) }"
					:style="{
						backgroundColor: isActiveRoute(link) ? props.activeColor : props.bgColor,
						color: isActiveRoute(link) ? 'white' : props.textColor,
					}" :to="link.to || '/'" @click="link.action"
				>
					<Icon :name="link.icon" size="1.2" />
					<span class="nav-text">
						{{ resolveI18n(link.label) }}
					</span>
				</Btn>
			</nav>
			<!-- Footer -->
			<div class="sidebar-footer flex column flex-stretch gap-025 align-items-start mt-auto">
				<!-- Footer Links -->
				<Btn
					v-for="link in props.footerLinks" :key="link.to || link.label"
					:title="!menuState.isOpen.value && !menuState.isMobile.value ? resolveI18n(link.label) : ''" alignTxt="start"
					fullWidth flat :icon="link.icon" class="flex-shrink-0 px-1" :to="link.to" @click="link.action"
				>
					<span class="nav-text">
						{{ resolveI18n(link.label) }}
					</span>
				</Btn>
				<!-- Custom Footer Content Slot -->
				<slot name="footer" />
			</div>
		</div>
	</aside>
</template>

<style>
.aside_frame {
	outline: 1px solid var(--border-color);
}

.card .aside_frame {
	outline-offset: -1px;
}

.app-sidebar {
	transition: width 0.4s ease;
	--input-font-size: 0.875rem;
	/* 14px */
}

/* הסתרת סרגל גלילה רק בזמן טרנזישן */
.sidebar-nav {
	overflow-y: auto;
	flex: 1;
}

.cardWrapSide .bgl_icon-font {
	visibility: visible !important;
}
/* הסתרת גלילה בזמן שינוי גודל */
.app-sidebar.transitioning .sidebar-nav {
	scrollbar-width: none;
	/* Firefox */
	-ms-overflow-style: none;
	/* IE and Edge */
}

.app-sidebar.transitioning .sidebar-nav::-webkit-scrollbar {
	display: none;
	/* Chrome, Safari and Opera */
}

/* אנימציות איטות לטקסט */
.nav-text {
	transition:
		opacity 0.3s ease,
		transform 0.3s ease;
	white-space: nowrap;
	overflow: hidden;
	opacity: 1;
	transform: translateX(0);
	max-width: 200px;
	font-weight: 300;
}

.app-sidebar.sidebar-collapsed .bgl_btn_fullWidth {
	width: fit-content !important;
}

.app-sidebar.sidebar-collapsed .bgl_btn-flex {
	gap: 0 !important;
}

/* אנימציות נכנסות ויוצאות */
@media (min-width: 911px) {
	.app-sidebar {
		transition: width 0.4s ease;
	}

	/* כשהמניו סגור - הטקסט נעלם תחילה */
	.app-sidebar.sidebar-collapsed .nav-text {
		opacity: 0;
		transform: translateX(-15px);
		max-width: 0;
		transition:
			opacity 0.15s ease,
			transform 0.15s ease,
			max-width 0.15s ease;
	}

	/* כשהמניו פתוח - הטקסט מופיע אחרי שהרוחב משתנה */
	.app-sidebar:not(.sidebar-collapsed) .nav-text {
		opacity: 1;
		transform: translateX(0);
		max-width: 200px;
		transition:
			opacity 0.3s ease 0.15s,
			transform 0.3s ease 0.15s,
			max-width 0.3s ease 0.15s;
	}
}

/* במובייל הטקסט תמיד מופיע */
@media (max-width: 910px) {
	.app-sidebar {
		transform: translateX(-100%);
		transition: transform 0.4s ease;
	}

	.sidebar-mobile-open {
		transform: translateX(0);
	}

	.sidebar-mobile-closed {
		transform: translateX(-100%);
	}

	[dir="rtl"] .sidebar-mobile-closed,
	.rtl .sidebar-mobile-closed {
		transform: translateX(100%);
	}
}
</style>
