/**
 * Windows Internet Shortcut (.url) downloads — local LAN ERP + cloud hub.
 * Uses CNP Solutions logo as shortcut icon (deployed at /static/icons/cnp-solutions-logo.ico).
 */
(function (global) {
  'use strict';

  const DEFAULT_CLOUD = 'https://erp.cnpsolutions.co.bw';
  const DEFAULT_LOCAL = 'http://localhost:8010';
  const ICON_PATH = '/static/icons/cnp-solutions-logo.ico';
  const LOGIN_PATH = '/static/login.html?from=home';

  let _setupHints = null;
  let _setupHintsPromise = null;

  function normalizeOrigin(url) {
    if (!url || typeof url !== 'string') return '';
    return url.trim().replace(/\/+$/, '');
  }

  function isLocalHostname(host) {
    return host === 'localhost' || host === '127.0.0.1' || host === '0.0.0.0';
  }

  function loginUrl(origin) {
    return normalizeOrigin(origin) + LOGIN_PATH;
  }

  function iconUrl(origin) {
    return normalizeOrigin(origin) + ICON_PATH;
  }

  function buildInternetShortcut(targetLoginUrl, iconOrigin) {
    const base = normalizeOrigin(iconOrigin || targetLoginUrl.split('/static/')[0]);
    return [
      '[InternetShortcut]',
      'URL=' + targetLoginUrl,
      'IDList=',
      'IconFile=' + iconUrl(base),
      'IconIndex=0',
      '[{000214A0-0000-0000-C000-000000000046}]',
      'Prop3=19,2',
    ].join('\r\n');
  }

  function triggerDownload(filename, content) {
    const blob = new Blob([content], { type: 'application/octet-stream' });
    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(a.href);
  }

  async function loadSetupHints() {
    if (_setupHints) return _setupHints;
    if (_setupHintsPromise) return _setupHintsPromise;
    _setupHintsPromise = (async () => {
      try {
        const res = await fetch('/api/v1/companies/check-setup');
        if (res.ok) {
          _setupHints = await res.json();
          return _setupHints;
        }
      } catch (_) { /* offline marketing page */ }
      _setupHints = {};
      return _setupHints;
    })();
    return _setupHintsPromise;
  }

  function resolveLocalOrigin(hints) {
    const host = window.location.hostname;
    if (isLocalHostname(host)) return window.location.origin;
    const port = window.location.port && !['80', '443', ''].includes(window.location.port)
      ? ':' + window.location.port
      : '';
    if (hints && hints.deployment_mode && hints.deployment_mode !== 'cloud' && isLocalHostname(host)) {
      return window.location.origin;
    }
    return DEFAULT_LOCAL;
  }

  function resolveCloudOrigin(hints) {
    const fromApi = normalizeOrigin(hints?.erp_public_url || hints?.license_cloud_url || '');
    if (fromApi) return fromApi;
    const host = window.location.hostname || '';
    if (host.includes('cnpsolutions.co.bw')) return window.location.origin;
    return DEFAULT_CLOUD;
  }

  async function downloadShortcut(kind, options) {
    const hints = await loadSetupHints();
    const opts = options || {};
    let origin;
    let filename;
    let label;

    if (kind === 'local') {
      origin = normalizeOrigin(opts.origin) || resolveLocalOrigin(hints);
      filename = opts.filename || 'CNPERP Local ERP.url';
      label = opts.label || 'Local ERP (LAN server)';
    } else if (kind === 'cloud') {
      origin = normalizeOrigin(opts.origin) || resolveCloudOrigin(hints);
      filename = opts.filename || 'CNPERP Cloud ERP.url';
      label = opts.label || 'Cloud ERP (online hub)';
    } else {
      throw new Error('Unknown shortcut kind: ' + kind);
    }

    const target = loginUrl(origin);
    const iconOrigin = normalizeOrigin(opts.iconOrigin) || window.location.origin || origin;
    triggerDownload(filename, buildInternetShortcut(target, iconOrigin));

    return { kind, origin, target, filename, label };
  }

  async function downloadLocal(options) {
    return downloadShortcut('local', options);
  }

  async function downloadCloud(options) {
    return downloadShortcut('cloud', options);
  }

  async function downloadBoth(options) {
    const local = await downloadLocal(options);
    await new Promise((r) => setTimeout(r, 400));
    const cloud = await downloadCloud(options);
    return { local, cloud };
  }

  function showShortcutInstructions(results) {
    const lines = Array.isArray(results) ? results : [results];
    const names = lines.map((r) => r.filename).join('\n  • ');
    alert(
      'Shortcut(s) downloaded!\n\n' +
      '  • ' + names + '\n\n' +
      'Move each file from Downloads to your Desktop (or right-click → Send to → Desktop).\n\n' +
      '• Local — your LAN server (default http://localhost:8010)\n' +
      '• Cloud — online hub linked to local via cloud sync\n\n' +
      'You can keep both shortcuts installed at the same time.'
    );
  }

  global.CNPDesktopShortcuts = {
    DEFAULT_CLOUD,
    DEFAULT_LOCAL,
    ICON_PATH,
    LOGIN_PATH,
    downloadLocal,
    downloadCloud,
    downloadBoth,
    showShortcutInstructions,
    buildInternetShortcut,
    resolveLocalOrigin,
    resolveCloudOrigin,
  };
})(typeof window !== 'undefined' ? window : globalThis);
