<?php

namespace Datalumo\Embed;

class WidgetEmbed
{
    public function __construct()
    {
        add_action('wp_enqueue_scripts', [$this, 'enqueueScript']);
        add_action('wp_footer', [$this, 'renderChatbot']);
        add_shortcode('datalumo_search', [$this, 'searchShortcode']);
        add_shortcode('datalumo_chat', [$this, 'chatShortcode']);
    }

    public function enqueueScript(): void
    {
        if (is_admin()) {
            return;
        }

        $chatbotEnabled = datalumo_is_chatbot_enabled() && datalumo_get_chatbot_integration_id();

        if (! $chatbotEnabled) {
            return;
        }

        $this->enqueueSdk();
    }

    public function renderChatbot(): void
    {
        if (is_admin()) {
            return;
        }

        $integrationId = datalumo_get_chatbot_integration_id();

        if (empty($integrationId) || ! datalumo_is_chatbot_enabled()) {
            return;
        }

        $this->enqueueSdk();

        echo $this->buildChatScript($integrationId);
    }

    public function searchShortcode($atts = []): string
    {
        $atts = shortcode_atts([
            'integration' => '',
            'mode'        => 'inline',
        ], $atts, 'datalumo_search');

        $integrationId = $atts['integration'] ?: datalumo_get_search_box_integration_id();

        if (empty($integrationId)) {
            return '';
        }

        $this->enqueueSdk();

        $mode = in_array($atts['mode'], ['inline', 'modal'], true) ? $atts['mode'] : 'inline';

        if ($mode === 'modal') {
            return sprintf(
                '<script>document.addEventListener("DOMContentLoaded",function(){Datalumo.search("%s").modal().mount()});</script>',
                esc_js($integrationId)
            );
        }

        $containerId = uniqid('datalumo-search-');

        return sprintf(
            '<div id="%s"></div><script>document.addEventListener("DOMContentLoaded",function(){Datalumo.search("%s").inline("#%s").mount()});</script>',
            esc_attr($containerId),
            esc_js($integrationId),
            esc_js($containerId)
        );
    }

    public function chatShortcode($atts = []): string
    {
        $atts = shortcode_atts([
            'integration' => '',
        ], $atts, 'datalumo_chat');

        $integrationId = $atts['integration'] ?: datalumo_get_chatbot_integration_id();

        if (empty($integrationId)) {
            return '';
        }

        $this->enqueueSdk();

        return $this->buildChatScript($integrationId);
    }

    private function buildChatScript(string $integrationId): string
    {
        $chain = '';
        $mode = datalumo_get_chatbot_mode();

        if ($mode === 'sidebar') {
            $chain .= '.sidebar(' . wp_json_encode(datalumo_get_chatbot_sidebar_side()) . ')';
            if (datalumo_chatbot_sidebar_pushes()) {
                $chain .= '.push()';
            }
        } else {
            $chain .= '.popup(' . wp_json_encode(datalumo_get_chatbot_popup_position()) . ')';
        }

        if (! datalumo_chatbot_shows_avatar()) {
            $chain .= '.avatar(false)';
        }

        $chain .= '.mount()';

        return sprintf(
            '<script>document.addEventListener("DOMContentLoaded",function(){Datalumo.chat(%s)%s});</script>',
            wp_json_encode($integrationId),
            $chain
        );
    }

    private function enqueueSdk(): void
    {
        if (wp_script_is('datalumo-sdk', 'enqueued') || wp_script_is('datalumo-sdk', 'registered')) {
            return;
        }

        $cdnUrl = datalumo_get_cdn_url();

        wp_enqueue_script(
            'datalumo-sdk',
            $cdnUrl . '/embed.v1.js',
            [],
            null,
            ['strategy' => 'defer', 'in_footer' => true]
        );
    }
}
