<?php
/**
 * Chat widget for melk — deferred so it does not compete with landing first paint.
 * (Shared chat-widget-boot.php injects blocking CSS/JS; we load after idle/load.)
 */
$acc_widget_cfg = [
    'portal'        => 'melk',
    'site_name'     => 'پشتیبانی اقتصاد ملک',
    'welcome_msg'   => 'سلام! برای آگهی ملک، ساخت‌وساز یا پرونده همکاری پیام بدهید.',
    'wizards_js'    => 'assets/js/chat-widget/melk-wizards.js',
    'tabs'          => [ 'home', 'services', 'track', 'chat', 'contact' ],
    'theme_color'   => '#4338ca',
    'launcher_icon' => '🏛️',
];

if ( ! defined( 'ACC_URL' ) ) {
    define( 'ACC_URL', '/acc-engine/' );
}

$base = ACC_URL;
$api_base = rtrim( $base . 'api.php/acc/v1', '/' );
$cfg = array_merge( [
    'api_base'      => $api_base,
    'nonce'         => '',
    'spa_slug'      => 'melk',
    'phone'         => '',
    'whatsapp'      => '',
    'telegram'      => '',
    'instagram'     => '',
    'poll_ms'       => 4000,
    'wp_user'       => null,
], $acc_widget_cfg );
$cfg['api_base'] = $cfg['api_base'] ?? $api_base;
$cfg['spa_slug'] = $cfg['portal'] ?? $cfg['spa_slug'] ?? 'melk';

$css   = $base . 'assets/css/base/chat-widget.css';
$wiz   = $base . ltrim( $cfg['wizards_js'], '/' );
$main  = $base . 'assets/js/chat-widget/widget.js';
?>

<!-- ACC Chat Widget [melk] — deferred -->
<script>
window.ACC_CHAT_CFG = <?= json_encode( $cfg, JSON_UNESCAPED_UNICODE ) ?>;
(function () {
    function loadMelkChat() {
        if (window.__melkChatBooted) return;
        window.__melkChatBooted = true;
        var link = document.createElement('link');
        link.rel = 'stylesheet';
        link.href = <?= json_encode( $css ) ?>;
        document.head.appendChild(link);
        var wiz = document.createElement('script');
        wiz.src = <?= json_encode( $wiz ) ?>;
        wiz.onload = function () {
            var s = document.createElement('script');
            s.src = <?= json_encode( $main ) ?>;
            document.body.appendChild(s);
        };
        document.body.appendChild(wiz);
    }
    if ('requestIdleCallback' in window) {
        requestIdleCallback(loadMelkChat, { timeout: 2500 });
    } else {
        window.addEventListener('load', function () { setTimeout(loadMelkChat, 1); });
    }
})();
</script>
