---
import type { AvailableIcons } from 'studiocms:ui/icons';
import type { StudioCMSColorway } from '../../utils/colors.js';
import Icon from '../Icon/Icon.astro';
import './dropdown.css';

/**
 * An option in the dropdown.
 */
interface Option {
	/**
	 * The label of the option.
	 */
	label: string;
	/**
	 * The value of the option, returned by the helper when listened for.
	 */
	value: string;
	/**
	 * Whether the option is disabled.
	 */
	disabled?: boolean;
	/**
	 * The color of the option.
	 */
	color?: StudioCMSColorway;
	/**
	 * The icon to display next to the option.
	 */
	icon?: AvailableIcons;
	/**
	 * The href to link to when the option is clicked. When given, the option will be rendered as an anchor tag.
	 */
	href?: string;
}

/**
 * The props for the Dropdown component.
 */
interface Props {
	/**
	 * The options to display in the dropdown.
	 */
	options: Option[];
	/**
	 * Whether the dropdown is disabled.
	 */
	disabled?: boolean;
	/**
	 * The ID of the dropdown. Required because of the helper.
	 */
	id: string;
	/**
	 * The alignment of the dropdown, defaults to `center`. Will not work on mobile due to size constraints.
	 */
	align?: 'start' | 'center' | 'end';
	/**
	 * The type of click with which the dropdown is clicked. Defaults to `left`.
	 */
	triggerOn?: 'left' | 'right' | 'both';
	/**
	 * The offset of the dropdown from the trigger element in pixels.
	 */
	offset?: number;
}

const {
	options,
	disabled = false,
	align = 'center',
	id,
	triggerOn = 'left',
	offset = 0,
} = Astro.props;
---
<div 
  class="sui-dropdown-container"
  class:list={[disabled && 'disabled']}
  data-align={align}
  id={`${id}-container`}
  data-trigger={triggerOn}
  transition:persist
  transition:persist-props
>
  <div class="sui-dropdown-toggle" id={`${id}-toggle-btn`}>
    <slot />
  </div>
  <ul 
    class="sui-dropdown" 
    class:list={[align]}
    role="listbox" id={`${id}-dropdown`} 
    transition:persist
    transition:persist-props
    aria-labelledby={`${id}-toggle-btn`}
    style={`--offset: ${offset}px;`}
  >
    {options.map(({ value, disabled, color, label, icon, href }) => (
      <li
        class="sui-dropdown-option"
        data-value={value}
        class:list={[disabled && "disabled", icon && "has-icon", color, href && "has-href"]}
        role="option"
        aria-selected="false"
      >
				{href ? (
          <a href={href} class="sui-dropdown-link sui-dropdown-line-container">
          	{icon && (<Icon width={24} height={24} name={icon} />)}
						<span>{label}</span>
					</a>
				) : (
					<div class="sui-dropdown-line-container">
						{icon && (<Icon width={24} height={24} name={icon} />)}
						<span>{label}</span>
					</div>
				)}
      </li>
    ))}
  </ul>
</div>
