import { render } from 'preact';
import { initApi, fetchInit } from './api';
import { loadTurnstile } from './captcha';
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;
    }

    // Preload Turnstile script so the captcha gate renders quickly on first open.
    // No-op if siteKey is empty (dev mode — backend fails open).
    if (config.captchaSiteKey) {
        loadTurnstile().catch(() => {
            console.warn('[HelixWidget] Turnstile preload failed — gate will retry on open');
        });
    }

    // Create shadow DOM host
    // No font-family here — we want the widget to inherit from the host page.
    const host = document.createElement('div');
    host.id = 'helix-widget-host';
    host.style.cssText = 'position:fixed;bottom:20px;right:20px;z-index:999999;';
    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();
}
