import { Accessor, createContext, For, useContext } from "solid-js";
import type {
	SimpleAction,
	SimplePlayerView,
} from "@games/shared/games/simple";
import { me, profile } from "~/profile";
import Hand from "./Hand";
import Pile from "./Pile";
import { TableContext } from "./Table";
import { Portal } from "solid-js/web";
import FannedHand from "./FannedHand";

export const GameContext = createContext<{
	view: Accessor<SimplePlayerView>;
	submitAction: (action: SimpleAction) => any;
}>();

export default () => {
	const table = useContext(TableContext)!;
	const view = table.view as Accessor<SimplePlayerView>;
	const submitAction = (action: SimpleAction) => table.sendWs({ action });

	return (
		<GameContext.Provider value={{ view, submitAction }}>
			<Pile
				count={view().deckCount}
				class="cursor-pointer fixed center"
				onClick={() => submitAction({ type: "draw" })}
			/>

			<Hand
				class="fixed bc"
				hand={view().myHand}
				onClickCard={(card) => submitAction({ type: "discard", card })}
			/>
			<div class="absolute tc text-align-center">
				It's{" "}
				<span class="font-bold">
					{view().playerTurn == me()
						? "your"
						: profile(view().playerTurn)()?.name + "'s"}
				</span>{" "}
				turn
			</div>
			<button
				class="button fixed tl m-4 p-1"
				onClick={() => {
					table.sendWs({ quit: true });
				}}
			>
				Quit
			</button>
			<For each={Object.entries(view().playerHandCounts)}>
				{([playerKey, handCount], i) => (
					<Portal
						mount={document.getElementById(`player-${playerKey}`)!}
						ref={(ref) => {
							const midOffset =
								i() + 0.5 - Object.values(view().playerHandCounts).length / 2;

							ref.style = `position: absolute; display: flex; justify-content: center; top: 65%; transform: translate(${Math.abs(
								midOffset * 0
							)}px, 0px) rotate(${midOffset * 1}rad)`;
						}}
					>
						<FannedHand handCount={handCount} />
					</Portal>
				)}
			</For>
		</GameContext.Provider>
	);
};
