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

if (class_exists('SailWP_Copilot_Dashboard_Hero')) return;

class SailWP_Copilot_Dashboard_Hero {
    const DISMISS_META    = 'swcp_dashboard_hero_dismissed';
    const ONBOARD_META    = 'swcp_onboarding_steps'; // array of completed step keys
    const BRAND_TAGLINE   = 'sailwp_copilot_brand_tagline'; // site option set during step 1

    public function __construct() {
        add_action('all_admin_notices', [$this, 'render']);
        add_action('wp_ajax_swcp_dismiss_dashboard_hero', [$this, 'handle_dismiss']);
        add_action('wp_ajax_swcp_onboard_step', [$this, 'handle_onboard_step']);
    }

    public function handle_dismiss() {
        if (!current_user_can('edit_posts')) wp_send_json_error(['message' => 'forbidden'], 403);
        check_ajax_referer('swcp_dismiss_hero', '_wpnonce');
        update_user_meta(get_current_user_id(), self::DISMISS_META, 1);
        wp_send_json_success(['dismissed' => true]);
    }

    /**
     * Mark an onboarding step complete (and optionally save the
     * tagline from step 1). Joost 2026-05-17 v0.24.8: 3-step checklist
     * replaces the "blank slate" first-install experience.
     */
    public function handle_onboard_step() {
        if (!current_user_can('edit_posts')) wp_send_json_error(['message' => 'forbidden'], 403);
        check_ajax_referer('swcp_dismiss_hero', '_wpnonce');
        $step = isset($_POST['step']) ? sanitize_key((string) $_POST['step']) : '';
        if (!in_array($step, ['brand', 'integrations', 'firstpage'], true)) {
            wp_send_json_error(['message' => 'unknown_step'], 400);
        }
        $tagline = isset($_POST['tagline']) ? sanitize_text_field((string) $_POST['tagline']) : '';
        if ($step === 'brand' && $tagline !== '') {
            update_option(self::BRAND_TAGLINE, $tagline);
            // Brand profile cache → invalidate so next AI call picks up
            // the new tagline as tone hint.
            if (class_exists('SailWP_Copilot_Brand_Profile')) {
                SailWP_Copilot_Brand_Profile::invalidate();
            }
        }
        $done = (array) get_user_meta(get_current_user_id(), self::ONBOARD_META, true);
        if (!in_array($step, $done, true)) $done[] = $step;
        update_user_meta(get_current_user_id(), self::ONBOARD_META, $done);
        wp_send_json_success(['done' => $done]);
    }

    /**
     * What counts as "onboarded": all 3 steps done OR any integration
     * URL set (heuristic — power users go to Settings directly and
     * shouldn't see the checklist forever). v0.24.8.
     */
    private function onboarding_state() {
        $done = (array) get_user_meta(get_current_user_id(), self::ONBOARD_META, true);
        // Auto-detect step 2 — if any integration URL set, count as done.
        $any_integration = trim((string) get_option('sailwp_copilot_stripe_pro_url', '')) !== ''
            || trim((string) get_option('sailwp_copilot_newsletter_url', '')) !== ''
            || trim((string) get_option('sailwp_copilot_form_endpoint', '')) !== '';
        if ($any_integration && !in_array('integrations', $done, true)) $done[] = 'integrations';
        // Auto-detect step 1 — if a tagline option exists OR brand
        // overrides have a tone sample, count as done.
        if (trim((string) get_option(self::BRAND_TAGLINE, '')) !== '' && !in_array('brand', $done, true)) {
            $done[] = 'brand';
        }
        return [
            'done'       => $done,
            'all_done'   => count(array_intersect(['brand', 'integrations', 'firstpage'], $done)) === 3,
        ];
    }

    public function render() {
        if (!is_admin()) return;
        $screen = function_exists('get_current_screen') ? get_current_screen() : null;
        if (!$screen || $screen->id !== 'dashboard') return;
        if (!current_user_can('edit_posts')) return;
        if ((int) get_user_meta(get_current_user_id(), self::DISMISS_META, true) === 1) return;

        // Onboarding state decides what to render. New installers get the
        // 3-step checklist; once all done OR they've engaged enough that
        // the checklist would feel patronising, we fall through to the
        // regular hero. v0.24.8 (Joost 2026-05-17).
        $onboard = $this->onboarding_state();
        if (!$onboard['all_done']) {
            $this->render_onboarding($onboard['done']);
            return;
        }

        // All 3 onboarding steps done — keep the same cream boat-card,
        // morph the content from spotlight-steps to "ready, what shall we
        // change today?" chips. Visual continuity. v0.25.11 (Joost 2026-05-18).
        $this->render_ready();
        return;

        $icon_url     = SAILWP_COPILOT_URL . 'assets/img/sailwp-icon.png';
        $settings_url = admin_url('options-general.php?page=sailwp-copilot');
        $home_url     = home_url('/');
        $is_pro       = SailWP_Copilot_Plugin::is_pro();
        $nonce        = wp_create_nonce('swcp_dismiss_hero');
        ?>
        <div class="swcp-dash-spotlight" data-swcp-spotlight aria-hidden="true"></div>
        <div class="swcp-dash-hero" role="region" aria-label="SailWP AI Co-pilot">
            <button type="button" class="swcp-dash-hero__dismiss" data-swcp-dismiss aria-label="Dismiss this welcome card" title="Dismiss">
                <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true">
                    <path d="M3 3 L11 11 M11 3 L3 11" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/>
                </svg>
            </button>
            <div class="swcp-dash-hero__inner">
                <div class="swcp-dash-hero__icon" aria-hidden="true">
                    <img src="<?php echo esc_url($icon_url); ?>" alt="" />
                </div>
                <div class="swcp-dash-hero__body">
                    <div class="swcp-dash-hero__eyebrow">
                        SailWP AI Co-pilot
                        <?php if ($is_pro): ?>
                            <span class="swcp-dash-hero__badge swcp-dash-hero__badge--pro">Pro</span>
                        <?php else: ?>
                            <span class="swcp-dash-hero__badge">Free</span>
                        <?php endif; ?>
                    </div>
                    <h2 class="swcp-dash-hero__title">Your site has an AI co-pilot.</h2>
                    <p class="swcp-dash-hero__lede">
                        Open the rail on the right and ask, in plain language, for the change you want.
                        Pages, blocks, headlines, images, buttons &mdash; the co-pilot edits them directly,
                        with previews and one-click undo.
                    </p>
                    <ul class="swcp-dash-hero__chips">
                        <li><button type="button" class="swcp-dash-hero__chip" data-swcp-prefill="Rewrite the homepage hero shorter and warmer.">&ldquo;Rewrite the homepage hero shorter and warmer.&rdquo;</button></li>
                        <li><button type="button" class="swcp-dash-hero__chip" data-swcp-prefill="Change the primary button label to &quot;Book a call&quot;.">&ldquo;Change the primary button to <em>Book a call</em>.&rdquo;</button></li>
                        <li><button type="button" class="swcp-dash-hero__chip" data-swcp-prefill="Replace the team photo with something neutral.">&ldquo;Replace the team photo with something neutral.&rdquo;</button></li>
                    </ul>
                    <div class="swcp-dash-hero__actions">
                        <button type="button" class="swcp-dash-hero__btn swcp-dash-hero__btn--primary" data-swcp-open-rail>
                            Open Co-pilot
                        </button>
                        <a class="swcp-dash-hero__btn swcp-dash-hero__btn--ghost" href="<?php echo esc_url($home_url); ?>" target="_blank" rel="noopener">
                            View your site
                        </a>
                        <a class="swcp-dash-hero__btn swcp-dash-hero__btn--ghost" href="<?php echo esc_url($settings_url); ?>">
                            Settings
                        </a>
                    </div>
                </div>
            </div>
        </div>
        <style>
            /* Spotlight: dim everything else on the dashboard so the hero is
               unambiguously the thing to look at. Cleared the moment the user
               clicks anywhere (see script below) — one-time attention grab,
               not a persistent annoyance. */
            body.swcp-dash-spotlit #wpwrap > #wpcontent #wpbody-content > *:not(.swcp-dash-spotlight):not(.swcp-dash-hero) {
                opacity: 0.35;
                filter: saturate(0.6);
                transition: opacity 0.25s ease, filter 0.25s ease;
                pointer-events: none;
            }
            body.swcp-dash-spotlit #adminmenumain,
            body.swcp-dash-spotlit #wpadminbar {
                opacity: 0.55;
                transition: opacity 0.25s ease;
            }
            .swcp-dash-spotlight {
                position: fixed;
                inset: 0;
                background: radial-gradient(circle at 50% 18%, transparent 0, transparent 280px, rgba(15, 12, 30, 0.55) 720px, rgba(15, 12, 30, 0.7) 100%);
                opacity: 0;
                pointer-events: none;
                z-index: 1;
                transition: opacity 0.25s ease;
            }
            body.swcp-dash-spotlit .swcp-dash-spotlight {
                opacity: 1;
            }
            .swcp-dash-hero {
                margin: 16px 20px 24px 2px;
                /* Joost 2026-05-17: was dark-navy + purple gradient, felt
                   "te dominant en intens". Now: warm cream wash with a soft
                   coral edge — present without being aggressive. Same
                   shape as WP's own welcome panel. */
                background: linear-gradient(135deg, #fdf6ec 0%, #f8ebd9 70%, #f1dcc0 100%);
                color: #1a1a2e;
                border-radius: 14px;
                border: 1px solid rgba(232, 132, 92, 0.18);
                box-shadow: 0 8px 22px rgba(232, 132, 92, 0.12), 0 1px 3px rgba(26, 26, 46, 0.04);
                overflow: hidden;
                position: relative;
                z-index: 2;
            }
            .swcp-dash-hero__dismiss {
                position: absolute;
                top: 10px;
                right: 10px;
                width: 28px;
                height: 28px;
                padding: 0;
                background: transparent;
                color: rgba(26, 26, 46, 0.45);
                border: none;
                border-radius: 50%;
                cursor: pointer;
                display: inline-flex;
                align-items: center;
                justify-content: center;
                z-index: 3;
                transition: background 0.12s ease, color 0.12s ease;
            }
            .swcp-dash-hero__dismiss:hover {
                background: rgba(26, 26, 46, 0.06);
                color: #1a1a2e;
            }
            .swcp-dash-hero__dismiss svg { display: block; }
            body.swcp-dash-spotlit .swcp-dash-hero {
                box-shadow:
                    0 0 0 1px rgba(232, 132, 92, 0.55),
                    0 0 30px 6px rgba(232, 132, 92, 0.45),
                    0 0 80px 20px rgba(232, 132, 92, 0.25),
                    0 10px 30px rgba(26, 26, 46, 0.35);
                animation: swcp-dash-hero-pulse 2.4s ease-in-out infinite;
                opacity: 1 !important;
                filter: none !important;
                pointer-events: auto !important;
            }
            @keyframes swcp-dash-hero-pulse {
                0%, 100% {
                    box-shadow:
                        0 0 0 1px rgba(232, 132, 92, 0.55),
                        0 0 30px 6px rgba(232, 132, 92, 0.45),
                        0 0 80px 20px rgba(232, 132, 92, 0.25),
                        0 10px 30px rgba(26, 26, 46, 0.35);
                }
                50% {
                    box-shadow:
                        0 0 0 1px rgba(232, 132, 92, 0.75),
                        0 0 40px 10px rgba(232, 132, 92, 0.6),
                        0 0 110px 28px rgba(232, 132, 92, 0.32),
                        0 10px 30px rgba(26, 26, 46, 0.35);
                }
            }
            @media (prefers-reduced-motion: reduce) {
                body.swcp-dash-spotlit .swcp-dash-hero { animation: none; }
            }
            .swcp-dash-hero::before {
                content: "";
                position: absolute;
                inset: 0;
                background:
                    radial-gradient(800px 200px at -10% -40%, rgba(232, 132, 92, 0.35), transparent 60%),
                    radial-gradient(600px 200px at 110% 130%, rgba(232, 184, 122, 0.22), transparent 60%);
                pointer-events: none;
            }
            .swcp-dash-hero__inner {
                position: relative;
                display: flex;
                gap: 22px;
                padding: 26px 30px;
                align-items: flex-start;
            }
            .swcp-dash-hero__icon img {
                width: 56px;
                height: 56px;
                display: block;
                filter: drop-shadow(0 2px 8px rgba(0,0,0,0.25));
            }
            .swcp-dash-hero__body { flex: 1; min-width: 0; }
            .swcp-dash-hero__eyebrow {
                font-size: 12px;
                letter-spacing: 0.08em;
                text-transform: uppercase;
                font-weight: 600;
                color: #e8b87a;
                display: flex;
                align-items: center;
                gap: 10px;
            }
            /* Light palette: cream bg + dark text. Joost 2026-05-17. */
            .swcp-dash-hero__eyebrow { color: #c4593a; }
            .swcp-dash-hero__badge {
                display: inline-block;
                padding: 2px 8px;
                border-radius: 999px;
                font-size: 10px;
                letter-spacing: 0.06em;
                background: rgba(26, 26, 46, 0.08);
                color: #1a1a2e;
                text-transform: uppercase;
            }
            .swcp-dash-hero__badge--pro {
                background: #e8845c;
                color: #ffffff;
            }
            .swcp-dash-hero__title {
                margin: 6px 0 8px;
                font-size: 26px;
                line-height: 1.15;
                font-weight: 700;
                color: #1a1a2e;
            }
            .swcp-dash-hero__lede {
                margin: 0 0 14px;
                font-size: 14px;
                line-height: 1.55;
                color: rgba(26, 26, 46, 0.72);
                max-width: 760px;
            }
            .swcp-dash-hero__chips {
                list-style: none;
                margin: 0 0 18px;
                padding: 0;
                display: flex;
                flex-wrap: wrap;
                gap: 8px;
            }
            .swcp-dash-hero__chips li { line-height: 0; }
            .swcp-dash-hero__chip {
                appearance: none;
                font: inherit;
                font-size: 12.5px;
                line-height: 1.4;
                background: rgba(255, 255, 255, 0.65);
                border: 1px solid rgba(26, 26, 46, 0.12);
                color: rgba(26, 26, 46, 0.85);
                padding: 6px 12px;
                border-radius: 999px;
                cursor: pointer;
                transition: background-color 0.15s ease, border-color 0.15s ease, transform 0.08s ease;
            }
            .swcp-dash-hero__chip:hover,
            .swcp-dash-hero__chip:focus-visible {
                background: rgba(232, 132, 92, 0.14);
                border-color: rgba(232, 132, 92, 0.45);
                color: #1a1a2e;
                outline: none;
                transform: translateY(-1px);
            }
            .swcp-dash-hero__chip em { font-style: italic; color: inherit; }
            .swcp-dash-hero__actions { display: flex; gap: 10px; flex-wrap: wrap; }
            .swcp-dash-hero__btn {
                display: inline-flex;
                align-items: center;
                justify-content: center;
                padding: 9px 16px;
                border-radius: 10px;
                font-size: 13px;
                font-weight: 600;
                text-decoration: none;
                cursor: pointer;
                border: 1px solid transparent;
                transition: transform 0.08s ease, background-color 0.15s ease, border-color 0.15s ease;
                line-height: 1.2;
            }
            .swcp-dash-hero__btn--primary {
                background: #e8845c;
                color: #ffffff;
                border-color: #e8845c;
            }
            .swcp-dash-hero__btn--primary:hover,
            .swcp-dash-hero__btn--primary:focus {
                background: #d4673c;
                border-color: #d4673c;
                color: #ffffff;
                transform: translateY(-1px);
            }
            .swcp-dash-hero__btn--ghost {
                background: rgba(255, 255, 255, 0.5);
                color: #1a1a2e;
                border-color: rgba(26, 26, 46, 0.14);
            }
            .swcp-dash-hero__btn--ghost:hover,
            .swcp-dash-hero__btn--ghost:focus {
                background: rgba(255, 255, 255, 0.85);
                border-color: rgba(26, 26, 46, 0.25);
                color: #1a1a2e;
            }
            @media (max-width: 720px) {
                .swcp-dash-hero__inner { flex-direction: column; padding: 22px; gap: 14px; }
                .swcp-dash-hero__title { font-size: 22px; }
            }
        </style>
        <script>
            (function(){
                var STORAGE_KEY = 'swcp_dash_spotlight_dismissed';
                var dismissed = false;
                try { dismissed = !!window.localStorage.getItem(STORAGE_KEY); } catch (_) { dismissed = false; }

                // Spotlight is on by default for first-time admins. Engage it
                // briefly after paint so the page isn't flashy on load.
                if (!dismissed) {
                    setTimeout(function(){ document.body.classList.add('swcp-dash-spotlit'); }, 200);
                }

                function dismissSpotlight() {
                    if (!document.body.classList.contains('swcp-dash-spotlit')) return;
                    document.body.classList.remove('swcp-dash-spotlit');
                    try { window.localStorage.setItem(STORAGE_KEY, '1'); } catch (_) {}
                }

                function openRail() {
                    var rail = document.getElementById('sailwp-copilot-rail');
                    if (!rail) return null;
                    // The rail is a self-mounted React-ish island; it watches
                    // its own data-collapsed attribute and re-renders. Click
                    // the boat-icon toggle if present (handles transitions
                    // cleanly); otherwise flip the attribute as a fallback.
                    var toggle = rail.querySelector('.sw-rail-toggle');
                    if (toggle && rail.getAttribute('data-collapsed') !== 'false') {
                        toggle.click();
                    } else {
                        rail.setAttribute('data-collapsed', 'false');
                    }
                    return rail;
                }

                function openRailWithText(text) {
                    var rail = openRail();
                    if (!rail) return;
                    // Wait one paint cycle for the panel to expand before
                    // we touch the textarea — otherwise focus() lands on a
                    // hidden element and the user sees nothing happen.
                    setTimeout(function () {
                        var ta = rail.querySelector('.sw-rail-composer textarea');
                        if (!ta) return;
                        ta.value = text;
                        try {
                            ta.dispatchEvent(new Event('input', { bubbles: true }));
                            ta.dispatchEvent(new Event('change', { bubbles: true }));
                        } catch (_) {}
                        try {
                            ta.focus();
                            ta.setSelectionRange(text.length, text.length);
                        } catch (_) {}
                    }, 80);
                }

                document.addEventListener('click', function(e){
                    var t = e.target;
                    if (!t || !t.closest) return;

                    // Permanent dismiss — × button. Persists per-user via
                    // user_meta so the hero stays gone on next dashboard
                    // load. Joost 2026-05-17.
                    var dismissBtn = t.closest('[data-swcp-dismiss]');
                    if (dismissBtn) {
                        e.preventDefault();
                        var hero = document.querySelector('.swcp-dash-hero');
                        if (hero) {
                            hero.style.transition = 'opacity 180ms ease, transform 180ms ease';
                            hero.style.opacity = '0';
                            hero.style.transform = 'translateY(-6px)';
                            setTimeout(function(){ hero.remove(); }, 200);
                        }
                        var spot = document.querySelector('.swcp-dash-spotlight');
                        if (spot) spot.remove();
                        document.body.classList.remove('swcp-dash-spotlit');
                        // Fire-and-forget AJAX — don't block UX on it.
                        try {
                            var fd = new FormData();
                            fd.append('action', 'swcp_dismiss_dashboard_hero');
                            fd.append('_wpnonce', <?php echo wp_json_encode($nonce); ?>);
                            fetch(ajaxurl, { method: 'POST', credentials: 'same-origin', body: fd }).catch(function(){});
                        } catch (_) {}
                        return;
                    }

                    // Any click on the page lifts the spotlight — engagement
                    // is enough. We don't want this following the user across
                    // their day.
                    if (document.body.classList.contains('swcp-dash-spotlit')) {
                        dismissSpotlight();
                    }

                    var chip = t.closest('[data-swcp-prefill]');
                    if (chip) {
                        e.preventDefault();
                        openRailWithText(chip.getAttribute('data-swcp-prefill') || '');
                        return;
                    }

                    var trigger = t.closest('[data-swcp-open-rail]');
                    if (trigger) {
                        e.preventDefault();
                        openRail();
                    }
                });
            })();
        </script>
        <?php
    }

    /**
     * Post-onboarding "ready" state — same cream boat-card as onboarding,
     * different content: prompt chips that prefill the rail composer.
     * Boat stays on the right, content morphs on the left. Joost 2026-05-18
     * v0.25.11.
     */
    private function render_ready() {
        $nonce       = wp_create_nonce('swcp_dismiss_hero');
        $boat_url    = SAILWP_COPILOT_URL . 'assets/img/sailwp-sailboat.png';
        $is_pro      = SailWP_Copilot_Plugin::is_pro();
        $user        = wp_get_current_user();
        $first_name  = '';
        if ($user->first_name) {
            $first_name = explode(' ', trim($user->first_name))[0];
        } elseif ($user->display_name && strcasecmp($user->display_name, $user->user_login) !== 0) {
            $first_name = explode(' ', trim($user->display_name))[0];
        }
        $greeting_pre = $first_name ? 'Welcome back, ' . $first_name . '.' : 'Welcome back.';

        // Brand tagline (set during onboarding step 1) personalises the chips.
        $tagline = trim((string) get_option(self::BRAND_TAGLINE, ''));

        $chips = [
            'Redesign my homepage',
            'Add a contact page',
            'Write an about page',
            'Change my logo',
        ];
        ?>
        <div class="swcp-dash-hero swcp-onboard swcp-ready" role="region" aria-label="SailWP Co-pilot">
            <button type="button" class="swcp-dash-hero__dismiss" data-swcp-dismiss aria-label="Dismiss" title="Dismiss">
                <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true">
                    <path d="M3 3 L11 11 M11 3 L3 11" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/>
                </svg>
            </button>
            <div class="swcp-onboard__cols">
                <div class="swcp-onboard__steps-col">
                    <div class="swcp-ready__inner">
                        <div class="swcp-spot__eyebrow">
                            <?php echo esc_html($greeting_pre); ?>
                            <?php if ($is_pro): ?><span class="swcp-ready__plan">CO-PILOT PRO</span><?php endif; ?>
                        </div>
                        <h2 class="swcp-spot__title">What shall we change today?</h2>
                        <?php if ($tagline): ?>
                            <p class="swcp-spot__lede">Your co-pilot knows: &ldquo;<?php echo esc_html($tagline); ?>&rdquo;. Pick one or just type.</p>
                        <?php else: ?>
                            <p class="swcp-spot__lede">Pick one of these, or open the rail and ask anything in plain language.</p>
                        <?php endif; ?>
                        <ul class="swcp-ready__chips">
                            <?php foreach ($chips as $c): ?>
                                <li><button type="button" class="swcp-ready__chip" data-swcp-prefill="<?php echo esc_attr($c); ?>"><?php echo esc_html($c); ?></button></li>
                            <?php endforeach; ?>
                        </ul>
                        <div class="swcp-ready__actions">
                            <button type="button" class="swcp-dash-hero__btn swcp-dash-hero__btn--primary" data-swcp-open-rail>Open Co-pilot</button>
                            <a class="swcp-ready__link" href="<?php echo esc_url(home_url('/')); ?>" target="_blank" rel="noopener">View your site &rarr;</a>
                        </div>
                    </div>
                </div>
                <div class="swcp-onboard__boat-col" aria-hidden="true">
                    <img class="swcp-onboard__boat" src="<?php echo esc_url($boat_url); ?>" alt="" />
                </div>
            </div>
        </div>
        <style>
            /* Base cream boat-card (shared with render_onboarding — duplicated
               here so the ready state can be standalone). */
            .swcp-onboard.swcp-ready {
                margin: 16px 20px 24px 2px;
                background: linear-gradient(135deg, #fdf6ec 0%, #f8ebd9 70%, #f1dcc0 100%);
                color: #1a1a2e;
                border-radius: 14px;
                border: 1px solid rgba(232, 132, 92, 0.18);
                box-shadow: 0 8px 22px rgba(232, 132, 92, 0.12);
                padding: 22px 28px 22px;
                position: relative;
                z-index: 2;
                font-family: 'DM Sans', -apple-system, BlinkMacSystemFont, sans-serif;
                overflow: hidden;
            }
            .swcp-ready .swcp-dash-hero__dismiss {
                position: absolute; top: 10px; right: 10px; width: 28px; height: 28px;
                padding: 0; background: transparent; color: rgba(26,26,46,0.45);
                border: none; border-radius: 50%; cursor: pointer;
                display: inline-flex; align-items: center; justify-content: center; z-index: 3;
                transition: background 0.12s ease, color 0.12s ease;
            }
            .swcp-ready .swcp-dash-hero__dismiss:hover { background: rgba(26,26,46,0.06); color: #1a1a2e; }
            .swcp-ready .swcp-onboard__cols {
                display: flex; gap: 24px; align-items: center;
            }
            .swcp-ready .swcp-onboard__steps-col { flex: 2 1 0; min-width: 0; }
            .swcp-ready .swcp-onboard__boat-col {
                flex: 0 0 220px;
                display: flex; align-items: center; justify-content: center;
                position: relative;
            }
            .swcp-ready .swcp-onboard__boat {
                width: 220px; max-width: 100%; height: auto; display: block;
                filter: drop-shadow(0 12px 28px rgba(232, 132, 92, 0.2));
                animation: swcp-ready-boat-bob 4.2s ease-in-out infinite;
            }
            @keyframes swcp-ready-boat-bob {
                0%   { transform: translateY(0)    rotate(-2deg); }
                50%  { transform: translateY(-7px) rotate(2deg); }
                100% { transform: translateY(0)    rotate(-2deg); }
            }
            @media (max-width: 900px) {
                .swcp-ready .swcp-onboard__boat-col { display: none; }
            }
            @media (prefers-reduced-motion: reduce) {
                .swcp-ready .swcp-onboard__boat { animation: none; }
            }

            .swcp-ready .swcp-spot__eyebrow {
                font-size: 11px; letter-spacing: 0.1em; text-transform: uppercase;
                font-weight: 600; color: #c4593a; margin-bottom: 6px;
            }
            .swcp-ready .swcp-spot__title {
                margin: 0 0 6px; font-size: 26px; line-height: 1.2; font-weight: 700;
                letter-spacing: -0.01em; color: #1a1a2e;
            }
            .swcp-ready .swcp-spot__lede {
                margin: 0 0 4px; font-size: 14px; line-height: 1.55;
                color: rgba(26,26,46,0.7); max-width: 640px;
            }
            .swcp-ready__inner { padding: 6px 4px 0; }
            .swcp-ready__plan {
                margin-left: 10px; padding: 2px 8px;
                background: #e8845c; color: #fff;
                font-size: 10px; letter-spacing: 0.08em; border-radius: 999px;
                vertical-align: middle;
            }
            .swcp-ready__chips {
                list-style: none; margin: 14px 0 18px; padding: 0;
                display: flex; flex-wrap: wrap; gap: 8px;
            }
            .swcp-ready__chip {
                appearance: none; font: inherit; font-size: 13px; font-family: inherit;
                padding: 9px 14px;
                background: rgba(255, 255, 255, 0.7);
                border: 1px solid rgba(26, 26, 46, 0.12);
                color: #1a1a2e;
                border-radius: 999px;
                cursor: pointer;
                transition: background 0.15s ease, border-color 0.15s ease, transform 0.08s ease;
            }
            .swcp-ready__chip:hover,
            .swcp-ready__chip:focus-visible {
                background: rgba(232, 132, 92, 0.14);
                border-color: rgba(232, 132, 92, 0.45);
                outline: none;
                transform: translateY(-1px);
            }
            .swcp-ready__actions {
                display: flex; align-items: center; gap: 16px; flex-wrap: wrap;
            }
            .swcp-ready__link {
                font-size: 13px; color: rgba(26, 26, 46, 0.7);
                text-decoration: none;
            }
            .swcp-ready__link:hover, .swcp-ready__link:focus { color: #c4593a; }
            .swcp-ready .swcp-dash-hero__btn {
                display: inline-flex; align-items: center; justify-content: center;
                padding: 10px 18px; border-radius: 10px; font-size: 14px; font-weight: 600;
                text-decoration: none; cursor: pointer; border: 1px solid transparent;
                transition: transform 0.08s ease, background-color 0.15s ease;
                line-height: 1.2; font-family: inherit;
            }
            .swcp-ready .swcp-dash-hero__btn--primary { background: #e8845c; color: #fff; border-color: #e8845c; }
            .swcp-ready .swcp-dash-hero__btn--primary:hover { background: #d4673c; border-color: #d4673c; color: #fff; transform: translateY(-1px); }
        </style>
        <script>
            (function () {
                var NONCE = <?php echo wp_json_encode($nonce); ?>;
                // Dismiss
                document.addEventListener('click', function (e) {
                    var dismiss = e.target.closest && e.target.closest('[data-swcp-dismiss]');
                    if (dismiss && e.target.closest('.swcp-ready')) {
                        e.preventDefault();
                        var hero = document.querySelector('.swcp-ready');
                        if (hero) { hero.style.transition = 'opacity .18s'; hero.style.opacity = '0'; setTimeout(function () { hero.remove(); }, 200); }
                        var fd = new FormData();
                        fd.append('action', 'swcp_dismiss_dashboard_hero');
                        fd.append('_wpnonce', NONCE);
                        fetch(ajaxurl, { method: 'POST', credentials: 'same-origin', body: fd }).catch(function(){});
                    }
                });
                // Chip prefill / Open Co-pilot — open the rail and put the
                // chip text in the composer.
                function openRailWithText(text) {
                    var rail = document.getElementById('sailwp-copilot-rail');
                    if (!rail) return;
                    var toggle = rail.querySelector('.sw-rail-toggle');
                    if (toggle && rail.getAttribute('data-collapsed') !== 'false') toggle.click();
                    else rail.setAttribute('data-collapsed', 'false');
                    if (!text) return;
                    setTimeout(function () {
                        var ta = rail.querySelector('.sw-rail-composer textarea');
                        if (!ta) return;
                        ta.value = text;
                        try { ta.dispatchEvent(new Event('input', { bubbles: true })); ta.focus(); ta.setSelectionRange(text.length, text.length); } catch (_) {}
                    }, 120);
                }
                document.addEventListener('click', function (e) {
                    var chip = e.target.closest && e.target.closest('.swcp-ready__chip');
                    if (chip) {
                        e.preventDefault();
                        openRailWithText(chip.getAttribute('data-swcp-prefill') || '');
                        return;
                    }
                    var openBtn = e.target.closest && e.target.closest('.swcp-ready [data-swcp-open-rail]');
                    if (openBtn) {
                        e.preventDefault();
                        openRailWithText('');
                    }
                });
            })();
        </script>
        <?php
    }

    /**
     * 3-step welcome checklist — spotlight layout. One step at a time is
     * expanded as a hero (active step), the other two collapse to a thin
     * row showing the number + title (so the user always knows what's
     * coming). Done steps stay in line with a checkmark for the sense of
     * progress. Joost 2026-05-18 v0.25.8.
     */
    private function render_onboarding($done) {
        $nonce        = wp_create_nonce('swcp_dismiss_hero');
        $settings_url = admin_url('options-general.php?page=sailwp-copilot');
        $is_done      = function ($k) use ($done) { return in_array($k, $done, true); };
        $order        = ['brand', 'integrations', 'firstpage'];

        // First-undone step gets the spotlight. If all done, the parent
        // render() flow would have skipped this function entirely.
        $active = null;
        foreach ($order as $k) { if (!$is_done($k)) { $active = $k; break; } }
        if ($active === null) $active = end($order);

        // Step 3 copy adapts to whether the user already has pages. Fresh
        // installs default to "Sample Page" (1 published) — only > 1 means
        // they've actually built something. Suppress fatal if counts fail.
        $page_counts = function_exists('wp_count_posts') ? wp_count_posts('page') : null;
        $has_real_pages = $page_counts && isset($page_counts->publish) && (int) $page_counts->publish > 1;
        $firstpage_title = $has_real_pages ? 'Design a new page' : 'Build your first page';
        $firstpage_lede  = $has_real_pages
            ? 'Open the chat rail and tell the Co-pilot what to design. About, services, a landing page — anything.'
            : 'Open the chat rail and ask the Co-pilot to design something for you. A homepage is a good first try.';
        $firstpage_btn   = $has_real_pages ? 'Open Co-pilot &amp; design a page' : 'Open Co-pilot &amp; redesign my homepage';
        $firstpage_prefill = $has_real_pages
            ? 'Please design a new page for me.'
            : 'Please redesign my homepage with a fresh, modern look.';

        $steps = [
            'brand' => [
                'num'   => 1,
                'title' => 'Tell us about your site',
                'lede'  => 'One sentence about what you do. We use it so the AI matches your voice from the first reply.',
            ],
            'integrations' => [
                'num'   => 2,
                'title' => 'Hook up your services',
                'lede'  => 'Drop in your Stripe Payment Link, Mailchimp / Buttondown URL, or Formspree endpoint — once. Any pattern you insert later auto-uses them.',
            ],
            'firstpage' => [
                'num'   => 3,
                'title' => $firstpage_title,
                'lede'  => $firstpage_lede,
            ],
        ];

        $check_svg = '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true"><path d="M3 7 L6 10 L11 4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';
        $boat_url  = SAILWP_COPILOT_URL . 'assets/img/sailwp-sailboat.png';
        ?>
        <div class="swcp-dash-hero swcp-onboard" role="region" aria-label="SailWP Co-pilot setup">
            <button type="button" class="swcp-dash-hero__dismiss" data-swcp-dismiss aria-label="Skip onboarding" title="Skip onboarding">
                <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true">
                    <path d="M3 3 L11 11 M11 3 L3 11" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/>
                </svg>
            </button>

            <div class="swcp-onboard__cols">
            <div class="swcp-onboard__steps-col">
            <?php foreach ($order as $key):
                $s        = $steps[$key];
                $done_s   = $is_done($key);
                $active_s = ($key === $active);
                $state    = $done_s ? 'is-done' : ($active_s ? 'is-active' : 'is-upcoming');
            ?>
            <div class="swcp-spot__step <?php echo esc_attr($state); ?>" data-swcp-step="<?php echo esc_attr($key); ?>">
                <span class="swcp-spot__num" aria-hidden="true">
                    <?php echo $done_s ? $check_svg : (int) $s['num']; ?>
                </span>
                <div class="swcp-spot__body">
                    <?php if ($active_s): ?>
                        <div class="swcp-spot__eyebrow">Let&rsquo;s get your co-pilot ready</div>
                        <h2 class="swcp-spot__title"><?php echo esc_html($s['title']); ?></h2>
                        <p class="swcp-spot__lede"><?php echo esc_html($s['lede']); ?></p>
                        <?php if ($key === 'brand'): ?>
                            <form data-swcp-onboard-form="brand" class="swcp-spot__form">
                                <input type="text" name="tagline" placeholder='e.g. "Calm yoga studio in Utrecht, since 2019"' required maxlength="160" autofocus />
                                <button type="submit" class="swcp-dash-hero__btn swcp-dash-hero__btn--primary">Save</button>
                            </form>
                        <?php elseif ($key === 'integrations'): ?>
                            <div class="swcp-spot__actions">
                                <a class="swcp-dash-hero__btn swcp-dash-hero__btn--primary" href="<?php echo esc_url($settings_url); ?>#integrations" data-swcp-onboard-mark="integrations">Open integrations</a>
                                <a class="swcp-dash-hero__btn swcp-dash-hero__btn--ghost" href="#" data-swcp-onboard-skip="integrations">Skip for now</a>
                            </div>
                        <?php elseif ($key === 'firstpage'): ?>
                            <div class="swcp-spot__actions">
                                <button type="button" class="swcp-dash-hero__btn swcp-dash-hero__btn--primary" data-swcp-onboard-firstpage data-swcp-firstpage-prefill="<?php echo esc_attr($firstpage_prefill); ?>"><?php echo wp_kses($firstpage_btn, ['amp' => []]); ?></button>
                            </div>
                        <?php endif; ?>
                    <?php else: ?>
                        <span class="swcp-spot__row-title"><?php echo esc_html($s['title']); ?></span>
                        <span class="swcp-spot__row-hint"><?php
                            if ($done_s) echo 'Done';
                            else echo $s['num'] > $steps[$active]['num'] ? 'Next' : 'Pending';
                        ?></span>
                    <?php endif; ?>
                </div>
            </div>
            <?php endforeach; ?>
            </div>
            <div class="swcp-onboard__boat-col" aria-hidden="true">
                <img class="swcp-onboard__boat" src="<?php echo esc_url($boat_url); ?>" alt="" />
            </div>
            </div>
        </div>
        <style>
            .swcp-onboard {
                margin: 16px 20px 24px 2px;
                background: linear-gradient(135deg, #fdf6ec 0%, #f8ebd9 70%, #f1dcc0 100%);
                color: #1a1a2e;
                border-radius: 14px;
                border: 1px solid rgba(232, 132, 92, 0.18);
                box-shadow: 0 8px 22px rgba(232, 132, 92, 0.12);
                padding: 22px 28px 16px;
                position: relative;
                z-index: 2;
                font-family: 'DM Sans', -apple-system, BlinkMacSystemFont, sans-serif;
                overflow: hidden;
            }
            .swcp-onboard__cols {
                display: flex; gap: 24px; align-items: stretch;
            }
            .swcp-onboard__steps-col { flex: 2 1 0; min-width: 0; }
            .swcp-onboard__boat-col {
                flex: 1 1 0; min-width: 200px;
                display: flex; align-items: center; justify-content: center;
                position: relative;
            }
            .swcp-onboard__boat {
                width: 100%; max-width: 260px; height: auto; display: block;
                filter: drop-shadow(0 12px 28px rgba(232, 132, 92, 0.2));
                animation: swcp-onboard-boat-bob 4.2s ease-in-out infinite;
            }
            @keyframes swcp-onboard-boat-bob {
                0%   { transform: translateY(0)    rotate(-2.5deg); }
                50%  { transform: translateY(-8px) rotate(2.5deg); }
                100% { transform: translateY(0)    rotate(-2.5deg); }
            }
            @media (max-width: 900px) {
                .swcp-onboard__boat-col { display: none; }
            }
            @media (prefers-reduced-motion: reduce) {
                .swcp-onboard__boat { animation: none; }
            }
            .swcp-onboard .swcp-dash-hero__dismiss {
                position: absolute; top: 10px; right: 10px; width: 28px; height: 28px;
                padding: 0; background: transparent; color: rgba(26,26,46,0.45);
                border: none; border-radius: 50%; cursor: pointer;
                display: inline-flex; align-items: center; justify-content: center; z-index: 3;
                transition: background 0.12s ease, color 0.12s ease;
            }
            .swcp-onboard .swcp-dash-hero__dismiss:hover { background: rgba(26,26,46,0.06); color: #1a1a2e; }

            .swcp-spot__step {
                display: flex; gap: 16px; align-items: flex-start;
                padding: 12px 4px;
                transition: opacity 0.25s ease, padding 0.25s ease;
            }
            .swcp-spot__step + .swcp-spot__step {
                border-top: 1px solid rgba(26, 26, 46, 0.07);
            }
            .swcp-spot__step.is-active { padding: 18px 4px 22px; }
            .swcp-spot__step.is-done { opacity: 0.55; }

            .swcp-spot__num {
                flex-shrink: 0; width: 30px; height: 30px;
                background: rgba(255, 255, 255, 0.7);
                border: 1.5px solid rgba(26, 26, 46, 0.16);
                border-radius: 50%;
                display: inline-flex; align-items: center; justify-content: center;
                font-size: 13px; font-weight: 600; color: rgba(26, 26, 46, 0.55);
                margin-top: 2px;
                transition: background 0.2s ease, border-color 0.2s ease, color 0.2s ease;
            }
            .swcp-spot__step.is-active .swcp-spot__num {
                background: #e8845c; border-color: #e8845c; color: #fff;
                box-shadow: 0 4px 12px rgba(232, 132, 92, 0.3);
            }
            .swcp-spot__step.is-done .swcp-spot__num {
                background: #e8845c; border-color: #e8845c; color: #fff;
            }

            .swcp-spot__body { flex: 1; min-width: 0; }

            /* Active step (spotlight) */
            .swcp-spot__eyebrow {
                font-size: 11px; letter-spacing: 0.1em; text-transform: uppercase;
                font-weight: 600; color: #c4593a; margin-bottom: 6px;
            }
            .swcp-spot__title {
                margin: 0 0 6px; font-size: 26px; line-height: 1.2; font-weight: 700;
                letter-spacing: -0.01em; color: #1a1a2e;
            }
            .swcp-spot__lede {
                margin: 0 0 16px; font-size: 14px; line-height: 1.55;
                color: rgba(26,26,46,0.7); max-width: 640px;
            }

            /* Collapsed (upcoming/done) — thin row */
            .swcp-spot__step.is-upcoming .swcp-spot__body,
            .swcp-spot__step.is-done .swcp-spot__body {
                display: flex; align-items: center; gap: 12px;
                min-height: 30px;
            }
            .swcp-spot__row-title {
                font-size: 14px; font-weight: 500; color: rgba(26,26,46,0.75);
            }
            .swcp-spot__step.is-done .swcp-spot__row-title { text-decoration: line-through; text-decoration-color: rgba(26,26,46,0.3); }
            .swcp-spot__row-hint {
                margin-left: auto;
                font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase;
                font-weight: 600; color: rgba(26,26,46,0.42);
            }

            /* Form + actions */
            .swcp-spot__form { display: flex; gap: 8px; flex-wrap: wrap; }
            .swcp-spot__form input {
                flex: 1 1 320px; min-width: 0; padding: 11px 14px; font: inherit; font-size: 14px;
                background: #ffffff; border: 1px solid rgba(26,26,46,0.16); border-radius: 10px; color: #1a1a2e;
            }
            .swcp-spot__form input:focus { outline: none; border-color: #e8845c; box-shadow: 0 0 0 3px rgba(232,132,92,0.18); }
            .swcp-spot__actions { display: flex; gap: 10px; flex-wrap: wrap; align-items: center; }

            .swcp-onboard .swcp-dash-hero__btn {
                display: inline-flex; align-items: center; justify-content: center;
                padding: 11px 18px; border-radius: 10px; font-size: 14px; font-weight: 600;
                text-decoration: none; cursor: pointer; border: 1px solid transparent;
                transition: transform 0.08s ease, background-color 0.15s ease;
                line-height: 1.2; font-family: inherit;
            }
            .swcp-onboard .swcp-dash-hero__btn--primary { background: #e8845c; color: #fff; border-color: #e8845c; }
            .swcp-onboard .swcp-dash-hero__btn--primary:hover { background: #d4673c; border-color: #d4673c; color: #fff; transform: translateY(-1px); }
            .swcp-onboard .swcp-dash-hero__btn--primary:disabled { background: rgba(232,132,92,0.55); border-color: rgba(232,132,92,0.55); cursor: progress; transform: none; }
            .swcp-onboard .swcp-dash-hero__btn--ghost { background: transparent; color: rgba(26,26,46,0.7); border-color: rgba(26,26,46,0.18); }
            .swcp-onboard .swcp-dash-hero__btn--ghost:hover { background: rgba(255,255,255,0.7); color: #1a1a2e; }

            @media (max-width: 720px) {
                .swcp-onboard { padding: 18px 18px 12px; }
                .swcp-spot__title { font-size: 22px; }
                .swcp-spot__row-hint { display: none; }
            }
            @media (prefers-reduced-motion: reduce) {
                .swcp-spot__step { transition: none; }
            }
        </style>
        <script>
            (function () {
                var NONCE = <?php echo wp_json_encode($nonce); ?>;
                function markStep(step, extra) {
                    var fd = new FormData();
                    fd.append('action', 'swcp_onboard_step');
                    fd.append('_wpnonce', NONCE);
                    fd.append('step', step);
                    if (extra && extra.tagline) fd.append('tagline', extra.tagline);
                    return fetch(ajaxurl, { method: 'POST', credentials: 'same-origin', body: fd })
                        .then(function (r) { return r.json(); });
                }
                function openRailWithText(text) {
                    var rail = document.getElementById('sailwp-copilot-rail');
                    if (!rail) return;
                    var toggle = rail.querySelector('.sw-rail-toggle');
                    if (toggle && rail.getAttribute('data-collapsed') !== 'false') toggle.click();
                    else rail.setAttribute('data-collapsed', 'false');
                    setTimeout(function () {
                        var ta = rail.querySelector('.sw-rail-composer textarea');
                        if (!ta) return;
                        ta.value = text;
                        try { ta.dispatchEvent(new Event('input', { bubbles: true })); ta.focus(); ta.setSelectionRange(text.length, text.length); } catch (_) {}
                    }, 120);
                }
                // Dismiss
                document.addEventListener('click', function (e) {
                    var dismiss = e.target.closest && e.target.closest('[data-swcp-dismiss]');
                    if (dismiss) {
                        e.preventDefault();
                        var hero = document.querySelector('.swcp-dash-hero');
                        if (hero) { hero.style.transition = 'opacity .18s'; hero.style.opacity = '0'; setTimeout(function () { hero.remove(); }, 200); }
                        var fd = new FormData();
                        fd.append('action', 'swcp_dismiss_dashboard_hero');
                        fd.append('_wpnonce', NONCE);
                        fetch(ajaxurl, { method: 'POST', credentials: 'same-origin', body: fd }).catch(function(){});
                        return;
                    }
                    // Step 3 — open rail with prefilled prompt + mark done.
                    // Prefill text comes from the button's data attribute so
                    // we can vary it for users who already have pages.
                    var firstpage = e.target.closest && e.target.closest('[data-swcp-onboard-firstpage]');
                    if (firstpage) {
                        e.preventDefault();
                        var prefill = firstpage.getAttribute('data-swcp-firstpage-prefill') || 'Please design a new page for me.';
                        openRailWithText(prefill);
                        markStep('firstpage').finally(function () { setTimeout(function () { location.reload(); }, 600); });
                        return;
                    }
                    // Step 2 — clicking "Open integrations" marks done (link still navigates)
                    var integrations = e.target.closest && e.target.closest('[data-swcp-onboard-mark="integrations"]');
                    if (integrations) {
                        markStep('integrations'); // fire and forget; user is navigating away
                        return;
                    }
                    // Step 2 skip
                    var skipInt = e.target.closest && e.target.closest('[data-swcp-onboard-skip="integrations"]');
                    if (skipInt) {
                        e.preventDefault();
                        markStep('integrations').finally(function () { location.reload(); });
                        return;
                    }
                });
                // Step 1 — tagline form
                document.querySelectorAll('[data-swcp-onboard-form="brand"]').forEach(function (form) {
                    form.addEventListener('submit', function (e) {
                        e.preventDefault();
                        var input = form.querySelector('input[name="tagline"]');
                        var val = (input && input.value || '').trim();
                        if (!val) { input && input.focus(); return; }
                        var btn = form.querySelector('button');
                        if (btn) { btn.disabled = true; btn.textContent = 'Saving…'; }
                        markStep('brand', { tagline: val }).finally(function () { location.reload(); });
                    });
                });
            })();
        </script>
        <?php
    }
}
