<?php
/**
 * MenuX Free — Onboarding Tutorial Mascot
 * Renders the step-by-step guided tour that appears on first visit.
 * @package MenuX
 */

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

function menux_render_tutorial() {
    ?>
    <!-- ===== MENUX TUTORIAL ===== -->
    <div id="menux-tut-backdrop" aria-hidden="true"></div>
    <div id="menux-tut-spotlight" aria-hidden="true"></div>
    <div id="menux-tut-bubble" role="dialog" aria-modal="true" aria-labelledby="menux-tut-heading">
        <div class="menux-tut-bee" aria-hidden="true">🐝</div>
        <div class="menux-tut-body">
            <div class="menux-tut-step-badge" id="menux-tut-step-badge"><?php
                /* translators: %1$s: current step number, %2$s: total number of steps. */
                printf( esc_html__( 'Step %1$s of %2$s', 'giuliomax-menu-builder' ), '1', '11' );
            ?></div>
            <div class="menux-tut-heading" id="menux-tut-heading"></div>
            <div class="menux-tut-text" id="menux-tut-text"></div>
            <div class="menux-tut-footer">
                <div class="menux-tut-dots">
                    <span class="menux-tut-dot"></span>
                    <span class="menux-tut-dot"></span>
                    <span class="menux-tut-dot"></span>
                    <span class="menux-tut-dot"></span>
                    <span class="menux-tut-dot"></span>
                    <span class="menux-tut-dot"></span>
                    <span class="menux-tut-dot"></span>
                    <span class="menux-tut-dot"></span>
                    <span class="menux-tut-dot"></span>
                    <span class="menux-tut-dot"></span>
                    <span class="menux-tut-dot"></span>
                </div>
                <div class="menux-tut-actions">
                    <button type="button" class="menux-tut-skip" id="menux-tut-skip"><?php esc_html_e( 'Skip', 'giuliomax-menu-builder' ); ?></button>
                    <button type="button" class="menux-tut-next" id="menux-tut-next"><?php esc_html_e( 'Next', 'giuliomax-menu-builder' ); ?> →</button>
                </div>
            </div>
        </div>
    </div>

    <style>
    /* ── Tutorial backdrop & spotlight ── */
    #menux-tut-backdrop {
        display: none;
        position: fixed;
        inset: 0;
        z-index: 999980;
    }
    #menux-tut-spotlight {
        display: none;
        position: fixed;
        z-index: 999982;
        border-radius: 12px;
        pointer-events: none;
        box-shadow: 0 0 0 9999px rgba(0,0,0,.65);
        outline: 2px solid rgba(255,255,255,.28);
        outline-offset: 2px;
        transition: top .3s ease, left .3s ease, width .3s ease, height .3s ease;
    }
    /* ── Bubble ── */
    #menux-tut-bubble {
        display: none;
        position: fixed;
        z-index: 999995;
        background: #fff;
        border-radius: 18px;
        box-shadow: 0 24px 64px rgba(0,0,0,.28), 0 0 0 1px rgba(102,126,234,.12);
        padding: 20px 22px 18px;
        width: 310px;
        max-width: calc(100vw - 32px);
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    }
    #menux-tut-bubble.menux-tut-visible {
        animation: menux-tut-pop .35s cubic-bezier(.34,1.56,.64,1) forwards;
    }
    @keyframes menux-tut-pop {
        from { opacity: 0; transform: scale(.82) translateY(8px); }
        to   { opacity: 1; transform: scale(1)   translateY(0); }
    }
    /* Arrow pointer (rotated square) */
    #menux-tut-bubble::before {
        content: '';
        position: absolute;
        width: 12px;
        height: 12px;
        background: #fff;
        transform: rotate(45deg);
    }
    #menux-tut-bubble.arrow-top::before    { top: -6px;    left: 42px; box-shadow: -2px -2px 5px rgba(0,0,0,.06); }
    #menux-tut-bubble.arrow-bottom::before { bottom: -6px; left: 42px; box-shadow:  2px  2px 5px rgba(0,0,0,.06); }
    #menux-tut-bubble.arrow-left::before   { left:  -6px;  top:  32px; box-shadow: -2px  2px 5px rgba(0,0,0,.06); }
    #menux-tut-bubble.arrow-right::before  { right: -6px;  top:  32px; box-shadow:  2px -2px 5px rgba(0,0,0,.06); }
    /* Bee mascot */
    .menux-tut-bee {
        font-size: 34px;
        display: block;
        text-align: center;
        margin-bottom: 8px;
        animation: menux-tut-float 3s ease-in-out infinite;
        line-height: 1;
    }
    @keyframes menux-tut-float {
        0%,100% { transform: translateY(0)   rotate(-4deg); }
        50%      { transform: translateY(-8px) rotate(4deg); }
    }
    /* Step label */
    .menux-tut-step-badge {
        font-size: 10px;
        font-weight: 700;
        letter-spacing: .8px;
        text-transform: uppercase;
        color: #a78bfa;
        margin-bottom: 5px;
    }
    /* Heading */
    .menux-tut-heading {
        font-size: 15px;
        font-weight: 700;
        color: #111827;
        margin-bottom: 8px;
        line-height: 1.3;
    }
    /* Body text */
    .menux-tut-text {
        font-size: 13px;
        color: #4b5563;
        line-height: 1.65;
        margin-bottom: 16px;
    }
    .menux-tut-text a        { color: #667eea; text-decoration: underline; }
    .menux-tut-text strong   { color: #374151; }
    /* Footer */
    .menux-tut-footer {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 10px;
    }
    /* Progress dots */
    .menux-tut-dots { display: flex; gap: 4px; align-items: center; }
    .menux-tut-dot {
        width: 5px; height: 5px;
        border-radius: 50%;
        background: #e5e7eb;
        transition: background .2s, transform .2s;
    }
    .menux-tut-dot.active {
        background: #667eea;
        transform: scale(1.5);
    }
    /* Buttons */
    .menux-tut-actions { display: flex; gap: 8px; align-items: center; }
    .menux-tut-skip {
        background: none; border: none;
        color: #9ca3af; font-size: 12px;
        cursor: pointer; padding: 4px 0;
        font-family: inherit;
        transition: color .15s;
    }
    .menux-tut-skip:hover { color: #6b7280; }
    .menux-tut-next {
        background: linear-gradient(135deg, #667eea, #764ba2);
        border: none; color: #fff;
        padding: 8px 16px; border-radius: 10px;
        font-size: 13px; font-weight: 600;
        cursor: pointer; font-family: inherit;
        transition: opacity .15s, transform .1s;
    }
    .menux-tut-next:hover  { opacity: .9; }
    .menux-tut-next:active { transform: scale(.97); }
    </style>

    <script>
    window.menuxTutorial = (function() {
        var STORAGE_KEY = 'menux_tutorial_done_v1';
        var current     = 0;

        var steps = [
            // ── 1. Menu Structure ──────────────────────────────────────────
            {
                section: 'structure',
                target:  '#panel-structure .bm-card-add-unified',
                heading: "Build your menu 🧩",
                text:    "Choose a <strong>Page</strong> or a <strong>Custom link</strong> from the dropdowns and hit <strong>+ Add</strong>. Drag rows to reorder. Expand any item (<em>▶</em>) to set its icon, badge, role-based visibility, CTA button style and more.<br><br><em>Tip: sub-items create the dropdown — just add them inside a top-level row.</em>",
                arrow:   'top'
            },
            // ── 2. Themes ─────────────────────────────────────────────────
            {
                section: 'themes',
                target:  '#panel-style',
                heading: "50 one-click themes ✨",
                text:    "Browse 50 designer presets across 10 categories (Dark, Minimal, Gradient, Glassmorphism…). Click a card — colors, fonts, animations and spacing are applied instantly. You can always fine-tune afterwards.",
                arrow:   'top'
            },
            // ── 3. Colors ─────────────────────────────────────────────────
            {
                section: 'colors',
                target:  '#panel-style',
                heading: "Colors 🎨",
                text:    "Tick the checkbox next to any swatch to override it. You can set the <strong>container background</strong> (solid or gradient), <strong>link colors</strong> for normal / hover / active states, <strong>submenu</strong> background, and <strong>mobile-specific text colors</strong> — all independent from desktop.",
                arrow:   'top'
            },
            // ── 4. Typography & Layout ────────────────────────────────────
            {
                section: 'typo',
                target:  '#panel-style',
                heading: "Typography & Layout 🔤📐",
                text:    "<strong>Typography</strong>: pick from 70+ Google Fonts with live preview; set size, weight, letter-spacing, transform and transitions.<br><br><strong>Layout</strong>: padding, item gap, border radius, <strong>sticky header</strong> (shrinks on scroll), <strong>scroll progress bar</strong>, justify alignment and dark-mode setting.",
                arrow:   'top'
            },
            // ── 5. Animations ─────────────────────────────────────────────
            {
                section: 'layout',
                target:  '#panel-style',
                heading: "Animations 🎭",
                text:    "<strong>Entrance animation</strong>: the whole nav fades / slides / zooms in when the page loads. Set duration, delay and stagger so items appear one after another.<br><br><strong>Link hover animation</strong>: Lift, Scale, Glow, Underline-grow and more — applied when the visitor hovers a menu item.",
                arrow:   'top'
            },
            // ── 6. Mobile ─────────────────────────────────────────────────
            {
                section: 'mobile',
                target:  '#panel-style',
                heading: "Mobile menu 📱",
                text:    "Choose the <strong>opening style</strong>: classic Dropdown, immersive Fullscreen, or a Drawer sliding from left or right. Pick one of 3 <strong>hamburger icon styles</strong>, set its color, and optionally add an overlay with blur. Mobile text colors are set independently in <em>Colors</em>.",
                arrow:   'top'
            },
            // ── 7. Mega Menu ──────────────────────────────────────────────
            {
                section: 'megamenu',
                target:  '#panel-megamenu',
                heading: "Mega Menu ⚡",
                text:    "Toggle ON any top-level item to replace its dropdown with a rich full-width panel. Click <strong>⚡ Edit Columns ▶</strong> to build up to 4 columns with headings, links (icon + description), images, shortcodes or auto-updating post lists.<br><br>Hit <strong>✨ Presets</strong> for 20 ready-made industry templates. The <strong>🎨 Appearance</strong> tab lets you set the panel background, colors and spacing per item.",
                arrow:   'top'
            },
            // ── 8. Logo ───────────────────────────────────────────────────
            {
                section: 'logo',
                target:  '#panel-logo',
                heading: "Logo 🖼️",
                text:    "Upload separate images for <strong>Desktop</strong>, <strong>Mobile</strong> and the <strong>Sticky</strong> state. Choose position (left, center, right), shape (natural, circle, pill) and set a max height. The logo renders inside the menu bar — no extra widgets needed.",
                arrow:   'top'
            },
            // ── 9. Announcement & Search ──────────────────────────────────
            {
                section: 'announcement',
                target:  '#panel-announcement',
                heading: "Announcement Bar & Search 📢🔍",
                text:    "<strong>Announcement bar</strong>: a dismissible stripe above or below the menu with custom colors, a clickable message and an optional <strong>live countdown timer</strong> — perfect for flash sales.<br><br><strong>Search</strong>: adds a 🔍 icon that opens a slide-out modal. It searches your menu items <em>and</em> in-page text — no server round-trip.",
                arrow:   'top'
            },
            // ── 10. WooCommerce & Accessibility ───────────────────────────
            {
                section: 'woocommerce',
                target:  '#panel-woocommerce',
                heading: "WooCommerce & Accessibility 🛒♿",
                text:    "<strong>Cart icon</strong>: drop a live cart (cart / bag / basket) anywhere in the nav. Shows a count badge, running total, and a mini-cart on hover or click. Auto-activates when WooCommerce is installed.<br><br><strong>Accessibility</strong>: 23 WCAG 2.2 AA options — keyboard nav, focus ring styling, touch targets, skip-to-content link and contrast enforcement.",
                arrow:   'top'
            },
            // ── 11. Deploy, Integration & Import/Export ───────────────────
            {
                section: 'import-export',
                target:  '#panel-import-export',
                heading: "Go live! 🚀",
                text:    "Paste <code style=\"background:#f3f4f6;padding:2px 5px;border-radius:4px;font-size:12px;\">[menux]</code> anywhere, or use the <strong>Giuliomax Menu block</strong> in the Site Editor.<br><br><strong>WP Integration</strong> (sidebar) replaces any <code style=\"background:#f3f4f6;padding:2px 5px;border-radius:4px;font-size:12px;\">wp_nav_menu()</code> theme location automatically.<br><br><strong>Import / Export</strong>: save your entire config as a JSON file and restore it on any site in one click. Great for client handoffs.",
                arrow:   'top',
                last:    true
            }
        ];

        function q(sel) { return document.querySelector(sel); }

        function setVisible(ids, show) {
            ids.forEach(function(id) {
                var el = document.getElementById(id);
                if (el) el.style.display = show ? 'block' : 'none';
            });
        }

        function positionSpotlight(el) {
            var r   = el.getBoundingClientRect();
            var pad = 8;
            var sp  = q('#menux-tut-spotlight');
            sp.style.top    = (r.top    - pad) + 'px';
            sp.style.left   = (r.left   - pad) + 'px';
            sp.style.width  = (r.width  + pad * 2) + 'px';
            sp.style.height = (r.height + pad * 2) + 'px';
        }

        function positionBubble(el, arrow) {
            var r      = el.getBoundingClientRect();
            var bub    = q('#menux-tut-bubble');
            var bw     = 310;
            var margin = 16;

            // Swap arrow class
            bub.className = bub.className.replace(/\barrow-\w+/g, '').trim();
            bub.classList.add('arrow-' + arrow);

            // Measure real height with content already set
            bub.style.visibility = 'hidden';
            bub.style.display    = 'block';
            var bh = bub.offsetHeight || 220;
            bub.style.visibility = '';

            var top, left;
            if (arrow === 'top') {
                // Bubble below target, arrow points up
                top  = r.bottom + margin;
                left = Math.round(r.left + r.width / 2 - bw / 2);
            } else if (arrow === 'bottom') {
                // Bubble above target, arrow points down
                top  = r.top - bh - margin;
                left = Math.round(r.left + r.width / 2 - bw / 2);
            } else if (arrow === 'left') {
                // Bubble right of target, arrow on left side
                top  = Math.round(r.top);
                left = r.right + margin;
            } else {
                // arrow === 'right': bubble left of target
                top  = Math.round(r.top);
                left = r.left - bw - margin;
            }

            // Clamp within viewport
            var vw = window.innerWidth;
            var vh = window.innerHeight;
            left = Math.max(margin, Math.min(left, vw - bw - margin));
            top  = Math.max(margin, Math.min(top,  vh - bh - margin));

            bub.style.top   = top  + 'px';
            bub.style.left  = left + 'px';
            bub.style.right = 'auto';
        }

        function render(idx) {
            var step = steps[idx];

            if (step.section && typeof menuxGoSection === 'function') {
                menuxGoSection(step.section);
            }

            setTimeout(function() {
                var targetEl = step.target ? q(step.target) : null;

                // Populate content (always, even without a target)
                q('#menux-tut-heading').textContent   = step.heading;
                q('#menux-tut-text').innerHTML         = step.text;
                q('#menux-tut-step-badge').textContent = 'Step ' + (idx + 1) + ' of ' + steps.length;
                q('#menux-tut-next').textContent       = step.last ? '🎉 Done!' : 'Next →';

                // Update dots
                document.querySelectorAll('.menux-tut-dot').forEach(function(d, i) {
                    d.classList.toggle('active', i === idx);
                });

                // Re-trigger entry animation
                var bub = q('#menux-tut-bubble');
                bub.classList.remove('menux-tut-visible');
                void bub.offsetWidth;
                bub.classList.add('menux-tut-visible');

                if (!targetEl) {
                    // No specific target — hide spotlight, center bubble
                    var sp = q('#menux-tut-spotlight');
                    if (sp) { sp.style.width = '0'; sp.style.height = '0'; sp.style.top = '-9999px'; }
                    bub.style.top   = Math.round((window.innerHeight - (bub.offsetHeight || 260)) / 2) + 'px';
                    bub.style.left  = Math.round((window.innerWidth  - 310) / 2) + 'px';
                    bub.style.right = 'auto';
                    bub.className   = bub.className.replace(/\barrow-\w+/g, '').trim();
                    return;
                }

                // Scroll target into view (skip for fixed/sticky elements)
                var cs = window.getComputedStyle(targetEl);
                if (cs.position !== 'fixed' && cs.position !== 'sticky') {
                    targetEl.scrollIntoView({ block: 'nearest' });
                }

                positionSpotlight(targetEl);
                positionBubble(targetEl, step.arrow);

            }, 140);
        }

        function advance() {
            if (current < steps.length - 1) {
                current++;
                render(current);
            } else {
                finish();
            }
        }

        function finish() {
            try { localStorage.setItem(STORAGE_KEY, '1'); } catch(e) {}
            close();
        }

        function close() {
            setVisible(['menux-tut-backdrop', 'menux-tut-spotlight', 'menux-tut-bubble'], false);
        }

        function start() {
            current = 0;
            setVisible(['menux-tut-backdrop', 'menux-tut-spotlight', 'menux-tut-bubble'], true);
            render(0);
        }

        document.addEventListener('DOMContentLoaded', function() {
            var nb = q('#menux-tut-next');
            var sb = q('#menux-tut-skip');
            var bd = q('#menux-tut-backdrop');
            if (nb) nb.addEventListener('click', advance);
            if (sb) sb.addEventListener('click', finish);

            try {
                if (!localStorage.getItem(STORAGE_KEY)) {
                    setTimeout(start, 800);
                }
            } catch(e) {}
        });

        return { start: start, close: close };
    })();
    </script>
    <!-- ===== /MENUX TUTORIAL ===== -->
    <?php
}
