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

// Extended interface for links with active route tracking
interface LinkWithAction extends NavLink {
	activeRoutes?: string[] // Routes that should be marked as active for this link
	children?: LinkWithAction[] // Nested sub-links (expandable group / collapsed flyout)
}

interface Props {
	navLinks: LinkWithAction[]
	footerLinks?: LinkWithAction[]
	logo?: string
	logoAlt?: string
	card?: boolean
	bgColor?: string
	textColor?: string
	activeColor?: string
	logoHeight?: string
	name?: string
	/** Small tagline rendered under the app name (hidden when collapsed). */
	nameSubtitle?: string
	frame?: boolean
	activeRoutes?: string[]
	centerlinks?: boolean
}

const props = withDefaults(defineProps<Props>(), {
	card: true,
	centerlinks: false,
	bgColor: 'var(--bgl-box-bg)',
	textColor: 'var(--bgl-text-color)',
	activeColor: 'var(--bgl-primary)',
	logoAlt: 'Logo',
	logoHeight: '2rem',
	name: 'App Name',
	footerLinks: () => [],
})

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

const { isOpen, isMobile, sidebarWidth, toggleMenu, closeOnMobile } = useAppLayout()

// visually "open" during transition — prevents logo/padding from jumping immediately
const isVisuallyOpen = computed(() => isOpen.value || isTransitioning.value)

// Watch for changes in menu state to handle transitioning
watch(
	() => isOpen.value,
	() => {
		if (!isMobile.value) {
			isTransitioning.value = true
			// Reset after transition completes
			setTimeout(() => {
				isTransitioning.value = false
			}, 400) // 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 (!isMobile.value) {
		const collapsedWidth = props.card ? SIDEBAR_COLLAPSED_WIDTH_CARD : SIDEBAR_COLLAPSED_WIDTH
		width = isOpen.value ? sidebarWidth : collapsedWidth
	}

	return {
		width,
	}
})
</script>

<template>
	<aside
		id="bgl-app-sidebar"
		class="app-sidebar transition-400 fixed start top bottom h-100vh z-99" :class="{
			'sidebar-mobile-open': isMobile && isOpen,
			'sidebar-mobile-closed': isMobile && !isOpen,
			'transitioning': isTransitioning,
			'p-05': props.card,
			'sidebar-collapsed': !isMobile && !isOpen,
		}" :style="sidebarStyles"
	>
		<div
			:style="{
				backgroundColor: props.bgColor,
				color: props.textColor,
				...(props.card && { borderRadius: 'var(--bgl-card-border-radius)' }),
			}" :class="{
				'card cardWrapSide': props.card,
				'px-05': !isVisuallyOpen,
				'aside_frame': props.frame,
			}" class="overflow-hidden flex column flex-stretch gap-1 w100p pt-1 pb-05 h-100p testMe1"
		>
			<!-- Logo/Brand -->
			<router-link
				to="/" class="decoration-none flex siderbarLogoWrap gap-05"
				:class="{ 'mx-1': isVisuallyOpen, 'mx-05': !isVisuallyOpen
				}"
			>
				<img
					v-if="props.logo" :src="props.logo" :alt="props.logoAlt" class="contain"
					:style="{ height: props.logoHeight }"
				>
				<slot name="brand" v-bind="{ isOpen: isVisuallyOpen }">
					<span class="nav-text flex column line-height-1 gap-025 align-items-start">
						<span>{{ props.name }}</span>
						<span v-if="props.nameSubtitle" class="txt11 opacity-6">{{ props.nameSubtitle }}</span>
					</span>
				</slot>
			</router-link>

			<!-- Navigation Links -->
			<nav class="sidebar-nav flex column flex-stretch gap-025 align-items-start" :class="{ 'justify-content-center': props.centerlinks }">
				<SidebarNavItem
					v-for="link in props.navLinks" :key="link.to || link.label"
					:link="link"
					:open="isVisuallyOpen"
					:real-open="isOpen"
					:is-mobile="isMobile"
					:bg-color="props.bgColor"
					:text-color="props.textColor"
					:active-color="props.activeColor"
				/>
			</nav>
			<!-- Footer -->
			<div class="sidebar-footer flex column flex-stretch gap-025 align-items-start px-025 mt-auto">
				<!-- Footer Links -->
				<Btn
					v-for="link in props.footerLinks" :key="link.to || link.label"
					:title="!isOpen && !isMobile ? resolveI18n(link.label) : ''"
					:style="{
						backgroundColor: isActiveRoute(link) ? props.activeColor : props.bgColor,
						color: isActiveRoute(link) ? 'white' : props.textColor,
					}"
					fullWidth alignTxt="start" class="flex-shrink-0 px-075" :class="{ 'nav-btn-active': isActiveRoute(link) }"
					:to="link.to || '/'" @click="link.action"
				>
					<Icon :name="link.icon" size="1.2" />
					<span class="nav-text">
						{{ resolveI18n(link.label) }}
					</span>
				</Btn>
				<!-- Custom Footer Content Slot -->
				<slot name="footer" v-bind="{ isOpen, isMobile, toggleMenu, closeOnMobile }" />
			</div>
		</div>
	</aside>
</template>

<style>

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

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

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

/* הסתרת סרגל גלילה רק בזמן טרנזישן */
.sidebar-nav {
overflow-y: auto;
flex: 1;
margin-inline: -0.05rem;
	scrollbar-gutter: stable both-edges;

}

.cardWrapSide .bgl_icon-font {
visibility: visible !important;
}

/* אנימציות איטות לטקסט */
.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;
}

.app-sidebar.sidebar-collapsed .sidebar-nav {
padding: 0 !important;
margin-inline: -0.5rem !important;
align-items: center !important;
/* scrollbar-gutter: stable both-edges; */
}

/* בזמן האנימציה - שמור על ה-open state */
.app-sidebar.transitioning.sidebar-collapsed .bgl_btn_fullWidth {
width: 100% !important;
}

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

.app-sidebar.transitioning.sidebar-collapsed .sidebar-nav {
align-items: flex-start !important;
padding: revert !important;
margin-inline: -0.05rem !important;
margin-block: 0 !important;
}

aside ::-webkit-scrollbar-track {
margin:  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>
