import { render } from 'preact';
import { initApi, fetchInit } from './api';
import { Widget } from './widget';
import type { WidgetConfig } from './types';

const init = async () => {
    const script = document.querySelector('script[data-key]') as HTMLScriptElement | null;
    if (!script) { console.error('[HelixWidget] Missing data-key attribute'); return; }

    const key = script.getAttribute('data-key') ?? '';
    const baseUrl = script.src.replace(/\/widget\.js.*$/, '');

    initApi(baseUrl, key);

    let config: WidgetConfig;
    try {
        config = await fetchInit();
    } catch (err) {
        console.error('[HelixWidget] Init failed:', err);
        return;
    }

    // Create shadow DOM host
    const host = document.createElement('div');
    host.id = 'helix-widget-host';
    host.style.cssText = 'position:fixed;bottom:20px;right:20px;z-index:999999;font-family:-apple-system,sans-serif;';
    document.body.appendChild(host);

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

    render(<Widget config={config} shadow={shadow} />, mountPoint);
};

if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
} else {
    init();
}
