import './cbre-signal';
import type { CbreSignal } from './cbre-signal';
import type { SignalSettings } from './types';

export { CbreSignal } from './cbre-signal';
export { capture } from './capture';
export type { SignalSettings } from './types';

let instance: CbreSignal | null = null;

/** Mount the widget from a settings object. Idempotent: a second call updates the existing element. */
export function init(settings: SignalSettings): CbreSignal {
  const el = (instance ?? document.querySelector('cbre-signal') ?? document.createElement('cbre-signal')) as CbreSignal;
  el.setAttribute('app-key', settings.appKey);
  el.setAttribute('api-base', settings.apiBase);
  if (settings.env) el.setAttribute('env', settings.env);
  if (settings.appVersion) el.setAttribute('app-version', settings.appVersion);
  if (settings.position) el.setAttribute('position', settings.position);
  if (settings.theme) el.setAttribute('theme', settings.theme);
  if (typeof settings.userRole === 'function') el.roleProvider = settings.userRole;
  else if (settings.userRole) el.setAttribute('user-role', settings.userRole);
  if (typeof settings.userName === 'function') el.nameProvider = settings.userName;
  else if (settings.userName) el.setAttribute('user-name', settings.userName);
  if (settings.appSecret) el.setAttribute('app-secret', settings.appSecret);
  if (settings.userEmail) el.setAttribute('user-email', settings.userEmail);
  if (settings.loadFonts) el.setAttribute('load-fonts', '');
  if (settings.captureHttp !== false) el.setAttribute('capture-http', '');
  el.tokenProvider = settings.tokenProvider ?? null;
  if (!el.isConnected) (document.body ?? document.documentElement).appendChild(el);
  instance = el;
  return el;
}

/** The mounted element, if any. */
export function get(): CbreSignal | null {
  return instance ?? (document.querySelector('cbre-signal') as CbreSignal | null);
}
export const open = () => get()?.open();
export const close = () => get()?.close();
export const setContext = (ctx: Record<string, unknown>) => get()?.setContext(ctx);
export const reportError = (err: { message: string; status?: number; method?: string; url?: string }) => get()?.reportError(err);
export const attach = (files: File[], opts?: { edit?: boolean }) => get()?.attach(files, opts);
export const refreshAuth = () => get()?.refreshAuth();
export const setTheme = (theme: 'light' | 'dark' | 'auto') => get()?.setAttribute('theme', theme);

// The IIFE build exposes the module as window.CbreSignal; do the same for ESM / dev so host code has one API.
const api = { init, get, open, close, setContext, reportError, attach, refreshAuth, setTheme };
(window as unknown as { CbreSignal?: typeof api }).CbreSignal ??= api;

// ---- snippet auto-init -------------------------------------------------------------
// Either  window.cbreSignalSettings = {...}  before the script tag, or data-* attributes on the tag.
function autoInit(): void {
  const fromWindow = window.cbreSignalSettings;
  const tag = document.currentScript as HTMLScriptElement | null;
  const d = (tag?.dataset ?? {}) as Record<string, string | undefined>;
  const fromTag: SignalSettings | null = d.appKey && d.apiBase
    ? { appKey: d.appKey, apiBase: d.apiBase, env: d.env, appVersion: d.appVersion, appSecret: d.appSecret,
        userEmail: d.userEmail, userName: d.userName, userRole: d.userRole, loadFonts: 'loadFonts' in d,
        captureHttp: d.captureHttp !== 'false', position: d.position as SignalSettings['position'],
        theme: d.theme as SignalSettings['theme'] }
    : null;
  const settings = fromWindow ?? fromTag;
  if (!settings || !settings.appKey || !settings.apiBase) return;
  const run = () => init(settings);
  if (document.body) run(); else document.addEventListener('DOMContentLoaded', run, { once: true });
}
autoInit();
