/**
 * useBreakout — Breakout window management
 *
 * Module-level Map survives HMR so we never lose window references.
 * Single source of truth for presets and token derivation.
 */

import { ref, type Ref } from 'vue';

export interface BreakoutRequest {
    name: string;
    preset: string;
    nonce: string;
    resolve: (confirmed: boolean) => void;
}

// ── Module-level (survives HMR) ──
const windows = new Map<string, Window>();

export const PRESETS: Record<string, [number, number]> = {
    mobile: [375, 812],
    tablet: [768, 1024],
    'tablet-landscape': [1024, 768],
    desktop: [1280, 800],
};

export function deriveToken(parentToken: string, name: string): string {
    return `${parentToken}-breakout-${name}`;
}

export function useBreakout() {
    const pendingRequest: Ref<BreakoutRequest | null> = ref(null);

    /** Open a breakout — shows confirmation modal, resolves when user confirms/denies */
    async function open(args: { name: string; preset?: string; w?: number; h?: number }): Promise<any> {
        const parentToken = sessionStorage.getItem('hermes_takeover_token');
        if (!parentToken) return { error: 'No takeover token active' };

        const name = args.name || 'mobile';
        const preset = args.preset || 'desktop';

        // Close existing with same name
        const existing = windows.get(name);
        if (existing && !existing.closed) existing.close();

        const nonce = Math.random().toString(36).slice(2, 6);
        const [pw, ph] = args.w && args.h ? [args.w, args.h] : (PRESETS[preset] || PRESETS.desktop);
        const presetLabel = `${pw}x${ph}`;

        return new Promise((resolve) => {
            pendingRequest.value = {
                name,
                preset: presetLabel,
                nonce,
                resolve: (confirmed: boolean) => {
                    pendingRequest.value = null;
                    if (!confirmed) { resolve({ error: 'rejected by user' }); return; }
                    const token = deriveToken(parentToken, name);
                    const url = `${window.location.origin}${window.location.pathname}?breakout_token=${token}#/agents`;
                    const popup = window.open(url, `hermes_breakout_${name}`, `width=${pw},height=${ph},resizable=yes,scrollbars=yes`);
                    if (!popup) { resolve({ error: 'popup blocked' }); return; }
                    windows.set(name, popup);
                    resolve({ opened: name, token, size: presetLabel });
                },
            };
        });
    }

    /** Open breakout directly from DevView UI (no modal — user is clicking the button) */
    function openDirect(name: string, presetStr: string, parentToken: string) {
        const [w, h] = presetStr.split('x').map(Number);
        const token = deriveToken(parentToken, name);
        const url = `${window.location.origin}${window.location.pathname}?breakout_token=${token}#/agents`;
        const popup = window.open(url, `hermes_breakout_${name}`, `width=${w},height=${h},resizable=yes,scrollbars=yes`);
        if (!popup) { alert('Popup blocked -- allow popups for this site'); return; }
        windows.set(name, popup);
    }

    function list(): Record<string, { alive: boolean }> {
        const result: Record<string, { alive: boolean }> = {};
        for (const [name, win] of windows) {
            result[name] = { alive: !win.closed };
            if (win.closed) windows.delete(name);
        }
        return result;
    }

    function close(args: { name: string }): { closed: string } | { error: string } {
        const win = windows.get(args.name);
        if (!win) return { error: `No breakout: ${args.name}` };
        if (!win.closed) win.close();
        windows.delete(args.name);
        return { closed: args.name };
    }

    return { windows, pendingRequest, open, openDirect, list, close };
}
