"use strict";
// FivoCell TUI v6 — Supreme AI Operating System
// 25% hero banner · live dashboard cards · premium home panel · 4-row command box
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.addOutput = addOutput;
exports.setHome = setHome;
exports.setStats = setStats;
exports.startTUI = startTUI;
exports.stopTUI = stopTUI;
const os = __importStar(require("os"));
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const figlet_1 = __importDefault(require("figlet"));
const pkg = require('../../../../package.json');
const CSI = '\x1b[';
const HIDE = CSI + '?25l';
const SHOW = CSI + '?25h';
const CLS = CSI + '2J' + CSI + 'H';
const ERL = CSI + '2K';
const ALT = CSI + '?1049h';
const MAIN = CSI + '?1049l';
const cu = (r, c) => CSI + r + ';' + c + 'H';
const OR = '\x1b[38;2;255;171;64m';
const OG = '\x1b[38;2;255;200;120m';
const GR = '\x1b[38;2;74;222;128m';
const RD = '\x1b[38;2;248;113;113m';
const YW = '\x1b[38;2;251;191;36m';
const BL = '\x1b[38;2;96;165;250m';
const CY = '\x1b[38;2;34;211;238m';
const DM = '\x1b[38;2;100;100;120m';
const D2 = '\x1b[38;2;70;70;90m';
const WT = '\x1b[38;2;240;240;250m';
const BG = '\x1b[48;2;255;171;64m';
const BG2 = '\x1b[48;2;30;30;45m';
const RS = '\x1b[0m';
const o = (s) => OR + s + RS;
const og = (s) => OG + s + RS;
const g = (s) => GR + s + RS;
const r = (s) => RD + s + RS;
const y = (s) => YW + s + RS;
const b = (s) => BL + s + RS;
const c = (s) => CY + s + RS;
const dm = (s) => DM + s + RS;
const dl = (s) => D2 + s + RS;
const wt = (s) => WT + s + RS;
const wts = WT; // raw string escape code (for composition)
const bl = (s) => '\x1b[1m' + s + RS;
const sel = (s) => BG + '\x1b[38;2;18;18;24m\x1b[1m' + s + RS;
const card = (s) => BG2 + s + RS;
const pad = (s, n) => s + ' '.repeat(Math.max(0, n - s.replace(/\x1b\[[0-9;]*m/g, '').length));
const CMDS = [
    ['/help', 'All commands', ''],
    ['/context', '@cell memory', 'context'],
    ['/scan', 'Scan codebase', 'scan'],
    ['/start', 'Start daemon', 'start'],
    ['/stop', 'Stop daemon', 'stop'],
    ['/status', 'Project status', 'status'],
    ['/doctor', 'Health check', 'doctor'],
    ['/vibe', 'Personality', 'vibe'],
    ['/profile', 'View profile', 'profile'],
    ['/memory', 'Memory stats', 'memory'],
    ['/handoff', 'Handoff', 'handoff'],
    ['/continue', 'Continue', 'continue'],
    ['/session', 'Sessions', 'session'],
    ['/decisions', 'Decisions', 'decisions'],
    ['/watch', 'File watcher', 'watch'],
    ['/blindspots', 'Quality', 'blindspots'],
    ['/sync', 'Encrypted sync', 'sync'],
    ['/cloud', 'Cloud', 'cloud'],
    ['/team', 'Team', 'team'],
    ['/community', 'Community', 'community'],
    ['/teach', 'Teach Cell', 'teach'],
    ['/install-hook', 'Git hooks', 'install-hook'],
    ['/exit', 'Exit', 'exit'],
];
var rr = 30, cc = 100;
var inp = '', pal = false, pi = 0;
var pf = [];
var out = [];
var cb = null;
var un = null;
var on = false;
var hd = {};
var stats = { memory: 0, patterns: 0, handoffs: 0, lastSync: '—' };
const sz = () => [process.stdout.rows || 30, process.stdout.columns || 100];
function visLen(s) { return s.replace(/\x1b\[[0-9;]*m/g, '').length; }
function center(text, w) {
    const l = visLen(text);
    const p = Math.max(0, Math.floor((w - l) / 2));
    return ' '.repeat(p) + text;
}
// ═══════════════════════════════════════════════════════════════════════════════
// DRAW
// ═══════════════════════════════════════════════════════════════════════════════
function draw() {
    [rr, cc] = sz();
    let b = CLS;
    // ═══════════════ BANNER — 25% of screen, full width ═══════════════
    const bannerH = Math.max(8, Math.floor(rr * 0.22));
    const BW = cc - 2; // full width
    const BL = 1;
    // Outer frame — thick double border
    b += cu(1, BL) + o('╔' + '═'.repeat(BW - 2) + '╗');
    for (let i = 2; i < bannerH; i++) {
        b += cu(i, BL) + o('║' + ' '.repeat(BW - 2) + '║');
    }
    b += cu(bannerH, BL) + o('╚' + '═'.repeat(BW - 2) + '╝');
    // FivoCell classic FIGlet banner — generate once on startup
    const fivoArt = figlet_1.default.textSync('FIVO CELL', { font: 'ANSI Shadow', width: 200, whitespaceBreak: true });
    const fivoLines = fivoArt.split('\n').filter((l) => l.length > 0);
    const fivoH = fivoLines.length;
    // Center the art vertically inside banner
    const fivoStart = Math.max(2, Math.floor((bannerH - fivoH) / 2) + 1);
    for (let i = 0; i < fivoH; i++) {
        if (fivoStart + i >= bannerH)
            break;
        b += cu(fivoStart + i, 1) + o('║') + center(og(bl(fivoLines[i])), BW - 2) + o('║');
    }
    // Subtitle (positioned below the FIVO CELL art)
    const sub = bl(wts + 'Developer Memory Intelligence' + RS);
    const subRow = Math.min(bannerH - 1, fivoStart + fivoH + 1);
    b += cu(subRow, 1) + o('║') + center(sub, BW - 2) + o('║');
    // Version line
    const ver = dm('  v' + pkg.version + '  ·  AI Operating System  ·  Ready  ');
    b += cu(subRow + 1, 1) + o('║') + center(ver, BW - 2) + o('║');
    // ═══════════════ STATUS DASHBOARD BAR — equal-width widgets ═══════════════
    const cardRow = bannerH + 2;
    const cards = [
        { ico: '●', lbl: 'DAEMON', val: 'Active', c: (s) => GR + s + RS },
        { ico: '●', lbl: 'COMMUNITY', val: 'Online', c: (s) => GR + s + RS },
        { ico: '●', lbl: 'MCP', val: ':9876', c: (s) => GR + s + RS },
        { ico: '●', lbl: 'SYNC', val: 'Ready', c: (s) => GR + s + RS },
        { ico: '●', lbl: 'WORKSTATION', val: os.userInfo().username.slice(0, 12), c: (s) => BL + s + RS },
    ];
    const cw = Math.floor((cc - 12) / 5);
    const cgap = 2;
    let cx = 2;
    for (let i = 0; i < 5; i++) {
        const cd = cards[i];
        b += cu(cardRow, cx) + card(o('┌' + '─'.repeat(cw) + '┐'));
        b += cu(cardRow + 1, cx) + card(o('│') + ' '.repeat(cw) + o('│'));
        b += cu(cardRow + 2, cx) + card(o('│') + cd.c(bl('  ' + cd.ico + '  ' + cd.val.padEnd(cw - 4))) + o('│'));
        b += cu(cardRow + 3, cx) + card(o('│') + ' '.repeat(cw) + o('│'));
        b += cu(cardRow + 4, cx) + card(o('└' + '─'.repeat(cw) + '┘'));
        b += cu(cardRow + 5, cx) + dm(center(cd.lbl, cw + 2));
        cx += cw + cgap + 1;
    }
    // ═══════════════ HOME PANEL — feels alive ═══════════════
    const homeTop = cardRow + 7;
    const hpW = cc - 4;
    b += cu(homeTop - 1, 1) + dm('─'.repeat(cc));
    // Panel header
    b += cu(homeTop, 3) + bl(o(' ' + '◈  HOME  '));
    b += cu(homeTop, Math.min(cc - 30, hpW - 4)) + dm('Live project state');
    // 3-column home panel
    const rH = homeTop + 1;
    const colW = Math.floor((hpW - 6) / 3);
    const items1 = [
        ['Project', hd.project || '—'],
        ['Workspace', hd.workspace || '—'],
        ['Workstation', os.hostname().slice(0, 16)],
    ];
    const items2 = [
        ['Memory', String(stats.memory) + ' events'],
        ['Patterns', String(stats.patterns) + ' learned'],
        ['Handoffs', String(stats.handoffs) + ' active'],
    ];
    const items3 = [
        ['Last Sync', stats.lastSync],
        ['Community', 'Online'],
        ['Cloud', 'Ready'],
    ];
    for (let r = 0; r < 3; r++) {
        const yL = rH + r;
        b += cu(yL, 3) + dm(' ▸ ') + o(items1[r][0].padEnd(11)) + wt(items1[r][1]);
        b += cu(yL, 3 + colW) + dm(' ▸ ') + o(items2[r][0].padEnd(11)) + wt(items2[r][1]);
        b += cu(yL, 3 + colW * 2) + dm(' ▸ ') + o(items3[r][0].padEnd(11)) + wt(items3[r][1]);
    }
    b += cu(homeTop + 4, 1) + dm('─'.repeat(cc));
    // ═══════════════ OUTPUT + PALETTE + INPUT ═══════════════
    const hintRow = homeTop + 5;
    b += cu(hintRow, 3) + dm('Type ') + o('/') + dm(' to open command palette  ·  Try ') + o('/help') + dm('  ') + o('/vibe') + dm('  ') + o('/scan') + dm('  ') + o('/cloud');
    let lp = hintRow + 1;
    const inH = 5; // tall input box
    const palH = pal ? Math.min(pf.length, rr - lp - inH - 1) : 0;
    const outH = Math.max(2, rr - lp - palH - inH - 1);
    // Output area
    const vis = out.slice(-outH);
    for (let i = 0; i < outH; i++) {
        b += cu(lp + i, 1) + ERL;
        if (i < vis.length)
            b += cu(lp + i, 3) + vis[i];
    }
    lp += outH;
    // Floating palette
    if (pal && palH > 0) {
        for (let i = 0; i < palH; i++) {
            const [cmd, desc] = pf[i];
            b += cu(lp + 1 + i, 1) + ERL;
            b += cu(lp + 1 + i, 3) + (i === pi ? sel : dm)('  ' + pad(cmd, 22) + '  ' + desc) + RS;
        }
        lp += palH + 1;
    }
    // Auto-suggestions above input
    if (!pal && inp.startsWith('/') && pf.length > 0) {
        for (let i = 0; i < Math.min(4, pf.length); i++) {
            const [cmd, desc] = pf[i];
            b += cu(rr - inH - 1 - i, 3) + (i === 0 ? o('▸ ') : dm('  ')) + o(cmd) + dm(' — ' + desc);
        }
    }
    // ═══════════════ COMMAND BOX — tall, full-width, premium ═══════════════
    const boxTop = rr - inH + 1;
    const boxW = cc - 6;
    // Top glow
    b += cu(boxTop, 3) + o('╔' + '═'.repeat(boxW) + '╗');
    // Inner empty
    b += cu(boxTop + 1, 3) + o('║') + ' '.repeat(boxW) + o('║');
    // Input row
    const ph = inp || dm('  Type / for commands…');
    const pW3 = boxW - visLen(ph) - 4;
    b += cu(boxTop + 2, 3) + o('║ ') + ph + ' '.repeat(Math.max(0, pW3)) + o(' ║');
    // Bottom row
    b += cu(boxTop + 3, 3) + o('║') + ' '.repeat(boxW) + o('║');
    b += cu(boxTop + 4, 3) + o('╚' + '═'.repeat(boxW) + '╝');
    // Cursor
    b += cu(boxTop + 2, 5 + inp.length) + SHOW;
    process.stdout.write(b);
}
// ═══════════════════════════════════════════════════════════════════════════════
// PUBLIC API
// ═══════════════════════════════════════════════════════════════════════════════
function addOutput(text, type = '') {
    const px = type === 'success' ? g('✓ ') : type === 'error' ? r('✗ ') : type === 'warn' ? y('⚠ ') : type === 'info' ? b('ℹ ') : '';
    const full = px + text;
    const mw = cc - 8;
    if (full.length <= mw) {
        if (out.length > 0 && (visLen(out[out.length - 1]) + full.length) <= mw)
            out[out.length - 1] += '  ' + full;
        else
            out.push(full);
    }
    else {
        let rem = full;
        while (rem.length > mw) {
            const brk = rem.lastIndexOf(' ', mw);
            const cut = brk > mw / 2 ? brk : mw;
            out.push(rem.slice(0, cut).trim());
            rem = '  ' + rem.slice(cut).trim();
        }
        if (rem.trim())
            out.push(rem);
    }
    if (out.length > 500)
        out = out.slice(-500);
    if (on)
        draw();
}
function setHome(data) { hd = data; if (on)
    draw(); }
function setStats(s) { stats = s; if (on)
    draw(); }
// ─── PALETTE ──────────────────────────────────────────────────────────────────
function openPal() { pal = true; pi = 0; pf = CMDS; inp = '/'; draw(); }
function closePal() { pal = false; inp = ''; pf = []; pi = 0; draw(); }
function filterPal() {
    const q = inp.slice(1).toLowerCase();
    pf = q ? CMDS.filter(([c, d]) => c.toLowerCase().includes(q) || d.toLowerCase().includes(q)) : CMDS;
    pi = 0;
    draw();
}
function inlineFilter(q) {
    if (!q.startsWith('/'))
        return;
    pf = CMDS.filter(([c, d]) => c.toLowerCase().includes(q.toLowerCase()) || d.toLowerCase().includes(q.toLowerCase()));
}
// ─── KEY HANDLER ──────────────────────────────────────────────────────────────
function key(buf) {
    const s = buf.toString();
    if (s === '\x03') {
        clean();
        process.exit(0);
    }
    if (pal) {
        if (s === '\x1b[A') {
            pi = Math.max(0, pi - 1);
            draw();
            return;
        }
        if (s === '\x1b[B') {
            pi = Math.min(pf.length - 1, pi + 1);
            draw();
            return;
        }
        if (s === '\r' || s === '\n') {
            const el = pf[pi];
            const cmd = el ? el[1] : inp;
            closePal();
            addOutput('▶ ' + cmd, '');
            if (el && el[2]) {
                if (cb)
                    cb(el[2]);
            }
            else {
                const cl = cmd.replace(/^\//, '');
                if (cb)
                    cb(cl);
            }
            return;
        }
        if (s === '\x1b') {
            closePal();
            return;
        }
        if (s === '\x7f' || s === '\b') {
            if (inp.length <= 1)
                closePal();
            else {
                inp = inp.slice(0, -1);
                filterPal();
            }
            return;
        }
        if (s.length === 1 && s.charCodeAt(0) >= 32) {
            inp += s;
            filterPal();
            return;
        }
        return;
    }
    if (s === '\r' || s === '\n') {
        const l = inp.trim();
        inp = '';
        if (l) {
            addOutput('▶ ' + l, '');
            if (cb)
                cb(l);
        }
        draw();
        return;
    }
    if (s === '\x7f' || s === '\b') {
        if (inp.length > 0) {
            inp = inp.slice(0, -1);
            draw();
        }
        return;
    }
    if (s === '/' && inp.length === 0) {
        openPal();
        return;
    }
    if (s === '\x1b[A' && inp.length === 0) {
        openPal();
        return;
    }
    if (s.length === 1 && s.charCodeAt(0) >= 32) {
        inp += s;
        inlineFilter(inp);
        draw();
    }
}
function clean() {
    if (un) {
        un();
        un = null;
    }
    process.stdout.write(SHOW + MAIN);
    on = false;
}
function startTUI(callback) {
    cb = callback;
    [rr, cc] = sz();
    on = true;
    // Detect project info
    try {
        const cwd = process.cwd();
        hd = { workspace: path.basename(cwd) };
        const pj = path.join(cwd, 'package.json');
        if (fs.existsSync(pj)) {
            const p = JSON.parse(fs.readFileSync(pj, 'utf-8'));
            hd.project = p.name || '';
        }
    }
    catch {
        hd = { project: 'unknown', workspace: path.basename(process.cwd()) };
    }
    // Detect stats
    try {
        const Database = require('better-sqlite3');
        const dbPath = path.join(os.homedir(), '.fivo', 'cell', 'cell.db');
        if (fs.existsSync(dbPath)) {
            const db = new Database(dbPath, { readonly: true });
            try {
                stats.memory = db.prepare('SELECT COUNT(*) as c FROM memory_events').get().c;
            }
            catch { }
            try {
                stats.patterns = db.prepare('SELECT COUNT(*) as c FROM anonymous_signals').get().c;
            }
            catch { }
            try {
                stats.handoffs = db.prepare('SELECT COUNT(*) as c FROM handoffs').get().c;
            }
            catch { }
            db.close();
        }
    }
    catch { }
    process.stdout.write(ALT + HIDE);
    const si = process.stdin;
    un = () => { try {
        si.setRawMode(false);
    }
    catch { } si.removeAllListeners('data'); si.pause(); };
    if (typeof si.setRawMode === 'function')
        si.setRawMode(true);
    si.resume();
    si.on('data', key);
    process.stdout.on('resize', () => { [rr, cc] = sz(); draw(); });
    out = [];
    addOutput('Welcome to FivoCell — your AI Operating System', 'info');
    addOutput('Everything you do is learned. Nothing is forgotten.', '');
    draw();
}
function stopTUI() { clean(); }
//# sourceMappingURL=tui.js.map