<script>
	import SectionCard from '$lib/SectionCard.svelte';
	import CollectionBuilderPage from '$lib/CollectionBuilderPage.svelte';
	import GenreCleanupPage from '$lib/GenreCleanupPage.svelte';
	import Icon from '$lib/Icon.svelte';
	import SyncPanel from '$lib/SyncPanel.svelte';
	import SqlModal from '$lib/SqlModal.svelte';
	import SettingsPanel from '$lib/SettingsPanel.svelte';
	import {
		applySectionStandards,
		createBoxSetSection,
		createEmptySection,
		createRecentlyWatchedSection,
		generateSQL
	} from '$lib/constants.js';

	/** @type {import('./$types').PageData} */
	export let data;

	let users = JSON.parse(JSON.stringify(data.users));
	let originalUsers = JSON.parse(JSON.stringify(data.users));
	let config = { ...data.config };

	let selectedUserId = users.find((u) => u.sections?.length > 0)?.id || null;
	let expandedIndex = -1;
	let activeTab = 'edit';
	let showSqlModal = false;
	let generatedSql = '';
	let changeCount = 0;
	let writeStatus = '';
	let writeMessage = '';
	let dbValidation = null;
	let userContext = {
		views: [],
		recentlyPlayed: [],
		excludedFolderLookup: {},
		source: '',
		lastSyncedAt: null,
		message: ''
	};
	let userContextBusy = false;
	let recentlyPlayedCollapsed = false;
	let lastRecentlyPlayedUserId = null;

	$: selectedUser = users.find((u) => u.id === selectedUserId);
	$: sections = selectedUser?.sections || [];
	$: activeUsers = users.filter((u) => u.sections?.length > 0);
	$: emptyUsers = users.filter((u) => !u.sections || u.sections.length === 0);
	$: totalSectionCount = users.reduce((n, u) => n + (u.sections?.length || 0), 0);
	$: dbConfigured = !!config.dbPath;
	$: selectedExcludedIds = [...new Set(sections.flatMap((section) => section.ExcludedFolders || []))];
	$: randomSectionCount = sections.filter((section) => section.SortBy === 'Random').length;
	$: filteredSectionCount = sections.filter((section) => !!section.Query).length;
	$: collectionSectionCount = sections.filter((section) => ['boxset', 'collections'].includes(section.SectionType)).length;
	$: currentTabMeta = {
		edit: {
			label: 'Editor',
			title: selectedUser ? `${selectedUser.name}'s Home Screen` : 'Home Screen Editor',
			description: selectedUser
				? 'Tune section order, filters, and collection rows with a flatter monitoring-style layout.'
				: 'Choose a user from the sidebar to begin editing.'
		},
		sync: {
			label: 'Sync',
			title: 'Section Sync',
			description: 'Copy or append curated home screen sections across users.'
		},
		collections: {
			label: 'Collections',
			title: 'Recommendation Collections',
			description: 'Generate box set sections from recent activity and seeded recommendations.'
		},
		genres: {
			label: 'Genres',
			title: 'Genre Cleanup',
			description: 'Inspect Emby and TMDB genres, then reduce a movie or show to a single genre.'
		},
		settings: {
			label: 'Settings',
			title: 'Connections and Database',
			description: 'Manage Emby connectivity, TMDB access, and live database operations.'
		}
	}[activeTab];
	$: if (selectedUserId !== lastRecentlyPlayedUserId) {
		lastRecentlyPlayedUserId = selectedUserId;
		recentlyPlayedCollapsed = false;
	}
	$: if (selectedUser?.embyGuid) {
		loadSelectedUserContext(selectedUser, selectedExcludedIds);
	} else {
		userContext = {
			views: [],
			recentlyPlayed: [],
			excludedFolderLookup: {},
			source: '',
			lastSyncedAt: null,
			message: ''
		};
	}

	function moveSection(index, dir) {
		const newIndex = index + dir;
		if (newIndex < 0 || newIndex >= sections.length) return;
		const arr = [...sections];
		[arr[index], arr[newIndex]] = [arr[newIndex], arr[index]];
		selectedUser.sections = arr;
		expandedIndex = newIndex;
		users = users;
		changeCount++;
	}

	function removeSection(index) {
		selectedUser.sections = sections.filter((_, i) => i !== index);
		if (expandedIndex === index) expandedIndex = -1;
		else if (expandedIndex > index) expandedIndex--;
		users = users;
		changeCount++;
	}

	function addSection() {
		const embyGuid = selectedUser.embyGuid || '';
		const newSection = createEmptySection(embyGuid);
		selectedUser.sections = [...sections, newSection];
		expandedIndex = sections.length - 1;
		users = users;
		changeCount++;
	}

	function addCollectionSection() {
		if (!selectedUser) return;
		const embyGuid = selectedUser.embyGuid || '';
		const newSection = createBoxSetSection(embyGuid, '', '');
		const insertIndex = sections[0]?.SectionType === 'resume' ? 1 : sections.length;
		selectedUser.sections = [
			...sections.slice(0, insertIndex),
			newSection,
			...sections.slice(insertIndex)
		];
		expandedIndex = insertIndex;
		users = users;
		changeCount++;
	}

	function addRecentlyWatchedSection() {
		if (!selectedUser) return;
		const sectionName = `Recently Watched${selectedUser.name ? ` - ${selectedUser.name}` : ''}`;
		const existingIndex = sections.findIndex(
			(section) => (section.CustomName || section.Name || '') === sectionName
		);
		if (existingIndex >= 0) {
			expandedIndex = existingIndex;
			return;
		}

		const embyGuid = selectedUser.embyGuid || '';
		const newSection = createRecentlyWatchedSection(embyGuid, selectedUser.name);
		const insertIndex = sections[0]?.SectionType === 'resume' ? 1 : 0;
		selectedUser.sections = [
			...sections.slice(0, insertIndex),
			newSection,
			...sections.slice(insertIndex)
		];
		expandedIndex = insertIndex;
		users = users;
		changeCount++;
	}

	function insertCollectionSection(targetUser, collection) {
		const existingIndex = (targetUser.sections || []).findIndex(
			(section) =>
				section.SectionType === 'boxset' &&
				(section.ParentItem?.Id === collection.id || section.ParentId === collection.id)
		);
		if (existingIndex >= 0) {
			return { index: existingIndex, changed: false };
		}

		const insertIndex =
			targetUser.sections?.[0]?.SectionType === 'resume' ? 1 : (targetUser.sections?.length || 0);
		const nextSection = createBoxSetSection(targetUser.embyGuid || '', collection.name, collection.id);
		targetUser.sections = [
			...(targetUser.sections || []).slice(0, insertIndex),
			nextSection,
			...(targetUser.sections || []).slice(insertIndex)
		];

		return { index: insertIndex, changed: true };
	}

	function onCollectionCreated(event) {
		const { collection, targetUserIds = [] } = event.detail;
		if (!collection?.id) return;

		let firstTargetId = null;
		let firstExpandedIndex = -1;
		let changes = 0;

		for (const targetId of targetUserIds) {
			const targetUser = users.find((user) => user.id === targetId);
			if (!targetUser?.embyGuid) continue;
			const result = insertCollectionSection(targetUser, collection);
			if (!firstTargetId) {
				firstTargetId = targetUser.id;
				firstExpandedIndex = result.index;
			}
			if (result.changed) changes += 1;
		}

		users = users;
		if (changes > 0) {
			changeCount += changes;
		}
		if (firstTargetId) {
			selectedUserId = firstTargetId;
			expandedIndex = firstExpandedIndex;
			activeTab = 'edit';
		}
	}

	const navigationItems = [
		{ id: 'edit', label: 'Editor', icon: 'edit' },
		{ id: 'collections', label: 'Collections', icon: 'collections' },
		{ id: 'genres', label: 'Genres', icon: 'search' },
		{ id: 'sync', label: 'Sync', icon: 'sync' },
		{ id: 'settings', label: 'Settings', icon: 'settings' }
	];

	function handleSync(event) {
		const { sourceUserId, targetUserIds, sections: syncSections, mode } = event.detail;
		const source = users.find((u) => u.id === sourceUserId);
		if (!source) return;

		for (const targetId of targetUserIds) {
			const target = users.find((u) => u.id === targetId);
			if (!target) continue;

			const cloned = JSON.parse(JSON.stringify(syncSections)).map((s) => {
				const normalized = applySectionStandards(s, target);
				normalized.UserId = target.embyGuid || '';
				normalized.Id = crypto.randomUUID().replace(/-/g, '').slice(0, 32);
				return normalized;
			});

			if (mode === 'replace') {
				target.sections = cloned;
			} else {
				target.sections = [...(target.sections || []), ...cloned];
			}
		}

		users = users;
		changeCount += targetUserIds.length;
		activeTab = 'edit';
	}

	function showSQL() {
		generatedSql = generateSQL(users, originalUsers);
		showSqlModal = true;
	}

	function resetAll() {
		if (confirm('Reset all changes? This cannot be undone.')) {
			users = JSON.parse(JSON.stringify(originalUsers));
			changeCount = 0;
			expandedIndex = -1;
			writeStatus = '';
		}
	}

	function onSectionChange() {
		users = users;
		changeCount++;
	}

	let lastUserContextKey = '';
	async function loadSelectedUserContext(user, excludedIds) {
		const key = `${user?.embyGuid || ''}:${excludedIds.join(',')}`;
		if (!user?.embyGuid || lastUserContextKey === key) return;
		lastUserContextKey = key;
		userContextBusy = true;

		try {
			const params = new URLSearchParams({ embyGuid: user.embyGuid });
			if (excludedIds.length > 0) {
				params.set('excludedIds', excludedIds.join(','));
			}
			const res = await fetch(`/api/emby-user-context?${params.toString()}`);
			if (!res.ok) throw new Error(await res.text());
			userContext = await res.json();
		} catch (e) {
			userContext = {
				views: [],
				recentlyPlayed: [],
				excludedFolderLookup: {},
				source: 'error',
				lastSyncedAt: null,
				message: e.message
			};
		} finally {
			userContextBusy = false;
		}
	}

	function buildChanges() {
		const changes = [];
		for (const user of users) {
			if (!user.sections || user.sections.length === 0) continue;
			const original = originalUsers.find((u) => u.id === user.id);
			if (!original) continue;
			const origJSON = JSON.stringify({ Sections: original.sections });
			const newJSON = JSON.stringify({ Sections: user.sections });
			if (origJSON !== newJSON) {
				changes.push({ userId: user.id, sections: user.sections, name: user.name });
			}
		}
		return changes;
	}

	async function writeToDb() {
		const changes = buildChanges();
		if (!changes.length) return;

		const names = changes.map((c) => c.name).join(', ');
		const confirmed = confirm(
			`This will write changes for ${changes.length} user(s) directly to the database:\n\n${names}\n\nIMPORTANT: Emby must be stopped before continuing.\n\nProceed?`
		);
		if (!confirmed) return;

		writeStatus = 'writing';
		writeMessage = '';
		try {
			const res = await fetch('/api/db-write', {
				method: 'POST',
				headers: { 'Content-Type': 'application/json' },
				body: JSON.stringify({ dbPath: config.dbPath, changes })
			});
			const body = await res.json();
			if (!res.ok) throw new Error(body.message || body.error || res.statusText);
			writeStatus = 'ok';
			writeMessage = `Wrote ${body.count} user(s) to database.${body.normalizedSections ? ` Normalized ${body.normalizedSections} section UserId values.` : ''}`;
			originalUsers = JSON.parse(JSON.stringify(users));
			changeCount = 0;
		} catch (e) {
			writeStatus = 'error';
			writeMessage = e.message;
		}
	}

	function onConfigSaved(e) {
		config = { ...e.detail };
	}

	function onNamesRefreshed(e) {
		const payload = Array.isArray(e.detail) ? { users: e.detail, source: 'live' } : e.detail;
		const embyUsers = payload.users || [];
		const nameMap = Object.fromEntries(embyUsers.map((u) => [u.embyGuid, u.name]));
		users = users.map((u) => ({
			...u,
			dbName: u.dbName || u.name,
			embyName: u.embyGuid && nameMap[u.embyGuid] ? nameMap[u.embyGuid] : u.embyName,
			name: u.embyGuid && nameMap[u.embyGuid] ? nameMap[u.embyGuid] : u.name
		}));
		originalUsers = originalUsers.map((u) => ({
			...u,
			dbName: u.dbName || u.name,
			embyName: u.embyGuid && nameMap[u.embyGuid] ? nameMap[u.embyGuid] : u.embyName,
			name: u.embyGuid && nameMap[u.embyGuid] ? nameMap[u.embyGuid] : u.name
		}));
	}

	function onUsersLoaded(e) {
		const payload = Array.isArray(e.detail) ? { users: e.detail, validation: null } : e.detail;
		const freshUsers = payload.users || [];
		users = JSON.parse(JSON.stringify(freshUsers));
		originalUsers = JSON.parse(JSON.stringify(freshUsers));
		dbValidation = payload.validation || null;
		changeCount = 0;
		expandedIndex = -1;
		writeStatus = '';
		selectedUserId = users.find((u) => u.sections?.length > 0)?.id || null;
	}
</script>

<div class="app">
	<aside class="sidebar">
		<div class="sidebar-top">
			<div class="brand-lockup">
				<div class="brand-mark">H</div>
				<div class="brand-copy">
					<div class="brand-name">HomeScreenPal</div>
					<div class="brand-subtitle">Emby layout control</div>
				</div>
			</div>

			<nav class="sidebar-nav" aria-label="Primary">
				{#each navigationItems as item}
					<button
						class="nav-link"
						class:active={activeTab === item.id}
						on:click={() => (activeTab = item.id)}
					>
						<span class="nav-icon"><Icon name={item.icon} size={15} /></span>
						<span>{item.label}</span>
					</button>
				{/each}
			</nav>
		</div>

		<div class="sidebar-panel">
			{#if activeTab === 'edit' || activeTab === 'sync'}
				<div class="sidebar-section">
					<div class="sidebar-title-row">
						<div>
							<div class="sidebar-title">Users</div>
							<div class="sidebar-copy">
								{activeTab === 'edit'
									? 'Pick a profile to edit its live home screen layout.'
									: 'Choose the users you want to sync from and into.'}
							</div>
						</div>
						<span class="sidebar-badge">{activeUsers.length}</span>
					</div>
					<div class="user-list">
						{#each activeUsers as user}
							<button
								class="user-item"
								class:active={selectedUserId === user.id}
								on:click={() => {
									selectedUserId = user.id;
									expandedIndex = -1;
									activeTab = 'edit';
								}}
							>
								<div class="user-copy">
									<span class="user-name">{user.name}</span>
									<span class="user-meta">{user.embyGuid ? 'Linked to Emby' : 'Unlinked'}</span>
								</div>
								<span class="user-count">{user.sections.length}</span>
							</button>
						{/each}

						{#if emptyUsers.length}
							<div class="user-divider">No sections yet</div>
							{#each emptyUsers as user}
								<button
									class="user-item dim"
									class:active={selectedUserId === user.id}
									on:click={() => {
										selectedUserId = user.id;
										expandedIndex = -1;
										activeTab = 'edit';
									}}
								>
									<div class="user-copy">
										<span class="user-name">{user.name}</span>
										<span class="user-meta">Ready for first section</span>
									</div>
									<span class="user-count">0</span>
								</button>
							{/each}
						{/if}
					</div>
				</div>
			{:else if activeTab === 'collections'}
				<div class="sidebar-section">
					<div class="sidebar-title">Collection Builder</div>
					<div class="sidebar-copy">
						Build recommendation box sets from recent viewing history, manual seeds, and TMDB-assisted matches.
					</div>
				</div>
				<div class="sidebar-note">
					<div class="note-title">Workflow</div>
					<div class="note-copy">
						Choose a source user, add seeds, preview the set, then create and attach the collection to one or more users.
					</div>
				</div>
				<div class="sidebar-note">
					<div class="note-title">Inline Editing</div>
					<div class="note-copy">
						You can also add a box set row from the editor and look up an existing collection directly inside that section.
					</div>
				</div>
			{:else if activeTab === 'genres'}
				<div class="sidebar-section">
					<div class="sidebar-title">Genre Cleanup</div>
					<div class="sidebar-copy">
						Search your Emby library, inspect TMDB genres, and write back a single genre per title.
					</div>
				</div>
				<div class="sidebar-note">
					<div class="note-title">Suggestion</div>
					<div class="note-copy">
						The tool suggests the first TMDB genre, but keeps the choice editable before anything is written.
					</div>
				</div>
				<div class="sidebar-note">
					<div class="note-title">Workflow</div>
					<div class="note-copy">
						Search, inspect, confirm the single genre you want, then apply it to one title or to the current inspected results.
					</div>
				</div>
			{:else if activeTab === 'settings'}
				<div class="sidebar-section">
					<div class="sidebar-title">Operations</div>
					<div class="sidebar-copy">
						Store your local config, refresh Emby names, and point the app at a live <code>users.db</code> file.
					</div>
				</div>
				<div class="sidebar-note">
					<div class="note-title">Safety</div>
					<div class="note-copy">
						Stop Emby before loading from or writing to the database so the file is not locked or partially updated.
					</div>
				</div>
			{/if}
		</div>

		<div class="sidebar-footer">
			<div class="footer-stat">
				<span>Users</span>
				<strong>{users.length}</strong>
			</div>
			<div class="footer-stat">
				<span>Sections</span>
				<strong>{totalSectionCount}</strong>
			</div>
		</div>
	</aside>

	<div class="workspace">
		<header class="topbar">
			<div class="topbar-copy">
				<div class="topbar-label">{currentTabMeta.label}</div>
				<h1>{currentTabMeta.title}</h1>
				<p>{currentTabMeta.description}</p>
			</div>
			<div class="header-actions">
				{#if writeStatus === 'ok'}
					<span class="status-pill ok">{writeMessage}</span>
				{:else if writeStatus === 'error'}
					<span class="status-pill error" title={writeMessage}>Write failed</span>
				{/if}
				{#if dbValidation && dbValidation.userSource}
					<span class="status-pill info" title={`${dbValidation.matchedUsers} matched, ${dbValidation.mismatchedUsers} mismatched, ${dbValidation.normalizedUsers} normalized on load`}>
						{dbValidation.userSource} linked
					</span>
				{/if}
				{#if changeCount > 0}
					<span class="status-pill pending">{changeCount} pending</span>
					<button class="btn ghost" on:click={resetAll}>Reset</button>
				{/if}
				<button class="btn ghost" on:click={showSQL} disabled={changeCount === 0}>Generate SQL</button>
				{#if dbConfigured}
					<button class="btn primary" on:click={writeToDb} disabled={changeCount === 0 || writeStatus === 'writing'}>
						{writeStatus === 'writing' ? 'Writing…' : 'Write to DB'}
					</button>
				{/if}
			</div>
		</header>

		<main class="main">
			{#if activeTab === 'edit' && selectedUser}
				<div class="builder-shell">
					<section class="builder-main">
						<div class="metrics-grid">
							<div class="metric-card">
								<div class="metric-icon"><Icon name="items" size={15} /></div>
								<div class="metric-copy">
									<strong>{sections.length}</strong>
									<span>Total rows</span>
								</div>
							</div>
							<div class="metric-card">
								<div class="metric-icon"><Icon name="spark" size={15} /></div>
								<div class="metric-copy">
									<strong>{randomSectionCount}</strong>
									<span>Randomized</span>
								</div>
							</div>
							<div class="metric-card">
								<div class="metric-icon"><Icon name="search" size={15} /></div>
								<div class="metric-copy">
									<strong>{filteredSectionCount}</strong>
									<span>Filtered</span>
								</div>
							</div>
							<div class="metric-card">
								<div class="metric-icon"><Icon name="collections" size={15} /></div>
								<div class="metric-copy">
									<strong>{collectionSectionCount}</strong>
									<span>Collections</span>
								</div>
							</div>
						</div>

						<div class="content-card">
							<div class="content-header">
								<div>
									<div class="content-title">Section Canvas</div>
									<div class="content-subtitle">
										Edit the rows exactly as they will be written back into Emby.
									</div>
								</div>
								<div class="main-header-actions">
									<button class="btn ghost small" on:click={() => (activeTab = 'collections')}>
										<Icon name="collections" size={14} />
										<span>Collections</span>
									</button>
									<button class="btn ghost small" on:click={addCollectionSection}>
										<Icon name="boxset" size={14} />
										<span>Add collection</span>
									</button>
									<button class="btn accent small" on:click={addSection}>Add section</button>
								</div>
							</div>

							{#if sections.length === 0}
								<div class="empty-state empty-state-inline">
									<p>No sections are configured for this user yet.</p>
									<div class="empty-actions">
										<button class="btn ghost" on:click={addCollectionSection}>
											<Icon name="boxset" size={14} />
											<span>Add collection section</span>
										</button>
										<button class="btn accent" on:click={addSection}>Add first section</button>
									</div>
								</div>
							{:else}
								<div class="section-list">
									{#each sections as section, i (section.Id + '-' + i)}
										<SectionCard
											{section}
											index={i}
											total={sections.length}
											genres={data.genres}
											expanded={expandedIndex === i}
											excludedFolderLookup={userContext.excludedFolderLookup}
											lookupUserId={selectedUser?.embyGuid || ''}
											on:toggle={() => (expandedIndex = expandedIndex === i ? -1 : i)}
											on:move={(e) => moveSection(i, e.detail)}
											on:remove={() => removeSection(i)}
											on:change={onSectionChange}
										/>
									{/each}
								</div>
							{/if}
						</div>
					</section>

					<aside class="builder-rail">
						<div class="rail-stack">
							<div class="content-card side-card">
								<div class="content-title">Quick Actions</div>
								<div class="rail-actions">
									<button class="btn ghost small rail-btn" on:click={() => (activeTab = 'collections')}>
										<Icon name="collections" size={14} />
										<span>Open collections</span>
									</button>
									<button class="btn ghost small rail-btn" on:click={addCollectionSection}>
										<Icon name="boxset" size={14} />
										<span>Add collection row</span>
									</button>
									<button class="btn ghost small rail-btn" on:click={addRecentlyWatchedSection}>
										<span>Add recently watched</span>
									</button>
									<button class="btn accent small rail-btn" on:click={addSection}>
										<span>Add section</span>
									</button>
								</div>
							</div>

							<div class="content-card side-card">
								<div class="content-title">User Profile</div>
								<div class="detail-row">
									<span>Source</span>
									<strong>{selectedUser.details?.sourceTable || dbValidation?.userSource || 'Unknown'}</strong>
								</div>
								<div class="detail-row">
									<span>Last login</span>
									<strong>{selectedUser.details?.lastLoginDate ? new Date(selectedUser.details.lastLoginDate).toLocaleString() : 'Not available'}</strong>
								</div>
								<div class="detail-row">
									<span>Last activity</span>
									<strong>{selectedUser.details?.lastActivityDate ? new Date(selectedUser.details.lastActivityDate).toLocaleString() : 'Not available'}</strong>
								</div>
								<div class="detail-row">
									<span>Rows</span>
									<strong>{sections.length}</strong>
								</div>
							</div>

							<div class="content-card side-card">
								<div class="content-title">Emby Context</div>
								<div class="detail-row">
									<span>Status</span>
									<strong>{userContextBusy ? 'Loading…' : (userContext.source || 'Not loaded')}</strong>
								</div>
								<div class="detail-row">
									<span>Accessible views</span>
									<strong>{userContext.views?.length || 0}</strong>
								</div>
								<div class="detail-row">
									<span>Recently played</span>
									<strong>{userContext.recentlyPlayed?.length || 0}</strong>
								</div>
								<div class="detail-row">
									<span>Last synced</span>
									<strong>{userContext.lastSyncedAt ? new Date(userContext.lastSyncedAt).toLocaleString() : 'Not available'}</strong>
								</div>
								{#if userContext.message}
									<p class="detail-message">{userContext.message}</p>
								{/if}
							</div>

							{#if userContext.recentlyPlayed?.length}
								<div class="content-card side-card rail-card">
									<div class="activity-header">
										<div>
											<div class="content-title">Recent Emby Activity</div>
											<div class="activity-summary">
												{userContext.recentlyPlayed.length} item{userContext.recentlyPlayed.length === 1 ? '' : 's'}
											</div>
										</div>
										<button
											class="btn ghost small"
											type="button"
											on:click={() => (recentlyPlayedCollapsed = !recentlyPlayedCollapsed)}
											aria-expanded={!recentlyPlayedCollapsed}
										>
											{recentlyPlayedCollapsed ? 'Show' : 'Hide'}
										</button>
									</div>
									{#if !recentlyPlayedCollapsed}
										<div class="activity-list">
											{#each userContext.recentlyPlayed as item}
												<div class="activity-item">
													<div class="activity-copy">
														<div class="activity-name">{item.name}</div>
														<div class="activity-meta">{item.seriesName ? `${item.seriesName} · ` : ''}{item.type}</div>
													</div>
													<div class="activity-time">{item.datePlayed ? new Date(item.datePlayed).toLocaleString() : 'Played'}</div>
												</div>
											{/each}
										</div>
									{/if}
								</div>
							{/if}
						</div>
					</aside>
				</div>
			{:else if activeTab === 'sync'}
				<div class="view-shell">
					<div class="content-card">
						<div class="content-header">
							<div>
								<div class="content-title">Sync Workflow</div>
								<div class="content-subtitle">
									Choose a source layout, decide how it should land, then push it to other users.
								</div>
							</div>
						</div>
						<SyncPanel {users} on:sync={handleSync} />
					</div>
				</div>
			{:else if activeTab === 'collections'}
				<div class="view-shell">
					<CollectionBuilderPage {users} {selectedUserId} on:created={onCollectionCreated} />
				</div>
			{:else if activeTab === 'genres'}
				<div class="view-shell">
					<GenreCleanupPage {users} {selectedUserId} />
				</div>
			{:else if activeTab === 'settings'}
				<div class="view-shell settings-grid">
					<div class="content-card">
						<div class="content-header">
							<div>
								<div class="content-title">Connection Settings</div>
								<div class="content-subtitle">
									Save your Emby and TMDB credentials, then manage database reads and writes.
								</div>
							</div>
						</div>
						<SettingsPanel
							{config}
							on:configSaved={onConfigSaved}
							on:namesRefreshed={onNamesRefreshed}
							on:usersLoaded={onUsersLoaded}
						/>
					</div>
					<div class="settings-cards">
						<div class="content-card info-card">
							<div class="content-title">Emby API</div>
							<div class="card-body">
								Connect to Emby to resolve real user names and gather live activity context for the collection tools.
							</div>
						</div>
						<div class="content-card info-card">
							<div class="content-title">Load From DB</div>
							<div class="card-body">
								Read the live <code>users.db</code> instead of the bundled snapshot whenever you want the current production state.
							</div>
						</div>
						<div class="content-card info-card">
							<div class="content-title">Write To DB</div>
							<div class="card-body">
								Only modified <code>homescreensettings</code> rows are touched, but Emby should be stopped first for safety.
							</div>
						</div>
					</div>
				</div>
			{:else}
				<div class="empty-state">
					<p>Select a user from the sidebar to start editing.</p>
				</div>
			{/if}
		</main>
	</div>
</div>

{#if showSqlModal}
	<SqlModal sql={generatedSql} on:close={() => (showSqlModal = false)} />
{/if}

<style>
	:global(*) {
		box-sizing: border-box;
	}

	:global(body) {
		margin: 0;
		font-family: 'Aptos', 'Aptos Display', 'Segoe UI Variable', sans-serif;
		--bg: #090a0d;
		--bg-secondary: #101115;
		--surface: #111318;
		--surface-strong: #161920;
		--surface-hover: #171b22;
		--surface-active: #1d2f36;
		--border: rgba(255, 255, 255, 0.08);
		--border-strong: rgba(45, 208, 232, 0.38);
		--text: #f7f8fb;
		--text-muted: #9ba3b2;
		--accent: #28c1dc;
		--accent-strong: #a6f4ff;
		--glow: rgba(40, 193, 220, 0.18);
		--success: #22c55e;
		--danger: #ef4444;
		background: linear-gradient(180deg, #08090c 0%, #0a0b0e 100%);
		color: var(--text);
	}

	.app {
		min-height: 100vh;
		display: grid;
		grid-template-columns: 290px minmax(0, 1fr);
	}

	.sidebar {
		display: flex;
		flex-direction: column;
		min-height: 100vh;
		background: #131418;
		border-right: 1px solid var(--border);
	}

	.sidebar-top {
		padding: 20px 16px 14px;
	}

	.brand-lockup {
		display: flex;
		align-items: center;
		gap: 12px;
		margin-bottom: 18px;
	}

	.brand-mark {
		display: grid;
		place-items: center;
		width: 28px;
		height: 28px;
		border-radius: 999px;
		font-size: 14px;
		font-weight: 800;
		color: #081116;
		background: linear-gradient(135deg, #2ad7ef 0%, #1798b4 100%);
		box-shadow: 0 0 0 1px rgba(42, 215, 239, 0.1), 0 10px 24px rgba(0, 0, 0, 0.32);
	}

	.brand-copy {
		display: flex;
		flex-direction: column;
	}

	.brand-name {
		font-size: 24px;
		font-weight: 800;
		letter-spacing: -0.04em;
		line-height: 1;
	}

	.brand-subtitle {
		margin-top: 3px;
		font-size: 12px;
		color: var(--text-muted);
	}

	.sidebar-nav {
		display: flex;
		flex-direction: column;
		gap: 4px;
	}

	.nav-link {
		all: unset;
		cursor: pointer;
		display: inline-flex;
		align-items: center;
		justify-content: flex-start;
		gap: 8px;
		padding: 10px 12px;
		border-radius: 10px;
		border: 1px solid transparent;
		color: var(--text-muted);
		font-size: 13px;
		font-weight: 600;
		line-height: 1;
		transition: background 0.16s ease, color 0.16s ease, border-color 0.16s ease, box-shadow 0.16s ease;
	}

	.nav-link:hover {
		background: var(--surface-hover);
		color: var(--text);
	}

	.nav-link.active {
		background: linear-gradient(90deg, rgba(40, 193, 220, 0.95), rgba(40, 193, 220, 0.85));
		color: #061116;
		border-color: rgba(40, 193, 220, 0.45);
		box-shadow: 0 0 0 1px rgba(40, 193, 220, 0.08) inset;
	}

	.nav-icon {
		display: inline-flex;
		color: currentColor;
	}

	.sidebar-panel {
		flex: 1;
		overflow-y: auto;
		padding: 8px 12px 16px;
	}

	.sidebar-section {
		padding: 10px 8px 12px;
	}

	.sidebar-title-row {
		display: flex;
		align-items: flex-start;
		justify-content: space-between;
		gap: 12px;
		padding: 0 4px 10px;
	}

	.sidebar-title {
		font-size: 12px;
		font-weight: 700;
		text-transform: uppercase;
		letter-spacing: 0.08em;
		color: var(--text);
		margin-bottom: 6px;
	}

	.sidebar-copy {
		font-size: 12px;
		line-height: 1.5;
		color: var(--text-muted);
	}

	.sidebar-badge {
		padding: 2px 8px;
		border-radius: 999px;
		font-size: 11px;
		border: 1px solid var(--border);
		color: var(--text-muted);
		background: #0d0f13;
	}

	.sidebar-note {
		margin: 0 8px 10px;
		padding: 12px;
		border: 1px solid var(--border);
		border-radius: 12px;
		background: #111419;
	}

	.note-title {
		font-size: 12px;
		font-weight: 700;
		color: var(--text);
		margin-bottom: 6px;
	}

	.note-copy {
		font-size: 12px;
		line-height: 1.55;
		color: var(--text-muted);
	}

	.sidebar-footer {
		display: grid;
		grid-template-columns: repeat(2, minmax(0, 1fr));
		gap: 10px;
		padding: 14px 16px 18px;
		border-top: 1px solid var(--border);
		background: #111317;
	}

	.footer-stat {
		padding: 10px 12px;
		border-radius: 12px;
		border: 1px solid var(--border);
		background: #0d0f13;
	}

	.footer-stat span {
		display: block;
		font-size: 11px;
		color: var(--text-muted);
		margin-bottom: 4px;
	}

	.footer-stat strong {
		font-size: 18px;
		font-weight: 800;
	}

	.workspace {
		min-width: 0;
		display: flex;
		flex-direction: column;
		min-height: 100vh;
	}

	.topbar {
		display: flex;
		align-items: flex-start;
		justify-content: space-between;
		gap: 20px;
		padding: 18px 22px;
		border-bottom: 1px solid var(--border);
		background: rgba(9, 10, 13, 0.96);
		position: sticky;
		top: 0;
		z-index: 20;
		backdrop-filter: blur(12px);
	}

	.topbar-copy {
		min-width: 0;
	}

	.topbar-label {
		font-size: 11px;
		font-weight: 700;
		text-transform: uppercase;
		letter-spacing: 0.1em;
		color: var(--accent-strong);
		margin-bottom: 8px;
	}

	h1 {
		margin: 0;
		font-size: 22px;
		font-weight: 800;
		letter-spacing: -0.04em;
		color: var(--text);
	}

	.topbar-copy p {
		margin: 6px 0 0;
		font-size: 13px;
		line-height: 1.5;
		color: var(--text-muted);
	}

	.header-actions {
		display: flex;
		align-items: center;
		justify-content: flex-end;
		gap: 8px;
		flex-wrap: wrap;
	}

	.status-pill {
		display: inline-flex;
		align-items: center;
		padding: 7px 10px;
		border-radius: 999px;
		border: 1px solid var(--border);
		background: #111419;
		font-size: 12px;
		color: var(--text-muted);
	}

	.status-pill.ok {
		border-color: rgba(34, 197, 94, 0.28);
		color: #86efac;
	}

	.status-pill.error {
		border-color: rgba(239, 68, 68, 0.28);
		color: #fca5a5;
	}

	.status-pill.info {
		border-color: var(--border-strong);
		color: #aeeef8;
	}

	.status-pill.pending {
		border-color: rgba(250, 204, 21, 0.2);
		color: #facc15;
	}

	.btn {
		all: unset;
		cursor: pointer;
		display: inline-flex;
		align-items: center;
		justify-content: center;
		gap: 8px;
		padding: 9px 14px;
		border-radius: 10px;
		font-size: 13px;
		font-weight: 600;
		font-family: inherit;
		transition: background 0.16s ease, border-color 0.16s ease, color 0.16s ease, opacity 0.16s ease;
		border: 1px solid transparent;
	}

	.btn.primary {
		background: var(--accent);
		border-color: rgba(42, 215, 239, 0.4);
		color: #031014;
		box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.14);
	}

	.btn.primary:hover:not(:disabled) {
		background: #35d2ea;
	}

	.btn.ghost {
		color: var(--text);
		border-color: var(--border);
		background: #15181e;
	}

	.btn.ghost:hover:not(:disabled) {
		background: var(--surface-hover);
		border-color: var(--border-strong);
	}

	.btn.accent {
		background: var(--accent);
		border-color: rgba(42, 215, 239, 0.4);
		color: #031014;
	}

	.btn.accent:hover:not(:disabled) {
		background: #35d2ea;
	}

	.btn.small {
		padding: 8px 12px;
		font-size: 12px;
	}

	.btn:disabled {
		opacity: 0.35;
		cursor: default;
	}

	.main {
		flex: 1;
		overflow-y: auto;
		padding: 20px;
	}

	.user-list {
		display: flex;
		flex-direction: column;
		gap: 8px;
	}

	.user-item {
		all: unset;
		cursor: pointer;
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		padding: 12px;
		border-radius: 12px;
		width: 100%;
		box-sizing: border-box;
		border: 1px solid var(--border);
		background: #111419;
		transition: background 0.12s ease, border-color 0.12s ease;
	}

	.user-item:hover {
		background: var(--surface-hover);
	}

	.user-item.active {
		background: var(--surface-active);
		border-color: var(--border-strong);
	}

	.user-item.dim {
		opacity: 0.7;
	}

	.user-copy {
		display: flex;
		flex-direction: column;
		gap: 4px;
		min-width: 0;
	}

	.user-name {
		font-size: 13px;
		font-weight: 600;
		color: var(--text);
	}

	.user-meta {
		font-size: 11px;
		color: var(--text-muted);
	}

	.user-count {
		font-size: 11px;
		color: var(--text);
		background: #0c0e12;
		padding: 4px 8px;
		border-radius: 999px;
		border: 1px solid var(--border);
		font-variant-numeric: tabular-nums;
	}

	.user-divider {
		font-size: 11px;
		color: var(--text-muted);
		padding: 8px 4px 2px;
		text-transform: uppercase;
		letter-spacing: 0.08em;
		font-weight: 600;
	}

	.builder-shell {
		display: grid;
		grid-template-columns: minmax(0, 1fr) 320px;
		gap: 18px;
		align-items: start;
	}

	.builder-main,
	.builder-rail,
	.view-shell {
		min-width: 0;
	}

	.view-shell {
		display: flex;
		flex-direction: column;
		gap: 16px;
	}

	.rail-stack {
		position: sticky;
		top: 86px;
		display: flex;
		flex-direction: column;
		gap: 16px;
	}

	.metrics-grid {
		display: grid;
		grid-template-columns: repeat(4, minmax(0, 1fr));
		gap: 12px;
		margin-bottom: 16px;
	}

	.metric-card {
		display: flex;
		align-items: center;
		gap: 12px;
		padding: 14px 16px;
		border-radius: 12px;
		border: 1px solid var(--border);
		background: #101217;
	}

	.metric-icon {
		display: grid;
		place-items: center;
		width: 28px;
		height: 28px;
		border-radius: 8px;
		background: rgba(40, 193, 220, 0.1);
		color: var(--accent);
	}

	.metric-copy {
		display: flex;
		flex-direction: column;
		gap: 3px;
	}

	.metric-copy strong {
		font-size: 24px;
		font-weight: 800;
		line-height: 1;
	}

	.metric-copy span {
		font-size: 12px;
		color: var(--text-muted);
	}

	.content-card {
		border: 1px solid var(--border);
		border-radius: 14px;
		background: #0f1116;
		padding: 18px;
	}

	.side-card {
		padding: 16px;
	}

	.content-header {
		display: flex;
		align-items: flex-start;
		justify-content: space-between;
		gap: 16px;
		padding-bottom: 16px;
		margin-bottom: 16px;
		border-bottom: 1px solid var(--border);
	}

	.content-title {
		font-size: 15px;
		font-weight: 800;
		color: var(--text);
		letter-spacing: -0.02em;
	}

	.content-subtitle {
		margin-top: 6px;
		font-size: 13px;
		line-height: 1.55;
		color: var(--text-muted);
	}

	.main-header-actions {
		display: flex;
		gap: 10px;
		flex-wrap: wrap;
	}

	.section-list {
		max-width: none;
	}

	.rail-actions {
		display: grid;
		grid-template-columns: 1fr;
		gap: 10px;
		margin-top: 14px;
	}

	.rail-btn {
		width: 100%;
		justify-content: flex-start;
	}

	.detail-row {
		display: flex;
		justify-content: space-between;
		gap: 12px;
		padding: 10px 0;
		border-bottom: 1px solid var(--border);
		font-size: 13px;
	}

	.detail-row:last-child {
		border-bottom: none;
	}

	.detail-row span {
		color: var(--text-muted);
	}

	.detail-row strong {
		color: var(--text);
		text-align: right;
	}

	.detail-message {
		margin: 14px 0 0;
		font-size: 12px;
		color: var(--text-muted);
		line-height: 1.5;
	}

	.rail-card {
		max-height: min(58vh, 680px);
		overflow: hidden;
	}

	.activity-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		gap: 12px;
		margin-bottom: 8px;
	}

	.activity-summary {
		margin-top: 5px;
		font-size: 12px;
		color: var(--text-muted);
	}

	.activity-list {
		display: flex;
		flex-direction: column;
		gap: 4px;
		overflow-y: auto;
		padding-right: 2px;
	}

	.activity-item {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		gap: 12px;
		padding: 10px 0;
		border-bottom: 1px solid var(--border);
	}

	.activity-item:last-child {
		border-bottom: none;
		padding-bottom: 0;
	}

	.activity-copy {
		min-width: 0;
	}

	.activity-name {
		font-size: 13px;
		font-weight: 600;
		color: var(--text);
	}

	.activity-meta,
	.activity-time {
		font-size: 12px;
		color: var(--text-muted);
	}

	.activity-time {
		flex-shrink: 0;
		text-align: right;
	}

	.empty-state {
		text-align: center;
		padding: 56px 24px;
		color: var(--text-muted);
		background: #0f1116;
		border: 1px solid var(--border);
		border-radius: 14px;
	}

	.empty-state-inline {
		margin-top: 8px;
	}

	.empty-state p {
		margin-bottom: 16px;
	}

	.empty-actions {
		display: inline-flex;
		flex-wrap: wrap;
		justify-content: center;
		gap: 10px;
	}

	.settings-grid {
		display: grid;
		grid-template-columns: minmax(0, 1.3fr) minmax(280px, 0.8fr);
		gap: 16px;
		align-items: start;
	}

	.settings-cards {
		display: grid;
		grid-template-columns: 1fr;
		gap: 12px;
	}

	.info-card {
		padding: 16px;
	}

	.card-body {
		margin-top: 8px;
		font-size: 13px;
		color: var(--text-muted);
		line-height: 1.6;
	}

	.card-body code,
	.sidebar-copy code,
	.note-copy code {
		font-size: 12px;
		background: #0c0e12;
		padding: 2px 6px;
		border-radius: 6px;
		color: var(--text);
	}

	@media (max-width: 1200px) {
		.builder-shell,
		.settings-grid {
			grid-template-columns: 1fr;
		}

		.rail-stack {
			position: static;
		}

		.metrics-grid {
			grid-template-columns: repeat(2, minmax(0, 1fr));
		}
	}

	@media (max-width: 900px) {
		.app {
			grid-template-columns: 1fr;
		}

		.sidebar {
			min-height: 0;
			border-right: none;
			border-bottom: 1px solid var(--border);
		}

		.topbar,
		.content-header {
			flex-direction: column;
		}

		.main {
			padding: 16px;
		}
	}

	@media (max-width: 640px) {
		.header-actions {
			justify-content: flex-start;
		}

		h1 {
			font-size: 20px;
		}

		.metrics-grid,
		.sidebar-footer {
			grid-template-columns: 1fr 1fr;
		}

		.content-card {
			padding: 16px;
		}

		.main-header-actions {
			width: 100%;
		}
	}
</style>
