const assertDialogUsingClaroStyles = (cy) => {
  cy.waitForElementsToStabilize('[data-dialog-style-from]');
  cy.get('[role="dialog"] .button--primary')
    .should('exist')
    .then((primaryButton) => {
      const expectedStyles = {
        color: 'rgb(255, 255, 255)',
        'background-color': 'rgb(0, 62, 204)',
        'padding-bottom': '15px',
        'padding-top': '15px',
        'padding-left': '23px',
        'padding-right': '23px',
      };

      const styles = window.getComputedStyle(primaryButton[0]);
      const styleObj = Array.from(styles).reduce((carry, style) => {
        carry[style] = styles.getPropertyValue(style);
        return carry;
      }, {});
      Object.keys(expectedStyles).forEach((style) => {
        const expectedValue = expectedStyles[style].trim();
        const actualValue = styleObj[style].trim();
        expect(
          actualValue,
          `Primary button ${style} should be ${expectedValue}`,
        ).to.include(expectedValue);
      });
    });
};

describe('ckeditor 5', () => {
  before(() => {
    cy.drupalCanvasInstall([
      'canvas_test_article_fields',
      'canvas_test_dialog_style',
    ]);
  });

  beforeEach(() => {
    cy.drupalSession();
    cy.drupalLogin('canvasUser', 'canvasUser');
  });

  after(() => {
    cy.drupalUninstall();
  });

  // @todo: bring back with necessary refactors in https://www.drupal.org/i/3522998
  // eslint-disable-next-line mocha/no-pending-tests
  it.skip('can change text formats', () => {
    cy.loadURLandWaitForCanvasLoaded();
    const wrap =
      '[data-drupal-selector="edit-field-cvt-textarea-summary-wrapper"]';
    const formatWrap = `${wrap} [data-drupal-selector="edit-field-cvt-textarea-summary-0-format"]`;
    const dialogWrap = `${formatWrap} [role="dialog"]`;

    cy.log('Confirm the Change Text Format warning dialog works properly');
    cy.get(`${formatWrap} button`)
      .first()
      .should('include.text', 'Text format');
    cy.get(`${formatWrap} button`).first().click();
    cy.get(`${formatWrap} [aria-haspopup="dialog"]`).should(
      'have.text',
      'Text format',
    );
    cy.get(
      `${formatWrap} [data-drupal-selector="edit-field-cvt-textarea-summary-0-format"]`,
    ).realClick({ force: true });
    cy.get(dialogWrap).should('be.visible');
    cy.get(`${dialogWrap} button`).should('have.text', 'Basic HTML');
    cy.get(`${dialogWrap} button`).click();
    cy.get('[role="listbox"][data-state="open"] [role="option"]')
      .contains('minimal_html')
      .realClick({ force: true });
    cy.get(`${dialogWrap} button`).should('have.text', 'minimal_html');
    cy.get(`${dialogWrap} button`).parent().realClick({ force: true });
    cy.get('.ui-dialog-title').contains('Change text format?').should('exist');
    cy.get('.ui-dialog-buttonset button').contains('Continue').click();
    cy.get('.ui-dialog-title').should('not.exist');

    cy.log('Confirm the Media Library dialog is rendered by Claro');
    cy.get(
      '[data-testid="canvas-contextual-panel"] [data-radix-scroll-area-viewport]',
    )
      .find(wrap)
      .scrollIntoView({ scrollBehavior: 'center' });
    cy.get(`${wrap} [data-cke-tooltip-text="Insert Media"]`).should('exist');
    cy.get(`${wrap} [data-cke-tooltip-text="Insert Media"]`).click({
      force: true,
    });

    // Confirm the modal has a class that is specific to Claro.
    cy.get('#drupal-modal .media-library-item__click-to-select-trigger').should(
      'exist',
    );
  });

  it('works with page data form', () => {
    cy.loadURLandWaitForCanvasLoaded({ url: 'canvas/editor/node/2' });
    cy.findByTestId('canvas-contextual-panel--page-data').click({
      force: true,
    });
    const wrap = '[data-drupal-selector="edit-field-cvt-textarea-wrapper"]';
    cy.get(wrap).findByTestId('text-format-select').select('minimal_html');

    cy.get(
      `${wrap} [data-cke-tooltip-text="Source"][aria-pressed="false"]`,
    ).click({ scrollBehavior: false, force: true });
    cy.get(
      `${wrap} [data-cke-tooltip-text="Source"][aria-pressed="true"]`,
    ).should('exist');
    cy.get(`${wrap} textarea[aria-label="Source code editing area"]`).type(
      '<em>some italic</em> <b>some bold</b>',
    );
    cy.get(
      `${wrap} [data-cke-tooltip-text="Source"][aria-pressed="true"]`,
    ).click();
    cy.get(
      `${wrap} [data-cke-tooltip-text="Source"][aria-pressed="false"]`,
    ).should('exist');

    cy.publishAllPendingChanges('I am an empty node');
    cy.drupalRelativeURL('node/2/edit');
    cy.get('[data-drupal-selector="edit-field-cvt-textarea-0-value"]').should(
      'contain',
      '<p><em>some italic</em> <strong>some bold</strong></p>',
    );
  });

  it('uses the admin theme for dialogs generated by JS only', () => {
    cy.loadURLandWaitForCanvasLoaded();
    cy.waitForElementsToStabilize('[data-dialog-style-from]');
    cy.clickComponentInPreview('Hero');
    cy.get('[test-drupal-dialog]').should('exist');
    cy.get('[test-drupal-dialog]').click();
    assertDialogUsingClaroStyles(cy);
  });

  it('uses the admin theme for dialogs triggered via CKEditor5', () => {
    cy.loadURLandWaitForCanvasLoaded();
    cy.waitForElementsToStabilize('[data-dialog-style-from]');

    cy.findByLabelText('Canvas Text Area').as('textarea');
    cy.get('@textarea')
      .parents('.js-text-format-wrapper')
      .as('textarea-wrapper');
    cy.get('@textarea-wrapper').findByTestId('text-format-select');
    cy.get('@textarea-wrapper')
      .findByTestId('text-format-select')
      .select('minimal_html');
    cy.get('@textarea').scrollIntoView({ scrollBehavior: 'bottom' });
    cy.get('@textarea-wrapper')
      .findByLabelText('Insert Media')
      .realClick({ force: true });

    // Within these tests sometimes an additional click is needed to open the
    // dialog. Setting the force option to true prevents a test failure even if
    // the dialog is already open.
    cy.get('@textarea-wrapper')
      .findByLabelText('Insert Media')
      .realClick({ force: true });
    assertDialogUsingClaroStyles(cy);
  });
});
