import { Icon } from "@ax/components";
import type { HeadingNode } from "@ax/types";

import * as S from "./style";

const HeadingItem = ({
	head,
	index,
	isFiltering,
	selected,
	onHeadingClick,
	counter,
	parentPath,
}: IHeadingItemProps) => {
	counter.value += 1;
	const headingId = counter.value;
	const uniqueKey = `${parentPath}${head.tag}-${head.level}-${index}-${head.text.slice(0, 20)}`;

	return (
		<>
			<S.HeadItem
				level={isFiltering ? 1 : head.level}
				tag={head.tag}
				tabIndex={0}
				role="button"
				onClick={onHeadingClick(headingId)}
				isSelected={selected === headingId}
				isHidden={head.isHidden}
				data-heading-id={headingId}
			>
				<S.HeadTag>
					<div>{head.tag}</div>
				</S.HeadTag>
				<S.StyledTooltip content={head.isHidden ? "Hidden with CSS" : null}>
					<S.HeadText>
						<div>{head.text}</div>
						{head.isHidden && (
							<S.HiddenIcon>
								<Icon name="hide" size="16" />
							</S.HiddenIcon>
						)}
					</S.HeadText>
				</S.StyledTooltip>
			</S.HeadItem>
			{head.children.map((child, childIndex) => (
				<HeadingItem
					key={`${uniqueKey}-child-${childIndex}`}
					head={child}
					index={childIndex}
					isFiltering={isFiltering}
					selected={selected}
					onHeadingClick={onHeadingClick}
					counter={counter}
					parentPath={`${uniqueKey}-`}
				/>
			))}
		</>
	);
};

interface IHeadingItemProps {
	head: HeadingNode;
	index: number;
	isFiltering: boolean;
	selected: number | null;
	onHeadingClick: (id: number) => () => void;
	counter: { value: number };
	parentPath: string;
}

export default HeadingItem;
