<?php
if (!defined('ABSPATH')) exit;

if (!function_exists('custausu_admin_dropdown_pages_lang')) {
  function custausu_admin_dropdown_pages_lang(array $args, string $lang): void {
    unset($lang);

    $name      = (string)($args['name'] ?? '');
    $selected  = (int)($args['selected'] ?? 0);
    $class     = (string)($args['class'] ?? '');
    $show_none = (string)($args['show_option_none'] ?? '— Select —');
    $none_val  = (string)($args['option_none_value'] ?? '0');

    $pages = get_posts([
      'post_type'        => 'page',
      'post_status'      => ['publish','private','draft','pending','future'],
      'posts_per_page'   => -1,
      'orderby'          => 'title',
      'order'            => 'ASC',
      'no_found_rows'    => true,
    ]);

    echo '<select name="'.esc_attr($name).'" class="'.esc_attr($class).'">';
    echo '<option value="'.esc_attr($none_val).'">'.esc_html($show_none).'</option>';

    foreach ((array)$pages as $p) {
      $pid = (int)$p->ID;
      $title = (string)get_the_title($pid);

      if ($title === '') {
        $title = '(no title)';
      }

      echo '<option value="'.esc_attr((string)$pid).'" '.selected($selected, $pid, false).'>'
        . esc_html($title) . ' (#' . esc_html((string)$pid) . ')'
        . '</option>';
    }

    echo '</select>';
  }
}

if (!function_exists('custausu_admin_render_assets_section')) {
  function custausu_admin_render_assets_section(
    callable $T,
    array $opt,
    callable $get_field_box_class,
    callable $get_field_note_html
  ): string {
    unset($opt, $get_field_box_class, $get_field_note_html);

    ob_start();

    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Internal admin gate renderer returns controlled admin HTML.
    echo wp_kses( custausu_admin_gate_wrap_start('assets_customization', $T), custausu_admin_allowed_output_html() );

    echo '<table id="custausu-section-assets" class="widefat striped custausu-assets-settings custausu-assets-settings--preview">';
    echo '<thead class="custausu-head"><tr><th colspan="2" class="custausu-assets-settings__head-cell"><h2 class="custausu-assets-settings__title"><span class="dashicons dashicons-format-image"></span> | Assets</h2></th></tr></thead>';
    echo '<tbody>';

    $preview_url_row = static function(string $id, string $label, string $help, string $extra = ''): void {
      echo '<tr><th scope="row"><label for="' . esc_attr($id) . '">' . esc_html($label) . '</label></th><td>';
      echo '<input id="' . esc_attr($id) . '" type="url" class="regular-text custausu-assets-settings__url-input" value="" placeholder="https://..." disabled aria-disabled="true">';
      if ($help !== '') {
        echo '<p class="description custausu-assets-settings__description">' . esc_html($help) . '</p>';
      }
      if ($extra !== '') {
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Extra preview HTML is built internally.
        echo wp_kses( $extra, custausu_admin_allowed_output_html() );
      }
      echo '</td></tr>';
    };

    $login_toggle = '<div class="custausu-assets-settings__login-gif-toggle">'
      . '<label><input type="checkbox" value="1" checked disabled aria-disabled="true"> '
      . esc_html($T(
        'Show the Login GIF/Icon on the CAS login page and the native WordPress password reset screens.',
        'Mostra la GIF/Icona di login nella pagina Login CAS e nelle schermate native WordPress di reimpostazione della password.'
      ))
      . '</label>'
      . '<p class="description custausu-assets-settings__description">'
      . esc_html($T(
        'Free always uses the built-in CAS login SVG on both the CAS login page and the native WordPress password reset screens. Advanced can replace or hide this visual.',
        'Free usa sempre il logo SVG CAS integrato sia nella pagina Login CAS sia nelle schermate native WordPress di reimpostazione della password. Advanced può sostituire o nascondere questo elemento visuale.'
      ))
      . '</p></div>';

    $preview_url_row(
      'custausu_assets_logingif_url',
      'Login GIF URL',
      $T(
        'Advanced can replace the built-in CAS login SVG with a custom visual on the CAS login page and the native WordPress password reset screens.',
        'Advanced può sostituire il logo SVG CAS integrato con un elemento visuale personalizzato nella pagina Login CAS e nelle schermate native WordPress di reimpostazione della password.'
      ),
      $login_toggle
    );

    $preview_url_row(
      'custausu_assets_checkgif_url',
      'Check GIF URL',
      $T(
        'Advanced can replace the built-in confirmation check SVG.',
        'Advanced può sostituire il check SVG di conferma integrato.'
      )
    );

    $preview_url_row(
      'custausu_assets_email_logo_url',
      'Email Logo URL',
      $T(
        'Advanced can add a custom logo to CAS service emails.',
        'Advanced può aggiungere un logo personalizzato alle email di servizio CAS.'
      )
    );

    echo '<tr><th scope="row">' . esc_html($T('Email logo width (px)', 'Larghezza logo email (px)')) . '</th><td>';
    echo '<input type="number" min="30" max="600" step="1" value="180" style="width:120px;" disabled aria-disabled="true">';
    echo '<p class="description custausu-assets-settings__description">' . esc_html($T(
      'Used only when an Advanced custom email logo is configured.',
      'Usata soltanto quando è configurato un logo email personalizzato Advanced.'
    )) . '</p>';
    echo '</td></tr>';

    $preview_url_row(
      'custausu_assets_support_url',
      $T('Support URL', 'URL supporto'),
      $T(
        'Advanced can override the {{support_url}} email token. Free resolves this token to the site home URL.',
        'Advanced può sostituire il token email {{support_url}}. Free risolve questo token con la home del sito.'
      )
    );

    echo '</tbody></table>';

    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Internal admin gate renderer returns controlled admin HTML.
    echo wp_kses( custausu_admin_gate_wrap_end(), custausu_admin_allowed_output_html() );

    return (string)ob_get_clean();
  }
}

if (!function_exists('custausu_auth_customizer_palette_defaults')) {
  function custausu_auth_customizer_palette_defaults(): array {
    return [
      'page_bg'      => '#ffffff',
      'box_bg'       => '#f2f2f2',
      'box_border'   => '#222222',
      'title_color'  => '#222222',
      'text_color'   => '#444444',
      'link_color'   => '#222222',
      'button_bg'    => '#222222',
      'button_text'  => '#ffffff',
      'input_border' => '#555555',
    ];
  }
}


if (!function_exists('custausu_auth_customizer_size_defaults')) {
  function custausu_auth_customizer_size_defaults(): array {
    return [
      'title_font_size'       => 36,
      'field_label_font_size' => 18,
      'body_font_size'        => 16,
      'button_font_size'      => 16,
    ];
  }
}

if (!function_exists('custausu_auth_customizer_saved_sizes')) {
  function custausu_auth_customizer_saved_sizes(array $opt): array {
    $raw = isset($opt['auth_theme']) && is_array($opt['auth_theme'])
      ? $opt['auth_theme']
      : [];

    $out = [];

    foreach (custausu_auth_customizer_size_defaults() as $key => $fallback) {
      $val = isset($raw[$key]) ? trim((string) $raw[$key]) : '';

      if ($val === '') {
        continue;
      }

      $px = absint($val);

      if ($px < 10) {
        $px = 10;
      }

      if ($px > 96) {
        $px = 96;
      }

      $out[$key] = $px;
    }

    return $out;
  }
}


if (!function_exists('custausu_auth_customizer_saved_palette')) {
  function custausu_auth_customizer_saved_palette(array $opt): array {
    $raw = isset($opt['auth_theme']) && is_array($opt['auth_theme'])
      ? $opt['auth_theme']
      : [];

    $out = [];

    foreach (custausu_auth_customizer_palette_defaults() as $key => $fallback) {
      $val = isset($raw[$key]) ? trim((string) $raw[$key]) : '';

      if ($val !== '' && $val[0] !== '#' && preg_match('/^[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/', $val)) {
        $val = '#' . $val;
      }

      $hex = sanitize_hex_color($val);

      if ($hex) {
        $out[$key] = $hex;
      }
    }

    return $out;
  }
}

if (!function_exists('custausu_admin_render_auth_customizer_section')) {
  function custausu_admin_render_auth_customizer_section(array $opt, callable $T): string {
    $defaults      = custausu_auth_customizer_palette_defaults();
    $saved         = custausu_auth_customizer_saved_palette($opt);
    $size_defaults = custausu_auth_customizer_size_defaults();
    $sizes         = custausu_auth_customizer_saved_sizes($opt);

    $rows = [
      'page_bg' => [
        $T('Page background', 'Sfondo pagina'),
        $T('Optional. Leave empty to let the active theme control the page background.', 'Opzionale. Lascia vuoto per far controllare lo sfondo pagina al tema attivo.'),
      ],
      'box_bg' => [
        $T('Auth box background', 'Sfondo box Auth'),
        $T('Background color for the login, registration and password recovery boxes.', 'Colore di sfondo dei box login, registrazione e recupero password.'),
      ],
      'box_border' => [
        $T('Auth box border', 'Bordo box Auth'),
        $T('Border color for the CAS authentication boxes.', 'Colore del bordo dei box di autenticazione CAS.'),
      ],
      'title_color' => [
        $T('Title color', 'Colore titoli'),
        $T('Color used for the main titles inside CAS auth pages.', 'Colore usato per i titoli principali nelle pagine Auth CAS.'),
      ],
      'text_color' => [
        $T('Text color', 'Colore testi'),
        $T('Base text color for labels, descriptions and messages.', 'Colore base per label, descrizioni e messaggi.'),
      ],
      'link_color' => [
        $T('Link color', 'Colore link'),
        $T('Color for auth-page links such as Forgot Password and Create one.', 'Colore dei link delle pagine Auth, come Password dimenticata e Crea account.'),
      ],
      'button_bg' => [
        $T('Button background', 'Sfondo pulsanti'),
        $T('Background color for the main CAS auth buttons.', 'Colore di sfondo dei pulsanti principali delle pagine Auth CAS.'),
      ],
      'button_text' => [
        $T('Button text', 'Testo pulsanti'),
        $T('Text color for the main CAS auth buttons.', 'Colore del testo dei pulsanti principali delle pagine Auth CAS.'),
      ],
      'input_border' => [
        $T('Input border', 'Bordo campi input'),
        $T('Border color for username, email and password fields.', 'Colore del bordo dei campi username, email e password.'),
      ],
    ];

    ob_start();

    echo '<table id="custausu-section-auth-customizer" class="widefat striped custausu-auth-customizer">';
    echo '<thead class="custausu-head"><tr><th colspan="2" class="custausu-auth-customizer__head-cell"><h2 class="custausu-auth-customizer__title"><span class="dashicons dashicons-admin-customizer"></span> | ' . esc_html($T('Auth Customizer', 'Personalizzazione Auth')) . '</h2></th></tr></thead>';
    echo '<tbody>';

    echo '<tr><th scope="row">' . esc_html($T('Auth pages palette', 'Palette pagine Auth')) . '</th><td>';
    echo '<p class="description custausu-auth-customizer__intro">' . esc_html($T(
      'Customize the colors and typography used by CAS login, registration, password recovery and reset confirmation pages, and by the native WordPress screens for requesting a new reset link, setting the new password and confirming the update.',
      'Personalizza colori e tipografia usati dalle pagine CAS di login, registrazione, recupero password e conferma reset, e dalle schermate native WordPress per richiedere un nuovo link, impostare la nuova password e confermare l’aggiornamento.'
    )) . '</p>';
    echo '<p class="description">' . esc_html($T(
      'Leave a field empty to keep the built-in CAS Auth fallback style. Clear all fields to return completely to the default CAS Auth design.',
      'Lascia un campo vuoto per mantenere lo stile fallback Auth integrato in CAS. Svuota tutti i campi per tornare completamente al design Auth predefinito CAS.'
    )) . '</p>';

    foreach ($rows as $key => $meta) {
      $label = (string) $meta[0];
      $help  = (string) $meta[1];
      $val   = (string) ($saved[$key] ?? '');
      $def   = (string) ($defaults[$key] ?? '#000000');

      echo '<div class="custausu-auth-color-row custausu-auth-customizer__option-row">';
      echo '<div class="custausu-auth-customizer__option-label">' . esc_html($label) . '</div>';
      echo '<input type="text" class="custausu-color custausu-auth-color" name="custausu_global_settings[auth_theme][' . esc_attr($key) . ']" value="' . esc_attr($val) . '" data-default-color="' . esc_attr($def) . '" placeholder="' . esc_attr($def) . '" />';
      echo '<span class="description custausu-auth-customizer__option-help">' . esc_html($help) . '</span>';
      echo '</div>';
    }

    echo '<hr class="custausu-auth-customizer__divider">';
    echo '<h3 class="custausu-auth-customizer__subheading">' . esc_html($T('Typography sizes', 'Dimensioni tipografiche')) . '</h3>';
    echo '<p class="description">' . esc_html($T(
      'Optional pixel sizes for CAS auth pages. Leave empty to keep the built-in CAS Auth fallback typography.',
      'Dimensioni opzionali in pixel per le pagine Auth CAS. Lascia vuoto per mantenere la tipografia fallback integrata in CAS.'
    )) . '</p>';

    $size_rows = [
      'title_font_size' => [
        $T('Main title size', 'Dimensione titolo principale'),
        $T('Controls headings such as Login, Create Account and Password Recovery.', 'Controlla titoli come Accedi, Crea Account e Recupero Password.'),
      ],
      'field_label_font_size' => [
        $T('Field label size', 'Dimensione titoli campi'),
        $T('Controls labels such as Username, Email and Password.', 'Controlla le label dei campi come Username, Email e Password.'),
      ],
      'body_font_size' => [
        $T('Body text size', 'Dimensione testi descrittivi'),
        $T('Controls descriptive texts, messages and secondary auth-page text.', 'Controlla testi descrittivi, messaggi e testi secondari delle pagine Auth.'),
      ],
      'button_font_size' => [
        $T('Button text size', 'Dimensione testo pulsanti'),
        $T('Controls the text size of the main auth action buttons.', 'Controlla la dimensione del testo dei pulsanti principali delle pagine Auth.'),
      ],
    ];

    foreach ($size_rows as $key => $meta) {
      $label = (string) $meta[0];
      $help  = (string) $meta[1];
      $val   = isset($sizes[$key]) ? (string) absint($sizes[$key]) : '';
      $def   = isset($size_defaults[$key]) ? (string) absint($size_defaults[$key]) : '';

      echo '<div class="custausu-auth-size-row custausu-auth-customizer__option-row">';
      echo '<div class="custausu-auth-customizer__option-label">' . esc_html($label) . '</div>';
      echo '<input type="number" class="small-text custausu-auth-size" min="10" max="96" step="1" name="custausu_global_settings[auth_theme][' . esc_attr($key) . ']" value="' . esc_attr($val) . '" placeholder="' . esc_attr($def) . '" />';
      echo '<span class="description">px — ' . esc_html($help) . '</span>';
      echo '</div>';
    }

    echo '<p class="description custausu-auth-customizer__footer-note">' . esc_html($T(
      'These controls are available in Free and also apply to Advanced and Premium packages.',
      'Questi controlli sono disponibili in Free e si applicano anche ai pacchetti Advanced e Premium.'
    )) . '</p>';

    echo '</td></tr>';
    echo '</tbody></table>';

    return (string) ob_get_clean();
  }
}


if (!function_exists('custausu_admin_render_email_customizer_section')) {
  function custausu_admin_render_email_customizer_section(
    array $opt,
    bool $polylang_active,
    bool $polylang_enabled,
    string $site_slug,
    string $default_lang,
    callable $T
  ): string {
    ob_start();

    $email_theme = (array)($opt['email_theme'] ?? []);
    $email_theme = array_merge([
      'wrap_bg'     => '#f7f7f7',
      'wrap_border' => '#222222',
      'wrap_text'   => '#222222',
      'h2_color'    => '#222222',
      'btn_bg'      => '#222222',
      'btn_text'    => '#ffffff',
    ], $email_theme);

    $email_tpl = (array)($opt['email_tpl'] ?? []);

    unset($polylang_active, $polylang_enabled);

    $single_lang = sanitize_key((string)$default_lang);
    if ($single_lang === '') $single_lang = sanitize_key((string)$site_slug);
    if ($single_lang === '') $single_lang = 'en';
    $langs_email = [$single_lang];

    $email_types = [
      'verify_register' => $T('Verify eMail (after register)', 'Verifica eMail (dopo registrazione)'),
      'verify_resend'   => $T('Verify eMail (admin resend)',   'Verifica eMail (reinviata da admin)'),
      'welcome'         => $T('Welcome eMail',                 'eMail di benvenuto'),
    ];

    if (function_exists('custausu_export_subscribers_csv_box')) {
      echo '<div id="custausu-section-export-subscribers" class="custausu-settings-section custausu-export-subscribers-section">';
      // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Export subscribers box renderer returns controlled admin HTML.
      echo custausu_export_subscribers_csv_box(false);
      echo '</div>';
    }

    echo '<table id="custausu-section-email-customizer" class="widefat striped" style="margin-top:14px">';
    echo '<thead class="custausu-head"><tr><th colspan="2" style="padding:10px 12px;"><h2 style="margin:0;font-size:18px;"><span class="dashicons dashicons-email-alt"></span> | '.esc_html($T('Email Customizer','Personalizzazione eMail')).'</h2></th></tr></thead>';
    echo '<tbody>';

    echo '<tr><th scope="row">'.esc_html($T('Email palette','Palette eMail')).'</th><td>';
    echo '<p class="description" style="margin-top:0">'.esc_html($T('One palette for all system emails (verify/resend/welcome).','Unica palette per tutte le email di servizio (verifica/reinvio/benvenuto).')).'</p>';

    // Email Customizer picker defaults are immutable and must not inherit saved values.
    $theme_defaults = [
      'wrap_bg'     => '#f7f7f7',
      'wrap_border' => '#222222',
      'wrap_text'   => '#222222',
      'h2_color'    => '#222222',
      'btn_bg'      => '#222222',
      'btn_text'    => '#ffffff',
    ];

    $email_theme = is_array($email_theme ?? null) ? $email_theme : [];
    $email_theme = array_merge($theme_defaults, $email_theme);

    $colorRow = function($k, $label) use ($email_theme, $theme_defaults) {
      $raw = (string)($email_theme[$k] ?? '');
      $raw_trim = trim($raw);

      if ($raw_trim !== '' && $raw_trim[0] !== '#' && preg_match('/^[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/', $raw_trim)) {
        $raw_trim = '#'.$raw_trim;
      }

      $val = sanitize_hex_color($raw_trim);
      if (!$val) $val = (string)($theme_defaults[$k] ?? '#000000');

      $def = (string)($theme_defaults[$k] ?? '#000000');

      echo '<div style="display:flex;gap:14px;flex-wrap:wrap;align-items:center;margin:8px 0;">';
      echo '<div style="min-width:180px;font-weight:600">'.esc_html($label).'</div>';
      echo '<input type="text" class="custausu-color" name="custausu_global_settings[email_theme]['.esc_attr($k).']" value="'.esc_attr($val).'" data-default-color="'.esc_attr($def).'" />';
      echo '</div>';
    };

    $colorRow('wrap_bg',     $T('Wrapper background','Sfondo wrapper'));
    $colorRow('wrap_border', $T('Wrapper border','Bordo wrapper'));
    $colorRow('wrap_text',   $T('Text color','Colore testo'));
    $colorRow('h2_color',    $T('Heading (H2) color','Colore titolo (H2)'));
    $colorRow('btn_bg',      $T('Button background','Sfondo bottone'));
    $colorRow('btn_text',    $T('Button text','Testo bottone'));

    echo '</td></tr>';

    echo '<tr><td colspan="2" style="padding:0;border-top:0;">';
    echo '<div class="custausu-acc-toolbar" style="display:flex;gap:8px;justify-content:flex-end;margin:10px 0 12px 0;">';
    echo '<button type="button" class="button custausu-email-acc-expand" style="margin-left:10px;">'.esc_html($T('Expand all','Espandi tutto')).'</button>';
    echo '<button type="button" class="button custausu-email-acc-collapse" style="margin-right:10px;">'.esc_html($T('Collapse all','Comprimi tutto')).'</button>';
    echo '</div>';

    foreach ($langs_email as $lng) {
      $open_attr = ($lng === $default_lang) ? 'open' : '';
      echo '<details class="custausu-acc custausu-email-acc" data-email-lang="' . esc_attr($lng) . '"' . ($open_attr !== '' ? ' ' . esc_attr($open_attr) : '') . '>';
      echo '<summary>'.esc_html(strtoupper($lng)).' <small>'.esc_html($T('Email templates','Template eMail')).'</small></summary>';
      echo '<div class="custausu-acc-body">';

      echo '<p class="description"><span style="font-size:11px;color:#333">'.esc_html(
        $T('Edit subject and HTML body. You can use basic HTML tags (br, a, strong, em, etc.).','Modifica oggetto e corpo HTML. Puoi usare tag HTML base (br, a, strong, em, ecc.).')
      ).'</span></p>';

      foreach ($email_types as $type => $label) {
        $sub = (string)($email_tpl[$lng][$type]['subject'] ?? '');
        $body = (string)($email_tpl[$lng][$type]['body'] ?? '');

        /*
         * The Email Customizer must always show a safe editable baseline.
         * Runtime delivery already falls back through custausu_email_tpl_get(); the
         * admin UI should mirror that behavior when options are missing or empty.
         */
        if (($sub === '' || $body === '') && function_exists('custausu_email_tpl_get')) {
          $custausu_email_ui_fallback = custausu_email_tpl_get((string) $lng, (string) $type);

          if ($sub === '') {
            $sub = (string)($custausu_email_ui_fallback['subject'] ?? '');
          }

          if ($body === '') {
            $body = (string)($custausu_email_ui_fallback['body'] ?? '');
          }
        }

        $editor_id = 'custausu_email_body_' . $lng . '_' . $type;

        echo '<div class="custausu-email-type" data-lang="'.esc_attr($lng).'" data-type="'.esc_attr($type).'" data-editor-id="'.esc_attr($editor_id).'" style="margin:14px 0 18px 0;padding:12px;border:1px solid rgba(0,0,0,.08);border-radius:10px;background:#fafafa">';
        echo '<div style="font-weight:800;margin:0 0 10px 0;">'.esc_html($label).'</div>';

        echo '<div style="margin:0 0 10px 0;">';
        echo '<div style="margin:0 0 6px 0;font-weight:700">'.esc_html($T('Subject','Oggetto')).'</div>';
        echo '<input data-role="subject" type="text" class="regular-text" style="width:100%;max-width:900px" name="' . esc_attr('custausu_global_settings[email_subject_' . $lng . '_' . $type . ']') . '" value="' . esc_attr($sub) . '" placeholder="">';
        echo '</div>';

        echo '<div class="custausu-email-grid">';
        echo '<div class="custausu-email-editor">';

        echo '<div style="margin:0 0 6px 0;font-weight:700">'.esc_html($T('Body (HTML)','Corpo (HTML)')).'</div>';

        echo '<div style="display:flex;gap:8px;flex-wrap:wrap;margin:10px 0 6px 0;">';
        $varsBtns = [
          'site_name','username','first_name',
          'verify_link','profile_url','support_url',
          'wrap_bg','wrap_border','wrap_text','h2_color','btn_bg','btn_text'
        ];
        foreach ($varsBtns as $vb) {
          $vb_key = sanitize_key((string) $vb);
          echo '<button type="button" class="button custausu-insert-var" data-var="' . esc_attr('{{' . $vb_key . '}}') . '">' . esc_html('{{' . $vb_key . '}}') . '</button>';
        }
        echo '</div>';
        echo '<p class="description" style="margin:0 0 6px 0;">'
          . esc_html($T(
          'Click a variable to insert it in the editor.',
          'Clicca una variabile per inserirla nell’editor.'
        ))
        . '</p>';

      echo '<p class="description" style="margin:0 0 10px 0;color:#b45309;font-weight:600;">'
        . esc_html($T(
          'Important: use CAS variables only in the HTML/Code tab of the editor, not in the Visual tab, to avoid rendering issues.',
          'Importante: usa le variabili CAS esclusivamente nel tab HTML/Codice dell’editor, non nel tab Visuale, per evitare problemi di rendering.'
        ))
        . '</p>';

        ob_start();
        wp_editor(
          $body,
          $editor_id,
          [
            'textarea_name' => 'custausu_global_settings[email_body_'.$lng.'_'.$type.']',
            'textarea_rows' => 12,
            'media_buttons' => false,
            'teeny'         => false,
            'quicktags'     => true,
            'tinymce'       => [
              'toolbar1' => 'bold,italic,underline,alignleft,aligncenter,alignright,link,unlink,bullist,numlist,removeformat,undo,redo',
              'toolbar2' => '',
            ],
          ]
        );
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- wp_editor() buffered markup is generated by WordPress.
        echo ob_get_clean();

        echo '<div style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin:10px 0 0 0;">';
        echo '<input data-role="test_to" type="email" class="regular-text" style="max-width:340px" placeholder="test@example.com">';
        echo '<button type="button" class="button button-primary custausu-send-test">'.esc_html($T('Send test', 'Invia test')).'</button>';
        echo '<span class="description">'.esc_html($T('Sends a test email using demo variables.','Invia una email di test usando variabili demo.')).'</span>';
        echo '</div>';

        echo '<div style="margin-top:12px;">';
        echo '<div style="font-weight:700;margin:0 0 6px 0;">'.esc_html($T('Preview','Anteprima')).'</div>';
        echo '<div class="description" style="margin:0 0 8px 0;">'.esc_html($T('eMail preview:','Anteprima eMail:')).' <code class="custausu-email-preview-subject"></code></div>';
        echo '<div class="custausu-email-preview" style="background:#fff;border:1px solid rgba(0,0,0,.10);border-radius:10px;padding:12px;"></div>';
        echo '</div>';
        echo '</div>';

        echo '<div class="custausu-email-help">';
        echo '<h4>'.esc_html($T('How to use variables','Come usare le variabili')).'</h4>';
        echo '<div class="description" style="margin:0 0 10px 0;line-height:1.4;">'
          . esc_html($T(
            'To make a clickable link you must wrap variables in an <a href="..."> tag. Colors in style use palette variables.',
            'Per avere un link cliccabile devi usare le variabili dentro un tag <a href="...">. I colori in style usano le variabili della palette.'
          ))
          . '</div>';

        echo '<code>&lt;a href="{{support_url}}"&gt;Support&lt;/a&gt;'."\n"
          . '&lt;a href="{{profile_url}}"&gt;Profile&lt;/a&gt;'."\n"
          . '&lt;a href="{{verify_link}}" style="background:{{btn_bg}};color:{{btn_text}};"&gt;Verify&lt;/a&gt;</code>';

        echo '<div class="description" style="margin:10px 0 0 0;">'
          . esc_html($T(
            'Logo and Support URL come from Assets section. If you see styles removed after saving, ensure you are using {{h2_color}}, {{wrap_text}}, {{btn_bg}}, {{btn_text}} exactly.',
            'Logo e Support URL arrivano dalla sezione Assets. Se dopo il salvataggio spariscono gli stili, assicurati di usare {{h2_color}}, {{wrap_text}}, {{btn_bg}}, {{btn_text}} esattamente.'
          ))
          . '</div>';

        echo '</div>';
        echo '</div>';
        echo '</div>';
      }

      echo '</div></details>';
    }

    echo '</td></tr>';
    echo '</tbody></table>';

    return (string) ob_get_clean();
  }
}

if (!function_exists('custausu_admin_render_routes_section')) {
  function custausu_admin_render_routes_section(
    array $opt,
    bool $polylang_active,
    bool $polylang_enabled,
    string $site_slug,
    string $default_lang,
    callable $T,
    callable $route_lang_has_alert,
    callable $get_field_box_class,
    callable $get_field_note_html
  ): string {
    ob_start();

    $site_slug = sanitize_key((string)$site_slug);
    if ($site_slug === '') $site_slug = 'en';

    $default_lang = sanitize_key((string)$default_lang);
    if ($default_lang === '') $default_lang = $site_slug;

    $routes_paths = (array)($opt['routes_paths'] ?? []);
    $routes_ids   = (array)($opt['routes_page_ids'] ?? []);
    $legal_links  = (array)($opt['legal_links'] ?? []);
    $logout_redirect = (array)($opt['routes_logout_redirect'] ?? []);

    unset($polylang_active, $polylang_enabled);

    $langs_ui = [$default_lang];

    echo '<table id="custausu-section-routes-templates" class="widefat striped custausu-routes-settings">';
    echo '<thead class="custausu-head"><tr><th colspan="2" class="custausu-routes-settings__head-cell"><h2 class="custausu-routes-settings__title"><span class="dashicons dashicons-randomize"></span> | '.esc_html($T('Routes & Templates','Percorsi e Template')).'</h2></th></tr></thead>';
    echo '<tbody>';

    echo '<tr><th scope="row">'.esc_html($T('Default language','Lingua predefinita')).'</th><td>';
    echo '<select class="custausu-select custausu-routes-settings__language-select" name="custausu_global_settings[routes_default_lang]">';

    foreach ($langs_ui as $slug) {
      echo '<option value="'.esc_attr($slug).'" '.selected($default_lang, $slug, false).'>'.esc_html($slug).'</option>';
    }

    echo '</select></td></tr>';

    echo '<tr><th scope="row">'.esc_html($T('After logout redirect','Redirect dopo logout')).'</th><td>';

    echo '<p class="description custausu-routes-settings__intro">'
      . esc_html($T(
        'Choose optional logout destinations. Leave fields empty to use the homepage for the detected language. Use relative paths only; external URLs are not allowed.',
        'Scegli destinazioni logout opzionali. Lascia i campi vuoti per usare la homepage della lingua rilevata. Usa solo path relativi; gli URL esterni non sono consentiti.'
      ))
      . '</p>';

    $logout_default = array_key_exists('default', $logout_redirect)
      ? (string) $logout_redirect['default']
      : '';

    echo '<div class="custausu-route-block custausu-routes-settings__compact-block">';
    echo '<div class="custausu-routes-settings__block-title">'.esc_html($T('Fallback when language is unknown','Fallback se la lingua non è rilevata')).'</div>';
    echo '<input type="text" class="regular-text" name="custausu_global_settings[routes_logout_redirect][default]" value="' . esc_attr($logout_default) . '" placeholder="">';
    echo '<p class="description custausu-routes-settings__help">'.esc_html(
      $T(
        'This is not the redirect for the default language. It is used only when CAS cannot detect the logout language. Leave empty to use the site homepage.',
        'Questo non è il redirect della lingua predefinita. Viene usato solo quando CAS non riesce a rilevare la lingua del logout. Lascia vuoto per usare la homepage del sito.'
      )
    ).'</p>';
    echo '</div>';

    echo '</td></tr>';

    $langs = [$default_lang];

    echo '<tr><td colspan="2" class="custausu-routes-settings__accordion-cell">';

    echo '<div class="custausu-acc-toolbar custausu-routes-settings__toolbar">';
    echo '<button type="button" class="button custausu-acc-expand custausu-routes-settings__expand-button">'.esc_html($T('Expand all','Espandi tutto')).'</button>';
    echo '<button type="button" class="button custausu-acc-collapse custausu-routes-settings__collapse-button">'.esc_html($T('Collapse all','Comprimi tutto')).'</button>';
    echo '</div>';

    $route_labels = [
      'login' => $T('Login page', 'Pagina login'),
      'register' => $T('Registration page', 'Pagina registrazione'),
      'lostpassword' => $T('Lost password page', 'Pagina recupero password'),
      'lostpassword_confirm' => $T('Password reset confirmation page', 'Pagina conferma reset password'),
      'landing' => $T('Landing page after Direct Login', 'Pagina di landing dopo Login Diretto'),
    ];

    $route_help = [
      'landing' => $T(
        'Optional but recommended. If a user logs in directly without first visiting a protected page, CAS sends them here. If left empty, CAS uses the site homepage. If the user originally requested a protected page, CAS will still redirect them automatically to that protected page after Registration/Login.',
        'Opzionale ma consigliata. Se un utente effettua login diretto senza aver prima visitato una pagina protetta, CAS lo invia qui. Se lasci vuoto, CAS usa la homepage del sito. Se invece l’utente aveva richiesto una pagina protetta, CAS lo reindirizzerà comunque automaticamente a quella pagina protetta dopo Registrazione/Login.'
      ),
    ];

    echo '<div class="notice notice-info inline custausu-routes-settings__setup-notice">';
    echo '<p class="custausu-routes-settings__setup-intro"><strong>'
      . esc_html($T('Important setup:','Setup importante:'))
      . '</strong> '
      . esc_html($T(
        'before configuring these routes, create the required WordPress pages and assign the correct CAS page templates to them.',
        'prima di configurare queste route, crea le pagine WordPress necessarie e assegna a ciascuna il corretto template pagina CAS.'
      ))
      . '</p>';

    echo '<ul class="custausu-routes-settings__setup-list">';
    echo '<li>' . esc_html($T('Login page → template "Account Login"', 'Pagina login → template "Account Login"')) . '</li>';
    echo '<li>' . esc_html($T('Registration page → template "Account Register"', 'Pagina registrazione → template "Account Register"')) . '</li>';
    echo '<li>' . esc_html($T('Lost password page → template "Lost Password"', 'Pagina recupero password → template "Lost Password"')) . '</li>';
    echo '<li>' . esc_html($T('Password reset confirmation page → template "Lost Password Confirm"', 'Pagina conferma reset password → template "Lost Password Confirm"')) . '</li>';
    echo '</ul>';

    echo '<p class="custausu-routes-settings__setup-footer">'
      . esc_html($T(
        'Page titles and slugs may be customized. What matters is: correct CAS template assigned, and correct page or path selected below.',
        'Titoli e slug delle pagine possono essere personalizzati. Ciò che conta è: template CAS corretto assegnato, e pagina o percorso corretto selezionato qui sotto.'
      ))
      . '</p>';
    echo '</div>';


    $custausu_norm_path_for_compare = static function($path): string {
      $path = trim((string) $path);
      if ($path === '') return '';

      $parsed = wp_parse_url($path, PHP_URL_PATH);
      if (is_string($parsed) && $parsed !== '') {
        $path = $parsed;
      }

      $path = '/' . trim($path, '/');
      return $path === '/' ? '/' : rtrim($path, '/');
    };

    $custausu_landing_matches_protected_path = static function(string $landing_path) use ($opt, $custausu_norm_path_for_compare): bool {
      $landing_path = $custausu_norm_path_for_compare($landing_path);
      if ($landing_path === '' || $landing_path === '/') {
        return false;
      }

      $raw = (string)($opt['protected_paths'] ?? '');
      if (trim($raw) === '') {
        return false;
      }

      foreach (preg_split('/\R+/', $raw) as $line) {
        $protected = $custausu_norm_path_for_compare($line);
        if ($protected === '' || $protected === '/') {
          continue;
        }

        if ($landing_path === $protected || strpos($landing_path . '/', $protected . '/') === 0) {
          return true;
        }
      }

      return false;
    };


    foreach ($langs as $lng) {
      $open_attr = ($lng === $default_lang || $route_lang_has_alert($lng)) ? 'open' : '';
      echo '<details class="custausu-acc" data-lang="' . esc_attr($lng) . '" data-route-alert="' . esc_attr($route_lang_has_alert($lng) ? '1' : '0') . '"' . ($open_attr !== '' ? ' ' . esc_attr($open_attr) : '') . '>';
      echo '<summary>'.esc_html(strtoupper($lng)).' <small>'.esc_html($T('Routes & templates','Percorsi e template')).'</small></summary>';
      echo '<div class="custausu-acc-body">';
      echo '<p class="description"><span class="custausu-routes-settings__small-note">'.esc_html($T(
        'When a WordPress page is selected, Path is optional: CAS uses that page public permalink. Use Path for a dynamic/no-ID page or as an explicit fallback.',
        'Quando è selezionata una pagina WordPress, Percorso è facoltativo: CAS usa il permalink pubblico della pagina. Usa Percorso per una pagina dinamica/senza ID oppure come fallback esplicito.'
      )).'</span></p>';

      $logout_path = array_key_exists($lng, $logout_redirect)
        ? (string) $logout_redirect[$lng]
        : '';

      echo '<div class="custausu-route-block custausu-routes-settings__logout-block">';
      echo '<div class="custausu-routes-settings__block-title">'.esc_html(sprintf($T('After logout redirect for %s','Redirect dopo logout per %s'), strtoupper($lng))).'</div>';
      echo '<p class="description custausu-routes-settings__intro">'
        . esc_html($T(
          'Leave empty to use the homepage for this detected language. Add a relative path only if this language needs a custom logout destination.',
          'Lascia vuoto per usare la homepage di questa lingua rilevata. Inserisci un path relativo solo se questa lingua richiede una destinazione logout personalizzata.'
        ))
        . '</p>';
      echo '<input type="text" class="regular-text" name="custausu_global_settings[routes_logout_redirect][' . esc_attr($lng) . ']" value="' . esc_attr($logout_path) . '" placeholder="">';
      echo '<p class="description custausu-routes-settings__help">'.esc_html(
        $T(
          'Example custom path: /your-page/. Include any language prefix exactly as it appears in the public URL.',
          'Esempio path personalizzato: /tua-pagina/. Includi qualsiasi prefisso lingua esattamente come appare nell’URL pubblico.'
        )
      ).'</p>';
      echo '</div>';

      foreach (['login','register','lostpassword','lostpassword_confirm','landing'] as $k) {
        $pid = (int)($routes_ids[$lng][$k] ?? 0);
        $pth = (string)($routes_paths[$lng][$k] ?? '');
        $route_target = 'route:' . $lng . ':' . $k;

        $is_landing_route = ($k === 'landing');
        $route_box_class = $get_field_box_class($route_target);

        if ($is_landing_route && $pid <= 0 && trim($pth) === '') {
          $route_box_class = '';
        }

        echo '<div class="custausu-route-block '.esc_attr($route_box_class).'" data-custausu-field="'.esc_attr($route_target).'">';
        echo '<div class="custausu-routes-settings__block-title">'.esc_html($route_labels[$k] ?? $k).'</div>';

        if (!empty($route_help[$k])) {
          echo '<p class="description custausu-routes-settings__intro">'.esc_html($route_help[$k]).'</p>';
        }

        if ($is_landing_route) {
          $landing_check_path = trim($pth);

          if ($landing_check_path === '' && $pid > 0) {
            $landing_url = get_permalink($pid);
            $landing_path = is_string($landing_url) ? wp_parse_url($landing_url, PHP_URL_PATH) : '';
            $landing_check_path = is_string($landing_path) ? $landing_path : '';
          }

          if ($pid <= 0 && trim($pth) === '') {
            echo '<div class="notice notice-info inline custausu-routes-settings__landing-notice">';
            echo '<p class="custausu-routes-settings__notice-text">' . esc_html($T(
              'No custom direct-login landing page configured. CAS will use the site homepage as fallback.',
              'Nessuna landing personalizzata per il login diretto configurata. CAS userà la homepage del sito come fallback.'
            )) . '</p>';
            echo '</div>';
          } elseif ($custausu_landing_matches_protected_path($landing_check_path)) {
            echo '<div class="notice inline custausu-routes-settings__landing-notice custausu-routes-settings__landing-notice--protected">';
            echo '<p class="custausu-routes-settings__notice-text"><strong>' . esc_html($T(
              'Protected landing confirmed.',
              'Landing protetta confermata.'
            )) . '</strong> ' . esc_html($T(
              'This direct-login landing destination matches, or is inside, a protected path. This is valid if you intentionally want authenticated users to land inside a protected area.',
              'Questa destinazione di landing dopo login diretto coincide con, o si trova dentro, un percorso protetto. È valido se vuoi intenzionalmente far arrivare gli utenti autenticati dentro un’area protetta.'
            )) . '</p>';
            echo '</div>';
          }
        }

        echo '<div class="custausu-routes-settings__field-group">';
        echo '<div class="custausu-routes-settings__field-label">'.esc_html($T('Page','Pagina')).'</div>';
        echo '<div class="custausu-input-row">';

        if (function_exists('custausu_admin_dropdown_pages_lang')) {
          custausu_admin_dropdown_pages_lang([
            'name' => 'custausu_global_settings[routes_page_id_' . $lng . '_' . $k . ']',
            'show_option_none'  => $T('— Select —','— Seleziona —'),
            'option_none_value' => '0',
            'selected'          => $pid,
            'class'             => 'custausu-select',
          ], $lng);
        }

        echo '</div>';
        echo '</div>';

        echo '<div>';
        echo '<div class="custausu-routes-settings__field-label">'.esc_html($T('Path','Percorso')).'</div>';
        echo '<div class="custausu-input-row">';
        echo '<input type="text" class="regular-text custausu-routes-settings__path-input" name="' . esc_attr('custausu_global_settings[routes_path_' . $lng . '_' . $k . ']') . '" value="' . esc_attr($pth) . '">';
        echo '</div>';
        echo '<p class="description custausu-routes-settings__help">'
          . esc_html($T(
            'Leave empty to use the selected page public permalink. For a fallback or dynamic route, use the exact public relative path, including any language prefix already present in the public URL.',
            'Lascia vuoto per usare il permalink pubblico della pagina selezionata. Per un fallback o una route dinamica, usa il percorso relativo pubblico esatto, includendo qualsiasi prefisso lingua già presente nell’URL pubblico.'
          ))
          . '</p>';
        echo '</div>';

        echo wp_kses( $get_field_note_html($route_target), custausu_admin_allowed_output_html() );
        echo '</div>';
      }

      /*
       * Legal links per language.
       * Placed immediately after Direct Login landing so the registration consent
       * link is configured in the same Auth routing context.
       */
      $legal_entry = isset($legal_links[$lng]['privacy_cookies']) && is_array($legal_links[$lng]['privacy_cookies'])
        ? $legal_links[$lng]['privacy_cookies']
        : [];

      $legal_page_id = absint($legal_entry['page_id'] ?? 0);
      $legal_url = isset($legal_entry['url']) && is_scalar($legal_entry['url'])
        ? (string) $legal_entry['url']
        : '';

      echo '<div class="custausu-route-block" data-custausu-field="' . esc_attr('legal_privacy_cookies_' . $lng) . '">';
      echo '<h4>' . esc_html($T(
        'Privacy, Cookies and Terms link',
        'Link Privacy, Cookies e Termini'
      )) . '</h4>';

      echo '<p class="description custausu-routes-settings__intro">' . esc_html($T(
        'Choose the page or path used by the registration consent link. If left empty, CAS falls back to the WordPress Privacy Policy page when available.',
        'Scegli la pagina o il percorso usato dal link di consenso nella registrazione. Se lasci vuoto, CAS usa come fallback la pagina Privacy Policy di WordPress quando disponibile.'
      )) . '</p>';

      echo '<div class="custausu-routes-settings__field-group">';
      echo '<label><strong>' . esc_html($T('Page', 'Pagina')) . '</strong></label><br>';

      wp_dropdown_pages([
        'name'              => esc_attr('custausu_global_settings[legal_privacy_cookies_page_id_' . $lng . ']'),
        'id'                => esc_attr('custausu-legal-privacy-cookies-page-' . $lng),
        'selected'          => absint($legal_page_id),
        'show_option_none'  => esc_html($T('— Select —', '— Seleziona —')),
        'option_none_value' => 0,
        'post_status'       => ['publish', 'draft', 'pending', 'private', 'future'],
      ]);

      echo '</div>';

      echo '<div class="custausu-routes-settings__field-group">';
      echo '<label><strong>' . esc_html($T('Path or URL', 'Percorso o URL')) . '</strong></label><br>';
      echo '<input type="text" class="regular-text custausu-routes-settings__legal-input" name="' . esc_attr('custausu_global_settings[legal_privacy_cookies_url_' . $lng . ']') . '" value="' . esc_attr($legal_url) . '" placeholder="' . esc_attr('/privacy-policy/') . '">';
      echo '<p class="description">' . esc_html($T(
        'Use a relative path such as /privacy-policy/ or a full https URL. If both page and path are set, the selected page has priority.',
        'Usa un percorso relativo come /privacy-policy/ oppure un URL https completo. Se imposti sia pagina sia percorso, la pagina selezionata ha priorità.'
      )) . '</p>';
      echo '</div>';

      echo '</div>';


      echo '</div></details>';
    }

    echo '</td></tr>';
    echo '</tbody></table>';

    return (string) ob_get_clean();
  }
}
