/**
 * MobileYouPage — full-screen profile view rendered when the user
 * taps the "You" tab in the MobileBottomNav. Mirrors the reference
 * layout: big accent banner at the top, avatar overlapping the banner
 * on the left (tap to change status), settings gear on the right,
 * name + handle, Edit Profile button, optional bio card, and a
 * status row that opens `MobileSetStatusSheet`.
 *
 * Unlike a BottomSheet, this is a regular page that mounts inside the
 * GuildsLayout content area so MobileBottomNav stays visible below.
 *
 * Edit Profile + settings gear both open the shared user settings
 * modal via the `brycord:open-user-settings` window event.
 */
import { useState } from 'react';
import { useQuery } from 'convex/react';
import { Gear, PencilSimple } from '@phosphor-icons/react';
import { Avatar } from '@discord-clone/ui';
import { api } from '../../../../../convex/_generated/api';
import { MobileSetStatusSheet } from './MobileSetStatusSheet';
import styles from './MobileYouPage.module.css';

function openUserSettings(tab?: 'account') {
	window.dispatchEvent(
		new CustomEvent('brycord:open-user-settings', {
			detail: tab ? { tab } : {},
		}),
	);
}

type PresenceStatus = 'online' | 'idle' | 'dnd' | 'offline' | 'invisible';

function presenceLabel(status: string): string {
	switch (status) {
		case 'online':
			return 'Online';
		case 'idle':
			return 'Idle';
		case 'dnd':
			return 'Do Not Disturb';
		case 'invisible':
			return 'Invisible';
		default:
			return 'Offline';
	}
}

export function MobileYouPage() {
	const userId = typeof localStorage !== 'undefined' ? localStorage.getItem('userId') : null;
	const username = typeof localStorage !== 'undefined' ? localStorage.getItem('username') : null;
	const allUsers = useQuery(api.auth.getPublicKeys) ?? [];
	const me = allUsers.find((u) => u.id === userId);
	const [statusSheetOpen, setStatusSheetOpen] = useState(false);

	const displayName = me?.displayName || username || 'User';
	const realName = me?.username || username || displayName;
	const hasCustomDisplayName = displayName !== realName;
	const handleText = hasCustomDisplayName ? realName : `@${realName}`;
	const avatarUrl = me?.avatarUrl ?? null;
	const rawStatus = (me?.status || 'online') as PresenceStatus;
	// Avatar only accepts online/idle/dnd/offline — map 'invisible' → 'offline'
	const avatarStatus: 'online' | 'idle' | 'dnd' | 'offline' =
		rawStatus === 'invisible' ? 'offline' : (rawStatus as 'online' | 'idle' | 'dnd' | 'offline');
	const bio = me?.aboutMe || '';

	return (
		<div className={styles.root}>
			{/* Banner — solid accent color. */}
			<div
				className={styles.banner}
				style={{
					backgroundColor:
						(me as any)?.accentColor || 'var(--brand-primary)',
				}}
			/>

			<div className={styles.headerRow}>
				<button
					type="button"
					className={styles.avatarButton}
					onClick={() => setStatusSheetOpen(true)}
					aria-label="Change online status"
				>
					<div className={styles.avatarWrap}>
						<Avatar src={avatarUrl} fallback={displayName} size={96} status={avatarStatus} />
					</div>
				</button>
				<button
					type="button"
					className={styles.settingsButton}
					onClick={() => openUserSettings()}
					aria-label="Open settings"
				>
					<Gear size={20} weight="fill" />
				</button>
			</div>

			<div className={styles.nameBlock}>
				<span className={styles.displayName}>{displayName}</span>
				<span className={styles.handle}>{handleText}</span>
			</div>

			<button
				type="button"
				className={styles.editProfileButton}
				onClick={() => openUserSettings('account')}
			>
				<PencilSimple size={18} weight="bold" />
				Edit Profile
			</button>

			<div className={styles.cardStack}>
				<button
					type="button"
					className={styles.card}
					onClick={() => setStatusSheetOpen(true)}
					style={{ cursor: 'pointer', border: 'none', textAlign: 'left', font: 'inherit' }}
				>
					<div className={styles.cardTitleRow}>
						<span className={styles.cardTitle}>Status</span>
						<span className={styles.cardValue}>{presenceLabel(rawStatus)}</span>
					</div>
				</button>

				{bio && (
					<div className={styles.card}>
						<span className={styles.cardTitle}>About Me</span>
						<span className={styles.cardValue}>{bio}</span>
					</div>
				)}
			</div>

			<MobileSetStatusSheet isOpen={statusSheetOpen} onClose={() => setStatusSheetOpen(false)} />
		</div>
	);
}
