import { describe, it, expect } from 'vitest';
import { mount } from '@vue/test-utils';
import MDatepicker from './MDatepicker.vue'; // adjust path accordingly

describe('MDatepicker component', () => {
  it('renders correctly with default props', () => {
    const wrapper = mount(MDatepicker, {
      props: {
        id: 'test-id',
      },
    });

    const input = wrapper.get('input');
    expect(input.attributes('id')).toBe('test-id');
    expect(input.element.value).toBe('');
  });

  it('binds props correctly', () => {
    const wrapper = mount(MDatepicker, {
      props: {
        id: 'date-id',
        name: 'date',
        modelValue: '2025-07-25',
        disabled: true,
        isInvalid: true,
        readonly: true,
      },
    });

    const input = wrapper.get('input');
    expect(input.element.value).toBe('2025-07-25');
    expect(input.attributes('disabled')).toBeDefined();
    expect(input.attributes('readonly')).toBeDefined();
    expect(input.attributes('aria-invalid')).toBe('true');
  });

  it('emits update:modelValue on input change', async () => {
    const wrapper = mount(MDatepicker, {
      props: {
        id: 'date-id',
        modelValue: '',
      },
    });

    const input = wrapper.get('input');
    await input.setValue('2025-01-01');

    const emitted = wrapper.emitted('update:modelValue');
    expect(emitted).toBeTruthy();
    expect(emitted![0]).toEqual(['2025-01-01']);
  });

  it('shows clear button when isClearable and modelValue are truthy', () => {
    const wrapper = mount(MDatepicker, {
      props: {
        id: 'date-id',
        modelValue: '2025-01-01',
        isClearable: true,
        clearLabel: 'Clear it',
      },
    });

    expect(wrapper.find('.mc-controls-options__button').exists()).toBe(true);
    expect(wrapper.text()).toContain('Clear it');
  });

  it('clears value when clear button is clicked', async () => {
    const wrapper = mount(MDatepicker, {
      props: {
        id: 'date-id',
        modelValue: '2025-01-01',
        isClearable: true,
      },
    });

    const button = wrapper.get('.mc-controls-options__button');
    await button.trigger('click');

    const emitted = wrapper.emitted('update:modelValue');
    expect(emitted).toBeTruthy();
    expect(emitted!.slice(-1)[0]).toEqual(['']);
  });

  it('does not show clear button if modelValue is empty', () => {
    const wrapper = mount(MDatepicker, {
      props: {
        id: 'date-id',
        modelValue: '',
        isClearable: true,
      },
    });

    expect(wrapper.find('.mc-controls-options__button').exists()).toBe(false);
  });
});
