/**
 * Страница «Центр обновлений» на Vue 3 без сборки.
 * Runtime-only режим (render-функция), подключать после vue.runtime/vue-i18n.
 */
(function () {
  'use strict';

  if (typeof Vue === 'undefined' || typeof VueI18n === 'undefined') {
    return;
  }

  var h = Vue.h;

  function request(path, options) {
    var opts = options || {};
    var url = path.startsWith('http') ? path : (window.location.origin || '') + path;
    return fetch(url, {
      method: opts.method || 'GET',
      credentials: 'same-origin',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json'
      },
      body: opts.body ? JSON.stringify(opts.body) : undefined
    })
      .then(function (resp) { return resp.text().then(function (text) { return { resp: resp, text: text }; }); })
      .then(function (ctx) {
        var data = null;
        try { data = ctx.text ? JSON.parse(ctx.text) : null; } catch (e) { data = null; }
        if (!ctx.resp.ok || (data && data.success === false)) {
          return { success: false, error: (data && data.error) || ('HTTP ' + ctx.resp.status), data: data };
        }
        return { success: true, data: data || {} };
      })
      .catch(function (err) {
        return { success: false, error: err.message || 'Network error' };
      });
  }

  function apiGet(path) { return request(path, { method: 'GET' }); }
  function apiPost(path, body) { return request(path, { method: 'POST', body: body || {} }); }

  var locale = (function () {
    try { return localStorage.getItem('cascad360_admin_locale') || 'ru'; } catch (e) { return 'ru'; }
  })();

  var messages = {
    ru: {
      updates: {
        title: 'Центр обновлений',
        source: 'Источник',
        core_version: 'Текущее ядро',
        check: 'Проверить обновления',
        installable: 'Доступные к установке',
        blocked: 'Заблокированные версии',
        artifact: 'Артефакт',
        type: 'Тип',
        installed: 'Установлено',
        target: 'Целевая версия',
        status: 'Статус',
        action: 'Действие',
        reason: 'Причина',
        update_core: 'Обновить ядро',
        update_ext: 'Обновить',
        no_installable: 'Нет совместимых обновлений',
        no_blocked: 'Нет заблокированных версий',
        last_job: 'Последняя задача',
        refresh_job: 'Обновить статус задачи',
        no_jobs: 'Задач пока нет'
      }
    },
    en: {
      updates: {
        title: 'Updates center',
        source: 'Source',
        core_version: 'Current core',
        check: 'Check updates',
        installable: 'Installable',
        blocked: 'Blocked versions',
        artifact: 'Artifact',
        type: 'Type',
        installed: 'Installed',
        target: 'Target version',
        status: 'Status',
        action: 'Action',
        reason: 'Reason',
        update_core: 'Update core',
        update_ext: 'Update',
        no_installable: 'No compatible updates',
        no_blocked: 'No blocked versions',
        last_job: 'Last job',
        refresh_job: 'Refresh job status',
        no_jobs: 'No jobs yet'
      }
    }
  };

  var i18n = VueI18n.createI18n({
    legacy: false,
    locale: locale,
    fallbackLocale: 'ru',
    messages: messages
  });

  var mountEl = document.getElementById('app-updates');
  if (!mountEl) return;

  var app = Vue.createApp({
    data: function () {
      return {
        loading: false,
        error: null,
        channel: 'stable',
        updates: {},
        lastJob: null,
        jobs: [],
        agentStatus: null,
        readinessStatus: null
      };
    },
    computed: {
      compatibleList: function () {
        return (((this.updates || {}).decisions || {}).compatible_updates || []);
      },
      blockedList: function () {
        return (((this.updates || {}).decisions || {}).blocked_updates || []);
      }
    },
    methods: {
      t: function (key) { return this.$t(key); },
      rowKey: function (item) {
        return [item.artifact_id, item.artifact_type, item.target_version].join(':');
      },
      loadUpdates: function () {
        var self = this;
        self.loading = true;
        self.error = null;
        apiGet('/api/v1/admin/updates/check?channel=' + encodeURIComponent(self.channel)).then(function (res) {
          self.loading = false;
          if (!res.success) {
            self.error = res.error || 'Error';
            return;
          }
          self.updates = res.data || {};
        });
      },
      loadJobs: function () {
        var self = this;
        apiGet('/api/v1/admin/updates/jobs').then(function (res) {
          if (!res.success) return;
          self.jobs = (res.data && res.data.jobs) || [];
          if (!self.lastJob && self.jobs.length) {
            self.lastJob = self.jobs[0];
          }
        });
      },
      checkAgentStatus: function () {
        var self = this;
        apiGet('/api/v1/admin/updates/agent/status').then(function (res) {
          if (!res.success) {
            self.agentStatus = { ok: false, error: res.error || 'unknown', mode: '—', socket: '—' };
            return;
          }
          var data = res.data || {};
          var health = data.agent || {};
          self.agentStatus = {
            ok: !!health.success,
            error: health.error || null,
            mode: data.execution_mode || '—',
            socket: data.socket_path || '—'
          };
        });
      },
      checkReadiness: function () {
        var self = this;
        apiGet('/api/v1/admin/updates/readiness').then(function (res) {
          if (!res.success) {
            self.readinessStatus = { ok: false, error: res.error || 'unknown', mode: '—', gates: [] };
            return;
          }
          var data = res.data || {};
          self.readinessStatus = {
            ok: !!data.production_ready,
            error: null,
            mode: data.execution_mode || '—',
            gates: data.gates || []
          };
        });
      },
      runInstall: function (item) {
        var self = this;
        apiPost('/api/v1/admin/updates/install', {
          artifact_id: item.artifact_id,
          artifact_type: item.artifact_type,
          version: item.target_version
        }).then(function (res) {
          if (!res.success) {
            self.error = res.error || 'Error';
            return;
          }
          self.lastJob = (res.data && res.data.job) || null;
          self.loadJobs();
        });
      },
      runCoreUpdate: function (item) {
        var self = this;
        apiPost('/api/v1/admin/updates/core', {
          artifact_id: item.artifact_id,
          version: item.target_version
        }).then(function (res) {
          if (!res.success) {
            self.error = res.error || 'Error';
            return;
          }
          self.lastJob = (res.data && res.data.job) || null;
          self.loadJobs();
        });
      },
      refreshJob: function () {
        var self = this;
        if (!self.lastJob || !self.lastJob.id) return;
        apiGet('/api/v1/admin/updates/jobs/' + encodeURIComponent(self.lastJob.id)).then(function (res) {
          if (res.success && res.data && res.data.job) {
            self.lastJob = res.data.job;
            self.loadJobs();
          }
        });
      }
    },
    mounted: function () {
      this.loadUpdates();
      this.loadJobs();
      this.checkAgentStatus();
      this.checkReadiness();
    },
    render: function () {
      var self = this;
      var t = this.t;

      function tableCell(text, className) {
        return h('td', className ? { class: className } : null, text == null ? '—' : String(text));
      }

      var installRows = this.compatibleList.map(function (item) {
        var actionBtn = item.artifact_type === 'core'
          ? h('button', {
              type: 'button',
              class: 'btn btn-outline-primary btn-sm',
              onClick: function () { self.runCoreUpdate(item); }
            }, t('updates.update_core'))
          : h('button', {
              type: 'button',
              class: 'btn btn-outline-primary btn-sm',
              onClick: function () { self.runInstall(item); }
            }, t('updates.update_ext'));
        return h('tr', { key: self.rowKey(item) }, [
          tableCell(item.artifact_id),
          tableCell(item.artifact_type),
          tableCell(item.installed_version || '—'),
          tableCell(item.target_version),
          h('td', [h('span', { class: 'badge bg-success' }, 'compatible')]),
          h('td', { class: 'text-end' }, [actionBtn])
        ]);
      });

      if (!installRows.length) {
        installRows.push(
          h('tr', [h('td', { colspan: 6, class: 'text-center text-muted py-3' }, t('updates.no_installable'))])
        );
      }

      var blockedRows = this.blockedList.map(function (item) {
        return h('tr', { key: self.rowKey(item) }, [
          tableCell(item.artifact_id),
          tableCell(item.artifact_type),
          tableCell(item.target_version),
          tableCell(item.block_reason || item.compatibility_reason || 'blocked')
        ]);
      });
      if (!blockedRows.length) {
        blockedRows.push(
          h('tr', [h('td', { colspan: 4, class: 'text-center text-muted py-3' }, t('updates.no_blocked'))])
        );
      }

      return h('div', { class: 'admin-page' }, [
        h('h1', { class: 'mb-3' }, [h('i', { class: 'bi bi-cloud-arrow-down-fill me-2', 'aria-hidden': 'true' }), t('updates.title')]),

        h('div', { class: 'card mb-3' }, [
          h('div', { class: 'card-body d-flex gap-2 align-items-center' }, [
            h('div', { class: 'form-check' }, [
              h('input', {
                id: 'updChannelStable',
                class: 'form-check-input',
                type: 'radio',
                value: 'stable',
                checked: this.channel === 'stable',
                onInput: function () { self.channel = 'stable'; }
              }),
              h('label', { class: 'form-check-label', for: 'updChannelStable' }, 'stable')
            ]),
            h('div', { class: 'form-check' }, [
              h('input', {
                id: 'updChannelBeta',
                class: 'form-check-input',
                type: 'radio',
                value: 'beta',
                checked: this.channel === 'beta',
                onInput: function () { self.channel = 'beta'; }
              }),
              h('label', { class: 'form-check-label', for: 'updChannelBeta' }, 'beta')
            ]),
            h('button', {
              type: 'button',
              class: 'btn btn-primary btn-sm ms-auto',
              disabled: this.loading,
              onClick: this.loadUpdates
            }, t('updates.check'))
          ])
        ]),

        h('div', { class: 'card mb-3' }, [
          h('div', { class: 'card-header d-flex align-items-center' }, [
            h('span', 'Статус Update Agent'),
            h('button', {
              type: 'button',
              class: 'btn btn-sm btn-outline-secondary ms-auto',
              onClick: this.checkAgentStatus
            }, 'Проверить agent')
          ]),
          h('div', { class: 'card-body' }, [
            this.agentStatus
              ? h('div', [
                  h('div', [h('strong', 'Mode: '), this.agentStatus.mode || '—']),
                  h('div', [h('strong', 'Socket: '), this.agentStatus.socket || '—']),
                  h('div', [
                    h('strong', 'Health: '),
                    h('span', { class: this.agentStatus.ok ? 'text-success' : 'text-danger' }, this.agentStatus.ok ? 'OK' : 'FAIL')
                  ]),
                  this.agentStatus.error ? h('div', { class: 'text-danger' }, this.agentStatus.error) : null
                ])
              : h('div', { class: 'text-muted' }, 'Нет данных')
          ])
        ]),

        h('div', { class: 'card mb-3' }, [
          h('div', { class: 'card-header d-flex align-items-center' }, [
            h('span', 'Readiness (production)'),
            h('button', {
              type: 'button',
              class: 'btn btn-sm btn-outline-secondary ms-auto',
              onClick: this.checkReadiness
            }, 'Проверить readiness')
          ]),
          h('div', { class: 'card-body' }, [
            this.readinessStatus
              ? h('div', [
                  h('div', [h('strong', 'Mode: '), this.readinessStatus.mode || '—']),
                  h('div', [
                    h('strong', 'Production ready: '),
                    h('span', { class: this.readinessStatus.ok ? 'text-success' : 'text-danger' }, this.readinessStatus.ok ? 'YES' : 'NO')
                  ]),
                  (this.readinessStatus.gates || []).map(function (gate) {
                    return h('div', { key: gate.id }, [
                      h('strong', String(gate.id || 'gate') + ': '),
                      h('span', { class: gate.ok ? 'text-success' : 'text-danger' }, gate.ok ? 'OK' : 'FAIL'),
                      h('span', { class: 'text-muted' }, ' — ' + String(gate.message || ''))
                    ]);
                  }),
                  this.readinessStatus.error ? h('div', { class: 'text-danger' }, this.readinessStatus.error) : null
                ])
              : h('div', { class: 'text-muted' }, 'Нет данных')
          ])
        ]),

        this.loading
          ? h('div', { class: 'text-center py-3' }, [h('div', { class: 'spinner-border text-primary', role: 'status' })])
          : this.error
            ? h('div', { class: 'alert alert-danger' }, this.error)
            : null,

        h('div', { class: 'alert alert-info' }, [
          h('div', [h('strong', t('updates.source') + ': '), ((this.updates || {}).registry_url || '—')]),
          h('div', [h('strong', t('updates.core_version') + ': '), ((this.updates || {}).current_core_version || '—')]),
          h('div', [h('strong', 'Mode: '), (((this.updates || {}).execution_mode) || '—')])
        ]),

        h('div', { class: 'card mb-3' }, [
          h('div', { class: 'card-header' }, t('updates.installable')),
          h('div', { class: 'card-body p-0' }, [
            h('div', { class: 'table-responsive' }, [
              h('table', { class: 'table table-sm mb-0' }, [
                h('thead', [h('tr', [
                  h('th', t('updates.artifact')),
                  h('th', t('updates.type')),
                  h('th', t('updates.installed')),
                  h('th', t('updates.target')),
                  h('th', t('updates.status')),
                  h('th', { class: 'text-end' }, t('updates.action'))
                ])]),
                h('tbody', installRows)
              ])
            ])
          ])
        ]),

        h('div', { class: 'card mb-3' }, [
          h('div', { class: 'card-header' }, t('updates.blocked')),
          h('div', { class: 'card-body p-0' }, [
            h('div', { class: 'table-responsive' }, [
              h('table', { class: 'table table-sm mb-0' }, [
                h('thead', [h('tr', [
                  h('th', t('updates.artifact')),
                  h('th', t('updates.type')),
                  h('th', t('updates.target')),
                  h('th', t('updates.reason'))
                ])]),
                h('tbody', blockedRows)
              ])
            ])
          ])
        ]),

        h('div', { class: 'card' }, [
          h('div', { class: 'card-header' }, t('updates.last_job')),
          h('div', { class: 'card-body' }, [
            this.lastJob
              ? h('div', [
                  h('div', [h('strong', 'ID: '), this.lastJob.id]),
                  h('div', [h('strong', 'Operation: '), this.lastJob.operation]),
                  h('div', [h('strong', 'Status: '), this.lastJob.status]),
                  h('div', [h('strong', 'Message: '), this.lastJob.message]),
                  h('button', { type: 'button', class: 'btn btn-sm btn-outline-secondary mt-2', onClick: this.refreshJob }, t('updates.refresh_job'))
                ])
              : h('div', { class: 'text-muted' }, t('updates.no_jobs'))
          ])
        ]),

        h('div', { class: 'card mt-3' }, [
          h('div', { class: 'card-header' }, 'История задач'),
          h('div', { class: 'card-body p-0' }, [
            h('div', { class: 'table-responsive' }, [
              h('table', { class: 'table table-sm mb-0' }, [
                h('thead', [h('tr', [
                  h('th', 'ID'),
                  h('th', 'Operation'),
                  h('th', 'Artifact'),
                  h('th', 'Version'),
                  h('th', 'Status')
                ])]),
                h('tbody', (this.jobs || []).length
                  ? this.jobs.map(function (job) {
                      return h('tr', { key: job.id }, [
                        h('td', String(job.id || '')),
                        h('td', String(job.operation || '')),
                        h('td', String(job.artifact_id || '')),
                        h('td', String(job.target_version || '')),
                        h('td', String(job.status || ''))
                      ]);
                    })
                  : [h('tr', [h('td', { colspan: 5, class: 'text-center text-muted py-3' }, 'Нет записей')])])
              ])
            ])
          ])
        ])
      ]);
    }
  });

  app.use(i18n);
  app.mount(mountEl);

  window.addEventListener('admin-locale-changed', function (e) {
    var nextLocale = e.detail && e.detail.locale;
    if (nextLocale && (nextLocale === 'ru' || nextLocale === 'en')) {
      i18n.global.locale.value = nextLocale;
    }
  });
})();
