/**
 * Tests for ModifyDeliverySettings component (delivery settings form in slidebox)
 * @jest-environment jsdom
 */

/* eslint-disable react/prop-types */

import React from 'react';
import { fireEvent, render, screen } from '@testing-library/react';
import ModifyDeliverySettings from '../../DeliverySettings/ModifyDeliverySettings';
import { CHANNELS } from '../../constants';

jest.mock('../../DeliverySettings/ModifyDeliverySettings.scss', () => ({}));

jest.mock('@capillarytech/cap-ui-library/CapRow', () => ({ children, className }) => <div className={className} data-testid="cap-row">{children}</div>);
jest.mock('@capillarytech/cap-ui-library/CapHeader', () => ({ title, className }) => <div className={className} data-testid="cap-header">{title}</div>);
jest.mock('@capillarytech/cap-ui-library/CapSelect', () => ({
  options = [],
  value,
  onChange,
  disabled,
  placeholder,
  componentClassName,
}) => (
  <div>
    <select
      data-testid="cap-select"
      data-placeholder={placeholder}
      data-component-classname={componentClassName}
      value={value ?? ''}
      onChange={(e) => {
        const matched = options.find((opt) => String(opt.value) === e.target.value);
        onChange(matched ? matched.value : e.target.value);
      }}
      disabled={disabled}
      aria-label={placeholder}
    >
      <option value="">--empty--</option>
      {(options || []).map((opt) => (
        <option key={`${opt.label}-${opt.value}`} value={String(opt.value)}>
          {opt.label}
        </option>
      ))}
    </select>
    <input
      data-testid="cap-select-raw-input"
      onChange={(e) => onChange(e.target.value)}
    />
  </div>
));
jest.mock('@capillarytech/cap-ui-library/CapButton', () => ({ children, onClick, type }) => (
  <button type="button" onClick={onClick} data-testid="cap-button" data-buttontype={type}>
    {children}
  </button>
));
jest.mock('@capillarytech/cap-ui-library/CapSpin', () => ({ spinning }) => (spinning ? <div data-testid="cap-spin">Loading...</div> : null));
jest.mock('@capillarytech/cap-ui-library/CapLabel', () => ({ children, type }) => <span data-testid="cap-label" data-type={type}>{children}</span>);

jest.mock('react-intl', () => ({
  FormattedMessage: ({ defaultMessage }) => <span>{defaultMessage}</span>,
  defineMessages: (obj) => obj,
}));

describe('ModifyDeliverySettings', () => {
  const defaultProps = {
    channel: CHANNELS.SMS,
    deliverySettings: {},
    senderDetailsOptions: [],
    wecrmAccounts: [],
    onSaveDeliverySettings: jest.fn(),
    onClose: jest.fn(),
    isLoading: false,
    formatMessage: (msg) => msg?.defaultMessage || msg?.id,
    whatsappAccountFromForm: undefined,
  };

  const smsDomains = [
    {
      domainId: 11,
      domainName: 'SMS Domain',
      dgmId: 111,
      gsmSenders: [{ value: 'GSM_A' }, { value: 'GSM_DEFAULT', default: true }],
      cdmaSenders: [{ value: 'CDMA_A' }, { value: 'CDMA_DEFAULT', default: true }],
    },
    {
      domainId: 22,
      dgmId: 222,
      gsmSenders: [],
      cdmaSenders: [],
    },
  ];

  const emailDomains = [
    {
      domainId: 31,
      domainName: 'Email Domain',
      dgmId: 331,
      emailSenders: [
        { value: 'noreply@test.com', label: 'No Reply' },
        { value: 'default@test.com', label: 'Default Label', default: true },
      ],
      emailRepliers: [
        { value: 'reply@test.com' },
        { value: 'default-reply@test.com', default: true },
      ],
    },
  ];

  const whatsappDomains = [
    {
      domainId: 41,
      sourceAccountIdentifier: 'waba-1',
      gsmSenders: [{ value: '+111' }, { value: '+112' }],
    },
    {
      domainId: 42,
      sourceAccountIdentifier: 'waba-2',
      gsmSenders: [{ value: '+221' }],
    },
  ];

  const wecrmAccounts = [
    { name: 'Account One', sourceAccountIdentifier: 'waba-1' },
    { name: 'Account Two', sourceAccountIdentifier: 'waba-2' },
  ];

  const renderComponent = (props = {}) => render(
    <ModifyDeliverySettings
      {...defaultProps}
      {...props}
    />
  );

  const getSelects = () => screen.getAllByTestId('cap-select');
  const getRawInputs = () => screen.getAllByTestId('cap-select-raw-input');

  beforeEach(() => {
    jest.clearAllMocks();
  });

  describe('loading state', () => {
    it('should render CapSpin when isLoading is true', () => {
      renderComponent({ isLoading: true });
      expect(screen.getByTestId('cap-spin')).toBeTruthy();
      expect(screen.getByText('Loading...')).toBeTruthy();
      expect(screen.queryByTestId('cap-button')).toBeNull();
    });
  });

  describe('fallbacks and unsupported channel', () => {
    it('should use destructured default values when optional props are undefined', () => {
      const onSave = jest.fn();

      render(
        <ModifyDeliverySettings
          channel={CHANNELS.SMS}
          deliverySettings={undefined}
          senderDetailsOptions={undefined}
          wecrmAccounts={undefined}
          onSaveDeliverySettings={onSave}
          onClose={jest.fn()}
          isLoading={false}
          formatMessage={(msg) => msg?.defaultMessage || msg?.id}
        />
      );

      expect(getSelects()).toHaveLength(2);
      fireEvent.click(screen.getByText('Done'));
      expect(onSave).toHaveBeenCalledWith({
        domainId: null,
        domainGatewayMapId: null,
        gsmSenderId: '',
        cdmaSenderId: '',
      });
    });

    it('should use fallback placeholder when formatMessage is not provided', () => {
      renderComponent({
        channel: CHANNELS.SMS,
        senderDetailsOptions: smsDomains,
      });
      expect(getSelects()[0].getAttribute('data-placeholder')).toBe('No options');
    });

    it('should render no select rows for unsupported channel and still save empty object', () => {
      const onSave = jest.fn();
      const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});

      renderComponent({
        channel: 'RCS',
        onSaveDeliverySettings: onSave,
      });

      expect(screen.queryAllByTestId('cap-select')).toHaveLength(0);
      fireEvent.click(screen.getByText('Done'));
      expect(onSave).toHaveBeenCalledWith({});

      consoleErrorSpy.mockRestore();
    });

    it('should handle locked WhatsApp lookup when wecrmAccounts is null', () => {
      const onSave = jest.fn();

      renderComponent({
        channel: CHANNELS.WHATSAPP,
        wecrmAccounts: null,
        senderDetailsOptions: whatsappDomains,
        whatsappAccountFromForm: { accountName: 'Account One' },
        onSaveDeliverySettings: onSave,
      });

      fireEvent.click(screen.getByText('Done'));
      expect(onSave).toHaveBeenCalledWith({
        domainId: null,
        senderMobNum: '',
        sourceAccountIdentifier: '',
      });
    });

    it('should evaluate account name fallback when locked WhatsApp account entry has no name', () => {
      const onSave = jest.fn();

      renderComponent({
        channel: CHANNELS.WHATSAPP,
        wecrmAccounts: [{ sourceAccountIdentifier: 'waba-1' }],
        senderDetailsOptions: whatsappDomains,
        whatsappAccountFromForm: { accountName: 'Account One' },
        onSaveDeliverySettings: onSave,
      });

      fireEvent.click(screen.getByText('Done'));
      expect(onSave).toHaveBeenCalledWith({
        domainId: null,
        senderMobNum: '',
        sourceAccountIdentifier: '',
      });
    });
  });

  describe('SMS flow', () => {
    it('should render SMS fields and button type', () => {
      renderComponent({
        channel: CHANNELS.SMS,
        senderDetailsOptions: smsDomains,
      });

      expect(getSelects()).toHaveLength(2);
      expect(screen.getByTestId('cap-button').getAttribute('data-buttontype')).toBe('primary');
    });

    it('should update gateway map, gsm sender, and cdma sender on SMS domain change using defaults', () => {
      const onSave = jest.fn();

      renderComponent({
        channel: CHANNELS.SMS,
        senderDetailsOptions: smsDomains,
        onSaveDeliverySettings: onSave,
      });

      fireEvent.change(getSelects()[0], { target: { value: '11' } });
      fireEvent.click(screen.getByText('Done'));

      expect(onSave).toHaveBeenCalledWith({
        domainId: 11,
        domainGatewayMapId: 111,
        gsmSenderId: 'GSM_DEFAULT',
        cdmaSenderId: 'CDMA_DEFAULT',
      });
    });

    it('should set empty sender values when SMS domain has no senders', () => {
      const onSave = jest.fn();

      renderComponent({
        channel: CHANNELS.SMS,
        senderDetailsOptions: smsDomains,
        deliverySettings: {
          domainId: null,
          domainGatewayMapId: null,
          gsmSenderId: 'OLD_GSM',
          cdmaSenderId: 'OLD_CDMA',
        },
        onSaveDeliverySettings: onSave,
      });

      fireEvent.change(getSelects()[0], { target: { value: '22' } });
      fireEvent.click(screen.getByText('Done'));

      expect(onSave).toHaveBeenCalledWith({
        domainId: 22,
        domainGatewayMapId: 222,
        gsmSenderId: '',
        cdmaSenderId: '',
      });
    });

    it('should keep previous gateway values when SMS domain is not found and still update domainId', () => {
      const onSave = jest.fn();

      renderComponent({
        channel: CHANNELS.SMS,
        senderDetailsOptions: smsDomains,
        deliverySettings: {
          domainId: 11,
          domainGatewayMapId: 999,
          gsmSenderId: 'KEEP_GSM',
          cdmaSenderId: 'KEEP_CDMA',
        },
        onSaveDeliverySettings: onSave,
      });

      fireEvent.change(getRawInputs()[0], { target: { value: '9999' } });
      fireEvent.click(screen.getByText('Done'));

      expect(onSave).toHaveBeenCalledWith({
        domainId: '9999',
        domainGatewayMapId: 999,
        gsmSenderId: 'KEEP_GSM',
        cdmaSenderId: 'KEEP_CDMA',
      });
    });

    it('should update SMS sender field directly', () => {
      const onSave = jest.fn();

      renderComponent({
        channel: CHANNELS.SMS,
        senderDetailsOptions: smsDomains,
        deliverySettings: {
          domainId: 11,
          domainGatewayMapId: 111,
          gsmSenderId: 'GSM_A',
          cdmaSenderId: 'CDMA_A',
        },
        onSaveDeliverySettings: onSave,
      });

      fireEvent.change(getSelects()[1], { target: { value: 'GSM_DEFAULT' } });
      fireEvent.click(screen.getByText('Done'));

      expect(onSave).toHaveBeenCalledWith({
        domainId: 11,
        domainGatewayMapId: 111,
        gsmSenderId: 'GSM_DEFAULT',
        cdmaSenderId: 'CDMA_A',
      });
    });

    it('should use sender label when gsm sender value is missing', () => {
      renderComponent({
        channel: CHANNELS.SMS,
        senderDetailsOptions: [{
          domainId: 55,
          domainName: 'Label Domain',
          gsmSenders: [{ label: 'Label GSM', value: '' }],
          cdmaSenders: [],
        }],
        deliverySettings: { domainId: 55 },
      });

      const senderOptions = Array.from(getSelects()[1].querySelectorAll('option')).map((opt) => opt.textContent);
      expect(senderOptions).toEqual(expect.arrayContaining(['Label GSM']));
    });

    it('should keep existing SMS domain options when TRAI DLT is not enabled', () => {
      renderComponent({
        channel: CHANNELS.SMS,
        senderDetailsOptions: [
          {
            domainId: 11,
            domainName: 'Domain One',
            gsmSenders: [{ value: 'ID1' }],
            cdmaSenders: [],
          },
          {
            domainId: 22,
            domainName: 'Domain Two',
            gsmSenders: [{ value: 'ID2' }],
            cdmaSenders: [],
          },
        ],
        smsTraiDltEnabled: false,
        registeredSenderIds: ['ID2'],
      });

      const domainOptions = Array.from(getSelects()[0].querySelectorAll('option')).map((opt) => opt.textContent);
      expect(domainOptions).toEqual(expect.arrayContaining(['Domain One', 'Domain Two']));
    });

    it('should filter SMS domains and sender IDs when TRAI DLT is enabled', () => {
      renderComponent({
        channel: CHANNELS.SMS,
        senderDetailsOptions: [
          {
            domainId: 11,
            domainName: 'Domain One',
            dgmId: 111,
            gsmSenders: [{ value: 'ID1' }, { value: 'ID2' }],
            cdmaSenders: [],
          },
          {
            domainId: 22,
            domainName: 'Domain Two',
            dgmId: 222,
            gsmSenders: [{ value: 'ID3' }],
            cdmaSenders: [],
          },
        ],
        smsTraiDltEnabled: true,
        registeredSenderIds: ['ID2'],
      });

      const domainOptions = Array.from(getSelects()[0].querySelectorAll('option')).map((opt) => opt.textContent);
      expect(domainOptions).toEqual(expect.arrayContaining(['Domain One']));
      expect(domainOptions).not.toEqual(expect.arrayContaining(['Domain Two']));

      fireEvent.change(getSelects()[0], { target: { value: '11' } });
      const senderOptions = Array.from(getSelects()[1].querySelectorAll('option')).map((opt) => opt.textContent);
      expect(senderOptions).toEqual(expect.arrayContaining(['ID2']));
      expect(senderOptions).not.toEqual(expect.arrayContaining(['ID1']));
    });

    it('should default to the first allowed GSM sender when SMS domain changes in TRAI DLT mode', () => {
      const onSave = jest.fn();

      renderComponent({
        channel: CHANNELS.SMS,
        senderDetailsOptions: [
          {
            domainId: 11,
            domainName: 'Domain One',
            dgmId: 111,
            gsmSenders: [{ value: 'ID1' }, { value: 'ID2' }],
            cdmaSenders: [{ value: 'CDMA1' }],
          },
        ],
        smsTraiDltEnabled: true,
        registeredSenderIds: ['ID2'],
        onSaveDeliverySettings: onSave,
      });

      fireEvent.change(getSelects()[0], { target: { value: '11' } });
      fireEvent.click(screen.getByText('Done'));

      expect(onSave).toHaveBeenCalledWith({
        domainId: 11,
        domainGatewayMapId: 111,
        gsmSenderId: 'ID2',
        cdmaSenderId: 'CDMA1',
      });
    });

    it('should show no SMS domain options when TRAI DLT is enabled and no registered sender ID matches', () => {
      renderComponent({
        channel: CHANNELS.SMS,
        senderDetailsOptions: [
          {
            domainId: 11,
            domainName: 'Domain One',
            gsmSenders: [{ value: 'ID1' }],
            cdmaSenders: [],
          },
        ],
        smsTraiDltEnabled: true,
        registeredSenderIds: ['UNMATCHED'],
      });

      const domainOptions = Array.from(getSelects()[0].querySelectorAll('option')).map((opt) => opt.textContent);
      expect(domainOptions).not.toEqual(expect.arrayContaining(['Domain One']));
    });
  });

  describe('EMAIL flow', () => {
    it('should render EMAIL fields', () => {
      renderComponent({
        channel: CHANNELS.EMAIL,
        senderDetailsOptions: emailDomains,
      });

      expect(getSelects()).toHaveLength(4);
    });

    it('should update email defaults on domain change', () => {
      const onSave = jest.fn();

      renderComponent({
        channel: CHANNELS.EMAIL,
        senderDetailsOptions: emailDomains,
        onSaveDeliverySettings: onSave,
      });

      fireEvent.change(getSelects()[0], { target: { value: '31' } });
      fireEvent.click(screen.getByText('Done'));

      expect(onSave).toHaveBeenCalledWith({
        domainId: 31,
        domainGatewayMapId: 331,
        senderEmail: 'default@test.com',
        senderLabel: 'Default Label',
        senderReplyTo: 'default-reply@test.com',
      });
    });

    it('should update sender email and fallback label from sender id selection', () => {
      const onSave = jest.fn();

      renderComponent({
        channel: CHANNELS.EMAIL,
        senderDetailsOptions: [{
          ...emailDomains[0],
          emailSenders: [{ value: 'solo@test.com' }],
        }],
        deliverySettings: { domainId: 31, domainGatewayMapId: 331 },
        onSaveDeliverySettings: onSave,
      });

      fireEvent.change(getSelects()[1], { target: { value: 'solo@test.com' } });
      fireEvent.click(screen.getByText('Done'));

      expect(onSave).toHaveBeenCalledWith({
        domainId: 31,
        domainGatewayMapId: 331,
        senderEmail: 'solo@test.com',
        senderLabel: 'solo@test.com',
        senderReplyTo: '',
      });
    });

    it('should update sender email and sender label from sender name selection when match exists', () => {
      const onSave = jest.fn();

      renderComponent({
        channel: CHANNELS.EMAIL,
        senderDetailsOptions: emailDomains,
        deliverySettings: { domainId: 31, domainGatewayMapId: 331 },
        onSaveDeliverySettings: onSave,
      });

      fireEvent.change(getSelects()[2], { target: { value: 'No Reply' } });
      fireEvent.click(screen.getByText('Done'));

      expect(onSave).toHaveBeenCalledWith({
        domainId: 31,
        domainGatewayMapId: 331,
        senderEmail: 'noreply@test.com',
        senderLabel: 'No Reply',
        senderReplyTo: '',
      });
    });

    it('should update only sender label when sender name selection has no match', () => {
      const onSave = jest.fn();

      renderComponent({
        channel: CHANNELS.EMAIL,
        senderDetailsOptions: emailDomains,
        deliverySettings: {
          domainId: 31,
          domainGatewayMapId: 331,
          senderEmail: 'keep@test.com',
        },
        onSaveDeliverySettings: onSave,
      });

      fireEvent.change(getRawInputs()[2], { target: { value: 'Custom Label' } });
      fireEvent.click(screen.getByText('Done'));

      expect(onSave).toHaveBeenCalledWith({
        domainId: 31,
        domainGatewayMapId: 331,
        senderEmail: 'keep@test.com',
        senderLabel: 'Custom Label',
        senderReplyTo: '',
      });
    });

    it('should update reply-to selection directly', () => {
      const onSave = jest.fn();

      renderComponent({
        channel: CHANNELS.EMAIL,
        senderDetailsOptions: emailDomains,
        deliverySettings: { domainId: 31, domainGatewayMapId: 331 },
        onSaveDeliverySettings: onSave,
      });

      fireEvent.change(getSelects()[3], { target: { value: 'reply@test.com' } });
      fireEvent.click(screen.getByText('Done'));

      expect(onSave).toHaveBeenCalledWith({
        domainId: 31,
        domainGatewayMapId: 331,
        senderEmail: '',
        senderLabel: '',
        senderReplyTo: 'reply@test.com',
      });
    });

    it('should use fallback labels for email sender name and reply-to options', () => {
      renderComponent({
        channel: CHANNELS.EMAIL,
        senderDetailsOptions: [{
          domainId: 88,
          domainName: 'Fallback Email Domain',
          emailSenders: [{ value: 'fallback@test.com' }],
          emailRepliers: [{ label: 'Reply Label', value: '' }],
        }],
        deliverySettings: { domainId: 88 },
      });

      const senderNameOptions = Array.from(getSelects()[2].querySelectorAll('option')).map((opt) => opt.textContent);
      const replyToOptions = Array.from(getSelects()[3].querySelectorAll('option')).map((opt) => opt.textContent);

      expect(senderNameOptions).toEqual(expect.arrayContaining(['fallback@test.com']));
      expect(replyToOptions).toEqual(expect.arrayContaining(['Reply Label']));
    });
  });

  describe('WHATSAPP flow', () => {
    it('should render WhatsApp fields', () => {
      renderComponent({
        channel: CHANNELS.WHATSAPP,
        senderDetailsOptions: whatsappDomains,
        wecrmAccounts,
      });

      expect(getSelects()).toHaveLength(2);
    });

    it('should show all sender numbers when no account is selected', () => {
      renderComponent({
        channel: CHANNELS.WHATSAPP,
        senderDetailsOptions: whatsappDomains,
        wecrmAccounts,
      });

      const senderSelect = getSelects()[1];
      const optionTexts = Array.from(senderSelect.querySelectorAll('option')).map((opt) => opt.textContent);

      expect(optionTexts).toEqual(expect.arrayContaining(['+111', '+112', '+221']));
    });

    it('should show sender numbers only for selected account', () => {
      renderComponent({
        channel: CHANNELS.WHATSAPP,
        senderDetailsOptions: whatsappDomains,
        wecrmAccounts,
        deliverySettings: { sourceAccountIdentifier: 'waba-2', senderMobNum: '' },
      });

      const senderSelect = getSelects()[1];
      const optionTexts = Array.from(senderSelect.querySelectorAll('option')).map((opt) => opt.textContent);

      expect(optionTexts).toEqual(expect.arrayContaining(['+221']));
      expect(optionTexts).not.toEqual(expect.arrayContaining(['+111']));
    });

    it('should update account and sender number when account selection changes', () => {
      const onSave = jest.fn();

      renderComponent({
        channel: CHANNELS.WHATSAPP,
        senderDetailsOptions: whatsappDomains,
        wecrmAccounts,
        onSaveDeliverySettings: onSave,
      });

      fireEvent.change(getSelects()[0], { target: { value: 'waba-2' } });
      fireEvent.click(screen.getByText('Done'));

      expect(onSave).toHaveBeenCalledWith({
        domainId: null,
        senderMobNum: '+221',
        sourceAccountIdentifier: 'waba-2',
      });
    });

    it('should set empty sender number when selected WhatsApp account has no matching domain', () => {
      const onSave = jest.fn();

      renderComponent({
        channel: CHANNELS.WHATSAPP,
        senderDetailsOptions: whatsappDomains,
        wecrmAccounts,
        onSaveDeliverySettings: onSave,
      });

      fireEvent.change(getRawInputs()[0], { target: { value: 'missing-account' } });
      fireEvent.click(screen.getByText('Done'));

      expect(onSave).toHaveBeenCalledWith({
        domainId: null,
        senderMobNum: '',
        sourceAccountIdentifier: 'missing-account',
      });
    });

    it('should update sender number directly', () => {
      const onSave = jest.fn();

      renderComponent({
        channel: CHANNELS.WHATSAPP,
        senderDetailsOptions: whatsappDomains,
        wecrmAccounts,
        deliverySettings: { sourceAccountIdentifier: 'waba-1', senderMobNum: '+111' },
        onSaveDeliverySettings: onSave,
      });

      fireEvent.change(getSelects()[1], { target: { value: '+112' } });
      fireEvent.click(screen.getByText('Done'));

      expect(onSave).toHaveBeenCalledWith({
        domainId: null,
        senderMobNum: '+112',
        sourceAccountIdentifier: 'waba-1',
      });
    });

    it('should lock account select, show disabled message, and seed settings from matching form account', () => {
      const onSave = jest.fn();

      renderComponent({
        channel: CHANNELS.WHATSAPP,
        senderDetailsOptions: whatsappDomains,
        wecrmAccounts,
        whatsappAccountFromForm: { accountName: 'Account One' },
        onSaveDeliverySettings: onSave,
      });

      const [accountSelect] = getSelects();
      expect(accountSelect.disabled).toBe(true);
      expect(accountSelect.getAttribute('data-component-classname')).toContain('modify-delivery-settings__select--disabled');
      expect(screen.getByText('Message template selected belongs to this account')).toBeTruthy();

      fireEvent.click(screen.getByText('Done'));

      expect(onSave).toHaveBeenCalledWith({
        domainId: null,
        senderMobNum: '+111',
        sourceAccountIdentifier: 'waba-1',
      });
    });

    it('should keep previous state when locked account already matches source account identifier', () => {
      const onSave = jest.fn();

      renderComponent({
        channel: CHANNELS.WHATSAPP,
        senderDetailsOptions: whatsappDomains,
        wecrmAccounts,
        whatsappAccountFromForm: { accountName: 'Account One' },
        deliverySettings: {
          domainId: null,
          senderMobNum: 'KEEP_ME',
          sourceAccountIdentifier: 'waba-1',
        },
        onSaveDeliverySettings: onSave,
      });

      fireEvent.click(screen.getByText('Done'));

      expect(onSave).toHaveBeenCalledWith({
        domainId: null,
        senderMobNum: 'KEEP_ME',
        sourceAccountIdentifier: 'waba-1',
      });
    });

    it('should show fallback account option when locked account name is not found in wecrm accounts', () => {
      renderComponent({
        channel: CHANNELS.WHATSAPP,
        senderDetailsOptions: whatsappDomains,
        wecrmAccounts,
        whatsappAccountFromForm: { accountName: 'Unknown Account' },
      });

      const accountSelect = getSelects()[0];
      const optionTexts = Array.from(accountSelect.querySelectorAll('option')).map((opt) => opt.textContent);

      expect(optionTexts).toEqual(expect.arrayContaining(['Unknown Account']));
    });

    it('should not update source account when locked account has no matching source identifier', () => {
      const onSave = jest.fn();

      renderComponent({
        channel: CHANNELS.WHATSAPP,
        senderDetailsOptions: whatsappDomains,
        wecrmAccounts: [{ name: 'Broken Account' }],
        whatsappAccountFromForm: { accountName: 'Broken Account' },
        onSaveDeliverySettings: onSave,
      });

      fireEvent.click(screen.getByText('Done'));

      expect(onSave).toHaveBeenCalledWith({
        domainId: null,
        senderMobNum: '',
        sourceAccountIdentifier: '',
      });
    });

    it('should use sourceAccountIdentifier as account label when account name is missing', () => {
      renderComponent({
        channel: CHANNELS.WHATSAPP,
        senderDetailsOptions: whatsappDomains,
        wecrmAccounts: [{ sourceAccountIdentifier: 'fallback-waba' }],
      });

      const accountOptions = Array.from(getSelects()[0].querySelectorAll('option')).map((opt) => opt.textContent);
      expect(accountOptions).toEqual(expect.arrayContaining(['fallback-waba']));
    });

    it('should keep sender number unchanged when locked account maps to domain without first sender value', () => {
      const onSave = jest.fn();

      renderComponent({
        channel: CHANNELS.WHATSAPP,
        senderDetailsOptions: [{
          sourceAccountIdentifier: 'waba-1',
          gsmSenders: [{}],
        }],
        wecrmAccounts: [{ name: 'Account One', sourceAccountIdentifier: 'waba-1' }],
        whatsappAccountFromForm: { accountName: 'Account One' },
        deliverySettings: {
          domainId: null,
          senderMobNum: 'KEEP_NUMBER',
          sourceAccountIdentifier: '',
        },
        onSaveDeliverySettings: onSave,
      });

      fireEvent.click(screen.getByText('Done'));

      expect(onSave).toHaveBeenCalledWith({
        domainId: null,
        senderMobNum: 'KEEP_NUMBER',
        sourceAccountIdentifier: 'waba-1',
      });
    });
  });

  describe('Done and close handling', () => {
    it('should call onSaveDeliverySettings with channel defaults when nothing changes', () => {
      const onSave = jest.fn();

      renderComponent({
        channel: CHANNELS.SMS,
        onSaveDeliverySettings: onSave,
        onClose: jest.fn(),
      });

      fireEvent.click(screen.getByText('Done'));

      expect(onSave).toHaveBeenCalledTimes(1);
      expect(onSave).toHaveBeenCalledWith({
        domainId: null,
        domainGatewayMapId: null,
        gsmSenderId: '',
        cdmaSenderId: '',
      });
    });

    it('should call onClose when Done is clicked if onClose is provided', () => {
      const onClose = jest.fn();

      renderComponent({
        onSaveDeliverySettings: jest.fn(),
        onClose,
      });

      fireEvent.click(screen.getByText('Done'));
      expect(onClose).toHaveBeenCalled();
    });

    it('should save successfully when onClose is not provided', () => {
      const onSave = jest.fn();

      renderComponent({
        onSaveDeliverySettings: onSave,
        onClose: undefined,
      });

      fireEvent.click(screen.getByText('Done'));
      expect(onSave).toHaveBeenCalled();
    });
  });

  describe('onDomainChange — dgmId edge cases', () => {
    it('should not update domainGatewayMapId when selected SMS domain has no dgmId', () => {
      const onSave = jest.fn();

      renderComponent({
        channel: CHANNELS.SMS,
        senderDetailsOptions: [
          {
            domainId: 99,
            domainName: 'No DGM Domain',
            // dgmId intentionally absent
            gsmSenders: [{ value: 'GSM_99', default: true }],
            cdmaSenders: [{ value: 'CDMA_99', default: true }],
          },
        ],
        deliverySettings: {
          domainId: null,
          domainGatewayMapId: 555,
          gsmSenderId: '',
          cdmaSenderId: '',
        },
        onSaveDeliverySettings: onSave,
      });

      fireEvent.change(getSelects()[0], { target: { value: '99' } });
      fireEvent.click(screen.getByText('Done'));

      expect(onSave).toHaveBeenCalledWith({
        domainId: 99,
        domainGatewayMapId: 555, // unchanged — domain has no dgmId
        gsmSenderId: 'GSM_99',
        cdmaSenderId: 'CDMA_99',
      });
    });

    it('should not update domainGatewayMapId when selected EMAIL domain has no dgmId', () => {
      const onSave = jest.fn();

      renderComponent({
        channel: CHANNELS.EMAIL,
        senderDetailsOptions: [
          {
            domainId: 55,
            domainName: 'No DGM Email Domain',
            // no dgmId
            emailSenders: [{ value: 'sender@test.com', label: 'Sender', default: true }],
            emailRepliers: [{ value: 'reply@test.com', default: true }],
          },
        ],
        deliverySettings: {
          domainId: null,
          domainGatewayMapId: 777,
          senderEmail: '',
          senderLabel: '',
          senderReplyTo: '',
        },
        onSaveDeliverySettings: onSave,
      });

      fireEvent.change(getSelects()[0], { target: { value: '55' } });
      fireEvent.click(screen.getByText('Done'));

      expect(onSave).toHaveBeenCalledWith({
        domainId: 55,
        domainGatewayMapId: 777, // unchanged — domain has no dgmId
        senderEmail: 'sender@test.com',
        senderLabel: 'Sender',
        senderReplyTo: 'reply@test.com',
      });
    });
  });

  describe('findDefault fallback — first item used when no default:true', () => {
    it('should use first gsm/cdma sender when none has default:true flag', () => {
      const onSave = jest.fn();

      renderComponent({
        channel: CHANNELS.SMS,
        senderDetailsOptions: [
          {
            domainId: 77,
            domainName: 'No Default Domain',
            dgmId: 777,
            gsmSenders: [{ value: 'FIRST_GSM' }, { value: 'SECOND_GSM' }],
            cdmaSenders: [{ value: 'FIRST_CDMA' }, { value: 'SECOND_CDMA' }],
          },
        ],
        onSaveDeliverySettings: onSave,
      });

      fireEvent.change(getSelects()[0], { target: { value: '77' } });
      fireEvent.click(screen.getByText('Done'));

      expect(onSave).toHaveBeenCalledWith({
        domainId: 77,
        domainGatewayMapId: 777,
        gsmSenderId: 'FIRST_GSM',
        cdmaSenderId: 'FIRST_CDMA',
      });
    });
  });
});
