<?php


if (!function_exists('tutorial_component')) {

    // ATENÇÃO: este arquivo está em views/pages/components/
    // Pra chegar em app/tutorials.php, sobe 3 níveis: components → pages → views → app
    require_once __DIR__ . '/../../../app/tutorials.php';

    function tutorial_component(array $opts = []): string {
        $pageId = trim($opts['page'] ?? '');
        if ($pageId === '') return '';

        $cfg = tutorial_for_page($pageId);
        if (!$cfg) return '';

        $videoRaw   = $cfg['video_url'];
        $extraUrl   = $cfg['extra_url'];
        $extraLabel = $cfg['extra_label'] !== '' ? $cfg['extra_label'] : 'Saiba mais';

        $catalog = tutorials_pages_catalog();
        $defaultTitle = isset($catalog[$pageId]) ? "Como usar — {$catalog[$pageId]}" : 'Tutorial rápido';

        $title      = trim($opts['title']  ?? $defaultTitle);
        $buttonText = trim($opts['button'] ?? 'Ver tutorial');
        $spotlight  = isset($opts['spotlight']) ? (bool)$opts['spotlight'] : true;

        // Normaliza embed do YouTube
        $embed = $videoRaw;
        if ($embed) {
            if (preg_match('~^(https?:)?//~i', $embed)) {
                if (preg_match('~[?&]v=([a-zA-Z0-9_-]{6,})~', $embed, $m)) {
                    $embed = $m[1];
                } elseif (preg_match('~youtu\.be/([a-zA-Z0-9_-]{6,})~', $embed, $m)) {
                    $embed = $m[1];
                }
            }
            if (!preg_match('~^https?://~', $embed)) {
                $embed = "https://www.youtube-nocookie.com/embed/" . $embed;
            }
        }

        $safeId    = preg_replace('~[^a-z0-9_-]~i', '', $pageId);
        $btnId     = "tbtn_$safeId";
        $modalId   = "tmodal_$safeId";
        $frameId   = "tframe_$safeId";
        $closeAId  = "tclosea_$safeId";
        $spotKey   = "tutorialSpotlightSeen_" . $safeId;

        ob_start();
        if (empty($GLOBALS['__TUTORIAL_COMPONENT_INJECTED'])): $GLOBALS['__TUTORIAL_COMPONENT_INJECTED'] = true; ?>
        <style>
            .tut-modal{position:fixed; inset:0; z-index:50; display:none;}
            .tut-modal.is-open{display:block;}
            .tut-backdrop{position:absolute; inset:0; background:rgba(0,0,0,.6);}
            .tut-dialog{position:absolute; inset:0; display:flex; align-items:center; justify-content:center; padding:1rem;}
            .tut-card{width:100%; max-width:960px; border-radius:16px; overflow:hidden; box-shadow:0 20px 40px rgba(0,0,0,.25);}
            .tut-card-header,.tut-card-footer{display:flex; align-items:center; justify-content:space-between; gap:.5rem; padding:.75rem 1rem; background:var(--tut-header-bg,#fff); border-bottom:1px solid var(--tut-border,#e5e7eb)}
            .tut-card-footer{border-top:1px solid var(--tut-border,#e5e7eb); border-bottom:none;}
            .tut-iframe-wrap{aspect-ratio:16/9; background:#000;}
            .tut-iframe{width:100%; height:100%;}
            .tut-spot-overlay{position:fixed; inset:0; z-index:60; background:radial-gradient(circle at var(--x,50%) var(--y,50%), transparent 0 var(--r,120px), rgba(0,0,0,.6) calc(var(--r,120px) + 1px));}
            .tut-spot-tip{position:fixed; z-index:70; background:#4f46e5; color:#fff; padding:8px 12px; border-radius:10px; font-size:12px; box-shadow:0 10px 18px rgba(0,0,0,.15); white-space:nowrap;}
            .tut-pulse{position:relative;}
            .tut-pulse::after{content:""; position:absolute; inset:-6px; border-radius:12px; box-shadow:0 0 0 0 rgba(99,102,241,.85); animation:tutPulse 1.6s ease-out infinite; pointer-events:none;}
            @keyframes tutPulse{0%{box-shadow:0 0 0 0 rgba(99,102,241,.85)}70%{box-shadow:0 0 0 16px rgba(99,102,241,0)}100%{box-shadow:0 0 0 0 rgba(99,102,241,0)}}
        </style>
        <script>
            (function(){
                if (window.__tutorialInit) return; window.__tutorialInit = true;

                function qs(s,root){return (root||document).querySelector(s)}
                function qsa(s,root){return (root||document).querySelectorAll(s)}

                function openModal(modal, frame, embed){
                    modal.classList.add('is-open');
                    frame.src = embed + (embed.includes('?') ? '&' : '?') + 'autoplay=1&rel=0';
                    document.addEventListener('keydown', onEsc);
                }
                function closeModal(modal, frame){
                    modal.classList.remove('is-open');
                    frame.src = '';
                    document.removeEventListener('keydown', onEsc);
                }
                function onEsc(e){
                    if (e.key === 'Escape') {
                        qsa('.tut-modal.is-open').forEach(m=>{
                            const f = qs('iframe', m);
                            closeModal(m, f);
                        });
                    }
                }

                document.addEventListener('click', function(ev){
                    const btn = ev.target.closest('[data-tutorial-btn]');
                    if (btn){
                        const target = btn.getAttribute('data-tutorial-target');
                        const embed  = btn.getAttribute('data-tutorial-embed');
                        const modal  = qs('#'+target);
                        const frame  = qs('iframe', modal);
                        openModal(modal, frame, embed);
                        return;
                    }
                    const closer = ev.target.closest('[data-tutorial-close]');
                    if (closer){
                        const modal = ev.target.closest('.tut-modal');
                        const frame = qs('iframe', modal);
                        closeModal(modal, frame);
                        return;
                    }
                    const back = ev.target.closest('.tut-backdrop');
                    if (back){
                        const modal = back.parentElement.parentElement.querySelector('.tut-modal.is-open') || back.parentElement.parentElement;
                        const frame = qs('iframe', modal);
                        closeModal(modal, frame);
                        return;
                    }
                });

                function spotlightOnce(btn, storageKey, label){
                    try{
                        if (!btn || localStorage.getItem(storageKey) === '1') return;
                        btn.classList.add('tut-pulse');
                        const ov = document.createElement('div'); ov.className = 'tut-spot-overlay';
                        const tip = document.createElement('div'); tip.className = 'tut-spot-tip'; tip.textContent = label || 'Novo: assista o tutorial';
                        document.body.appendChild(ov); document.body.appendChild(tip);

                        function position(){
                            const r = btn.getBoundingClientRect();
                            const x = r.left + r.width/2 + window.scrollX;
                            const y = r.top  + r.height/2 + window.scrollY;
                            const rad = Math.max(r.width, r.height) * .9 + 22;
                            ov.style.setProperty('--x', x+'px'); ov.style.setProperty('--y', y+'px'); ov.style.setProperty('--r', rad+'px');
                            const tipW = tip.offsetWidth;
                            const left = r.left + (r.width/2) - (tipW/2) + window.scrollX;
                            const top  = r.top - 40 + window.scrollY;
                            tip.style.left = Math.max(12, left)+'px';
                            tip.style.top  = Math.max(12, top)+'px';
                        }
                        function end(){
                            ov.remove(); tip.remove(); btn.classList.remove('tut-pulse');
                            localStorage.setItem(storageKey, '1');
                            window.removeEventListener('resize', position);
                            window.removeEventListener('scroll', onScroll, true);
                        }
                        function onScroll(){ position(); }
                        ov.addEventListener('click', end);
                        btn.addEventListener('click', end);
                        window.addEventListener('resize', position);
                        window.addEventListener('scroll', onScroll, {passive:true, capture:true});
                        setTimeout(position, 80);
                    }catch(_){}
                }

                window.__tutorialSpotlightOnce = spotlightOnce;
            })();
        </script>
        <?php endif; ?>

        <button
            id="<?= $btnId ?>"
            type="button"
            class="inline-flex items-center gap-2 rounded-lg border border-indigo-200 dark:border-indigo-800 bg-indigo-50 dark:bg-indigo-900/40 px-3 py-1.5 text-sm font-medium text-indigo-700 dark:text-indigo-200 hover:bg-indigo-100 dark:hover:bg-indigo-900/60 focus:outline-none focus:ring-2 focus:ring-indigo-500"
            data-tutorial-btn
            data-tutorial-target="<?= $modalId ?>"
            data-tutorial-embed="<?= htmlspecialchars($embed, ENT_QUOTES, 'UTF-8') ?>">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="currentColor" viewBox="0 0 24 24"><path d="M8 5v14l11-7z"/></svg>
            <?= htmlspecialchars($buttonText, ENT_QUOTES, 'UTF-8') ?>
        </button>

        <div id="<?= $modalId ?>" class="tut-modal" role="dialog" aria-modal="true" aria-labelledby="<?= $modalId ?>_title">
            <div class="tut-backdrop" data-tutorial-close></div>
            <div class="tut-dialog">
                <div class="tut-card" style="--tut-header-bg: #fff; --tut-border:#e5e7eb;">
                    <div class="tut-card-header">
                        <h3 id="<?= $modalId ?>_title" class="text-base font-semibold"><?= htmlspecialchars($title, ENT_QUOTES, 'UTF-8') ?></h3>
                        <button id="<?= $closeAId ?>" class="rounded p-2 hover:bg-gray-100 dark:hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-500" aria-label="Fechar" data-tutorial-close>
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 24 24" fill="currentColor"><path d="M18.3 5.71 12 12l6.3 6.29-1.41 1.42L10.59 13.41 4.29 19.71 2.88 18.3 9.17 12 2.88 5.71 4.29 4.29l6.3 6.3 6.29-6.3z"/></svg>
                        </button>
                    </div>
                    <div class="tut-iframe-wrap">
                        <iframe
                            id="<?= $frameId ?>"
                            class="tut-iframe"
                            src=""
                            title="<?= htmlspecialchars($title, ENT_QUOTES, 'UTF-8') ?>"
                            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
                            allowfullscreen
                            referrerpolicy="strict-origin-when-cross-origin"></iframe>
                    </div>
                    <div class="tut-card-footer flex items-center justify-end gap-2">
                        <?php if ($extraUrl !== ''): ?>
                            <a href="<?= htmlspecialchars($extraUrl, ENT_QUOTES, 'UTF-8') ?>"
                               target="_blank"
                               rel="noopener"
                               class="rounded-lg bg-indigo-600 text-white px-4 py-2 text-sm font-semibold hover:bg-indigo-700">
                                <?= htmlspecialchars($extraLabel, ENT_QUOTES, 'UTF-8') ?>
                            </a>
                        <?php endif; ?>
                        <button class="rounded-lg border px-3 py-1.5 text-sm hover:bg-gray-50 dark:hover:bg-gray-800" data-tutorial-close>
                            Fechar
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <?php if ($spotlight): ?>
            <script>
                (function(){
                    const btn = document.getElementById('<?= $btnId ?>');
                    if (window.__tutorialSpotlightOnce) {
                        window.__tutorialSpotlightOnce(btn, '<?= $spotKey ?>', 'Novo: assista o tutorial');
                    }
                })();
            </script>
        <?php endif; ?>

        <?php
        return ob_get_clean();
    }
}