<script lang="ts">
	import { STATUS_READ } from "@src/const";
	import {
		createMetadata,
		setMetadataContext,
	} from "@ui/stores/metadata.svelte";
	import {
		createSettings,
		setSettingsContext,
	} from "@ui/stores/settings.svelte";
	import { onDestroy } from "svelte";
	import { ShelfSettingsSchema } from "./ShelfCodeBlock";
	import { parseYaml } from "obsidian";
	import DateFilter from "@ui/components/DateFilter.svelte";
	import BookshelfView from "@ui/components/BookshelfView.svelte";
	import TableView from "@ui/components/TableView.svelte";
	import DetailsView from "@ui/components/DetailsView.svelte";
	import { setAppContext } from "@ui/stores/app";
	import type { SvelteCodeBlockProps } from "./SvelteCodeBlockRenderer";

	const { plugin, source }: SvelteCodeBlockProps = $props();
	setAppContext(plugin.app);

	const settings = ShelfSettingsSchema.parse(parseYaml(source));

	const settingsStore = createSettings(plugin);
	setSettingsContext(settingsStore);

	const metadataStore = createMetadata(plugin, {
		statusFilter: settings.statusFilter,
		initialMonth: true,
	});
	setMetadataContext(metadataStore);

	let view = $state(settings.defaultView);

	onDestroy(() => metadataStore.destroy());
</script>

<div
	class="shelf-code-block"
	class:table-view={view === "table"}
	class:bookshelf-view={view === "bookshelf"}
	class:details-view={view === "details"}
>
	<div class="controls">
		<select bind:value={view}>
			<option value="table">Table</option>
			<option value="bookshelf">Bookshelf</option>
			<option value="details">Details</option>
		</select>
		{#if settings.statusFilter === STATUS_READ}
			<DateFilter store={metadataStore} />
		{/if}
	</div>
	{#if view === "bookshelf"}
		<BookshelfView {plugin} />
	{:else if view === "table"}
		<TableView {plugin} {settings} />
	{:else if view === "details"}
		<DetailsView {plugin} {settings} />
	{/if}
</div>

<style lang="scss">
	.shelf-code-block {
		container: bookshelf / inline-size;

		.controls {
			margin-bottom: 1rem;

			@container (width < 600px) {
				width: 100% !important;
			}
		}

		&.bookshelf-view {
			.controls {
				margin-left: auto;
				margin-right: auto;
				width: 80%;
			}
		}
	}
</style>
