import { logger } from './logger.js';
import { fileLogger } from './log.js';
let resizeTimer = null;
let pendingResize = null;
let stats = {
    lastCols: 0,
    lastRows: 0,
    burstCount: 0,
    lastResizeTime: 0,
    totalResizes: 0,
};
const DEBOUNCE_MS = 150;
const BURST_WINDOW_MS = 500;
let rebuildCallback = null;
/**
 * Initialize resize controller
 */
export function initResizeController(screen, onRebuild) {
    rebuildCallback = onRebuild;
    // Get initial size
    stats.lastCols = screen.width;
    stats.lastRows = screen.height;
    // Listen for resize events
    screen.on('resize', () => {
        const cols = screen.width;
        const rows = screen.height;
        fileLogger.force(`[RESIZE] Resize event detected: ${cols}x${rows}`);
        handleResize(cols, rows);
    });
    // CRITICAL: Check if screen size changed after initialization
    // Sometimes blessed reports a different size after a short delay
    setTimeout(() => {
        const currentCols = screen.width;
        const currentRows = screen.height;
        if (currentCols !== stats.lastCols || currentRows !== stats.lastRows) {
            fileLogger.force(`[RESIZE] Screen size changed after init: ${stats.lastCols}x${stats.lastRows} -> ${currentCols}x${currentRows}`);
            handleResize(currentCols, currentRows);
        }
    }, 100); // Check after 100ms
    logger.debug(`Resize controller initialized: ${stats.lastCols}x${stats.lastRows}`);
}
/**
 * Handle resize event (debounced)
 */
function handleResize(cols, rows) {
    const now = Date.now();
    // Check if this is part of a burst
    if (now - stats.lastResizeTime < BURST_WINDOW_MS) {
        stats.burstCount++;
    }
    else {
        stats.burstCount = 1;
    }
    stats.lastResizeTime = now;
    pendingResize = { cols, rows };
    // Clear existing timer
    if (resizeTimer) {
        clearTimeout(resizeTimer);
    }
    // Debounce: wait 150ms before committing
    resizeTimer = setTimeout(() => {
        commitResize();
    }, DEBOUNCE_MS);
    logger.debug(`Resize event: ${cols}x${rows} (burst: ${stats.burstCount})`);
}
/**
 * Commit resize (atomic rebuild)
 */
async function commitResize() {
    if (!pendingResize || !rebuildCallback) {
        return;
    }
    const { cols, rows } = pendingResize;
    pendingResize = null;
    stats.lastCols = cols;
    stats.lastRows = rows;
    stats.totalResizes++;
    logger.debug(`Committing resize: ${cols}x${rows} (total: ${stats.totalResizes})`);
    try {
        // Atomic rebuild: destroy + recreate everything
        await rebuildCallback(cols, rows);
        logger.debug(`Resize committed successfully`);
    }
    catch (error) {
        logger.error(`Resize rebuild failed: ${error.message}`);
    }
}
/**
 * Get resize statistics
 */
export function getResizeStats() {
    return { ...stats };
}
/**
 * Force immediate rebuild (for dbg:panic)
 */
export async function forceRebuild() {
    if (resizeTimer) {
        clearTimeout(resizeTimer);
        resizeTimer = null;
    }
    if (pendingResize && rebuildCallback) {
        await commitResize();
    }
    else if (rebuildCallback) {
        // Rebuild with current stats
        await rebuildCallback(stats.lastCols, stats.lastRows);
    }
}
/**
 * Destroy resize controller
 */
export function destroyResizeController() {
    if (resizeTimer) {
        clearTimeout(resizeTimer);
        resizeTimer = null;
    }
    rebuildCallback = null;
    pendingResize = null;
    logger.debug('Resize controller destroyed');
}
//# sourceMappingURL=resizeController.js.map