<?php

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

class AIEO_DMM_Newsletter_Signup extends AIEO_DMM_Module_Base {

    const OPTION_KEY = 'aieo_newsletter_signup_settings';
    const BLOCK_NAME = 'aieo/newsletter-signup';
    const SUB_NONCE  = 'aieo_nl_sub';

    public function get_id()       { return 'newsletter_signup'; }
    public function get_label()    { return __('Newsletter Signup', 'ai-eshop-optimizer'); }
    public function get_priority() { return 35; }
    public function get_group()    { return 'visuals'; } 

    public function register_hooks() {
        add_action('init', array($this, 'register_block'));
        add_action('enqueue_block_editor_assets', array($this, 'enqueue_block_editor_assets'));
        add_shortcode('aieo_newsletter_signup', array($this, 'shortcode'));
        add_action('wp_ajax_aieo_newsletter_signup_save', array($this, 'ajax_save'));
        
        add_action('wp_ajax_aieo_newsletter_subscribe',        array($this, 'ajax_subscribe'));
        add_action('wp_ajax_nopriv_aieo_newsletter_subscribe', array($this, 'ajax_subscribe'));
        
        
        add_action('wp_enqueue_scripts', array($this, 'dequeue_tnp_assets'), 100);
    }

    
    public function dequeue_tnp_assets() {
        if (is_admin()) { return; }
        if (isset($_GET['na']) && $_GET['na'] !== '') { return; } 
        if (!apply_filters('aieo_newsletter_dequeue_tnp_assets', true)) { return; }
        foreach (array('newsletter', 'newsletter-subscription') as $h) {
            wp_dequeue_style($h);
            wp_dequeue_script($h);
        }
    }

    public function enqueue_admin_assets() {
        if (function_exists('wp_enqueue_media')) { wp_enqueue_media(); }
        
        if (class_exists('AIEO_Admin_Color')) { AIEO_Admin_Color::enqueue(); }
    }

    
    
    

    public static function defaults() {
        return array(
            'enabled'            => true,
            'heading'            => __('Εγγραφείτε στο newsletter μας', 'ai-eshop-optimizer'),
            'intro'              => __('Λάβετε πρώτοι τις προσφορές και τα νέα μας.', 'ai-eshop-optimizer'),
            'button_text'        => __('Εγγραφή', 'ai-eshop-optimizer'),
            'placeholder'        => __('Διεύθυνση Ηλ. Ταχυδρομίου', 'ai-eshop-optimizer'),
            'name_placeholder'      => __('Όνομα', 'ai-eshop-optimizer'),
            'last_name_placeholder' => __('Επώνυμο', 'ai-eshop-optimizer'),
            'collect_name'       => true,   
            'success_msg'        => __('Ευχαριστούμε! Η εγγραφή σας ολοκληρώθηκε.', 'ai-eshop-optimizer'),
            
            'privacy_enabled'    => true,
            'privacy_text'       => __('Αποδέχομαι την πολιτική απορρήτου', 'ai-eshop-optimizer'),
            
            
            
            'privacy_link_text'  => __('πολιτική απορρήτου', 'ai-eshop-optimizer'),
            'privacy_url'        => '',     
            'logo_id'            => 0,
            'logo_url'           => '',
            'bg_desktop_color'   => '#111111',
            'bg_desktop_image_id'=> 0,
            'bg_desktop_url'     => '',
            'bg_mobile_color'    => '#111111',
            'bg_mobile_image_id' => 0,
            'bg_mobile_url'      => '',
            'glass_mobile'       => true,   
            'glass_desktop'      => false,  
            'text_color'         => '#1a1a1a',
            'accent_color'       => '#F46767',
            'provider_mode'      => 'newsletter', 
            'gravity_form_id'    => 0,
            'sso_enabled'        => true,
        );
    }

    public function settings() {
        $s = get_option(self::OPTION_KEY, array());
        return array_merge(self::defaults(), is_array($s) ? $s : array());
    }

    private function vcolor($v, $def) {
        $v = trim((string) $v);
        if ($v === '') { return $def; }
        if (class_exists('AIEO_Admin_Color')) { $c = AIEO_Admin_Color::sanitize($v); return $c !== '' ? $c : $def; }
        $c = sanitize_hex_color($v); return $c ? $c : $def;
    }

    public function ajax_save() {
        AIEO_DMM::verify_ajax_request();
        $d = $this->settings();
        $d['enabled']         = !empty($_POST['enabled']);
        $d['collect_name']    = !empty($_POST['collect_name']);
        $d['glass_mobile']    = !empty($_POST['glass_mobile']);
        $d['glass_desktop']   = !empty($_POST['glass_desktop']);
        $d['privacy_enabled'] = !empty($_POST['privacy_enabled']);
        $d['sso_enabled']     = !empty($_POST['sso_enabled']);
        foreach (array('heading','intro','button_text','placeholder','name_placeholder','last_name_placeholder','success_msg','privacy_text','privacy_link_text') as $k) {
            if (isset($_POST[$k])) { $d[$k] = sanitize_text_field(wp_unslash((string) $_POST[$k])); }
        }
        $d['privacy_url'] = isset($_POST['privacy_url']) ? esc_url_raw(wp_unslash((string) $_POST['privacy_url'])) : $d['privacy_url'];
        foreach (array('logo_id','bg_desktop_image_id','bg_mobile_image_id','gravity_form_id') as $k) {
            $d[$k] = isset($_POST[$k]) ? max(0, (int) $_POST[$k]) : $d[$k];
        }
        $d['bg_desktop_color'] = $this->vcolor($_POST['bg_desktop_color'] ?? '', $d['bg_desktop_color']);
        $d['bg_mobile_color']  = $this->vcolor($_POST['bg_mobile_color']  ?? '', $d['bg_mobile_color']);
        $d['text_color']       = $this->vcolor($_POST['text_color']       ?? '', $d['text_color']);
        $d['accent_color']     = $this->vcolor($_POST['accent_color']     ?? '', $d['accent_color']);
        $mode = sanitize_key(wp_unslash((string) ($_POST['provider_mode'] ?? 'newsletter')));
        $d['provider_mode'] = in_array($mode, array('newsletter','gravity','none'), true) ? $mode : 'newsletter';
        update_option(self::OPTION_KEY, $d, false);
        wp_send_json_success(array('message' => __('Saved.', 'ai-eshop-optimizer')));
    }

    public function ajax_subscribe() {
        if (!check_ajax_referer(self::SUB_NONCE, 'nonce', false)) {
            wp_send_json_error(array('message' => __('Security check failed. Reload and try again.', 'ai-eshop-optimizer')));
        }
        $email = isset($_POST['email']) ? sanitize_email(wp_unslash((string) $_POST['email'])) : '';
        if ($email === '' || !is_email($email)) {
            wp_send_json_error(array('message' => __('Please enter a valid email.', 'ai-eshop-optimizer')));
        }
        $name = isset($_POST['name'])      ? sanitize_text_field(wp_unslash((string) $_POST['name']))      : '';
        $last = isset($_POST['last_name']) ? sanitize_text_field(wp_unslash((string) $_POST['last_name'])) : '';
        $s = $this->settings();

        
        if (!empty($s['privacy_enabled']) && empty($_POST['privacy'])) {
            wp_send_json_error(array('message' => __('Please accept the privacy policy to continue.', 'ai-eshop-optimizer')));
        }

        $synced = false;
        if ($s['provider_mode'] === 'newsletter' && class_exists('AIEO_Newsletter_Registry')) {
            $adapter = (new AIEO_Newsletter_Registry())->adapter();
            if ($adapter) {
                $res = $adapter->sync_contacts(array(array('email' => $email, 'first_name' => $name, 'last_name' => $last)), 'newsletter');
                $synced = is_array($res) && !empty($res['ok']);
            }
        }
        
        do_action('aieo_newsletter_subscribe', $email, $name, $synced, $last);

        wp_send_json_success(array('message' => (string) $s['success_msg']));
    }

    
    
    

    public function register_block() {
        if (!function_exists('register_block_type')) { return; }
        
        
        
        $handle = 'aieo-newsletter-signup-editor';
        $rel    = 'assets/js/aieo-newsletter-signup-editor.js';
        $path   = defined('AIEO_DIR') ? AIEO_DIR . $rel : '';
        if ($path && file_exists($path)) {
            wp_register_script(
                $handle,
                plugins_url($rel, defined('AIEO_FILE') ? AIEO_FILE : __FILE__),
                array('wp-blocks', 'wp-block-editor', 'wp-components', 'wp-element', 'wp-i18n'),
                filemtime($path),
                true
            );
            
            wp_localize_script($handle, 'aieoNewsletterCfg', array(
                'defaults'         => self::defaults(),
                'gravityAvailable' => function_exists('shortcode_exists') && shortcode_exists('gravityform'),
            ));
        }
        
        
        $attrs = array('align' => array('type' => 'string'));
        foreach (self::defaults() as $k => $v) {
            if ($k === 'enabled') { continue; }
            $type = is_bool($v) ? 'boolean' : (is_int($v) ? 'number' : 'string');
            $attrs[$k] = array('type' => $type, 'default' => $v);
        }
        register_block_type(self::BLOCK_NAME, array(
            'api_version'     => 3,
            'title'           => __('AIEO Newsletter Signup', 'ai-eshop-optimizer'),
            'category'        => 'theme',
            'icon'            => 'email',
            'description'     => __('Theme-independent newsletter signup banner — fully configurable in the block.', 'ai-eshop-optimizer'),
            'keywords'        => array('newsletter', 'signup', 'email', 'subscribe', 'aieo'),
            'supports'        => array(
                'align'      => array('wide', 'full'),
                'spacing'    => array('margin' => true, 'padding' => true),
                'typography' => array('fontSize' => true, 'lineHeight' => true),
                'color'      => array('background' => true, 'text' => true),
            ),
            'attributes'      => $attrs,
            'editor_script'   => $handle,
            'render_callback' => array($this, 'render_block'),
        ));
    }

    
    public function enqueue_block_editor_assets() {
        $h = 'aieo-newsletter-signup-editor';
        if (wp_script_is($h, 'registered')) { wp_enqueue_script($h); }
    }

    public function render_block($attrs = array(), $content = '', $block = null) {
        
        
        
        $s = self::defaults();
        foreach ((array) $attrs as $k => $v) {
            if ($k === 'align' || $v === null) { continue; }
            if (array_key_exists($k, $s)) { $s[$k] = $v; }
        }
        
        
        
        
        
        $global  = $this->settings();
        $img_map = array('logo_id' => 'logo_url', 'bg_desktop_image_id' => 'bg_desktop_url', 'bg_mobile_image_id' => 'bg_mobile_url');
        foreach ($img_map as $id_key => $url_key) {
            if (empty($s[$id_key]) && empty($s[$url_key]) && !empty($global[$id_key])) {
                $s[$id_key] = $global[$id_key];
            }
        }
        $s['enabled'] = true; 
        $align = isset($attrs['align']) ? sanitize_html_class((string) $attrs['align']) : '';
        
        
        
        
        if (function_exists('get_block_wrapper_attributes') && $block instanceof WP_Block) {
            return '<div ' . get_block_wrapper_attributes() . '>' . $this->render_banner($s, '') . '</div>';
        }
        return $this->render_banner($s, $align);
    }

    
    public function shortcode($atts = array()) { return $this->render_banner($this->settings(), ''); }

    
    private function privacy_label_html($text, $link_text, $url) {
        $text = (string) $text;
        if ($url === '') {
            return esc_html($text);
        }
        $open  = sprintf('<a href="%s" target="_blank" rel="noopener">', esc_url($url));
        $close = '</a>';
        $link_text = trim((string) $link_text);
        if ($link_text !== '') {
            $pos = function_exists('mb_strpos') ? mb_strpos($text, $link_text) : strpos($text, $link_text);
            if ($pos !== false) {
                $len    = function_exists('mb_strlen') ? mb_strlen($link_text) : strlen($link_text);
                $before = function_exists('mb_substr') ? mb_substr($text, 0, $pos)        : substr($text, 0, $pos);
                $after  = function_exists('mb_substr') ? mb_substr($text, $pos + $len)    : substr($text, $pos + $len);
                return esc_html($before) . $open . esc_html($link_text) . $close . esc_html($after);
            }
        }
        return $open . esc_html($text) . $close;
    }

    
    public function render_banner($s = null, $align = '') {
        if (!is_array($s)) { $s = $this->settings(); }
        if (empty($s['enabled'])) { return ''; }

        static $uid = 0; $uid++;
        $id = 'aieo-nl-' . $uid;
        
        
        $align_cls  = ($align === 'full') ? ' alignfull' : (($align === 'wide') ? ' alignwide' : '');
        if (!empty($s['glass_desktop'])) { $align_cls .= ' aieo-nl--glass-desktop'; }
        if (empty($s['glass_mobile']))   { $align_cls .= ' aieo-nl--no-glass-mobile'; }

        
        
        $bg_d = !empty($s['bg_desktop_url']) ? $s['bg_desktop_url'] : (!empty($s['bg_desktop_image_id']) ? wp_get_attachment_image_url((int) $s['bg_desktop_image_id'], 'full')  : '');
        $bg_m = !empty($s['bg_mobile_url'])  ? $s['bg_mobile_url']  : (!empty($s['bg_mobile_image_id'])  ? wp_get_attachment_image_url((int) $s['bg_mobile_image_id'],  'large') : '');
        if ($bg_m === '' && $bg_d !== '') { $bg_m = $bg_d; }
        $logo = !empty($s['logo_url']) ? $s['logo_url'] : (!empty($s['logo_id']) ? wp_get_attachment_image_url((int) $s['logo_id'], 'medium') : '');

        $nonce        = wp_create_nonce(self::SUB_NONCE);
        $ajax         = admin_url('admin-ajax.php');
        $collect_name = !empty($s['collect_name']);
        $privacy_on   = !empty($s['privacy_enabled']);
        $privacy_url  = !empty($s['privacy_url']) ? $s['privacy_url'] : (function_exists('get_privacy_policy_url') ? get_privacy_policy_url() : '');

        ob_start();
        $this->emit_css_once();
        
        
        
        echo '<style>';
        printf('#%1$s{--aieo-nl-accent:%2$s;--aieo-nl-text:%3$s;background-color:%4$s;}',
            esc_attr($id), esc_attr($s['accent_color']), esc_attr($s['text_color']), esc_attr($s['bg_desktop_color']));
        if ($bg_m !== '') { printf('#%1$s{--aieo-nl-bg-m:url(%2$s);}', esc_attr($id), esc_url($bg_m)); }
        if ($bg_d !== '') { printf('#%1$s{--aieo-nl-bg-d:url(%2$s);}', esc_attr($id), esc_url($bg_d)); }
        echo '</style>';
        ?>
        <section id="<?php echo esc_attr($id); ?>" class="aieo-nl<?php echo esc_attr($align_cls); ?>">
            <div class="aieo-nl__content">
                <?php if ($logo !== '') : ?>
                    <div class="aieo-nl__logo"><img src="<?php echo esc_url($logo); ?>" alt="" loading="lazy" decoding="async"></div>
                <?php endif; ?>

                <div class="aieo-nl__intro">
                    <?php if (trim((string) $s['heading']) !== '') : ?>
                        <h2 class="aieo-nl__title"><?php echo esc_html($s['heading']); ?></h2>
                    <?php endif; ?>
                    <?php if (trim((string) $s['intro']) !== '') : ?>
                        <p class="aieo-nl__desc"><?php echo esc_html($s['intro']); ?></p>
                    <?php endif; ?>
                </div>

                <?php if ($s['provider_mode'] === 'gravity' && (int) $s['gravity_form_id'] > 0 && shortcode_exists('gravityform')) : ?>
                    <div class="aieo-nl__form aieo-nl__form--gf"><?php echo do_shortcode('[gravityform id="' . (int) $s['gravity_form_id'] . '" title="false" description="false" ajax="true"]'); ?></div>
                <?php else : ?>
                    <form class="aieo-nl__form" data-aieo-nl data-nonce="<?php echo esc_attr($nonce); ?>" data-ajax="<?php echo esc_url($ajax); ?>">
                        <?php if ($collect_name) : ?>
                            <div class="aieo-nl__field">
                                <label><?php echo esc_html($s['name_placeholder']); ?></label>
                                <input type="text" name="name" placeholder="<?php echo esc_attr($s['name_placeholder']); ?>" autocomplete="given-name">
                            </div>
                            <div class="aieo-nl__field">
                                <label><?php echo esc_html($s['last_name_placeholder']); ?></label>
                                <input type="text" name="last_name" placeholder="<?php echo esc_attr($s['last_name_placeholder']); ?>" autocomplete="family-name">
                            </div>
                        <?php endif; ?>
                        <div class="aieo-nl__field">
                            <label><?php echo esc_html($s['placeholder']); ?></label>
                            <input type="email" name="email" placeholder="<?php echo esc_attr($s['placeholder']); ?>" required autocomplete="email">
                        </div>
                        <?php if ($privacy_on) : ?>
                            <label class="aieo-nl__privacy">
                                <input type="checkbox" name="privacy" value="1" required>
                                <span class="aieo-nl__privacy-text"><?php
                                    
                                    
                                    echo $this->privacy_label_html($s['privacy_text'], isset($s['privacy_link_text']) ? $s['privacy_link_text'] : '', $privacy_url); 
                                ?></span>
                            </label>
                        <?php endif; ?>
                        <button type="submit" class="aieo-nl__btn"><?php echo esc_html($s['button_text']); ?></button>
                        <div class="aieo-nl__msg" role="status" aria-live="polite"></div>
                    </form>
                <?php endif; ?>

                <?php
                if (!empty($s['sso_enabled'])) {
                    
                    
                    
                    if (!class_exists('AIEO_SSO_Buttons') && defined('AIEO_DIR')) {
                        
                        
                        
                        
                        
                        if (!class_exists('AIEO_SSO_Buttons_Data')) {
                            $p = AIEO_DIR . 'includes/social-login/class-aieo-sso-buttons-data.php';
                            if (is_readable($p)) { require_once $p; }
                        }
                        if (!class_exists('AIEO_SSO_Buttons')) {
                            $p = AIEO_DIR . 'includes/social-login/class-aieo-sso-buttons.php';
                            if (is_readable($p)) { require_once $p; }
                        }
                    }
                    if (class_exists('AIEO_SSO_Buttons')) {
                        $sso_html = AIEO_SSO_Buttons::render('subscribe', array(
                            'layout' => 'stack',
                            'intro'  => __('ή εγγραφείτε μέσω:', 'ai-eshop-optimizer'),
                        ));
                        
                        
                        if (trim((string) $sso_html) !== '') {
                            echo '<div class="aieo-nl__sso">' . $sso_html . '</div>'; 
                        }
                    }
                }
                ?>
            </div>
        </section>
        <?php
        return (string) ob_get_clean();
    }

    
    private function emit_css_once() {
        static $done = false;
        if ($done) { return; }
        $done = true;
        ?>
        <style id="aieo-nl-css">
        /* Newsletter banner — self-contained replica of the FF specimen.
         * Mobile: full-bleed bg image + a frosted-glass content card.
         * Desktop (>=782px): wide banner, content reflows to a 3-column grid
         * (intro | form | SSO) with the logo spanning the top row. */
        .aieo-nl{position:relative;width:100%;box-sizing:border-box;display:flex;align-items:center;justify-content:center;flex-direction:column;padding:20px 0;min-height:70vh;margin-bottom:30px;overflow:hidden;background-color:#111;background-image:var(--aieo-nl-bg-m,none);background-position:center;background-size:cover;background-repeat:no-repeat;color:var(--aieo-nl-text,#1a1a1a)}
        .aieo-nl.alignfull{margin-left:calc(50% - 50vw);margin-right:calc(50% - 50vw);max-width:100vw}
        .aieo-nl__content{position:relative;width:90%;max-width:400px;box-sizing:border-box;text-align:center;padding:30px 15px;border-radius:4px;background:rgba(255,255,255,.4);-webkit-backdrop-filter:blur(5px);backdrop-filter:blur(5px)}
        .aieo-nl--no-glass-mobile .aieo-nl__content{background:transparent;-webkit-backdrop-filter:none;backdrop-filter:none}
        .aieo-nl__logo{text-align:center;margin-bottom:12px}
        .aieo-nl__logo img{display:block;max-width:70%;height:auto;margin:0 auto}
        .aieo-nl__intro{margin:0 0 14px}
        .aieo-nl__title{margin:0 0 8px;font-size:1.5rem;line-height:1.2;font-weight:700;color:inherit}
        .aieo-nl__desc{margin:0;font-size:14px;line-height:1.5;opacity:.9;color:inherit}
        .aieo-nl__form{display:flex;flex-direction:column;gap:10px;margin:14px 0 0;text-align:left}
        .aieo-nl__form--gf{display:block}
        .aieo-nl__field{margin:0}
        .aieo-nl__form label{display:block;font-size:11px;line-height:1.2;margin:0 0 2px;text-transform:uppercase;letter-spacing:.03em;opacity:.75;color:inherit}
        .aieo-nl__form input[type=text],.aieo-nl__form input[type=email]{width:100%;box-sizing:border-box;padding:10px 12px;border:1px solid rgba(0,0,0,.15);background:#fff;color:#111;font-size:14px;border-radius:0}
        /* Clean two-column row: [checkbox] [text], both vertically centred.
           flex-direction:row + nowrap is forced so nothing can stack them.
           The checkbox is enlarged with transform:scale (scales the actual
           native control and keeps it centred on its box) — a plain width/height
           left the native control top-aligned in its box, making the text look
           bottom-aligned. */
        .aieo-nl__privacy{display:flex;flex-direction:row;flex-wrap:nowrap;align-items:center;gap:9px;text-align:left;font-size:12px;line-height:1.3;color:inherit;margin:6px 0 0}
        .aieo-nl__privacy > input{flex:0 0 auto;margin:0;width:14px;height:14px;transform:scale(1.3);transform-origin:center;accent-color:var(--aieo-nl-accent,#F46767);cursor:pointer}
        .aieo-nl__privacy-text{flex:1 1 auto;min-width:0}
        .aieo-nl__privacy a{color:var(--aieo-nl-accent,#F46767);text-decoration:underline}
        .aieo-nl__btn{box-sizing:border-box;width:100%;padding:12px 16px;background:#fff;color:var(--aieo-nl-accent,#F46767);border:1px solid var(--aieo-nl-accent,#F46767);cursor:pointer;font-size:14px;font-weight:500;letter-spacing:.04em;text-transform:uppercase;transition:background-color .15s ease,color .15s ease}
        .aieo-nl__btn:hover{background:var(--aieo-nl-accent,#F46767);color:#fff}
        .aieo-nl__btn:disabled{opacity:.6;cursor:default}
        .aieo-nl__msg{min-height:18px;font-size:13px;margin-top:4px}
        .aieo-nl__msg.is-ok{color:#15803d}
        .aieo-nl__msg.is-err{color:#b91c1c}
        .aieo-nl__sso{margin-top:14px}
        @media(min-width:782px){
            .aieo-nl{flex-direction:row;align-items:center;justify-content:flex-start;padding:0;min-height:300px;margin-bottom:0;background-image:var(--aieo-nl-bg-d,var(--aieo-nl-bg-m,none))}
            .aieo-nl__content{position:static;width:100%;max-width:none;margin:0;padding:28px clamp(40px,6vw,96px);background:transparent;-webkit-backdrop-filter:none;backdrop-filter:none;border-radius:0;text-align:left;display:grid;grid-template-columns:minmax(260px,1fr) minmax(320px,1fr) minmax(220px,.7fr);column-gap:clamp(24px,3vw,56px);row-gap:16px;align-items:center}
            .aieo-nl--glass-desktop .aieo-nl__content{background:rgba(255,255,255,.4);-webkit-backdrop-filter:blur(5px);backdrop-filter:blur(5px);padding:24px clamp(28px,4vw,56px);border-radius:4px}
            .aieo-nl__logo{grid-column:1/-1;text-align:left;margin-bottom:4px}
            .aieo-nl__logo img{max-width:213px;margin:0}
            .aieo-nl__intro{margin:0;display:flex;flex-direction:column;gap:12px}
            .aieo-nl__title{font-size:28px;margin:0}
            .aieo-nl__desc{font-size:15px;opacity:.85}
            .aieo-nl__form{margin:0}
            .aieo-nl__form input[type=text],.aieo-nl__form input[type=email]{padding:7px 10px;font-size:13px;line-height:1.3;height:34px}
            .aieo-nl__btn{width:auto;min-width:180px;padding:9px 22px;font-size:13px}
            .aieo-nl__sso{align-self:stretch;margin-top:0}
            .aieo-nl__sso .aieo-sso-buttons__intro{font-size:12px;margin:0 0 8px}
        }
        </style>
        <script>
        (function(){
            if (window.__aieoNlInit) { return; } window.__aieoNlInit = true;
            document.addEventListener('submit', function(ev){
                var f = ev.target.closest('form[data-aieo-nl]');
                if (!f) { return; }
                ev.preventDefault();
                var msg = f.querySelector('.aieo-nl__msg'), btn = f.querySelector('.aieo-nl__btn');
                var val = function(sel){ var el = f.querySelector(sel); return el ? el.value : ''; };
                var fd = new FormData();
                fd.append('action','aieo_newsletter_subscribe');
                fd.append('nonce', f.getAttribute('data-nonce'));
                fd.append('email', val('[name=email]'));
                fd.append('name', val('[name=name]'));
                fd.append('last_name', val('[name=last_name]'));
                var pv = f.querySelector('[name=privacy]');
                fd.append('privacy', (pv && pv.checked) ? '1' : '');
                if (btn) { btn.disabled = true; }
                fetch(f.getAttribute('data-ajax'), { method:'POST', credentials:'same-origin', body: fd })
                    .then(function(r){ return r.json(); })
                    .then(function(j){
                        if (btn) { btn.disabled = false; }
                        if (!msg) { return; }
                        var ok = j && j.success;
                        msg.className = 'aieo-nl__msg ' + (ok ? 'is-ok' : 'is-err');
                        msg.textContent = (j && j.data && j.data.message) ? j.data.message : (ok ? 'OK' : 'Error');
                        if (ok) { f.querySelectorAll('input[type=text],input[type=email]').forEach(function(i){ i.value=''; }); if (pv) { pv.checked = false; } }
                    })
                    .catch(function(){ if (btn) { btn.disabled = false; } if (msg) { msg.className='aieo-nl__msg is-err'; msg.textContent='Network error.'; } });
            });
        })();
        </script>
        <?php
    }

    
    
    

    public function render_subtab() {
        $s     = $this->settings();
        $nonce = wp_create_nonce(AIEO_DMM::NONCE_ACTION);
        $ajax  = admin_url('admin-ajax.php');
        $logo_url = $s['logo_id'] ? wp_get_attachment_image_url((int) $s['logo_id'], 'thumbnail') : '';
        $img = function ($id) { return $id ? wp_get_attachment_image_url((int) $id, 'thumbnail') : ''; };
        ?>
        <div class="aieo-dmm-section">
            <h2><?php esc_html_e('Newsletter Signup', 'ai-eshop-optimizer'); ?></h2>
            <p class="description" style="max-width:880px;">
                <?php esc_html_e('A theme-independent newsletter signup banner. Configure the look + behaviour here, then place it on a block theme with the “Newsletter signup” block, or on a LEGACY (classic) theme with the shortcode below. Same full functionality on any theme.', 'ai-eshop-optimizer'); ?>
            </p>
            <p>
                <code class="aieo-promo-shortcode" style="user-select:all;font-size:13px;background:#f0f0f1;padding:6px 10px;border-radius:4px;">[aieo_newsletter_signup]</code>
                <span class="description"><?php esc_html_e(' ← legacy-theme shortcode (click to select)', 'ai-eshop-optimizer'); ?></span>
            </p>

            <form id="aieo-nl-form" class="aieo-dmm-card">
                <table class="form-table">
                    <tr><th scope="row"><?php esc_html_e('Enable', 'ai-eshop-optimizer'); ?></th>
                        <td><label><input type="checkbox" name="enabled" value="1" <?php checked(!empty($s['enabled'])); ?>> <?php esc_html_e('Render the newsletter signup banner', 'ai-eshop-optimizer'); ?></label></td></tr>

                    <tr><td colspan="2"><strong style="font-size:13px;"><?php esc_html_e('Content', 'ai-eshop-optimizer'); ?></strong></td></tr>
                    <tr><th scope="row"><?php esc_html_e('Heading', 'ai-eshop-optimizer'); ?></th>
                        <td><input type="text" name="heading" value="<?php echo esc_attr($s['heading']); ?>" class="regular-text" style="width:420px;"></td></tr>
                    <tr><th scope="row"><?php esc_html_e('Intro text', 'ai-eshop-optimizer'); ?></th>
                        <td><input type="text" name="intro" value="<?php echo esc_attr($s['intro']); ?>" class="regular-text" style="width:420px;"></td></tr>
                    <tr><th scope="row"><?php esc_html_e('Button / placeholder / success', 'ai-eshop-optimizer'); ?></th>
                        <td>
                            <input type="text" name="button_text" value="<?php echo esc_attr($s['button_text']); ?>" placeholder="Button" style="width:130px;">
                            <input type="text" name="placeholder" value="<?php echo esc_attr($s['placeholder']); ?>" placeholder="Email placeholder" style="width:160px;">
                            <input type="text" name="success_msg" value="<?php echo esc_attr($s['success_msg']); ?>" placeholder="Success message" style="width:240px;">
                        </td></tr>
                    <tr><th scope="row"><?php esc_html_e('Company logo', 'ai-eshop-optimizer'); ?></th>
                        <td>
                            <input type="hidden" name="logo_id" id="aieo-nl-logo_id" value="<?php echo (int) $s['logo_id']; ?>">
                            <img id="aieo-nl-logo_preview" src="<?php echo esc_url($logo_url); ?>" style="max-height:40px;vertical-align:middle;<?php echo $logo_url ? '' : 'display:none;'; ?>">
                            <button type="button" class="button aieo-nl-pick" data-target="logo_id"><?php esc_html_e('Choose', 'ai-eshop-optimizer'); ?></button>
                            <button type="button" class="button aieo-nl-clear" data-target="logo_id"><?php esc_html_e('Clear', 'ai-eshop-optimizer'); ?></button>
                        </td></tr>
                    <tr><th scope="row"><?php esc_html_e('Collect name', 'ai-eshop-optimizer'); ?></th>
                        <td>
                            <label><input type="checkbox" name="collect_name" value="1" <?php checked(!empty($s['collect_name'])); ?>> <?php esc_html_e('Show first + last name fields', 'ai-eshop-optimizer'); ?></label>
                            <br><input type="text" name="name_placeholder" value="<?php echo esc_attr($s['name_placeholder']); ?>" placeholder="<?php esc_attr_e('First-name field', 'ai-eshop-optimizer'); ?>" style="width:180px;margin-top:6px;">
                            <input type="text" name="last_name_placeholder" value="<?php echo esc_attr($s['last_name_placeholder']); ?>" placeholder="<?php esc_attr_e('Last-name field', 'ai-eshop-optimizer'); ?>" style="width:180px;margin-top:6px;">
                        </td></tr>

                    <tr><td colspan="2"><strong style="font-size:13px;"><?php esc_html_e('Appearance', 'ai-eshop-optimizer'); ?></strong></td></tr>
                    <tr><th scope="row"><?php esc_html_e('Background — Desktop', 'ai-eshop-optimizer'); ?></th>
                        <td><input type="text" name="bg_desktop_color" value="<?php echo esc_attr($s['bg_desktop_color']); ?>" class="aieo-color" style="width:120px;">
                            <input type="hidden" name="bg_desktop_image_id" id="aieo-nl-bg_desktop_image_id" value="<?php echo (int) $s['bg_desktop_image_id']; ?>">
                            <button type="button" class="button aieo-nl-pick" data-target="bg_desktop_image_id"><?php esc_html_e('Image…', 'ai-eshop-optimizer'); ?></button>
                            <button type="button" class="button aieo-nl-clear" data-target="bg_desktop_image_id"><?php esc_html_e('Clear', 'ai-eshop-optimizer'); ?></button>
                            <img id="aieo-nl-bg_desktop_image_id_preview" src="<?php echo esc_url($img($s['bg_desktop_image_id'])); ?>" style="max-height:32px;vertical-align:middle;<?php echo $img($s['bg_desktop_image_id']) ? '' : 'display:none;'; ?>"></td></tr>
                    <tr><th scope="row"><?php esc_html_e('Background — Mobile', 'ai-eshop-optimizer'); ?></th>
                        <td><input type="text" name="bg_mobile_color" value="<?php echo esc_attr($s['bg_mobile_color']); ?>" class="aieo-color" style="width:120px;">
                            <input type="hidden" name="bg_mobile_image_id" id="aieo-nl-bg_mobile_image_id" value="<?php echo (int) $s['bg_mobile_image_id']; ?>">
                            <button type="button" class="button aieo-nl-pick" data-target="bg_mobile_image_id"><?php esc_html_e('Image…', 'ai-eshop-optimizer'); ?></button>
                            <button type="button" class="button aieo-nl-clear" data-target="bg_mobile_image_id"><?php esc_html_e('Clear', 'ai-eshop-optimizer'); ?></button>
                            <img id="aieo-nl-bg_mobile_image_id_preview" src="<?php echo esc_url($img($s['bg_mobile_image_id'])); ?>" style="max-height:32px;vertical-align:middle;<?php echo $img($s['bg_mobile_image_id']) ? '' : 'display:none;'; ?>"></td></tr>
                    <tr><th scope="row"><?php esc_html_e('Glass effect (mobile)', 'ai-eshop-optimizer'); ?></th>
                        <td><label><input type="checkbox" name="glass_mobile" value="1" <?php checked(!empty($s['glass_mobile'])); ?>> <?php esc_html_e('Frosted-glass card over the mobile background', 'ai-eshop-optimizer'); ?></label></td></tr>
                    <tr><th scope="row"><?php esc_html_e('Glass effect (desktop)', 'ai-eshop-optimizer'); ?></th>
                        <td><label><input type="checkbox" name="glass_desktop" value="1" <?php checked(!empty($s['glass_desktop'])); ?>> <?php esc_html_e('Also frost the desktop content card (off = text sits directly on the banner)', 'ai-eshop-optimizer'); ?></label></td></tr>
                    <tr><th scope="row"><?php esc_html_e('Text / accent colour', 'ai-eshop-optimizer'); ?></th>
                        <td><input type="text" name="text_color" value="<?php echo esc_attr($s['text_color']); ?>" class="aieo-color" style="width:120px;" placeholder="#ffffff">
                            <input type="text" name="accent_color" value="<?php echo esc_attr($s['accent_color']); ?>" class="aieo-color" style="width:120px;" placeholder="#F46767"></td></tr>

                    <tr><td colspan="2"><strong style="font-size:13px;"><?php esc_html_e('Integration', 'ai-eshop-optimizer'); ?></strong></td></tr>
                    <tr><th scope="row"><?php esc_html_e('Submit to', 'ai-eshop-optimizer'); ?></th>
                        <td>
                            <select name="provider_mode" style="min-width:280px;">
                                <option value="newsletter" <?php selected($s['provider_mode'], 'newsletter'); ?>><?php esc_html_e('Newsletter provider (configured under Web Push / Newsletter)', 'ai-eshop-optimizer'); ?></option>
                                <option value="gravity" <?php selected($s['provider_mode'], 'gravity'); ?>><?php esc_html_e('Gravity Form (embed by ID)', 'ai-eshop-optimizer'); ?></option>
                                <option value="none" <?php selected($s['provider_mode'], 'none'); ?>><?php esc_html_e('Collect only (fires aieo_newsletter_subscribe hook)', 'ai-eshop-optimizer'); ?></option>
                            </select>
                            <label style="margin-left:10px;"><?php esc_html_e('Gravity Form ID:', 'ai-eshop-optimizer'); ?>
                                <input type="number" name="gravity_form_id" value="<?php echo (int) $s['gravity_form_id']; ?>" min="0" style="width:80px;"></label>
                        </td></tr>
                    <tr><th scope="row"><?php esc_html_e('SSO sign-up', 'ai-eshop-optimizer'); ?></th>
                        <td><label><input type="checkbox" name="sso_enabled" value="1" <?php checked(!empty($s['sso_enabled'])); ?>> <?php esc_html_e('Allow subscription via our own SSO — Google / Facebook / Magic Link (Social Login “subscribe” providers)', 'ai-eshop-optimizer'); ?></label></td></tr>

                    <tr><td colspan="2"><strong style="font-size:13px;"><?php esc_html_e('Privacy', 'ai-eshop-optimizer'); ?></strong></td></tr>
                    <tr><th scope="row"><?php esc_html_e('Privacy consent', 'ai-eshop-optimizer'); ?></th>
                        <td>
                            <label><input type="checkbox" name="privacy_enabled" value="1" <?php checked(!empty($s['privacy_enabled'])); ?>> <?php esc_html_e('Require a privacy-policy consent checkbox', 'ai-eshop-optimizer'); ?></label>
                            <br><input type="text" name="privacy_text" value="<?php echo esc_attr($s['privacy_text']); ?>" class="regular-text" style="width:360px;margin-top:6px;" placeholder="<?php esc_attr_e('Consent label', 'ai-eshop-optimizer'); ?>">
                            <br><input type="text" name="privacy_link_text" value="<?php echo esc_attr(isset($s['privacy_link_text']) ? $s['privacy_link_text'] : ''); ?>" class="regular-text" style="width:360px;margin-top:6px;" placeholder="<?php esc_attr_e('Linked words only — must appear in the label (blank = link whole label)', 'ai-eshop-optimizer'); ?>">
                            <br><input type="url" name="privacy_url" value="<?php echo esc_attr($s['privacy_url']); ?>" class="regular-text" style="width:360px;margin-top:6px;" placeholder="<?php esc_attr_e('Privacy-policy URL (blank → WordPress privacy page)', 'ai-eshop-optimizer'); ?>">
                        </td></tr>
                </table>
                <p class="submit">
                    <button type="submit" class="button button-primary" id="aieo-nl-save"><?php esc_html_e('Save', 'ai-eshop-optimizer'); ?></button>
                    <span id="aieo-nl-status" style="margin-left:12px;font-weight:600;"></span>
                </p>
            </form>
        </div>
        <script>
        (function () {
            var f = document.getElementById('aieo-nl-form'); if (!f) { return; }
            var st = document.getElementById('aieo-nl-status');
            var ajax = <?php echo wp_json_encode($ajax); ?>, nonce = <?php echo wp_json_encode($nonce); ?>;
            // wp.media pickers.
            f.querySelectorAll('.aieo-nl-pick').forEach(function(b){
                b.addEventListener('click', function(){
                    var t = b.getAttribute('data-target');
                    if (!window.wp || !wp.media) { return; }
                    var frame = wp.media({ multiple:false });
                    frame.on('select', function(){
                        var a = frame.state().get('selection').first().toJSON();
                        document.getElementById('aieo-nl-' + t).value = a.id;
                        var p = document.getElementById('aieo-nl-' + t + '_preview');
                        if (p) { p.src = (a.sizes && a.sizes.thumbnail ? a.sizes.thumbnail.url : a.url); p.style.display=''; }
                    });
                    frame.open();
                });
            });
            f.querySelectorAll('.aieo-nl-clear').forEach(function(b){
                b.addEventListener('click', function(){
                    var t = b.getAttribute('data-target');
                    document.getElementById('aieo-nl-' + t).value = 0;
                    var p = document.getElementById('aieo-nl-' + t + '_preview'); if (p) { p.style.display='none'; }
                });
            });
            f.addEventListener('submit', function(e){
                e.preventDefault();
                var fd = new FormData(f); fd.append('action','aieo_newsletter_signup_save'); fd.append('nonce', nonce);
                ['enabled','collect_name','glass_mobile','glass_desktop','privacy_enabled','sso_enabled'].forEach(function(k){ var el=f.querySelector('[name='+k+']'); fd.set(k, el && el.checked ? 1 : 0); });
                if (st) { st.style.color='#6b7280'; st.textContent=<?php echo wp_json_encode(__('Saving…', 'ai-eshop-optimizer')); ?>; }
                fetch(ajax, { method:'POST', credentials:'same-origin', body: fd }).then(function(r){return r.json();}).then(function(j){
                    if (st) { st.style.color=(j&&j.success)?'#15803d':'#b91c1c'; st.textContent=(j&&j.data&&j.data.message)?j.data.message:(j&&j.success?'Saved ✓':'Error'); }
                }).catch(function(){ if(st){st.style.color='#b91c1c';st.textContent='Network error.';} });
            });
        })();
        </script>
        <?php
    }
}
