// Мост Unity ↔ VK Bridge для DragonPicker (VK-сборка, define DP_VK).
// Подключает VK Bridge (window.vkBridge), отдаёт игрока в PlatformBridge.VK_OnReady,
// показывает рекламу и таблицу лидеров. Все вызовы безопасны, если Bridge не загружен.
var DragonPickerVK = {

  $DPVK: {
    unity: function () {
      return window.unityInstance || window.gameInstance || window.myGameInstance || null;
    },
    bridge: function () {
      return window.vkBridge || (typeof vkBridge !== 'undefined' ? vkBridge : null);
    },
    send: function (method, arg) {
      var u = window.unityInstance || window.gameInstance || window.myGameInstance;
      if (u) { try { u.SendMessage('PlatformBridge', method, arg || ''); } catch (e) {} }
    }
  },

  DPVKInit: function () {
    var b = window.vkBridge || (typeof vkBridge !== 'undefined' ? vkBridge : null);
    var send = function (m, a) {
      var u = window.unityInstance || window.gameInstance || window.myGameInstance;
      if (u) { try { u.SendMessage('PlatformBridge', m, a || ''); } catch (e) {} }
    };
    if (!b) { send('VK_OnReady', '{}'); return; }
    try {
      b.send('VKWebAppInit', {}).catch(function () {});
      b.send('VKWebAppGetUserInfo', {}).then(function (info) {
        var name = ((info.first_name || '') + ' ' + (info.last_name || '')).trim();
        var photo = info.photo_100 || info.photo_200 || '';
        send('VK_OnReady', JSON.stringify({ name: name, photo: photo }));
      }).catch(function () { send('VK_OnReady', '{}'); });
    } catch (e) { send('VK_OnReady', '{}'); }
  },

  DPVKInterstitial: function () {
    var b = window.vkBridge || (typeof vkBridge !== 'undefined' ? vkBridge : null);
    if (!b) return;
    try { b.send('VKWebAppShowNativeAds', { ad_format: 'interstitial' }).catch(function () {}); } catch (e) {}
  },

  DPVKRewarded: function () {
    var b = window.vkBridge || (typeof vkBridge !== 'undefined' ? vkBridge : null);
    var send = function (m, a) {
      var u = window.unityInstance || window.gameInstance || window.myGameInstance;
      if (u) { try { u.SendMessage('PlatformBridge', m, a || ''); } catch (e) {} }
    };
    if (!b) return;
    try {
      b.send('VKWebAppShowNativeAds', { ad_format: 'reward' }).then(function (r) {
        if (r && r.result) send('VK_OnReward', 'bonus');
      }).catch(function () {});
    } catch (e) {}
  },

  DPVKLeaderboard: function (score) {
    var b = window.vkBridge || (typeof vkBridge !== 'undefined' ? vkBridge : null);
    if (!b) return;
    try { b.send('VKWebAppShowLeaderBoardBox', { user_result: score }).catch(function () {}); } catch (e) {}
  }
};

autoAddDeps(DragonPickerVK, '$DPVK');
mergeInto(LibraryManager.library, DragonPickerVK);
