/**
 * TypeScript definitions for the msger JavaScript API
 *
 * This module provides type-safe access to msger's window control,
 * data persistence, and file system features.
 *
 * Usage:
 * ```typescript
 * import type { MsgerAPI } from '@bobfrankston/msgerdefs';
 *
 * declare global {
 *     interface Window {
 *         msger?: MsgerAPI;
 *     }
 * }
 *
 * // Check if running in msger
 * if (window.msger) {
 *     window.msger.setTitle('My App');
 * }
 * ```
 */

/**
 * Result object returned when the window closes
 */
export interface MsgerResult {
    /** Button that was clicked */
    button: string;
    /** Optional input field value */
    value?: string;
    /** Optional form data */
    form?: Record<string, any>;
    /** True if window was closed via close button */
    closed?: boolean;
    /** True if window was dismissed via Escape key */
    dismissed?: boolean;
    /** True if window was closed due to timeout */
    timeout?: boolean;
}

/**
 * File information returned by file system operations
 */
export interface FileInfo {
    /** File name */
    name: string;
    /** Full file path */
    path: string;
    /** True if this is a directory */
    isDir: boolean;
    /** File size in bytes (0 for directories) */
    size: number;
    /** Last modified timestamp (ISO 8601 string) */
    modified?: string;
}

/**
 * Options for file selection dialogs
 */
export interface FileDialogOptions {
    /** Dialog title */
    title?: string;
    /** Default filename for save dialogs */
    defaultFilename?: string;
    /** File filters (e.g., [{name: "Text", extensions: ["txt", "md"]}]) */
    filters?: Array<{name: string; extensions: string[]}>;
    /** Default directory to open */
    defaultPath?: string;
}

/**
 * Selected file with content
 */
export interface SelectedFile {
    /** File name */
    name: string;
    /** Full file path */
    path: string;
    /** File content as string */
    content: string;
}

/**
 * msger JavaScript API
 *
 * Available when running inside msger via window.msger
 */
export interface MsgerAPI {
    // ========================================
    // Window Control
    // ========================================

    /**
     * Toggle fullscreen mode on/off
     * @example
     * msger.toggleFullscreen();
     */
    toggleFullscreen(): void;

    /**
     * Set fullscreen mode
     * @param enabled - true to enter fullscreen, false to exit
     * @example
     * msger.setFullscreen(true);
     */
    setFullscreen(enabled: boolean): void;

    /**
     * Minimize the window
     * @example
     * msger.minimize();
     */
    minimize(): void;

    /**
     * Toggle maximize/restore window
     * @example
     * msger.maximize();
     */
    maximize(): void;

    /**
     * Set window size
     * @param width - Window width in pixels
     * @param height - Window height in pixels
     * @example
     * msger.setSize(800, 600);
     */
    setSize(width: number, height: number): void;

    /**
     * Set window position
     * @param x - X coordinate in pixels
     * @param y - Y coordinate in pixels
     * @example
     * msger.setPosition(100, 100);
     */
    setPosition(x: number, y: number): void;

    /**
     * Set always-on-top behavior
     * @param enabled - true to keep window on top
     * @example
     * msger.setAlwaysOnTop(true);
     */
    setAlwaysOnTop(enabled: boolean): void;

    /**
     * Set window title
     * @param title - New window title
     * @example
     * msger.setTitle("My Application");
     */
    setTitle(title: string): void;

    /**
     * Close the window
     * @param result - Optional result to return to parent process
     * @example
     * // Close with default dismissed result
     * msger.close();
     *
     * // Close with custom result
     * msger.close({button: 'OK', value: 'user data'});
     */
    close(result?: Partial<MsgerResult>): void;

    /**
     * Send result and close window (legacy compatibility)
     * @param result - Result to return to parent process
     * @example
     * msger.sendResult({button: 'Submit', value: 'form data'});
     */
    sendResult(result: Partial<MsgerResult>): void;

    // ========================================
    // Data Persistence (localStorage wrapper)
    // ========================================

    /**
     * Save data to persistent storage
     * Data is stored with 'msger_' prefix in localStorage
     * @param key - Storage key
     * @param value - Value to store (will be JSON.stringify'd)
     * @returns true on success, false on failure
     * @example
     * msger.saveData('userPrefs', {theme: 'dark', fontSize: 14});
     */
    saveData(key: string, value: any): boolean;

    /**
     * Load data from persistent storage
     * @param key - Storage key
     * @param defaultValue - Default value if key not found
     * @returns Stored value or defaultValue
     * @example
     * const prefs = msger.loadData('userPrefs', {theme: 'light'});
     */
    loadData<T = any>(key: string, defaultValue?: T): T;

    /**
     * Remove data from persistent storage
     * @param key - Storage key to remove
     * @returns true on success, false on failure
     * @example
     * msger.removeData('tempData');
     */
    removeData(key: string): boolean;

    /**
     * Clear all msger data from persistent storage
     * Only removes items with 'msger_' prefix
     * @returns true on success, false on failure
     * @example
     * msger.clearData();
     */
    clearData(): boolean;

    // ========================================
    // File System Access (to be implemented)
    // ========================================

    /**
     * File system operations namespace
     */
    fs?: {
        /**
         * Select a file using native file picker
         * @param options - File dialog options
         * @returns Selected file with content, or null if cancelled
         * @example
         * const file = await msger.fs.selectFile({
         *     title: 'Open File',
         *     filters: [{name: 'Text', extensions: ['txt', 'md']}]
         * });
         * if (file) {
         *     console.log(file.content);
         * }
         */
        selectFile(options?: FileDialogOptions): Promise<SelectedFile | null>;

        /**
         * Select multiple files using native file picker
         * @param options - File dialog options
         * @returns Array of selected files with content
         * @example
         * const files = await msger.fs.selectFiles({
         *     title: 'Open Files'
         * });
         */
        selectFiles(options?: FileDialogOptions): Promise<SelectedFile[]>;

        /**
         * Save file using native save dialog
         * @param content - File content to save
         * @param defaultFilename - Default filename
         * @param options - Additional dialog options
         * @returns Path where file was saved, or null if cancelled
         * @example
         * const path = await msger.fs.saveFileAs('Hello World', 'greeting.txt');
         */
        saveFileAs(
            content: string,
            defaultFilename?: string,
            options?: FileDialogOptions
        ): Promise<string | null>;

        /**
         * Select a directory using native folder picker
         * @param options - Dialog options
         * @returns Selected directory path, or null if cancelled
         * @example
         * const dir = await msger.fs.selectFolder({
         *     title: 'Select Output Folder'
         * });
         */
        selectFolder(options?: FileDialogOptions): Promise<string | null>;

        /**
         * Read file contents
         * Note: Requires allowFs: true flag when launching msger
         * @param path - File path to read
         * @returns File content as string
         * @example
         * const content = await msger.fs.read('/path/to/file.txt');
         */
        read(path: string): Promise<string>;

        /**
         * Write file contents
         * Note: Requires allowFs: true flag when launching msger
         * @param path - File path to write
         * @param content - Content to write
         * @example
         * await msger.fs.write('/path/to/file.txt', 'Hello World');
         */
        write(path: string, content: string): Promise<void>;

        /**
         * List directory contents
         * Note: Requires allowFs: true flag when launching msger
         * @param path - Directory path to list
         * @returns Array of file information
         * @example
         * const files = await msger.fs.list('/path/to/dir');
         */
        list(path: string): Promise<FileInfo[]>;

        /**
         * Check if file or directory exists
         * Note: Requires allowFs: true flag when launching msger
         * @param path - Path to check
         * @returns true if exists
         * @example
         * const exists = await msger.fs.exists('/path/to/file.txt');
         */
        exists(path: string): Promise<boolean>;

        /**
         * Delete file or directory
         * Note: Requires allowFs: true flag when launching msger
         * @param path - Path to delete
         * @example
         * await msger.fs.delete('/path/to/file.txt');
         */
        delete(path: string): Promise<void>;
    };
}

/**
 * Helper to check if code is running in msger
 * @returns true if running in msger environment
 * @example
 * if (isMsger()) {
 *     msger.setTitle('Running in msger!');
 * } else {
 *     console.log('Running in browser');
 * }
 */
export function isMsger(): boolean {
    return typeof window !== 'undefined' && typeof window.msger !== 'undefined';
}

/**
 * Get msger API with fallback for browser compatibility
 * @returns msger API if available, or stub implementation for browser
 * @example
 * const api = getMsgerAPI();
 * api.saveData('key', 'value'); // Works in both msger and browser
 */
export function getMsgerAPI(): MsgerAPI {
    if (isMsger()) {
        return window.msger!;
    }

    // Return browser-compatible stub
    return {
        // Window control - no-op in browser
        toggleFullscreen: () => {},
        setFullscreen: () => {},
        minimize: () => {},
        maximize: () => {},
        setSize: () => {},
        setPosition: () => {},
        setAlwaysOnTop: () => {},
        setTitle: (title: string) => { document.title = title; },
        close: () => { window.close(); },
        sendResult: () => { window.close(); },

        // Data persistence - use localStorage in browser
        saveData: (key: string, value: any): boolean => {
            try {
                localStorage.setItem('msger_' + key, JSON.stringify(value));
                return true;
            } catch {
                return false;
            }
        },
        loadData: <T = any>(key: string, defaultValue?: T): T => {
            try {
                const item = localStorage.getItem('msger_' + key);
                return item ? JSON.parse(item) : (defaultValue as T);
            } catch {
                return defaultValue as T;
            }
        },
        removeData: (key: string): boolean => {
            try {
                localStorage.removeItem('msger_' + key);
                return true;
            } catch {
                return false;
            }
        },
        clearData: (): boolean => {
            try {
                const keys = Object.keys(localStorage);
                for (const key of keys) {
                    if (key.startsWith('msger_')) {
                        localStorage.removeItem(key);
                    }
                }
                return true;
            } catch {
                return false;
            }
        },

        // File system - not available in browser
        fs: undefined
    };
}

/**
 * Declare global window.msger
 */
declare global {
    interface Window {
        msger?: MsgerAPI;
    }
}

export default {
    isMsger,
    getMsgerAPI
};
