<?php

if ( !defined( 'ABSPATH' ) ) {
    exit;
}
/**
 * The public-facing functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the public-facing stylesheet and JavaScript.
 *
 * @package    Storyposts
 * @subpackage Storyposts/public
 * @author     thunder-team
 * @license    GPL-2.0-or-later
 * @link       https://www.gnu.org/licenses/gpl-2.0.txt
 */
class Storyposts_Public {
    /**
     * The ID of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string    $plugin_name    The ID of this plugin.
     */
    private $plugin_name;

    /**
     * The version of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string    $version    The current version of this plugin.
     */
    private $version;

    /**
     * Initialize the class and set its properties.
     *
     * @since    1.0.0
     * @param      string    $plugin_name       The name of the plugin.
     * @param      string    $version    The version of this plugin.
     */
    public function __construct( $plugin_name, $version ) {
        $this->plugin_name = $plugin_name;
        $this->version = $version;
    }

    /**
     * Register the stylesheets for the public-facing side of the site.
     *
     * @since    1.0.0
     */
    public function enqueue_styles() {
        // Register Swiper CSS (local)
        wp_register_style(
            'swiper',
            STORYPOSTS_URL . 'public/css/lib/swiper-bundle.min.css',
            [],
            '11.0.0'
        );
        // Register StoryPosts CSS
        wp_register_style(
            'storyposts',
            STORYPOSTS_URL . 'public/css/storyposts.css',
            ['swiper'],
            $this->version
        );
        // Conditionally enqueue on BuddyPress activity page
        if ( $this->should_load_storyposts() ) {
            wp_enqueue_style( 'swiper' );
            wp_enqueue_style( 'storyposts' );
            // Inject dynamic CSS variables
            $vars = $this->get_css_variables();
            $dynamic_css = ":root {\n";
            foreach ( $vars as $name => $value ) {
                // Strip invalid characters from CSS variable names
                $safe_name = preg_replace( '/[^a-zA-Z0-9-]/', '', $name );
                // Prevent CSS injection by stripping brackets and semicolons
                $safe_value = str_replace( array(
                    ';',
                    '{',
                    '}',
                    '<',
                    '>'
                ), '', $value );
                $dynamic_css .= "    {$safe_name}: {$safe_value};\n";
            }
            $dynamic_css .= "}";
            // Escape late using esc_html() to satisfy Plugin Check escaping requirements
            wp_add_inline_style( 'storyposts', esc_html( $dynamic_css ) );
        }
    }

    /**
     * Get CSS variables for the plugin.
     * 
     * @return array Array of CSS variable names and values.
     */
    public function get_css_variables() {
        $vars = array(
            '--sp-modal-bg'         => '#fff',
            '--sp-card-bg'          => '#f9f9f9',
            '--sp-text-color'       => '#4d4d4d',
            '--sp-text-color--dark' => '#1a1a1a',
            '--sp-border-color'     => '#edebf0',
            '--sp-primary-color'    => Storyposts_Settings::get( 'primary_color', '#93278f' ),
        );
        /**
         * Filter the CSS variables used by StoryPosts.
         * 
         * @param array $vars Array of CSS variable names and values.
         */
        return apply_filters( 'storyposts_css_variables', $vars );
    }

    /**
     * Register the JavaScript for the public-facing side of the site.
     *
     * @since    1.0.0
     */
    public function enqueue_scripts() {
        // Register Swiper JS (local)
        wp_register_script(
            'swiper',
            STORYPOSTS_URL . 'public/js/lib/swiper-bundle.min.js',
            [],
            '11.0.0',
            true
        );
        // Register StoryPosts scripts
        wp_register_script(
            'storyposts-viewer',
            STORYPOSTS_URL . 'public/js/storyposts.js',
            ['swiper'],
            $this->version,
            true
        );
        // Register storyposts-form (Pro only)
        if ( storyposts_component_exists( 'user-stories' ) ) {
            wp_register_script(
                'storyposts-form',
                STORYPOSTS_URL . 'public/js/storyposts-form.js',
                [],
                $this->version,
                true
            );
        }
        // Conditionally enqueue on BuddyPress activity page
        if ( $this->should_load_storyposts() ) {
            wp_enqueue_script( 'swiper' );
            wp_enqueue_script( 'storyposts-viewer' );
            // Enqueue storyposts-form (Pro only)
            if ( storyposts_component_exists( 'user-stories' ) && storyposts_user_can_create_story() ) {
                wp_enqueue_script( 'storyposts-form' );
            }
            // Localize script data to viewer (always enqueued, needed by both viewer and form)
            $storyposts_data = [
                'ajax_url'        => admin_url( 'admin-ajax.php' ),
                'current_user_id' => get_current_user_id(),
                'settings'        => [
                    'duration'             => (int) Storyposts_Settings::get( 'story_duration', 5000 ),
                    'mute_by_default'      => Storyposts_Settings::get( 'mute_by_default', false ),
                    'max_file_size'        => (int) Storyposts_Settings::get( 'max_file_size', 10 ),
                    'allowed_types'        => Storyposts_Settings::get( 'allowed_types', ['image', 'video'] ),
                    'max_title_length'     => (int) Storyposts_Settings::get( 'max_title_length', 30 ),
                    'max_desc_length'      => (int) Storyposts_Settings::get( 'max_desc_length', 120 ),
                    'enable_privacy'       => Storyposts_Settings::get( 'enable_privacy', 'off' ),
                    'privacy_levels'       => Storyposts_Settings::get( 'privacy_levels', ['public', 'friends', 'private'] ),
                    'user_slides_per_view' => (int) Storyposts_Settings::get( 'user_slides_per_view', 5 ),
                    'user_slide_gap'       => (int) Storyposts_Settings::get( 'user_slide_gap', 4 ),
                    'stories_per_load'     => (int) Storyposts_Settings::get( 'stories_per_load', 12 ),
                ],
                'i18n'            => [
                    'upload_failed'       => esc_html__( 'Failed to upload story. Please try again.', 'storyposts' ),
                    'upload_error'        => esc_html__( 'Upload failed.', 'storyposts' ),
                    'no_stories'          => esc_html__( 'No stories yet. Create your first story!', 'storyposts' ),
                    'no_stories_found'    => esc_html__( 'No stories found.', 'storyposts' ),
                    'load_stories_failed' => esc_html__( 'Failed to load stories.', 'storyposts' ),
                    'load_stories_error'  => esc_html__( 'Error loading stories.', 'storyposts' ),
                    'delete_failed'       => esc_html__( 'Failed to delete story', 'storyposts' ),
                    'privacy_updated'     => esc_html__( 'Privacy updated!', 'storyposts' ),
                    'privacy_failed'      => esc_html__( 'Failed to update privacy.', 'storyposts' ),
                    'privacy_error'       => esc_html__( 'Something went wrong.', 'storyposts' ),
                    'privacy_public'      => esc_html__( 'Public', 'storyposts' ),
                    'privacy_friends'     => esc_html__( 'Friends Only', 'storyposts' ),
                    'privacy_private'     => esc_html__( 'Only Me', 'storyposts' ),
                    'read_more'           => esc_html__( 'Read More', 'storyposts' ),
                    'delete'              => esc_html__( 'Delete', 'storyposts' ),
                    'confirm_delete'      => esc_html__( 'Are you sure you want to delete this story?', 'storyposts' ),
                    'delete_error'        => esc_html__( 'Something went wrong while deleting the story.', 'storyposts' ),
                ],
            ];
            // Add generic fetch nonce
            $storyposts_data['nonce'] = wp_create_nonce( 'storyposts_fetch_stories' );
            // Add nonces conditionally for user stories
            if ( storyposts_component_exists( 'user-stories' ) ) {
                $storyposts_data = array_merge( $storyposts_data, $this->get_user_stories_nonces__premium_only() );
            }
            wp_localize_script( 'storyposts-viewer', 'storypostsStory', $storyposts_data );
            // Add type="module" to script tags
            add_filter(
                'script_loader_tag',
                function ( $tag, $handle ) {
                    if ( $handle === 'storyposts-viewer' || $handle === 'storyposts-form' ) {
                        $tag = str_replace( '<script ', '<script type="module" ', $tag );
                    }
                    return $tag;
                },
                10,
                2
            );
        }
    }

    /**
     * Determine if StoryPosts scripts/styles should be loaded on current page.
     *
     * @since    1.0.0
     * @return   bool    True if scripts should load, false otherwise.
     */
    private function should_load_storyposts() {
        // Check if we're on BuddyPress activity page
        $should_load = function_exists( 'bp_is_activity_directory' ) && bp_is_activity_directory();
        $should_load = true;
        /**
         * Filter whether StoryPosts assets should load on current page.
         *
         * @param bool $should_load Whether to load StoryPosts assets.
         */
        return apply_filters( 'storyposts_should_load_assets', $should_load );
    }

    /**
     * Get the storyposts story slider
     *
     * @return null
     */
    public function render_story_slider() {
        if ( !storyposts_component_exists( 'user-stories' ) ) {
            // @fs_premium_only
            return;
            // @fs_premium_only
        }
        // @fs_premium_only
        if ( function_exists( 'storyposts_get_template_part' ) ) {
            // Check if user stories are enabled globally
            if ( Storyposts_Settings::get( 'enable_user_stories', 'on' ) !== 'on' ) {
                return;
            }
            // Check if stories should be shown on the activity page
            if ( Storyposts_Settings::get( 'user_stories_show_on_activity', 'on' ) !== 'on' ) {
                return;
            }
            $mode = 'users';
            $ajax_action = 'storyposts_get_user_stories';
            $layout = Storyposts_Settings::get( 'user_stories_layout', 'avatar' );
            $limit = absint( Storyposts_Settings::get( 'stories_per_load', 12 ) );
            $slides_per_view = absint( Storyposts_Settings::get( "user_slides_per_view_{$layout}", 12 ) );
            $slide_gap = (int) Storyposts_Settings::get( "user_slide_gap_{$layout}", 12 );
            storyposts_get_template_part( ( $layout === 'avatar' ? 'story-slider-avatar' : 'story-slider' ), compact(
                'mode',
                'ajax_action',
                'limit',
                'layout',
                'slides_per_view',
                'slide_gap'
            ) );
            storyposts_render_modals( $mode );
        }
    }

}
