import {LitElement, html, map, unsafeHTML} from './lit-all.min.js';
import {markdown} from './markdown.js';
import * as tfrpc from '/static/tfrpc.js';

class BookClubElement extends LitElement {
	static get properties() {
		return {
			hash: {type: String},
		};
	}
	constructor() {
		super();
		let self = this;
		tfrpc.rpc.getHash().then(function (hash) {
			self.set_hash(hash);
		});
		tfrpc.register(function hashChanged(hash) {
			self.set_hash(hash);
		});
	}

	set_hash(hash) {
		this.hash = hash ? decodeURIComponent(hash) : '#';
	}

	render_add_button() {
		return html`
			<a
				class="w3-card-4 w3-button w3-display-container w3-margin-bottom"
				style="width: 100%; aspect-ratio: 2 / 1"
				target="_top"
				href="#!"
			>
				<h2 class="w3-display-middle">Add a new book.</h2>
			</a>
		`;
	}

	render() {
		if (this.hash?.length > 1) {
			let hash = this.hash.substring(1);
			let edit = hash.startsWith('!');
			if (edit) {
				hash = hash.substring(1);
			}
			let book = g_data[hash];
			if (edit) {
				return html`<bc-book-edit .book=${book} />`;
			} else {
				if (book) {
					return html`<bc-book-page .book=${book} />`;
				} else {
					return html`
						<link rel="stylesheet" href="w3.css"></link>
						<div class="w3-container">
							<h1>${hash} not found.</h1>
							<a class="w3-button w3-gray" href="#" target="_top">Back</a>
						</div>
					`;
				}
			}
		} else if (!Object.keys(g_data).length) {
			return html`
				<h1>No bookclub messages to display.</h1>
				${this.render_add_button()}
			`;
		} else {
			return html`
				<link rel="stylesheet" href="w3.css"></link>
				<div style="background-color: #fff; columns: 3in" class="w3-padding">
					${this.render_add_button()}
					${map(
						Object.values(g_data),
						(x) =>
							html` <div style="break-inside: avoid">
								<bc-book-tile .book=${x}></bc-book-tile>
							</div>`
					)}
				</div>`;
		}
	}
}

customElements.define('bc-app', BookClubElement);
