<?php
declare(strict_types=1);

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

/**
 * Checkout element renderer (shared).
 *
 * Phase 1, step 36. Frontend dispatches `[instinctor_checkout]` (the real
 * checkout UI lives in CheckoutController). Editor renders an inert static
 * preview: the configured fields laid out in the same grid the live page
 * would show, with placeholder input boxes the designer can style but not
 * type into.
 *
 * Both branches kept distinct because they serve different roles:
 *   - frontend: real form, hooked to payment gateway via REST
 *   - editor:   visual preview, no submission
 *
 * Branches on `$context`. Frontend output identical to the previous
 * inline shortcode dispatch (no behaviour change).
 */
function impulse_element_render_checkout($el, array $settings, string $context): string {
    if (is_object($el)) $el = (array) $el;
    $isEditor = ($context === 'editor');

    if (!$isEditor) {
        ob_start();
        $GLOBALS['impulse_checkout_settings'] = $settings;
        if (function_exists('do_shortcode')) {
            echo do_shortcode('[instinctor_checkout]');
        }
        unset($GLOBALS['impulse_checkout_settings']);
        return (string) ob_get_clean();
    }

    // ── Editor preview ───────────────────────────────────────────────────
    $device       = (string) ($GLOBALS['impulse_preview_device'] ?? 'desktop');
    $isScreenMode = true; // every page is a screen sequence
    $buttonBg     = (string) ($settings['checkout_design_button']       ?? '#1d2327');
    $buttonText   = (string) ($settings['checkout_design_button_text']  ?? '#ffffff');
    $formBg       = (string) ($settings['checkout_design_form_bg']      ?? 'transparent');

    // Auto-contrast: derive text color from effective bg.
    $effectiveBg = ($formBg !== 'transparent' && $formBg !== '')
        ? $formBg
        : (string) ($GLOBALS['impulse_parent_bg'] ?? ($GLOBALS['impulse_page_bg_color'] ?? '#ffffff'));
    $textColor      = function_exists('impulse_contrast_color') ? impulse_contrast_color($effectiveBg) : '#111827';
    $fieldBg        = (string) ($settings['checkout_design_field_bg'] ?? ($isScreenMode ? 'rgba(255,255,255,0.7)' : 'rgba(0,0,0,0.05)'));
    $fieldAutoText  = (strpos($fieldBg, 'rgba') !== false)
        ? $textColor
        : (function_exists('impulse_contrast_color') ? impulse_contrast_color($fieldBg) : '#111827');
    $fieldBorder    = (string) ($settings['checkout_design_field_border'] ?? '#d2d2d7');
    $fieldBorderWidth = function_exists('impulse_device_val')
        ? intval(impulse_device_val($settings, 'checkout_design_field_border_width', $device, 1))
        : 1;
    $fieldRadius      = function_exists('impulse_device_val')
        ? intval(impulse_device_val($settings, 'checkout_design_field_radius', $device, 4))
        : 4;
    $buttonRadius     = function_exists('impulse_device_val')
        ? intval(impulse_device_val($settings, 'checkout_design_button_radius', $device, 4))
        : 4;
    if ($isScreenMode) $fieldBorderWidth = 0; // screen mode never shows form borders

    // Fields config — JSON string or default field set.
    $fields = [];
    $fieldsJson = $settings['checkout_design_fields'] ?? '';
    if (is_string($fieldsJson) && $fieldsJson !== '') {
        $decoded = json_decode($fieldsJson, true);
        if (is_array($decoded)) $fields = $decoded;
    }
    if (empty($fields)) {
        $fields = [
            ['id' => 'email',      'label' => 'Email',      'enabled' => true, 'required' => true,  'width' => 'half'],
            ['id' => 'phone',      'label' => 'Phone',      'enabled' => true, 'required' => false, 'width' => 'half'],
            ['id' => 'first_name', 'label' => 'First Name', 'enabled' => true, 'required' => true,  'width' => 'half'],
            ['id' => 'last_name',  'label' => 'Last Name',  'enabled' => true, 'required' => true,  'width' => 'half'],
            ['id' => 'address_1',  'label' => 'Address',    'enabled' => true, 'required' => true,  'width' => 'full'],
            ['id' => 'city',       'label' => 'City',       'enabled' => true, 'required' => true,  'width' => 'half'],
            ['id' => 'state',      'label' => 'State',      'enabled' => true, 'required' => true,  'width' => 'half'],
            ['id' => 'postcode',   'label' => 'ZIP Code',   'enabled' => true, 'required' => true,  'width' => 'half'],
            ['id' => 'country',    'label' => 'Country',    'enabled' => true, 'required' => true,  'width' => 'half'],
        ];
    }

    $sectionMaxWidth = intval($settings['section_max_width'] ?? 400);
    $sectionStyle    = 'font-size:12px;font-weight:600;margin:0 0 10px;text-transform:uppercase;letter-spacing:0.5px;opacity:0.6;';
    $inputBaseStyle  = 'width:100%;box-sizing:border-box;background-color:' . esc_attr($fieldBg) . ';'
                     . 'border-width:' . $fieldBorderWidth . 'px;border-style:solid;border-color:' . esc_attr($fieldBorder) . ';'
                     . 'border-radius:' . $fieldRadius . 'px;'
                     . 'padding:10px 12px;font-size:13px;color:' . esc_attr($fieldAutoText) . ';outline:none;font-family:inherit;';

    $renderFieldGroup = function (array $fieldsArr) use ($inputBaseStyle): string {
        $html = '<div class="impulse-checkout-fields-grid" style="display:grid;grid-template-columns:1fr 1fr;gap:8px">';
        foreach (array_values($fieldsArr) as $f) {
            $width        = (string) ($f['width']        ?? 'full');
            $widthTablet  = (string) ($f['width_tablet'] ?? $width);
            $widthMobile  = (string) ($f['width_mobile'] ?? 'full');
            $classes  = 'impulse-checkout-field impulse-field-' . $width;
            $classes .= ' impulse-field-tablet-' . $widthTablet;
            $classes .= ' impulse-field-mobile-' . $widthMobile;
            $placeholder = esc_attr((string) ($f['label'] ?? '') . (!empty($f['required']) ? ' *' : ''));
            $html .= '<div class="' . $classes . '">';
            $html .= '<input type="text" placeholder="' . $placeholder . '" style="' . esc_attr($inputBaseStyle) . '" tabindex="-1" autocomplete="off">';
            $html .= '</div>';
        }
        $html .= '</div>';
        return $html;
    };

    ob_start();
    echo '<div class="impulse-checkout-block" style="width:100%;margin:0 auto;';
    if ($sectionMaxWidth > 0) echo 'max-width:' . esc_attr((string) $sectionMaxWidth) . 'px;';
    echo 'background-color:' . esc_attr($formBg) . ';';
    echo 'color:' . esc_attr($textColor) . ';';
    echo 'padding:24px">';

    $enabledFields = array_filter($fields, static fn ($f) => !empty($f['enabled']));
    if (!empty($enabledFields)) {
        // $renderFieldGroup() returns a grid of preview <input> controls with
        // per-field values already esc_attr()'d internally; input/div aren't
        // SVG-allowlist tags, so run it through a bespoke form-control allowlist.
        echo '<div style="margin-bottom:16px"><div style="' . esc_attr($sectionStyle) . '">Shipping Address</div>' . wp_kses($renderFieldGroup($enabledFields), [
            'div'   => ['class' => true, 'style' => true],
            'input' => ['type' => true, 'placeholder' => true, 'style' => true, 'tabindex' => true, 'autocomplete' => true],
        ]) . '</div>';
    }

    // Payment — inert preview fields. Real Stripe Element gets injected here on the live frontend.
    $cardStyle = $inputBaseStyle . 'opacity:0.55;';
    echo '<div style="margin-bottom:16px"><div style="' . esc_attr($sectionStyle) . '">Payment</div>';
    echo '<div style="display:grid;grid-template-columns:1fr 1fr;gap:8px">';
    echo '<input type="text" placeholder="Card number" style="' . esc_attr($cardStyle) . '" tabindex="-1" autocomplete="off">';
    echo '<div style="display:grid;grid-template-columns:1fr 1fr;gap:8px">';
    echo '<input type="text" placeholder="Expiry" style="' . esc_attr($cardStyle) . '" tabindex="-1" autocomplete="off">';
    echo '<input type="text" placeholder="CVC"    style="' . esc_attr($cardStyle) . '" tabindex="-1" autocomplete="off">';
    echo '</div></div></div>';

    // Pay button
    $checkoutBtnText = (string) ($settings['checkout_button_text'] ?? 'Pay now');
    echo '<button class="impulse-checkout-btn" style="width:100%;padding:12px 20px;margin-top:12px;'
       . 'background-color:' . esc_attr($buttonBg) . ';'
       . 'color:' . esc_attr($buttonText) . ';'
       . 'border:none;'
       . 'border-radius:' . esc_attr((string) $buttonRadius) . 'px;'
       . 'font-weight:600;font-size:14px;cursor:pointer">' . esc_html($checkoutBtnText) . '</button>';

    echo '</div>';

    return (string) ob_get_clean();
}
