/**
 * MobileBottomNav — the 3-tab bottom navigation bar used on mobile
 * layouts. Tabs: Home, Notifications, You. Shows an unread dot on the
 * Home tab when any channel has new messages since the last read
 * timestamp. The You tab shows the current user's avatar.
 */
import { useEffect, useMemo } from 'react';
import { useQuery } from 'convex/react';
import { useNavigate, useLocation } from 'react-router-dom';
import { House, Bell } from '@phosphor-icons/react';
import { Avatar } from '@discord-clone/ui';
import { api } from '../../../../../convex/_generated/api';
import styles from './MobileBottomNav.module.css';

// sessionStorage key for the last-visited "home" path. Used to make
// the Home tab resume wherever the user was — server channel list
// or DM — instead of always bouncing to the DM root.
const LAST_HOME_PATH_KEY = 'mobileHomePath';

function isHomePath(pathname: string): boolean {
	if (pathname === '/channels/you') return false;
	return pathname.startsWith('/channels');
}

export function MobileBottomNav() {
	const navigate = useNavigate();
	const location = useLocation();

	// Remember the last non-You /channels/* path so the Home tab can
	// resume where the user left off. We persist to sessionStorage so
	// the choice survives page navigation but not a full tab close.
	useEffect(() => {
		if (isHomePath(location.pathname)) {
			try {
				sessionStorage.setItem(LAST_HOME_PATH_KEY, location.pathname);
			} catch {
				/* ignore storage errors */
			}
		}
	}, [location.pathname]);

	const userId =
		typeof localStorage !== 'undefined' ? localStorage.getItem('userId') : null;

	const allUsers = useQuery(api.auth.getPublicKeys) ?? [];
	const me = allUsers.find((u) => u.id === userId);

	const channelsRaw = useQuery(api.channels.list);
	const readStates = useQuery(
		api.readState.getAllReadStates,
		userId ? { userId: userId as any } : 'skip',
	);
	const channelIdList = useMemo(
		() => (channelsRaw ?? []).map((c: any) => c._id as any),
		[channelsRaw],
	);
	const latestTimestamps = useQuery(
		api.readState.getLatestMessageTimestamps,
		channelIdList.length > 0 ? { channelIds: channelIdList } : 'skip',
	);

	const hasUnread = useMemo(() => {
		const readMap = new Map<string, number>();
		for (const r of readStates ?? []) {
			readMap.set(r.channelId as unknown as string, r.lastReadTimestamp);
		}
		for (const l of latestTimestamps ?? []) {
			const last = readMap.get(l.channelId as unknown as string) ?? 0;
			if (l.latestTimestamp > last) return true;
		}
		return false;
	}, [readStates, latestTimestamps]);

	const isYou = location.pathname === '/channels/you';
	const isHome = location.pathname.startsWith('/channels') && !isYou;
	const isNotifications = location.pathname === '/notifications';

	const displayName = me?.displayName || me?.username || 'You';
	const avatarUrl = me?.avatarUrl ?? null;
	const status = (me?.status as any) ?? 'online';

	const handleHomeClick = () => {
		// Pick up the last remembered home path; fall back to the DM
		// home when nothing's been visited yet this session.
		let target = '/channels/@me';
		try {
			const stored = sessionStorage.getItem(LAST_HOME_PATH_KEY);
			if (stored && isHomePath(stored)) target = stored;
		} catch {
			/* ignore */
		}
		navigate(target);
	};

	return (
		<nav className={styles.nav}>
			<button
				className={`${styles.tab} ${isHome ? styles.active : ''}`}
				onClick={handleHomeClick}
			>
				<div className={styles.tabIconWrap}>
					<House size={24} weight="fill" />
					{hasUnread && <span className={styles.unreadDot} />}
				</div>
				<span className={styles.label}>Home</span>
			</button>
			<button
				className={`${styles.tab} ${isNotifications ? styles.active : ''}`}
				onClick={() => navigate('/notifications')}
			>
				<Bell size={24} weight="fill" />
				<span className={styles.label}>Notifications</span>
			</button>
			<button
				className={`${styles.tab} ${styles.youTab} ${isYou ? styles.active : ''}`}
				onClick={() => navigate('/channels/you')}
			>
				<div className={styles.youAvatar}>
					<Avatar
						src={avatarUrl}
						fallback={displayName}
						size={24}
						status={status}
					/>
				</div>
				<span className={styles.label}>You</span>
			</button>
		</nav>
	);
}
