<?php
/**
 * SearchShifter Shortcodes
 * Handles public shortcode rendering for glossary, FAQ, light checker, and more.
 */

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

class SS_Shortcodes {

    /**
     * Initialize all shortcodes
     */
    public static function init() {
        // Register shortcodes
        add_shortcode('ss_light_checker', [__CLASS__, 'render_light_checker']);
        add_shortcode('searchshifter_glossary', [__CLASS__, 'render_glossary']);
        add_shortcode('searchshifter_faq', [__CLASS__, 'render_faq']);

        // Enqueue assets for light checker
        add_action('wp_enqueue_scripts', [__CLASS__, 'enqueue_light_checker_assets']);
    }

    /**
     * Light Checker Shortcode
     * Usage: [ss_light_checker]
     */
    public static function render_light_checker() {
        ob_start(); ?>
        <div class="ss-light-checker">
            <form id="ss-light-form" style="max-width:480px;margin:auto;text-align:center;">
                <input type="url" id="ss-light-url" placeholder="https://example.com" required
                    style="width:100%;padding:10px;border:1px solid #ccc;border-radius:6px;">
                <button type="submit"
                    style="margin-top:10px;padding:10px 16px;background:#111;color:#fff;border:0;border-radius:6px;cursor:pointer;">
                    Check My Site
                </button>
            </form>
            <div id="ss-light-result" style="margin-top:20px;text-align:left;"></div>
        </div>
        <?php
        return ob_get_clean();

    }

    /**
     * Enqueue JS for the light checker
     */
    public static function enqueue_light_checker_assets() {
        $handle = 'ss-light-checker';
        wp_enqueue_script(
            $handle,
            plugins_url('../../public/js/light-checker.js', __FILE__),
            ['jquery'],
            SEARCHSHIFTER_VERSION,
            true
        );
        wp_localize_script($handle, 'SS_LIGHT', [
            'endpoint' => rest_url('searchshifter/v1/light-check'),
        ]);
    }

    /**
     * Glossary Shortcode
     * Usage: [searchshifter_glossary]
     */
    public static function render_glossary() {

        $plan = ss_get_current_plan();

        $terms = get_posts([
            'post_type'      => 'ss_glossary',
            'posts_per_page' => -1,
            'orderby'        => 'title',
            'order'          => 'ASC'
        ]);

        if (empty($terms)) {
            return "<p>No glossary terms found.</p>";
        }

        // Active letters (UTF safe)
        $active_letters = [];
        foreach ($terms as $t) {
            $active_letters[] = strtoupper(mb_substr($t->post_title, 0, 1));
        }
        $active_letters = array_unique($active_letters);

        // Grouping
        $groups = [];
        foreach ($terms as $t) {
            $letter = strtoupper(mb_substr($t->post_title, 0, 1));
            $groups[$letter][] = $t;
        }

        ob_start();
        ?>

        <div class="ss-glossary-wrapper">

            <h1 class="ss-glossary-main-title">SearchShifter™ Glossary</h1>

            <div class="ss-glossary-page">

                <!-- Search -->
                <div class="ss-glossary-search-wrapper">
                    <input type="text" id="ss-glossary-search" placeholder="Search glossary terms...">
                </div>

                <!-- A-Z -->
                <div class="ss-glossary-nav">
                    <?php foreach (range('A','Z') as $l): ?>
                        <a href="<?php echo esc_url( in_array($l, $active_letters) ? '#ss-' . $l : '#' ); ?>"
                        class="<?php echo in_array($l, $active_letters) ? '' : 'inactive'; ?>">
                            <?php echo esc_html($l); ?>
                        </a>
                    <?php endforeach; ?>
                </div>

                <!-- Content -->
                <div id="ss-glossary-container">
                    <?php foreach ($groups as $letter => $items): ?>
                        <div class="ss-letter-section" data-letter="<?php echo esc_attr($letter); ?>">
                            <h2 id="ss-<?php echo esc_attr($letter); ?>">
                                <?php echo esc_html($letter); ?>
                            </h2>

                            <ul class="ss-term-list">
                                <?php foreach ($items as $t):

                                    $def = get_post_meta($t->ID, 'ss_definition', true);
                                    $vid = get_post_meta($t->ID, 'ss_video_url', true);

                                    $preview = $def ? wp_trim_words(wp_strip_all_tags($def), 22) : '';

                                    $show_lock = false;
                                    if (($plan === 'free' || $plan === 'pro') && $vid) {
                                        $show_lock = true;
                                    }
                                ?>

                                <li class="ss-term-item"
                                    data-term="<?php echo esc_attr(sanitize_title($t->post_title)); ?>">

                                    <a class="ss-term-title"
                                    href="<?php echo esc_url(get_permalink($t->ID)); ?>">
                                        <?php echo esc_html($t->post_title); ?>
                                    </a>

                                    <?php if ($vid && $plan === 'authority'): ?>
                                        <span class="ss-video-badge">🎥</span>
                                    <?php endif; ?>

                                    <?php if ($show_lock): ?>
                                        <span class="ss-lock-badge">🔒</span>
                                    <?php endif; ?>

                                    <?php if (!empty($preview)): ?>
                                        <p class="ss-term-preview"><?php echo esc_html($preview); ?></p>
                                    <?php endif; ?>

                                </li>

                                <?php endforeach; ?>
                            </ul>
                        </div>
                    <?php endforeach; ?>
                </div>

            </div>
        </div>

        <script>
        document.addEventListener("DOMContentLoaded", function() {

            const input = document.getElementById("ss-glossary-search");
            const items = document.querySelectorAll(".ss-term-item");
            const sections = document.querySelectorAll(".ss-letter-section");

            input.addEventListener("keyup", function() {
                let q = this.value.toLowerCase();

                items.forEach(item => {
                    let text = item.dataset.term;
                    item.style.display = text.includes(q) ? "list-item" : "none";
                });

                // FIXED logic
                sections.forEach(section => {
                    const visible = section.querySelectorAll(".ss-term-item:not([style*='none'])").length > 0;
                    section.style.display = visible ? "block" : "none";
                });
            });
        });
        </script>

        <style>
        .ss-glossary-wrapper {
            max-width: 900px;
            margin: auto;
            padding: 20px;
        }

        .ss-glossary-main-title {
            text-align: center;
            font-size: 32px;
            margin-bottom: 10px;
        }

        .ss-glossary-page {
            text-align: left; /* reset */
        }
        .ss-term-list {
            list-style: none !important;
            padding: 0 !important;
        }

        .ss-term-item {
            display: list-item;
            margin-bottom: 18px;
        }

        #ss-glossary-search {
            width: 100%;
            max-width: 420px;
            padding: 12px 14px;
            border-radius: 6px;
            border: 1px solid #ddd;
            font-size: 14px;
        }
        </style>

        <?php
        return ob_get_clean();
    }



    /**
     * FAQ Shortcode
     * Usage: [searchshifter_faq]
     */
    public static function render_faq() {

        $query = new WP_Query([
            'post_type' => 'ss_qa',
            'post_status' => 'publish',
            'posts_per_page' => -1
        ]);

        if (!$query->have_posts()) {
            return '<p>No FAQs found.</p>';
        }

        ob_start(); ?>

        <section class="ss-public-faq">
            <h2 class="ss-faq-title">Frequently Asked Questions</h2>

            <div class="ss-faq-wrapper">

                <?php while ($query->have_posts()): $query->the_post(); 
                    $answer = get_post_meta(get_the_ID(), '_ss_qa_answer', true);
                ?>

                    <div class="ss-faq-item">
                        <div class="ss-faq-question">
                            <span class="ss-faq-text"><?php the_title(); ?></span>
                            <span class="ss-faq-icon">+</span>
                        </div>

                        <div class="ss-faq-answer">
                            <?php echo esc_html($answer); ?>
                        </div>
                    </div>

                <?php endwhile; wp_reset_postdata(); ?>

            </div>
        </section>

        <style>
        .ss-faq-question {
            padding: 15px;
            cursor: pointer;
            font-weight: 600;
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: #f9f9f9;
            gap: 10px;
        }

        .ss-faq-text {
            flex: 1;
            text-align: left;
        }

        .ss-faq-item {
            transition: all 0.3s ease;
        }

        .ss-faq-item.active {
            border-color: #e0a800;
        }

        .ss-faq-question:hover {
            background: #f1f1f1;
        }
        .ss-public-faq {
            max-width: 800px;
            margin: auto;
            padding: 40px 20px;
        }

        .ss-faq-title {
            font-size: 28px;
            margin-bottom: 20px;
        }

        .ss-faq-item {
            border: 1px solid #ddd;
            border-radius: 6px;
            margin-bottom: 10px;
            overflow: hidden;
        }

        .ss-faq-question {
            padding: 15px;
            cursor: pointer;
            font-weight: 600;
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: #f9f9f9;
        }

        .ss-faq-answer {
            display: none;
            padding: 15px;
            font-size: 15px;
            color: #555;
            background: #fff;
        }

        .ss-faq-item.active .ss-faq-answer {
            display: block;
        }

        .ss-faq-icon {
            font-size: 20px;
        }
        </style>

        <script>
        document.addEventListener("DOMContentLoaded", function() {
            document.querySelectorAll(".ss-faq-question").forEach(item => {
                item.addEventListener("click", function() {
                    const parent = this.parentElement;

                    parent.classList.toggle("active");

                    const icon = this.querySelector(".ss-faq-icon");
                    icon.textContent = parent.classList.contains("active") ? "-" : "+";
                });
            });
        });
        </script>

        <?php
        return ob_get_clean();
    }
}

 

// ✅ Initialize the shortcodes after WordPress loads
add_action('init', ['SS_Shortcodes', 'init']);
