import type { Meta, StoryObj } from '@storybook/angular';
import { moduleMetadata } from '@storybook/angular';
import { expect, within } from 'storybook/test';
import { FormFieldComponent } from './form-field.component';
import { TextInputComponent } from '@shared/ui/text-input/text-input.component';

const meta: Meta<FormFieldComponent> = {
  title: 'Design System/Molecules/Form Field',
  component: FormFieldComponent,
  decorators: [moduleMetadata({ imports: [TextInputComponent] })],
  render: (args) => ({
    props: args,
    // form-horizontal + .row context, same as every real caller (wizard-shell, login-form, …).
    template: `
      <form class="form-horizontal">
        <app-form-field [label]="label" [fieldId]="fieldId" [description]="description" [error]="error" [required]="required">
          <app-text-input [inputId]="fieldId" [hasDescription]="!!description" [invalid]="!!error" placeholder="Vul in" />
        </app-form-field>
      </form>`,
  }),
};
export default meta;
type Story = StoryObj<FormFieldComponent>;

export const Default: Story = {
  args: { label: 'BSN', fieldId: 'bsn', description: '9 cijfers', required: true },
  // Composition contract: fieldId must equal the input's id — enforced here, not by DI
  // (see WP-16). Catches drift in the description→aria-describedby wiring.
  play: async ({ canvasElement }) => {
    const canvas = within(canvasElement);
    const input = canvas.getByRole('textbox');
    await expect(input).toHaveAttribute('aria-describedby', 'bsn-desc');
  },
};
export const WithError: Story = {
  args: {
    label: 'Straat en huisnummer',
    fieldId: 'street',
    error: 'Dit veld is verplicht.',
    required: true,
  },
  play: async ({ canvasElement }) => {
    const canvas = within(canvasElement);
    const input = canvas.getByRole('textbox');
    await expect(input).toHaveAttribute('aria-describedby', 'street-error');
  },
};
export const WithDescriptionAndError: Story = {
  args: {
    label: 'BSN',
    fieldId: 'bsn',
    description: '9 cijfers',
    error: 'Ongeldig BSN.',
    required: true,
  },
  play: async ({ canvasElement }) => {
    const canvas = within(canvasElement);
    const input = canvas.getByRole('textbox');
    await expect(input).toHaveAttribute('aria-describedby', 'bsn-desc bsn-error');
  },
};
