/**
 * Settings → Cloud Sync (LAN client + cloud hub admin visibility)
 */
(function () {
  function authHeaders() {
    const h = { 'Content-Type': 'application/json' };
    if (window.auth && window.auth.authHeader) Object.assign(h, window.auth.authHeader());
    return h;
  }

  function notify(msg, type) {
    if (window.modernUI && window.modernUI.showNotification) {
      window.modernUI.showNotification(msg, type || 'info');
    } else {
      alert(msg);
    }
  }

  function setVisible(el, show) {
    if (!el) return;
    el.classList.toggle('d-none', !show);
  }

  function showMirrorResult(msg, type) {
    const box = document.getElementById('csMirrorResult');
    if (!box) return;
    box.className = 'alert mb-3 alert-' + (type || 'info');
    box.textContent = msg;
    setVisible(box, true);
  }

  async function loadCloudSyncStatus() {
    const panel = document.getElementById('cloud-sync-settings');
    const nav = document.getElementById('navCloudSync');
    if (!panel) return;

    try {
      const res = await fetch('/api/v1/sync/status', { headers: authHeaders() });
      if (res.status === 403) {
        setVisible(panel, false);
        setVisible(nav, false);
        return;
      }
      if (!res.ok) {
        setVisible(panel, true);
        setVisible(nav, true);
        const err = document.getElementById('csDisabledBanner');
        if (err) {
          err.textContent = 'Could not load cloud sync status (' + res.status + ').';
          setVisible(err, true);
        }
        return;
      }

      const s = await res.json();
      const mode = s.ui_mode || (s.enabled ? 'lan_client' : 'disabled');
      const showPanel = mode === 'lan_client' || mode === 'cloud_hub' || mode === 'disabled';
      setVisible(panel, showPanel);
      setVisible(nav, showPanel);

      const hubBanner = document.getElementById('csHubBanner');
      const hubStats = document.getElementById('csHubStats');
      const lanPanel = document.getElementById('csLanPanel');
      const disabledBanner = document.getElementById('csDisabledBanner');

      setVisible(hubBanner, mode === 'cloud_hub');
      setVisible(hubStats, mode === 'cloud_hub');
      setVisible(lanPanel, mode === 'lan_client');
      setVisible(disabledBanner, mode === 'disabled');

      if (mode === 'cloud_hub') {
        const msg = document.getElementById('csHubMessage');
        if (msg) msg.textContent = s.message || 'This server receives LAN transaction sync.';
        const nc = document.getElementById('csNodeCount');
        if (nc) nc.textContent = s.registered_nodes ?? 0;
        return;
      }

      if (mode === 'disabled') {
        if (disabledBanner) {
          disabledBanner.textContent = s.message || 'Cloud sync is not enabled on this server.';
        }
        return;
      }

      document.getElementById('csCloudUrl').textContent = s.cloud_url || '—';
      document.getElementById('csNodeId').textContent = s.node_configured ? (s.node_id || '—') : 'Not registered';
      document.getElementById('csPending').textContent = s.pending_events ?? 0;
      document.getElementById('csFailed').textContent = s.failed_events ?? 0;
      document.getElementById('csRealtime').checked = !!s.realtime_enabled;
      const deploy = document.getElementById('csDeployMode');
      if (deploy) deploy.textContent = s.deployment_mode || 'local';
      const badge = document.getElementById('csNodeBadge');
      if (badge) {
        badge.className = 'badge ' + (s.node_configured ? 'bg-success' : 'bg-warning text-dark');
        badge.textContent = s.node_configured ? 'Node registered' : 'Register node or create mirror';
      }
      setVisible(document.getElementById('csLicenseKeyWrap'), !s.license_key_configured);

      const provBtn = document.getElementById('csProvisionMirrorBtn');
      if (provBtn) {
        provBtn.disabled = false;
        provBtn.title = s.node_configured
          ? 'Refresh cloud tenant and re-register sync node'
          : 'Create cloud login with same company code and admin password';
      }
    } catch (e) {
      console.warn('Cloud sync status:', e);
      setVisible(panel, true);
      const err = document.getElementById('csDisabledBanner');
      if (err) {
        err.textContent = 'Cloud sync status unavailable: ' + e.message;
        setVisible(err, true);
      }
    }
  }

  async function runCloudSync() {
    const btn = document.getElementById('csSyncNowBtn');
    if (btn) btn.disabled = true;
    try {
      const res = await fetch('/api/v1/sync/run', { method: 'POST', headers: authHeaders() });
      const data = await res.json();
      const detail = typeof data.detail === 'string' ? data.detail : null;
      const msg = detail || data.message || (data.success ? 'Sync complete' : 'Sync failed');
      notify(msg + (data.pushed != null ? ' (pushed: ' + data.pushed + ')' : ''), data.success ? 'success' : 'error');
      loadCloudSyncStatus();
    } catch (e) {
      notify('Sync failed: ' + e.message, 'error');
    } finally {
      if (btn) btn.disabled = false;
    }
  }

  async function whatsAppMyCloudLogin() {
    const phone = prompt(
      'WhatsApp number to receive your cloud login (E.164 or local, e.g. 26771234567):',
      ''
    );
    if (phone === null) return;
    const trimmed = phone.trim();
    if (!trimmed) {
      notify('Phone number is required', 'error');
      return;
    }
    const custom = prompt('Optional note to include in the message:', '') || undefined;
    const btn = document.getElementById('csWhatsAppLoginBtn');
    if (btn) btn.disabled = true;
    try {
      const body = { phone_number: trimmed, prefer_cloud: true };
      if (custom) body.custom_message = custom;
      const res = await fetch('/api/v1/whatsapp/send-login', {
        method: 'POST',
        headers: authHeaders(),
        body: JSON.stringify(body),
      });
      const data = await res.json();
      const detail = typeof data.detail === 'string' ? data.detail : null;
      if (!res.ok) throw new Error(detail || data.message || 'Send failed');
      notify(data.message || 'Sent via WhatsApp', 'success');
      showMirrorResult(data.message || 'Cloud login sent via WhatsApp', 'success');
    } catch (e) {
      notify(e.message, 'error');
      showMirrorResult(e.message, 'danger');
    } finally {
      if (btn) btn.disabled = false;
    }
  }

  async function createCloudMirror() {
    const btn = document.getElementById('csProvisionMirrorBtn');
    if (btn) btn.disabled = true;
    const licenseKey = (document.getElementById('csLicenseKeyInput')?.value || '').trim();
    const body = {};
    if (licenseKey) body.license_key = licenseKey;

    if (!confirm(
      'Create or refresh the cloud mirror tenant?\n\n' +
      'The cloud hub will use the same company code and admin password as this server. ' +
      'Existing transactions can be pushed with Sync now.'
    )) {
      if (btn) btn.disabled = false;
      return;
    }

    try {
      const res = await fetch('/api/v1/sync/provision-mirror', {
        method: 'POST',
        headers: authHeaders(),
        body: JSON.stringify(body),
      });
      const data = await res.json();
      const detail = typeof data.detail === 'string' ? data.detail : null;
      const msg = detail || data.message || (data.success ? 'Cloud mirror ready' : 'Failed');
      showMirrorResult(
        data.cloud_login_url
          ? msg + ' Log in at: ' + data.cloud_login_url
          : msg,
        data.success ? 'success' : 'danger'
      );
      notify(msg, data.success ? 'success' : 'error');
      if (data.success) {
        document.getElementById('csLicenseKeyInput').value = '';
      }
      loadCloudSyncStatus();
    } catch (e) {
      showMirrorResult('Could not create cloud mirror: ' + e.message, 'danger');
      notify(e.message, 'error');
    } finally {
      if (btn) btn.disabled = false;
    }
  }

  async function toggleRealtime() {
    const on = document.getElementById('csRealtime').checked;
    try {
      const res = await fetch('/api/v1/sync/settings', {
        method: 'PATCH',
        headers: authHeaders(),
        body: JSON.stringify({ realtime_enabled: on }),
      });
      const data = await res.json();
      if (!res.ok) {
        notify(data.detail || 'Could not update realtime setting', 'error');
        document.getElementById('csRealtime').checked = !on;
        return;
      }
      notify(on ? 'Real-time sync enabled' : 'Real-time sync disabled', 'success');
    } catch (e) {
      notify(e.message, 'error');
      document.getElementById('csRealtime').checked = !on;
    }
  }

  document.addEventListener('DOMContentLoaded', () => {
    loadCloudSyncStatus();
    document.getElementById('csSyncNowBtn')?.addEventListener('click', runCloudSync);
    document.getElementById('csProvisionMirrorBtn')?.addEventListener('click', createCloudMirror);
    document.getElementById('csWhatsAppLoginBtn')?.addEventListener('click', whatsAppMyCloudLogin);
    document.getElementById('csRealtime')?.addEventListener('change', toggleRealtime);
    document.getElementById('csRefreshBtn')?.addEventListener('click', loadCloudSyncStatus);
  });

  window.loadCloudSyncStatus = loadCloudSyncStatus;
})();
