import { mountToolbar, type WidgetConfig } from './toolbar';

(function () {
  const cfg = (window as unknown as Record<string, unknown>).accessmateWidgetConfig as WidgetConfig | undefined;

  const config: WidgetConfig = cfg ?? {
    color:    '#7c6aff',
    position: 'bottom-right',
    features: ['font', 'contrast', 'dyslexia'],
  };

  if (config.enabled === false) return;
  if (!config.features || config.features.length === 0) return;

  const h = config.offset_horizontal ?? 15;

  // A logged-in admin viewing the frontend still sees WP's own #wpadminbar
  // (fixed, 32px tall, or 46px under its own <=782px breakpoint) — a widget
  // positioned top-right/top-left would otherwise render UNDER it, since
  // offset_vertical has no awareness of the admin bar's actual height.
  const adminBarH = (document.getElementById('wpadminbar') as HTMLElement | null)?.offsetHeight ?? 0;
  const v = (config.offset_vertical ?? 15) + adminBarH;

  const POSITIONS: Record<string, string> = {
    'bottom-right': `bottom:${config.offset_vertical ?? 15}px;right:${h}px`,
    'bottom-left':  `bottom:${config.offset_vertical ?? 15}px;left:${h}px`,
    'top-right':    `top:${v}px;right:${h}px`,
    'top-left':     `top:${v}px;left:${h}px`,
  };

  const host   = document.createElement('div');
  host.id      = 'accessmate-widget-host';
  host.style.cssText = `position:fixed;z-index:2147483647;${POSITIONS[config.position] ?? POSITIONS['bottom-right']}`;

  const shadow = host.attachShadow({ mode: 'open' });
  document.body.appendChild(host);

  mountToolbar(shadow, config);
})();
