<?php

/**
 * @file
 * Hooks for the CKEditor 5 Div Widget module.
 */

use Drupal\ckeditor5_div_widget\BoxBreakpoints;
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_page_attachments().
 *
 * The box – item grid layout is theme independent, so it is added to every
 * page where box divs may show up in the content.
 */
function ckeditor5_div_widget_page_attachments(array &$attachments): void {
  $attachments['#attached']['library'][] = 'ckeditor5_div_widget/box';
}

/**
 * Implements hook_library_info_build().
 *
 * The responsive rules of the box are generated from the breakpoint settings
 * (see BoxBreakpoints) and loaded right after css/box.css.
 */
function ckeditor5_div_widget_library_info_build(): array {
  BoxBreakpoints::ensure();
  return [
    'box' => [
      'css' => [
        'layout' => [
          BoxBreakpoints::libraryPath() => [],
        ],
      ],
    ],
  ];
}

/**
 * Implements hook_form_FORM_ID_alter() for filter_format_form.
 *
 * The breakpoints on the Div Widget tab are shared by all text formats, so
 * they are saved in the module settings, only on the final submit (CKEditor 5
 * also submits the plugin forms while validating and on AJAX rebuilds).
 */
function ckeditor5_div_widget_form_filter_format_form_alter(array &$form, FormStateInterface $form_state): void {
  if (isset($form['actions']['submit'])) {
    $form['actions']['submit']['#submit'][] = 'ckeditor5_div_widget_breakpoints_submit';
  }
}

/**
 * Submit handler: saves the breakpoints of the Div Widget tab.
 */
function ckeditor5_div_widget_breakpoints_submit(array $form, FormStateInterface $form_state): void {
  $values = $form_state->getValue(['editor', 'settings', 'plugins', 'ckeditor5_div_widget_divWidget', 'breakpoints']);
  if (is_array($values) && isset($values['breakpoint_wide'], $values['breakpoint_medium'])) {
    BoxBreakpoints::save((string) $values['breakpoint_wide'], (string) $values['breakpoint_medium']);
  }
}
