import { css } from "@linaria/core"
import type { CSSProperties, ReactNode } from "react"
import React from "react"

/** width / heigt */
const hexAspectRatio = 4 / 3 * Math.sqrt(3) / 2

export function HexGrid({
	gap,
	rows,
	cols,
	children
}: {
	gap: number,
	rows: number,
	cols: number,
	children: ReactNode
}) {
	return (
		<div className={css`position: relative;`}>
			<div
				style={{
					"--hex-y-gap": `${gap}px`,
					"--hex-x-gap": `${gap * Math.sqrt(3) / 2}px`,
					/* Add .5 to account for staggered columns */
					"--hex-rows": rows + .5,
					"--hex-cols": cols
				} as CSSProperties}
				className={css`
					/* available width divided by columns adjusted for overlap */
					--hex-width: calc(
						(100% - ((var(--hex-cols) - 1) * var(--hex-x-gap)))
						/ (var(--hex-cols) * 3 / 4 + 1 / 4)
					);

					/* total y gaps plus total hex heights */
					padding-bottom: calc(
						(var(--hex-rows) - 1) * var(--hex-y-gap)
						+ var(--hex-rows) * var(--hex-width) / ${hexAspectRatio}
					);
				`}
			>
				{children}
			</div>
		</div>
	)
}

export function Hex({
	children,
	row,
	col
}: {
	children: ReactNode,
	row: number,
	col: number
}) {
	const colStyle = css`
		/* available height minus total y gaps divided by rows */
		--hex-height: calc(
			(100% - (var(--hex-rows) - 1) * var(--hex-y-gap))
			/ var(--hex-rows)
		);

		position: absolute;
		width: var(--hex-width);
		height: var(--hex-height);
		top: calc((var(--hex-height) + var(--hex-y-gap)) * var(--hex-row));
		left: calc((var(--hex-width) * 3 / 4 + var(--hex-x-gap)) * var(--hex-col));
	`

	return <div
		className={colStyle}
		style={{
			"--hex-row": row + (col % 2 === 0 ? .5 : 0),
			"--hex-col": col
		} as CSSProperties}
	>
		<div
			className={css`
				position: absolute;
				inset: 0;
				display: grid;
				grid-template: 100% / 100%;
			`}
		>
			{children}
		</div>
	</div>
}
