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

class SailWP_Copilot_Settings {
    public function __construct() {
        add_action('admin_menu', [$this, 'register_menu']);
        add_action('admin_init', [$this, 'register_settings']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_assets']);
        // Strip third-party admin noise on the Co-pilot settings screen so
        // theme / plugin "Get started" banners don't compete for attention.
        add_action('in_admin_header', [$this, 'silence_other_notices'], 1000);
        // Patch the "Open Dashboard ↗" external submenu to open in a new tab.
        add_action('admin_footer', [$this, 'open_dashboard_target_blank']);
        // Privacy-aware Umami analytics — only on SailWP-Co-pilot admin pages.
        add_action('admin_head', [$this, 'inject_umami']);
    }

    public function inject_umami() {
        $screen = function_exists('get_current_screen') ? get_current_screen() : null;
        // Only on SailWP-Co-pilot admin screens (top-level + submenu pages).
        if (!$screen || strpos($screen->id, 'sailwp-copilot') === false) return;
        ?>
        <script async defer src="https://analytics.31ventures.io/script.js" data-website-id="sailwp-plugin-admin"></script>
        <?php
    }

    public function silence_other_notices() {
        $screen = function_exists('get_current_screen') ? get_current_screen() : null;
        if (!$screen || $screen->id !== 'toplevel_page_sailwp-copilot') return;
        remove_all_actions('admin_notices');
        remove_all_actions('all_admin_notices');
        remove_all_actions('user_admin_notices');
        remove_all_actions('network_admin_notices');
    }

    public function register_menu() {
        add_menu_page(
            __('SailWP Co-pilot', 'sailwp-ai-copilot'),
            __('SailWP Co-pilot', 'sailwp-ai-copilot'),
            'manage_options',
            'sailwp-copilot',
            [$this, 'render_page'],
            'dashicons-format-chat',
            58
        );

        // "Open Dashboard ↗" submenu — links the editor straight into the
        // SailWP cloud dashboard at ai.sailwp.com/app, signed in via the
        // proxy's HMAC handoff (no email link, no password). The proxy
        // resolves the email + license, signs the URL, redirects.
        $license = SailWP_Copilot_Plugin::get_license_key();
        $email   = wp_get_current_user() ? wp_get_current_user()->user_email : '';
        if ($license && $email) {
            $proxy = SailWP_Copilot_Plugin::get_ai_proxy_url();
            $url = $proxy . '/api/v1/open-dashboard?license=' . urlencode($license) . '&email=' . urlencode($email);
            add_submenu_page(
                'sailwp-copilot',
                __('Open Dashboard', 'sailwp-ai-copilot'),
                __('Open Dashboard ↗', 'sailwp-ai-copilot'),
                'edit_posts',
                esc_url($url) // submenu slug = full URL → WP renders as external link, opens in new tab via target=_blank below
            );
        }
    }

    /**
     * Force the "Open Dashboard ↗" external submenu link to open in a new
     * tab. WordPress renders the submenu slug verbatim as the href when it
     * starts with http(s), but does not add target=_blank. We patch it via
     * an inline script restricted to the SailWP-Copilot menu items.
     */
    public function open_dashboard_target_blank() {
        ?>
        <script>
        document.addEventListener('DOMContentLoaded', function () {
            document.querySelectorAll('#toplevel_page_sailwp-copilot a.wp-has-submenu + ul a').forEach(function (a) {
                if (a.href && a.href.indexOf('/api/v1/open-dashboard') !== -1) {
                    a.target = '_blank';
                    a.rel = 'noopener';
                }
            });
        });
        </script>
        <?php
    }

    public function register_settings() {
        register_setting('sailwp_copilot', 'sailwp_copilot_license_key', ['type' => 'string', 'sanitize_callback' => 'sanitize_text_field']);
        register_setting('sailwp_copilot', 'sailwp_copilot_site_api_key', ['type' => 'string', 'sanitize_callback' => 'sanitize_text_field']);
        register_setting('sailwp_copilot', 'sailwp_copilot_workspace_id', ['type' => 'integer', 'sanitize_callback' => 'absint']);
        register_setting('sailwp_copilot', 'sailwp_copilot_site_id', ['type' => 'integer', 'sanitize_callback' => 'absint']);
        register_setting('sailwp_copilot', 'sailwp_copilot_ai_proxy_url', ['type' => 'string', 'sanitize_callback' => 'esc_url_raw']);
        register_setting('sailwp_copilot', 'sailwp_copilot_cloud_url', ['type' => 'string', 'sanitize_callback' => 'esc_url_raw']);
        // Integrations — used to swap placeholder URLs in inserted patterns
        // so the user's pricing button / signup form / contact form already
        // point at their own Stripe / newsletter service / form endpoint.
        register_setting('sailwp_copilot', 'sailwp_copilot_stripe_pro_url', ['type' => 'string', 'sanitize_callback' => 'esc_url_raw']);
        register_setting('sailwp_copilot', 'sailwp_copilot_newsletter_url', ['type' => 'string', 'sanitize_callback' => 'esc_url_raw']);
        register_setting('sailwp_copilot', 'sailwp_copilot_form_endpoint', ['type' => 'string', 'sanitize_callback' => [$this, 'sanitize_form_endpoint']]);
    }

    /**
     * Form endpoint can be either an https:// URL (Formspree / Basin /
     * Getform) OR a mailto: address. esc_url_raw strips mailto, so we
     * special-case it here.
     */
    public function sanitize_form_endpoint($value) {
        $value = trim((string) $value);
        if ($value === '') return '';
        if (stripos($value, 'mailto:') === 0) {
            $email = substr($value, 7);
            $email = sanitize_email($email);
            return $email ? 'mailto:' . $email : '';
        }
        return esc_url_raw($value);
    }

    public function enqueue_assets($hook) {
        if ($hook !== 'toplevel_page_sailwp-copilot') return;
        wp_enqueue_style(
            'sailwp-copilot-admin',
            SAILWP_COPILOT_URL . 'assets/css/admin.css',
            [],
            SAILWP_COPILOT_VERSION
        );
    }

    /**
     * Brand profile editor. Auto-extracted from the host site (colors,
     * fonts, tone-of-voice samples, photo cues). User overrides win.
     * The Co-pilot designers consume this so generated pages match
     * what already exists on the site instead of inventing a new look.
     */
    private function render_brand_profile_section() {
        if (!class_exists('SailWP_Copilot_Brand_Profile')) return;
        $profile   = SailWP_Copilot_Brand_Profile::get();
        $overrides = SailWP_Copilot_Brand_Profile::get_overrides();
        $colors    = isset($profile['colors']) && is_array($profile['colors']) ? $profile['colors'] : [];
        $fonts     = isset($profile['fonts'])  && is_array($profile['fonts'])  ? $profile['fonts']  : [];
        // Dedupe colors on normalized hex value — theme + default palettes
        // routinely overlap (Astra ships 21 slots, many duplicate the same
        // hex). For the editor we want one swatch per distinct colour;
        // overrides still target the first slug that produced that hex.
        $colors_unique = [];
        foreach ($colors as $slug => $hex) {
            $norm = strtolower(trim((string) $hex));
            // Resolve simple CSS-var indirection (var(--ast-global-color-0)) by
            // skipping — they're not real colours, just references.
            if (strpos($norm, 'var(') === 0) continue;
            if ($norm === '' || isset($colors_unique[$norm])) continue;
            $colors_unique[$norm] = $slug;
        }
        $tone_h    = $profile['tone']['headings']   ?? [];
        $tone_p    = $profile['tone']['paragraphs'] ?? [];
        $photo_alt = $profile['photos']['alt_samples'] ?? [];
        $photo_src = $profile['photos']['sources'] ?? [];
        $nonce     = wp_create_nonce('wp_rest');
        $rest_base = esc_url_raw(rest_url('sailwp-copilot/v1/brand-profile'));
        ?>
        <div class="sailwp-copilot-card swcp-brand-profile" id="swcp-brand-profile">
            <h2><?php esc_html_e('Brand profile', 'sailwp-ai-copilot'); ?></h2>
            <p class="description">
                <?php esc_html_e('The Co-pilot reads this when designing a new page so the result matches your existing look and voice. Auto-extracted from your site. Edit any field to override.', 'sailwp-ai-copilot'); ?>
            </p>

            <div class="swcp-bp-grid">
                <div class="swcp-bp-block">
                    <h3><?php esc_html_e('Colors', 'sailwp-ai-copilot'); ?></h3>
                    <?php if (empty($colors_unique)): ?>
                        <p class="description"><?php esc_html_e('No theme palette detected. The Co-pilot will pick brand-fit colors on its own.', 'sailwp-ai-copilot'); ?></p>
                    <?php else: ?>
                        <p class="description"><?php echo esc_html(sprintf(__('%d distinct colors from your theme. Click a swatch to copy its hex.', 'sailwp-ai-copilot'), count($colors_unique))); ?></p>
                        <div class="swcp-bp-palette" role="list">
                            <?php foreach ($colors_unique as $hex => $slug): ?>
                                <button type="button" class="swcp-bp-swatch" role="listitem"
                                        data-bp-swatch-hex="<?php echo esc_attr($hex); ?>"
                                        data-bp-swatch-slug="<?php echo esc_attr($slug); ?>"
                                        title="<?php echo esc_attr($slug . ' — ' . $hex); ?>"
                                        aria-label="<?php echo esc_attr(sprintf(__('%s, hex %s — click to copy', 'sailwp-ai-copilot'), $slug, $hex)); ?>">
                                    <span class="swcp-bp-swatch-fill" style="background: <?php echo esc_attr($hex); ?>;"></span>
                                </button>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>

                <div class="swcp-bp-block">
                    <h3><?php esc_html_e('Typography', 'sailwp-ai-copilot'); ?></h3>
                    <?php if (empty($fonts)): ?>
                        <p class="description"><?php esc_html_e('No theme fonts detected. The Co-pilot will pick system fonts unless you override below.', 'sailwp-ai-copilot'); ?></p>
                    <?php endif; ?>
                    <div class="swcp-bp-fields">
                        <?php foreach ($fonts as $slug => $family): ?>
                            <label class="swcp-bp-row">
                                <span class="swcp-bp-slug"><?php echo esc_html($slug); ?></span>
                                <input type="text" data-bp-font="<?php echo esc_attr($slug); ?>" value="<?php echo esc_attr($family); ?>" class="regular-text" />
                            </label>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>

            <div class="swcp-bp-block">
                <h3><?php esc_html_e('Tone of voice — samples from your site', 'sailwp-ai-copilot'); ?></h3>
                <?php if ($tone_h || $tone_p): ?>
                    <details class="swcp-bp-details">
                        <summary><?php echo esc_html(sprintf(__('Show %d headings and %d paragraphs', 'sailwp-ai-copilot'), count($tone_h), count($tone_p))); ?></summary>
                        <?php if ($tone_h): ?>
                            <p><strong><?php esc_html_e('Headings', 'sailwp-ai-copilot'); ?>:</strong></p>
                            <ul class="swcp-bp-samples">
                                <?php foreach ($tone_h as $h): ?><li><?php echo esc_html($h); ?></li><?php endforeach; ?>
                            </ul>
                        <?php endif; ?>
                        <?php if ($tone_p): ?>
                            <p><strong><?php esc_html_e('Paragraphs', 'sailwp-ai-copilot'); ?>:</strong></p>
                            <ul class="swcp-bp-samples">
                                <?php foreach ($tone_p as $p): ?><li><?php echo esc_html($p); ?></li><?php endforeach; ?>
                            </ul>
                        <?php endif; ?>
                    </details>
                <?php else: ?>
                    <p class="description"><?php esc_html_e('No body copy detected yet on the site. The Co-pilot will fall back to a neutral, brand-fit voice until you publish a few pages.', 'sailwp-ai-copilot'); ?></p>
                <?php endif; ?>
                <label class="swcp-bp-row swcp-bp-row-full">
                    <span class="swcp-bp-label"><?php esc_html_e('Add a tone note (optional)', 'sailwp-ai-copilot'); ?></span>
                    <textarea data-bp-note="tone_note" rows="3" class="large-text" placeholder="<?php esc_attr_e('e.g. Warm and direct, "je" not "u", short sentences, no jargon.', 'sailwp-ai-copilot'); ?>"><?php echo esc_textarea($overrides['tone_note'] ?? ''); ?></textarea>
                </label>
            </div>

            <div class="swcp-bp-block">
                <h3><?php esc_html_e('Photo style', 'sailwp-ai-copilot'); ?></h3>
                <?php if ($photo_alt || $photo_src): ?>
                    <p class="description">
                        <?php
                        $own = (int) ($photo_src['own_uploads'] ?? 0);
                        $ext = (int) ($photo_src['external']    ?? 0);
                        echo esc_html(sprintf(
                            __('Recent media: %d on this site, %d external.', 'sailwp-ai-copilot'),
                            $own, $ext
                        ));
                        ?>
                    </p>
                    <?php if ($photo_alt): ?>
                        <p class="description"><strong><?php esc_html_e('Sample alt-text', 'sailwp-ai-copilot'); ?>:</strong> <?php echo esc_html(implode(' · ', array_slice($photo_alt, 0, 3))); ?></p>
                    <?php endif; ?>
                <?php else: ?>
                    <p class="description"><?php esc_html_e('No recent media uploads found.', 'sailwp-ai-copilot'); ?></p>
                <?php endif; ?>
                <label class="swcp-bp-row swcp-bp-row-full">
                    <span class="swcp-bp-label"><?php esc_html_e('Add a photo-style note (optional)', 'sailwp-ai-copilot'); ?></span>
                    <textarea data-bp-note="photo_note" rows="2" class="large-text" placeholder="<?php esc_attr_e('e.g. Always use your own product photos, no stock imagery, soft natural light.', 'sailwp-ai-copilot'); ?>"><?php echo esc_textarea($overrides['photo_note'] ?? ''); ?></textarea>
                </label>
            </div>

            <div class="swcp-bp-actions">
                <button type="button" class="button button-primary" id="swcp-bp-save"><?php esc_html_e('Save my notes', 'sailwp-ai-copilot'); ?></button>
                <button type="button" class="button" id="swcp-bp-refresh"><?php esc_html_e('Read my site again', 'sailwp-ai-copilot'); ?></button>
                <button type="button" class="button-link" id="swcp-bp-reset"><?php esc_html_e('Reset to what is on my site', 'sailwp-ai-copilot'); ?></button>
                <span class="swcp-bp-status" id="swcp-bp-status" aria-live="polite"></span>
            </div>
        </div>

        <script>
        (function(){
            var REST = <?php echo wp_json_encode($rest_base); ?>;
            var NONCE = <?php echo wp_json_encode($nonce); ?>;
            var status = document.getElementById('swcp-bp-status');
            function flash(msg, kind) {
                if (!status) return;
                status.textContent = msg;
                status.className = 'swcp-bp-status is-' + (kind || 'info');
                setTimeout(function(){ status.textContent = ''; status.className = 'swcp-bp-status'; }, 4000);
            }
            function collectOverrides() {
                var out = { fonts: {} };
                document.querySelectorAll('[data-bp-font]').forEach(function(el){
                    var slug = el.getAttribute('data-bp-font');
                    var v = (el.value || '').trim();
                    if (slug && v) out.fonts[slug] = v;
                });
                document.querySelectorAll('[data-bp-note]').forEach(function(el){
                    var k = el.getAttribute('data-bp-note');
                    var v = (el.value || '').trim();
                    if (k && v) out[k] = v;
                });
                return out;
            }
            // Click a colour swatch to copy its hex.
            document.querySelectorAll('.swcp-bp-swatch').forEach(function(btn){
                btn.addEventListener('click', function(e){
                    e.preventDefault();
                    var hex = btn.getAttribute('data-bp-swatch-hex') || '';
                    if (!hex) return;
                    if (navigator.clipboard && navigator.clipboard.writeText) {
                        navigator.clipboard.writeText(hex).then(function(){
                            btn.classList.add('is-copied');
                            flash(hex + ' <?php echo esc_js(__('copied', 'sailwp-ai-copilot')); ?>', 'success');
                            setTimeout(function(){ btn.classList.remove('is-copied'); }, 900);
                        }).catch(function(){ flash('<?php echo esc_js(__('Could not copy. Select and copy manually.', 'sailwp-ai-copilot')); ?>', 'error'); });
                    } else {
                        flash(hex, 'info');
                    }
                });
            });
            document.getElementById('swcp-bp-save').addEventListener('click', function(e){
                e.preventDefault();
                var btn = e.currentTarget; btn.disabled = true;
                fetch(REST + '/overrides', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': NONCE },
                    body: JSON.stringify({ overrides: collectOverrides() })
                }).then(function(r){ return r.json(); }).then(function(j){
                    btn.disabled = false;
                    if (j && j.ok) flash('<?php echo esc_js(__('Saved. New designs will use this.', 'sailwp-ai-copilot')); ?>', 'success');
                    else flash('<?php echo esc_js(__('Could not save. Reload and try again.', 'sailwp-ai-copilot')); ?>', 'error');
                }).catch(function(){ btn.disabled = false; flash('<?php echo esc_js(__('Network hiccup. Try again.', 'sailwp-ai-copilot')); ?>', 'error'); });
            });
            document.getElementById('swcp-bp-refresh').addEventListener('click', function(e){
                e.preventDefault();
                var btn = e.currentTarget; btn.disabled = true;
                fetch(REST + '/refresh', { method: 'POST', headers: { 'X-WP-Nonce': NONCE } })
                    .then(function(r){ return r.json(); }).then(function(j){
                        btn.disabled = false;
                        if (j && j.ok) { flash('<?php echo esc_js(__('Refreshed. Reloading…', 'sailwp-ai-copilot')); ?>', 'success'); setTimeout(function(){ window.location.reload(); }, 700); }
                        else flash('<?php echo esc_js(__('Refresh failed.', 'sailwp-ai-copilot')); ?>', 'error');
                    }).catch(function(){ btn.disabled = false; flash('<?php echo esc_js(__('Network hiccup. Try again.', 'sailwp-ai-copilot')); ?>', 'error'); });
            });
            document.getElementById('swcp-bp-reset').addEventListener('click', function(e){
                e.preventDefault();
                if (!confirm('<?php echo esc_js(__('Clear all brand-profile overrides and go back to auto-extracted values?', 'sailwp-ai-copilot')); ?>')) return;
                fetch(REST + '/overrides/reset', { method: 'POST', headers: { 'X-WP-Nonce': NONCE } })
                    .then(function(r){ return r.json(); }).then(function(j){
                        if (j && j.ok) { flash('<?php echo esc_js(__('Overrides cleared. Reloading…', 'sailwp-ai-copilot')); ?>', 'success'); setTimeout(function(){ window.location.reload(); }, 700); }
                        else flash('<?php echo esc_js(__('Reset failed.', 'sailwp-ai-copilot')); ?>', 'error');
                    }).catch(function(){ flash('<?php echo esc_js(__('Network hiccup. Try again.', 'sailwp-ai-copilot')); ?>', 'error'); });
            });
        })();
        </script>
        <?php
    }

    public function render_page() {
        if (!current_user_can('manage_options')) return;
        $license   = SailWP_Copilot_Plugin::get_license_key();
        $api_key   = SailWP_Copilot_Plugin::get_site_api_key();
        $proxy_url = SailWP_Copilot_Plugin::get_ai_proxy_url();
        $cloud_url = SailWP_Copilot_Plugin::get_cloud_url();
        $connected = SailWP_Copilot_Plugin::is_connected_to_cloud();
        ?>
        <div class="wrap sailwp-copilot-wrap">
            <header class="sailwp-copilot-header">
                <h1><?php esc_html_e('SailWP AI Co-pilot', 'sailwp-ai-copilot'); ?></h1>
                <p class="sailwp-copilot-tagline">
                    <?php esc_html_e('AI companion for WordPress — works with any theme.', 'sailwp-ai-copilot'); ?>
                </p>
            </header>

            <?php if ($license): ?>
            <?php
            $is_pro    = SailWP_Copilot_Plugin::is_pro();
            $quota     = SailWP_Copilot_Plugin::get_quota_cache();
            $sub_type  = is_array($quota) && isset($quota['subscription_type']) ? (string) $quota['subscription_type'] : '';
            $manageable = ($sub_type === 'stripe');
            ?>
            <div class="swcp-hero-cta <?php echo $is_pro ? 'is-pro' : 'is-free'; ?>">
                <?php if ($is_pro): ?>
                    <div class="swcp-hero-mark">✓</div>
                    <div class="swcp-hero-body">
                        <div class="swcp-hero-eyebrow"><?php esc_html_e('Plan', 'sailwp-ai-copilot'); ?></div>
                        <?php if ($sub_type === 'founder'): ?>
                            <h2><?php esc_html_e('Founder access — Co-pilot Pro', 'sailwp-ai-copilot'); ?></h2>
                            <p><?php esc_html_e('Unlimited everything, complimentary for life. There is no billing to manage.', 'sailwp-ai-copilot'); ?></p>
                        <?php elseif ($sub_type === 'coupon'): ?>
                            <h2><?php esc_html_e('Co-pilot Pro — coupon unlocked', 'sailwp-ai-copilot'); ?></h2>
                            <p><?php esc_html_e('Unlimited fresh designs and refinements on this site. Reach out to joost@sailwp.com if you need to change anything.', 'sailwp-ai-copilot'); ?></p>
                        <?php else: ?>
                            <h2><?php esc_html_e('You are on Co-pilot Pro', 'sailwp-ai-copilot'); ?></h2>
                            <p><?php esc_html_e('Unlimited fresh designs and refinements. All tools, voice and uploads always on.', 'sailwp-ai-copilot'); ?></p>
                        <?php endif; ?>
                    </div>
                    <?php if ($manageable): ?>
                    <div class="swcp-hero-actions">
                        <a class="swcp-btn-secondary" href="<?php echo esc_url(SailWP_Copilot_Plugin::get_ai_proxy_url() . '/api/v1/manage?license=' . rawurlencode($license)); ?>" target="_blank" rel="noopener noreferrer">
                            <?php esc_html_e('Manage subscription', 'sailwp-ai-copilot'); ?> →
                        </a>
                    </div>
                    <?php endif; ?>
                <?php else: ?>
                    <div class="swcp-hero-mark"><img src="<?php echo esc_url(SAILWP_COPILOT_URL . 'assets/img/sailwp-icon.png'); ?>" alt="" /></div>
                    <div class="swcp-hero-body">
                        <div class="swcp-hero-eyebrow"><?php esc_html_e('Plan', 'sailwp-ai-copilot'); ?> · Free</div>
                        <h2><?php esc_html_e('Upgrade to Co-pilot Pro', 'sailwp-ai-copilot'); ?></h2>
                        <p><?php esc_html_e('5 fresh designs / month, 100 refinements, unlimited cleanup tools, priority support. Cancel any time.', 'sailwp-ai-copilot'); ?></p>
                        <div class="swcp-hero-price">€19 <span class="per"><?php esc_html_e('/mo', 'sailwp-ai-copilot'); ?></span> &nbsp;·&nbsp; €190 <span class="per"><?php esc_html_e('/yr (2 months free)', 'sailwp-ai-copilot'); ?></span></div>
                    </div>
                    <div class="swcp-hero-actions">
                        <a class="swcp-btn-primary" href="<?php echo esc_url(SailWP_Copilot_Plugin::get_ai_proxy_url() . '/api/v1/upgrade?plan=monthly&license=' . rawurlencode($license)); ?>" target="_blank" rel="noopener noreferrer">
                            <?php esc_html_e('Monthly €19', 'sailwp-ai-copilot'); ?> →
                        </a>
                        <a class="swcp-btn-secondary" href="<?php echo esc_url(SailWP_Copilot_Plugin::get_ai_proxy_url() . '/api/v1/upgrade?plan=yearly&license=' . rawurlencode($license)); ?>" target="_blank" rel="noopener noreferrer" style="margin-left: 8px;">
                            <?php esc_html_e('Yearly €190', 'sailwp-ai-copilot'); ?> →
                        </a>
                    </div>
                <?php endif; ?>
            </div>

            <?php if (!$is_pro): ?>
            <div class="sailwp-copilot-card swcp-coupon-card">
                <div class="swcp-coupon-header">
                    <span class="swcp-coupon-badge" aria-hidden="true">🎁</span>
                    <div class="swcp-coupon-headtext">
                        <h2><?php esc_html_e('Have a coupon code?', 'sailwp-ai-copilot'); ?></h2>
                        <p class="description">
                            <?php esc_html_e('Codes from Joost or a Pro friend unlock Co-pilot Pro on this site instantly. One code per site.', 'sailwp-ai-copilot'); ?>
                        </p>
                    </div>
                </div>
                <label class="swcp-coupon-label" for="swcp-coupon-input"><?php esc_html_e('Your coupon code', 'sailwp-ai-copilot'); ?></label>
                <div class="swcp-coupon-row">
                    <input type="text" id="swcp-coupon-input" placeholder="SWCP-XXXX-XXXX-XXXX" autocomplete="off" spellcheck="false" />
                    <button type="button" class="button button-primary" id="swcp-coupon-submit"><?php esc_html_e('Redeem', 'sailwp-ai-copilot'); ?></button>
                </div>
                <p class="swcp-coupon-hint"><?php esc_html_e('Codes look like SWCP- followed by three groups of four characters.', 'sailwp-ai-copilot'); ?></p>
                <div id="swcp-coupon-result" class="swcp-coupon-result" hidden></div>
                <script>
                (function(){
                    var btn   = document.getElementById('swcp-coupon-submit');
                    var input = document.getElementById('swcp-coupon-input');
                    var out   = document.getElementById('swcp-coupon-result');
                    // Map upstream error codes to copy that actually helps the user know
                    // what to do next. Falls back to the upstream message if the code
                    // is unknown — that way new error codes still display something.
                    // Error codes here match what the proxy /api/v1/redeem-coupon
                    // endpoint actually returns: unknown_code, already_redeemed,
                    // expired, unknown_license, license_required, code_required.
                    // Keep these in sync if the proxy changes.
                    var ERROR_COPY = {
                        unknown_code:     'That code does not exist. Double-check for typos, or ask whoever shared it with you.',
                        already_redeemed: 'This code has already been redeemed. If that was not you, email joost@start24.nl and I will sort it.',
                        expired:          'This code has expired. Email joost@start24.nl if you think it should still be valid.',
                        unknown_license:  'This site is not connected to SailWP yet. Reload the page, then try again.',
                        license_required: 'This site is not connected to SailWP yet. Reload the page, then try again.',
                        code_required:    'Type in your coupon code first.',
                        rate_limited:     'Too many attempts in a short time. Wait a moment and try again.',
                    };
                    function friendlyError(body){
                        var code = body && body.error;
                        if (code && ERROR_COPY[code]) return ERROR_COPY[code];
                        if (body && body.message) return body.message;
                        return 'Could not redeem that code. Try again, or email joost@start24.nl.';
                    }
                    btn.addEventListener('click', function(){
                        var code = (input.value || '').trim().toUpperCase();
                        if (!code) { input.focus(); return; }
                        btn.disabled = true; btn.textContent = '<?php echo esc_js(__('Checking…', 'sailwp-ai-copilot')); ?>';
                        out.hidden = true;
                        fetch('<?php echo esc_url(rest_url('sailwp-copilot/v1/redeem-coupon')); ?>', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': '<?php echo esc_js(wp_create_nonce('wp_rest')); ?>' },
                            body: JSON.stringify({ code: code })
                        }).then(function(r){ return r.json().then(function(j){ return { ok: r.ok, body: j }; }); })
                          .then(function(o){
                            out.hidden = false;
                            if (o.ok && o.body && o.body.ok) {
                                out.className = 'swcp-coupon-result is-success';
                                out.textContent = (o.body.message || '<?php echo esc_js(__('Code redeemed — you are on Pro!', 'sailwp-ai-copilot')); ?>') + ' <?php echo esc_js(__('Reloading…', 'sailwp-ai-copilot')); ?>';
                                setTimeout(function(){ window.location.search = '?page=sailwp-copilot&swcp_refresh=1'; }, 900);
                            } else {
                                out.className = 'swcp-coupon-result is-error';
                                out.textContent = friendlyError(o.body);
                                btn.disabled = false; btn.textContent = '<?php echo esc_js(__('Redeem', 'sailwp-ai-copilot')); ?>';
                                input.focus(); input.select();
                            }
                        }).catch(function(){
                            out.hidden = false;
                            out.className = 'swcp-coupon-result is-error';
                            out.textContent = '<?php echo esc_js(__('Network hiccup. Check your connection and try again.', 'sailwp-ai-copilot')); ?>';
                            btn.disabled = false; btn.textContent = '<?php echo esc_js(__('Redeem', 'sailwp-ai-copilot')); ?>';
                        });
                    });
                    input.addEventListener('keydown', function(e){ if (e.key === 'Enter') { e.preventDefault(); btn.click(); } });
                })();
                </script>
            </div>
            <?php endif; ?>

            <?php endif; ?>

            <div class="sailwp-copilot-status sailwp-copilot-status--quiet <?php echo $connected ? 'is-connected' : 'is-disconnected'; ?>">
                <span class="sailwp-copilot-status-dot"></span>
                <?php if ($connected): ?>
                    <?php
                    $ws = SailWP_Copilot_Plugin::get_workspace_id();
                    $sid = SailWP_Copilot_Plugin::get_site_id();
                    if ($ws && $sid) {
                        echo esc_html(sprintf(__('Connected · workspace #%d, site #%d', 'sailwp-ai-copilot'), $ws, $sid));
                    } else {
                        esc_html_e('Connected to SailWP Cloud', 'sailwp-ai-copilot');
                    }
                    ?>
                <?php else: ?>
                    <?php esc_html_e('Basic features work. Paste a coupon code above to unlock everything.', 'sailwp-ai-copilot'); ?>
                <?php endif; ?>
            </div>

            <section class="swcp-capabilities" aria-label="<?php esc_attr_e('What you can do with SailWP Co-pilot', 'sailwp-ai-copilot'); ?>">
                <h3 class="swcp-capabilities__title"><?php esc_html_e('What you can do', 'sailwp-ai-copilot'); ?></h3>
                <div class="swcp-capabilities__grid">
                    <article class="swcp-capability">
                        <div class="swcp-capability__icon" aria-hidden="true">
                            <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a8 8 0 0 1-11.5 7.2L4 21l1.8-5.5A8 8 0 1 1 21 12Z"/></svg>
                        </div>
                        <h4><?php esc_html_e('Talk to your site', 'sailwp-ai-copilot'); ?></h4>
                        <p><?php esc_html_e('Type or speak in plain language. "Make the headline shorter." "Swap the team photo." The co-pilot does it.', 'sailwp-ai-copilot'); ?></p>
                    </article>
                    <article class="swcp-capability">
                        <div class="swcp-capability__icon" aria-hidden="true">
                            <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="m12 2 2.4 5.4L20 9l-4 4 1 6-5-3-5 3 1-6-4-4 5.6-1.6Z"/></svg>
                        </div>
                        <h4><?php esc_html_e('Designed pages', 'sailwp-ai-copilot'); ?></h4>
                        <p><?php esc_html_e('Generate full custom layouts from a description. Refine in chat until the page feels like yours.', 'sailwp-ai-copilot'); ?></p>
                    </article>
                    <article class="swcp-capability">
                        <div class="swcp-capability__icon" aria-hidden="true">
                            <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="5"/><circle cx="12" cy="12" r="1.5" fill="currentColor"/></svg>
                        </div>
                        <h4><?php esc_html_e('Point and edit', 'sailwp-ai-copilot'); ?></h4>
                        <p><?php esc_html_e('Click a block or highlight text on the page. The co-pilot edits exactly that — never the rest.', 'sailwp-ai-copilot'); ?></p>
                    </article>
                    <article class="swcp-capability">
                        <div class="swcp-capability__icon" aria-hidden="true">
                            <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M3 7v6h6"/><path d="M21 17a9 9 0 0 0-15.5-6.2L3 13"/></svg>
                        </div>
                        <h4><?php esc_html_e('Undo, always', 'sailwp-ai-copilot'); ?></h4>
                        <p><?php esc_html_e('Every change is versioned. One click rolls back to any prior state — including before-AI.', 'sailwp-ai-copilot'); ?></p>
                    </article>
                </div>
            </section>

            <?php $this->render_brand_profile_section(); ?>

            <form method="post" action="options.php" class="sailwp-copilot-form">
                <?php settings_fields('sailwp_copilot'); ?>

                <?php
                    $stripe_pro_url  = (string) get_option('sailwp_copilot_stripe_pro_url', '');
                    $newsletter_url  = (string) get_option('sailwp_copilot_newsletter_url', '');
                    $form_endpoint   = (string) get_option('sailwp_copilot_form_endpoint', '');
                ?>
                <div class="sailwp-copilot-card">
                    <h2><?php esc_html_e('Integrations', 'sailwp-ai-copilot'); ?></h2>
                    <p class="description">
                        <?php esc_html_e('Tell us your service URLs once and any pattern you insert will already point at the right place — no manual editing per pattern.', 'sailwp-ai-copilot'); ?>
                    </p>
                    <table class="form-table" role="presentation">
                        <tr>
                            <th scope="row"><label for="sailwp_copilot_stripe_pro_url"><?php esc_html_e('Stripe Payment Link (Pro plan)', 'sailwp-ai-copilot'); ?></label></th>
                            <td>
                                <input type="url" id="sailwp_copilot_stripe_pro_url" name="sailwp_copilot_stripe_pro_url" value="<?php echo esc_attr($stripe_pro_url); ?>" class="regular-text code" placeholder="https://buy.stripe.com/..." />
                                <p class="description">
                                    <?php esc_html_e('Create a Payment Link in your Stripe dashboard. The Pro button in any pricing pattern will use this URL.', 'sailwp-ai-copilot'); ?>
                                </p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="sailwp_copilot_newsletter_url"><?php esc_html_e('Newsletter signup URL', 'sailwp-ai-copilot'); ?></label></th>
                            <td>
                                <input type="url" id="sailwp_copilot_newsletter_url" name="sailwp_copilot_newsletter_url" value="<?php echo esc_attr($newsletter_url); ?>" class="regular-text code" placeholder="https://buttondown.email/api/emails/embed-subscribe/your-name" />
                                <p class="description">
                                    <?php esc_html_e('Your Buttondown embed-subscribe URL, your Mailchimp embed action, or your MailerLite endpoint. The newsletter signup pattern will POST here.', 'sailwp-ai-copilot'); ?>
                                </p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><label for="sailwp_copilot_form_endpoint"><?php esc_html_e('Contact form endpoint', 'sailwp-ai-copilot'); ?></label></th>
                            <td>
                                <input type="text" id="sailwp_copilot_form_endpoint" name="sailwp_copilot_form_endpoint" value="<?php echo esc_attr($form_endpoint); ?>" class="regular-text code" placeholder="https://formspree.io/f/xxxx  —  or  mailto:you@example.com" />
                                <p class="description">
                                    <?php esc_html_e('A Formspree / Basin / Getform endpoint (https://) OR a mailto: address. Contact form patterns will post here.', 'sailwp-ai-copilot'); ?>
                                </p>
                            </td>
                        </tr>
                    </table>
                    <?php submit_button(__('Save integrations', 'sailwp-ai-copilot'), 'primary', 'submit_integrations'); ?>
                </div>

                <details class="sailwp-copilot-details">
                    <summary><?php esc_html_e('Advanced — license &amp; endpoints', 'sailwp-ai-copilot'); ?></summary>
                    <div class="sailwp-copilot-card">
                        <h2><?php esc_html_e('License key', 'sailwp-ai-copilot'); ?></h2>
                        <p class="description">
                            <?php esc_html_e('Auto-issued when you activate the plugin. You normally do not need to touch this.', 'sailwp-ai-copilot'); ?>
                        </p>
                        <table class="form-table" role="presentation">
                            <tr>
                                <th scope="row"><label for="sailwp_copilot_license_key"><?php esc_html_e('License key', 'sailwp-ai-copilot'); ?></label></th>
                                <td><input type="text" id="sailwp_copilot_license_key" name="sailwp_copilot_license_key" value="<?php echo esc_attr($license); ?>" class="regular-text code" placeholder="SW-XXXX-XXXX-XXXX" /></td>
                            </tr>
                            <tr>
                                <th scope="row"><label for="sailwp_copilot_site_api_key"><?php esc_html_e('Site API key', 'sailwp-ai-copilot'); ?></label></th>
                                <td>
                                    <input type="text" id="sailwp_copilot_site_api_key" name="sailwp_copilot_site_api_key" value="<?php echo esc_attr($api_key); ?>" class="regular-text code" placeholder="sw_site_..." readonly />
                                </td>
                            </tr>
                        </table>
                    </div>

                    <div class="sailwp-copilot-card">
                        <h2><?php esc_html_e('Endpoints', 'sailwp-ai-copilot'); ?></h2>
                        <p class="description">
                            <?php esc_html_e('Defaults work for production. Override only for local development.', 'sailwp-ai-copilot'); ?>
                        </p>
                        <table class="form-table" role="presentation">
                            <tr>
                                <th scope="row"><label for="sailwp_copilot_ai_proxy_url"><?php esc_html_e('AI proxy URL', 'sailwp-ai-copilot'); ?></label></th>
                                <td><input type="url" id="sailwp_copilot_ai_proxy_url" name="sailwp_copilot_ai_proxy_url" value="<?php echo esc_attr($proxy_url); ?>" class="regular-text code" placeholder="<?php echo esc_attr(SAILWP_COPILOT_AI_PROXY_DEFAULT); ?>" /></td>
                            </tr>
                            <tr>
                                <th scope="row"><label for="sailwp_copilot_cloud_url"><?php esc_html_e('Cloud dashboard URL', 'sailwp-ai-copilot'); ?></label></th>
                                <td><input type="url" id="sailwp_copilot_cloud_url" name="sailwp_copilot_cloud_url" value="<?php echo esc_attr($cloud_url); ?>" class="regular-text code" placeholder="<?php echo esc_attr(SAILWP_COPILOT_CLOUD_DEFAULT); ?>" /></td>
                            </tr>
                        </table>
                    </div>

                    <?php submit_button(__('Save advanced settings', 'sailwp-ai-copilot')); ?>
                </details>
            </form>

            <details class="sailwp-copilot-card sailwp-copilot-privacy">
                <summary>
                    <span class="swcp-privacy-summary-label"><?php esc_html_e('How your data flows', 'sailwp-ai-copilot'); ?></span>
                    <span class="swcp-privacy-summary-hint"><?php esc_html_e('What goes out, what stays, who sees what.', 'sailwp-ai-copilot'); ?></span>
                </summary>
                <ul>
                    <li><strong><?php esc_html_e('What goes out:', 'sailwp-ai-copilot'); ?></strong> <?php esc_html_e('the page content you ask the co-pilot to work on, the chat messages you type or speak, and any files you attach (text from Word docs, image bytes for photos and screenshots, raw bytes for PDFs).', 'sailwp-ai-copilot'); ?></li>
                    <li><strong><?php esc_html_e('Where it goes:', 'sailwp-ai-copilot'); ?></strong> <?php esc_html_e('first to the SailWP proxy on our server, then to Anthropic (the makers of Claude) for the AI part. Anthropic does not use your data to train models.', 'sailwp-ai-copilot'); ?></li>
                    <li><strong><?php esc_html_e('What we keep:', 'sailwp-ai-copilot'); ?></strong> <?php esc_html_e('a per-call usage log on our proxy (how many tokens, which model, cost) so we can keep the lights on. We also keep your chat history so you can re-open old conversations from any device — max 1 year, then auto-deleted. Page content sent for design jobs is NOT kept beyond the one request it powers.', 'sailwp-ai-copilot'); ?></li>
                    <li><strong><?php esc_html_e('Photos you upload:', 'sailwp-ai-copilot'); ?></strong> <?php esc_html_e('go straight into your own WordPress media library on this site, never to a third-party server.', 'sailwp-ai-copilot'); ?></li>
                    <li><strong><?php esc_html_e('Voice input:', 'sailwp-ai-copilot'); ?></strong> <?php esc_html_e('happens entirely in your browser using the built-in speech recognition. The audio is converted to text locally before anything leaves your computer.', 'sailwp-ai-copilot'); ?></li>
                    <li><strong><?php esc_html_e('Your right to leave:', 'sailwp-ai-copilot'); ?></strong> <?php esc_html_e('uninstall the plugin and the per-call logs tied to your license get deleted. Your media library, content, and revisions stay yours.', 'sailwp-ai-copilot'); ?></li>
                </ul>
                <p>
                    <a href="https://sailwp.com/privacy" target="_blank" rel="noopener noreferrer"><?php esc_html_e('Full privacy policy', 'sailwp-ai-copilot'); ?> →</a>
                    &nbsp;·&nbsp;
                    <a href="https://sailwp.com/terms" target="_blank" rel="noopener noreferrer"><?php esc_html_e('Terms of service', 'sailwp-ai-copilot'); ?> →</a>
                </p>
            </details>
        </div>
        <?php
    }
}
