<?php
declare(strict_types=1);

if (!defined('ABSPATH')) { exit; }

/**
 * Register form element renderer (shared).
 *
 * Phase 1, step 13. Sibling of login.php — same unification approach:
 * adopts the editor's polished version as canonical, frontend gains
 * auto-contrast, Google sign-up, autofill CSS, and a name-row pair
 * alongside its existing nonce + honeypot security extras.
 *
 * Pre-extraction defaults that drifted (resolved to editor canonical):
 *   - field_radius: 6 (frontend) / 4 (editor) → 4
 *   - button_bg:   #1d2327 (frontend) / #1c2226 (editor) → #1c2226
 *
 * Pre-extraction shape differences resolved:
 *   - Frontend rendered name fields in a single horizontal row
 *     (first + last side by side). Editor rendered the same when
 *     show_name_fields was true. Unified.
 *   - Frontend asked for first/last + email + password (4 fields).
 *     Editor rendered the same set. Unified.
 *
 * @sideeffect Primes $GLOBALS['impulse_needs_forms'] on frontend.
 */
function impulse_element_render_register($el, array $settings, string $context): string {
    if (is_object($el)) $el = (array) $el;
    $isEditor = ($context === 'editor');
    $device   = $isEditor ? ($GLOBALS['impulse_preview_device'] ?? 'desktop') : 'desktop';
    $elId     = preg_replace('/[^A-Za-z0-9_-]/', '', (string) ($el['id'] ?? '0'));

    $read = function (string $key, $default) use ($settings, $isEditor, $device) {
        if ($isEditor && function_exists('impulse_device_val')) {
            return impulse_device_val($settings, $key, $device, $default);
        }
        return $settings[$key] ?? $default;
    };

    $fieldGap         = intval($read('field_gap',    16));
    $fieldRadius      = intval($read('field_radius',  4));
    $sectionMaxWidth  = intval($settings['section_max_width']   ?? 400);
    $fieldBg          = (string) ($settings['field_bg']           ?? '#f5f5f5');
    $fieldBorderColor = (string) ($settings['field_border_color'] ?? '#e0e0e0');
    $fieldBorderWidth = intval($settings['field_border_width']    ?? 1);
    $buttonBg         = (string) ($settings['button_bg']          ?? '#1c2226');
    $buttonColor      = (string) ($settings['button_color']       ?? '#ffffff');
    $buttonText       = (string) ($settings['button_text']        ?? 'Create Account');
    $showNameFields   = ($settings['show_name_fields'] ?? true) !== false;
    $requireName      = !empty($settings['require_name']);
    $showGoogleBtn    = ($settings['show_google']      ?? true) !== false;
    $redirectUrl      = (string) ($settings['redirect_url']       ?? '');

    if (!$isEditor) $GLOBALS['impulse_needs_forms'] = true;

    $parentBg = (string) ($GLOBALS['impulse_parent_bg'] ?? ($GLOBALS['impulse_current_section_bg'] ?? ($GLOBALS['impulse_page_bg_color'] ?? '#ffffff')));
    $autoText = function_exists('impulse_contrast_color') ? impulse_contrast_color($parentBg) : '#1d2327';
    $isLight  = ($autoText === '#111827' || $autoText === '#1d2327');
    $autoMid     = $isLight ? '#888'    : 'rgba(255,255,255,0.5)';
    $autoDivider = $isLight ? '#e0e0e0' : 'rgba(255,255,255,0.15)';
    $fieldText  = function_exists('impulse_contrast_color') ? impulse_contrast_color($fieldBg) : '#111827';
    $fieldIsLight = ($fieldText === '#111827' || $fieldText === '#1d2327');
    $fieldPlaceholder = $fieldIsLight ? '#86868b' : 'rgba(255,255,255,0.45)';

    $inputStyle = 'width:100%;padding:12px 16px;background:' . esc_attr($fieldBg) . ';border:' . $fieldBorderWidth . 'px solid ' . esc_attr($fieldBorderColor) . ';border-radius:' . $fieldRadius . 'px;font-size:14px;color:' . esc_attr($fieldText) . ';outline:none;box-sizing:border-box;transition:border-color 0.15s';

    // v2.1.1401: optional Label colour override (placeholder text).
    $fieldLabelColor = trim((string) ($settings['field_label_color'] ?? ''));

    if (function_exists('wp_add_inline_style')) {
        $css = '.impulse-register-form input::placeholder{color:' . $fieldPlaceholder . ';opacity:1}'
             . '.impulse-register-form input:focus{border-color:#888!important;outline:none!important;box-shadow:none!important}'
             . '.impulse-register-form input:-webkit-autofill,.impulse-register-form input:-webkit-autofill:hover,.impulse-register-form input:-webkit-autofill:focus{-webkit-box-shadow:0 0 0 1000px ' . esc_attr($fieldBg) . ' inset!important;-webkit-text-fill-color:' . esc_attr($fieldText) . '!important}';
        if ($fieldLabelColor !== '' && $elId) {
            $_sel = '.impulse-el[data-id="' . intval($elId) . '"]';
            $css .= $_sel . ' .impulse-register-form input::placeholder{color:' . esc_attr($fieldLabelColor) . '!important;opacity:1!important}';
        }
        wp_add_inline_style('instinctor-page-inline', $css);
    }

    $wrapStyle = 'display:flex;justify-content:center;width:100%;margin:0 auto'
               . ($sectionMaxWidth > 0 ? ';max-width:' . $sectionMaxWidth . 'px' : '');

    ob_start();
    echo '<div style="' . esc_attr($wrapStyle) . '">';
    echo '<div class="impulse-register-wrapper" style="width:100%;color:' . esc_attr($autoText) . '">';

    // Google sign-up removed 2026-07-05 — see login.php (Platform-mediated,
    // non-functional off-Platform, and carried the prohibited auto-login).

    echo '<form class="impulse-register-form" autocomplete="off" style="display:flex;flex-direction:column;gap:' . (int) $fieldGap . 'px" data-redirect="' . esc_attr($redirectUrl) . '">';

    if (!$isEditor) {
        if (function_exists('wp_nonce_field')) wp_nonce_field('instinctor_frontend', 'nonce', true, true);
        if (class_exists('\\Instinctor\\Core\\Security')) {
            $_hpInput = ['type' => true, 'name' => true, 'value' => true, 'tabindex' => true, 'autocomplete' => true];
            echo wp_kses(\Instinctor\Core\Security::honeypotField(), [
                'div'   => ['style' => true, 'aria-hidden' => true],
                'input' => $_hpInput,
            ]);
        }
    }

    if ($showNameFields) {
        $reqAttr  = $requireName ? ' required' : '';
        $reqStar  = $requireName ? ' *' : '';
        echo '<div style="display:flex;gap:' . (int) $fieldGap . 'px">';
        echo '<input type="text" name="first_name" placeholder="First Name' . esc_attr($reqStar) . '" autocomplete="one-time-code" tabindex="-1" style="' . esc_attr($inputStyle) . '"' . esc_attr($reqAttr) . '>';
        echo '<input type="text" name="last_name" placeholder="Last Name'  . esc_attr($reqStar) . '" autocomplete="one-time-code" tabindex="-1" style="' . esc_attr($inputStyle) . '"' . esc_attr($reqAttr) . '>';
        echo '</div>';
    }

    echo '<div style="display:flex;gap:' . (int) $fieldGap . 'px">';
    echo '<input type="email" name="email" placeholder="Email Address *" autocomplete="one-time-code" tabindex="-1" style="' . esc_attr($inputStyle) . '" required>';
    echo '<input type="password" name="password" placeholder="Password *" autocomplete="new-password" tabindex="-1" style="' . esc_attr($inputStyle) . '" required minlength="8">';
    echo '</div>';

    echo '<button type="submit" class="impulse-form-submit" style="background:' . esc_attr($buttonBg) . ';color:' . esc_attr($buttonColor) . ';padding:14px 28px;border:none;border-radius:' . (int) $fieldRadius . 'px;font-size:15px;font-weight:600;cursor:pointer">' . esc_html($buttonText) . '</button>';
    echo '<div class="impulse-form-message" style="display:none;padding:12px;border-radius:6px;font-size:14px;text-align:center"></div>';
    echo '</form>';
    echo '</div></div>';

    return ob_get_clean();
}
