/// <reference types="vite/client" />
import type { Meta, StoryObj } from '@storybook/web-components-vite';
import { getStorybookHelpers } from '@wc-toolkit/storybook-helpers';
import type { CfpbButtonProps } from '../../../../../storybook/custom-elements-types';
import { CfpbButton } from './index.js';

CfpbButton.init();

// Build the icon name list from the SVG filenames
// TODO: Pull this out into a helper function
const iconNames = Object.keys(
  import.meta.glob('../../components/cfpb-icons/icons/*.svg'),
).map((p) => p.split('/').pop()!.replace('.svg', ''));

/**
 * `properties` is excluded because wc-toolkit emits a control for both a prop
 * and its attribute whenever the two are named differently (EG `styleAsLink and`
 * `style-as-link`). Both describe one piece of state and `template()` binds both.
 * In doing that it applys the prop _after_ the attr. So, leaving them in lets a property
 * with a default overwrite whatever a story set through the attribute name
 */
const { args, argTypes, template } = getStorybookHelpers<CfpbButtonProps>(
  'cfpb-button',
  { excludeCategories: ['methods', 'properties'] },
);

type ButtonStoryArgs = CfpbButtonProps & { 'default-slot'?: string };

const meta: Meta<ButtonStoryArgs> = {
  title: 'Web Components/cfpb-button',
  component: 'cfpb-button',
  tags: ['autodocs'],
  args: {
    ...args,
    variant: 'primary',
    'default-slot': 'Button label',
  },
  argTypes: {
    ...argTypes,
    variant: {
      control: 'select',
      options: ['primary', 'secondary', 'warning'],
    },
    'icon-left': {
      control: 'select',
      options: ['', ...iconNames],
    },
    'icon-right': {
      control: 'select',
      options: ['', ...iconNames],
    },
  },
  render: (args) => template(args),
};

export default meta;

type Story = StoryObj<ButtonStoryArgs>;

export const Primary: Story = {};

export const Secondary: Story = {
  args: { variant: 'secondary' },
};

export const Warning: Story = {
  args: { variant: 'warning' },
};

export const Disabled: Story = {
  args: { disabled: true },
};

export const AsLink: Story = {
  args: {
    href: '#',
    'style-as-link': true,
  },
};

export const WithIcon: Story = {
  args: {
    'icon-right': 'download',
  },
};

export const WithSpinningIcon: Story = {
  args: {
    'icon-left': 'update',
    'icon-left-spin': true,
  },
};

/**
 * Behavior is covered in index.spec.js - see STORYBOOK.md for the split.
 */
