// The MIT License (MIT)
//
// Copyright (C) 2026 Scott Duensing
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.

#define DVX_WIDGET_IMPL
// widgetTextInput.c  -- TextInput and TextArea widgets
//
// This file implements two text editing widgets:
//
// 1. TextInput  -- single-line text field with scroll, selection,
//    undo, password masking, and masked input (e.g., phone/SSN).
// 2. TextArea  -- multi-line text editor with row/col cursor,
//    dual-axis scrolling, and full selection/clipboard support.
//
// Shared text-editing infrastructure lives in the texthelp library
// (src/libs/kpunch/texthelp/textHelp.c/h): clipboard, multi-click
// detection, word-boundary helpers, cross-widget selection clearing,
// the single-line edit engine, and the full multi-line edit engine
// (cache, paint, mouse/drag, key handler, find/replace, goto-line,
// get-word-at-cursor).  This widget is a thin consumer that owns
// widget chrome (border, gutter, scrollbars, colorizer callbacks)
// and routes editing calls into the library via TextEditMultiT.
//
// All text editing is done in-place in fixed-size char buffers
// allocated at widget creation. No dynamic resizing -- this keeps
// memory management simple and predictable on DOS where heap
// fragmentation is a real concern.
//
// Undo is single-level swap: before each mutation, the current
// buffer is copied to undoBuf. Ctrl+Z swaps current<->undo, so
// a second Ctrl+Z is "redo". This is simpler than a multi-level
// undo stack and sufficient for typical DOS text entry.
//
// Selection model: selStart/selEnd (single-line) or selAnchor/
// selCursor (multi-line) form a directed range. selStart is where
// the user began selecting, selEnd is where they stopped. The
// "low" end for deletion/copy is always min(start, end). The
// -1 sentinel means "no selection".
//
// Masked input: a special TextInput mode where the buffer is
// pre-filled from a mask pattern (e.g., "###-##-####" for SSN).
// '#' accepts digits, 'A' accepts letters, '*' accepts any
// printable char. Literal characters in the mask are fixed and the
// cursor skips over them. This provides constrained input without
// needing a separate widget type.
//
// Password mode: renders bullets instead of characters (CP437 0xF9)
// and blocks copy/cut operations for security.

#include "dvxWgtP.h"
#include "../../../libs/kpunch/texthelp/textHelp.h"

static int32_t sTextInputTypeId = -1;
static int32_t sTextAreaTypeId  = -1;

typedef enum {
    InputNormalE,
    InputPasswordE,
    InputMaskedE
} InputModeE;

typedef struct {
    char       *buf;
    int32_t     bufSize;
    int32_t     len;
    int32_t     cursorPos;
    int32_t     scrollOff;
    int32_t     selStart;
    int32_t     selEnd;
    char       *undoBuf;
    int32_t     undoLen;
    int32_t     undoCursor;
    InputModeE  inputMode;
    const char *mask;
} TextInputDataT;

typedef struct {
    // Core multi-line editor state (buffer, cursor, selection, scroll,
    // undo, line cache) is owned by textHelp via TextEditMultiT.
    TextEditMultiT te;

    int32_t  sbDragOrient;
    int32_t  sbDragOff;
    bool     sbDragging;
    bool     showLineNumbers;
    bool     autoIndent;
    bool     captureTabs;    // true = Tab key inserts tab/spaces; false = Tab moves focus
    bool     useTabChar;     // true = insert '\t'; false = insert spaces
    int32_t  tabWidth;       // display width and space count (default 3)

    // Syntax colorizer callback (optional). Called for each visible line.
    // line: text of the line (NOT null-terminated, use lineLen).
    // colors: output array of color indices (0=default, 1-7=syntax colors).
    // The callback fills colors[0..lineLen-1].
    void   (*colorize)(const char *line, int32_t lineLen, uint8_t *colors, void *ctx);
    void    *colorizeCtx;

    // Line decorator callback (optional). Called for each visible line during paint.
    // Returns background color override (0 = use default). Sets *gutterColor to a
    // non-zero color to draw a filled circle in the gutter for breakpoints.
    uint32_t (*lineDecorator)(int32_t lineNum, uint32_t *gutterColor, void *ctx);
    void     *lineDecoratorCtx;

    // Gutter click callback (optional). Fired when user clicks in the gutter.
    void     (*onGutterClick)(WidgetT *w, int32_t lineNum);

    // Custom syntax colors (0x00RRGGBB; 0 = use default hardcoded color)
    uint32_t customSyntaxColors[TEXT_SYNTAX_MAX];

    // Pre-allocated paint buffers (avoid 3KB stack alloc per visible line per frame)
    uint8_t *rawSyntax;  // syntax color buffer (MAX_COLORIZE_LEN)
    char    *expandBuf;  // tab-expanded text (MAX_COLORIZE_LEN)
    uint8_t *syntaxBuf;  // tab-expanded syntax colors (MAX_COLORIZE_LEN)

    // Cached gutter width (recomputed only when line count changes)
    int32_t  cachedGutterW;
    int32_t  cachedGutterLines; // line count when cachedGutterW was computed
} TextAreaDataT;

// Visible-region geometry for a text area, computed by textAreaComputeGeom.
// Centralizes the inner-size / visible-rows / horizontal-scrollbar
// reservation math that every scroll, hit-test, and paint site needs.
// Values are unclamped; callers apply their own visRows/visCols >= 1 floor
// where required.
typedef struct {
    int32_t gutterW;    // line-number gutter width, 0 when hidden
    int32_t innerW;     // content width inside border, pad, vscrollbar, gutter
    int32_t innerH;     // content height inside border and hscrollbar reserve
    int32_t visCols;    // whole columns that fit in innerW
    int32_t visRows;    // whole rows that fit in innerH
    int32_t maxLL;      // longest logical line length
    bool    needHSb;    // horizontal scrollbar required (maxLL > visCols)
} TextAreaGeomT;

#include <ctype.h>
#include <strings.h>
#include <time.h>

#define TEXTAREA_BORDER    2
#define TEXTAREA_PAD       2
#define TEXTAREA_SB_W      14
#define TEXTAREA_MIN_ROWS  4
#define TEXTAREA_MIN_COLS  20

#define MAX_COLORIZE_LEN   1024
// Match the ANSI terminal cursor blink rate (CURSOR_MS in widgetAnsiTerm.c)
#define CURSOR_BLINK_MS    250

// Default buffer sizes when the caller passes maxLen <= 0 and when
// the BASIC iface registers a control without specifying a size.
#define TEXTINPUT_DEFAULT_BUF   256
#define TEXTAREA_DEFAULT_BUF  65536

// sCursorBlinkOn is defined in widgetCore.c (shared state)


// ============================================================
// Prototypes
// ============================================================

static void basColorize(const char *line, int32_t lineLen, uint8_t *colors, void *ctx);
static const char *basGetWordAtCursor(const WidgetT *w);
static void basSetSyntaxMode(WidgetT *w, const char *mode);
static void dhsColorize(const char *line, int32_t lineLen, uint8_t *colors, void *ctx);
static bool maskCharValid(char slot, char ch);
static void maskedInputOnKey(WidgetT *w, int32_t key, int32_t mod);
static int32_t maskFirstSlot(const char *mask);
static bool maskIsSlot(char ch);
static int32_t maskNextSlot(const char *mask, int32_t pos);
static int32_t maskPrevSlot(const char *mask, int32_t pos);
static void textAreaComputeGeom(WidgetT *w, const BitmapFontT *font, TextAreaGeomT *g);
static inline void textAreaDirtyCache(WidgetT *w);
static void textAreaEnsureVisible(WidgetT *w, int32_t visRows, int32_t visCols);
static int32_t textAreaGetLineCount(WidgetT *w);
static int32_t textAreaGetMaxLineLen(WidgetT *w);
static int32_t textAreaGutterWidth(WidgetT *w, const BitmapFontT *font);
WidgetT *wgtMaskedInput(WidgetT *parent, const char *mask);
WidgetT *wgtPasswordInput(WidgetT *parent, int32_t maxLen);
WidgetT *wgtTextArea(WidgetT *parent, int32_t maxLen);
void wgtTextAreaAppendText(WidgetT *w, const char *text);
void wgtTextAreaCursorToEnd(WidgetT *w);
bool wgtTextAreaFindNext(WidgetT *w, const char *needle, bool caseSensitive, bool forward);
int32_t wgtTextAreaGetCursorLine(const WidgetT *w);
int32_t wgtTextAreaGetWordAtCursor(const WidgetT *w, char *buf, int32_t bufSize);
void wgtTextAreaGoToLine(WidgetT *w, int32_t line);
int32_t wgtTextAreaReplaceAll(WidgetT *w, const char *needle, const char *replacement, bool caseSensitive);
bool wgtTextAreaReplaceSelection(WidgetT *w, const char *needle, const char *replacement, bool caseSensitive, bool forward);
void wgtTextAreaSetAutoIndent(WidgetT *w, bool enable);
void wgtTextAreaSetCaptureTabs(WidgetT *w, bool capture);
void wgtTextAreaSetColorize(WidgetT *w, void (*fn)(const char *, int32_t, uint8_t *, void *), void *ctx);
void wgtTextAreaSetGutterClickCallback(WidgetT *w, void (*fn)(WidgetT *, int32_t));
void wgtTextAreaSetLineDecorator(WidgetT *w, uint32_t (*fn)(int32_t, uint32_t *, void *), void *ctx);
void wgtTextAreaSetShowLineNumbers(WidgetT *w, bool show);
void wgtTextAreaSetSyntaxColors(WidgetT *w, const uint32_t *colors, int32_t count);
void wgtTextAreaSetTabWidth(WidgetT *w, int32_t width);
void wgtTextAreaSetUseTabChar(WidgetT *w, bool useChar);
WidgetT *wgtTextInput(WidgetT *parent, int32_t maxLen);
void widgetTextAreaCalcMinSize(WidgetT *w, const BitmapFontT *font);
static bool widgetTextAreaClearSelection(WidgetT *w);
void widgetTextAreaDestroy(WidgetT *w);
static void widgetTextAreaDragSelect(WidgetT *w, WidgetT *root, int32_t vx, int32_t vy);
const char *widgetTextAreaGetText(const WidgetT *w);
static void widgetTextAreaOnDragUpdate(WidgetT *w, WidgetT *root, int32_t x, int32_t y);
void widgetTextAreaOnKey(WidgetT *w, int32_t key, int32_t mod);
void widgetTextAreaOnMouse(WidgetT *w, WidgetT *root, int32_t vx, int32_t vy);
void widgetTextAreaPaint(WidgetT *w, DisplayT *d, const BlitOpsT *ops, const BitmapFontT *font, const ColorSchemeT *colors);
static void widgetTextAreaScrollDragUpdate(WidgetT *w, int32_t orient, int32_t dragOff, int32_t mouseX, int32_t mouseY);
void widgetTextAreaSetText(WidgetT *w, const char *text);
void widgetTextInputCalcMinSize(WidgetT *w, const BitmapFontT *font);
static bool widgetTextInputClearSelection(WidgetT *w);
void widgetTextInputDestroy(WidgetT *w);
const char *widgetTextInputGetText(const WidgetT *w);
static void widgetTextInputOnDragUpdate(WidgetT *w, WidgetT *root, int32_t vx, int32_t vy);
void widgetTextInputOnKey(WidgetT *w, int32_t key, int32_t mod);
void widgetTextInputOnMouse(WidgetT *w, WidgetT *root, int32_t vx, int32_t vy);
void widgetTextInputPaint(WidgetT *w, DisplayT *d, const BlitOpsT *ops, const BitmapFontT *font, const ColorSchemeT *colors);
void widgetTextInputSetText(WidgetT *w, const char *text);


// BASIC keyword colorizer (simplified version of IDE's basicColorize)
static void basColorize(const char *line, int32_t lineLen, uint8_t *colors, void *ctx) {
    (void)ctx;

    static const char *sBasKeywords[] = {
        "AND", "AS", "BYVAL", "CALL", "CASE", "CLOSE", "CONST",
        "CREATECONTROL", "CREATEFORM",
        "DATA", "DECLARE", "DIM", "DO", "DOEVENTS",
        "ELSE", "ELSEIF", "END", "ERASE", "EXIT",
        "FOR", "FUNCTION", "GET", "GOSUB", "GOTO",
        "HIDE", "IF", "INPUT", "IS",
        "LET", "LIBRARY", "LINE", "LOAD", "LOOP",
        "ME", "MOD", "MSGBOX",
        "NEXT", "NOTHING", "NOT",
        "ON", "OPEN", "OPTIONAL", "OPTION", "OR",
        "PRINT", "PUT",
        "RANDOMIZE", "READ", "REDIM", "REMOVECONTROL", "RESTORE", "RESUME", "RETURN",
        "SEEK", "SELECT", "SET", "SETEVENT", "SHARED", "SHELL", "SHOW", "SLEEP",
        "STATIC", "STEP", "SUB", "SWAP",
        "THEN", "TO", "TYPE",
        "UNLOAD", "UNTIL",
        "WEND", "WHILE", "WRITE",
        "XOR",
        NULL
    };

    static const char *sBasTypes[] = {
        "BOOLEAN", "DOUBLE", "FALSE", "INTEGER", "LONG", "SINGLE", "STRING", "TRUE",
        NULL
    };

    int32_t i = 0;

    while (i < lineLen) {
        char ch = line[i];

        // Comment
        if (ch == '\'') {
            while (i < lineLen) {
                colors[i++] = TEXT_SYNTAX_COMMENT;
            }

            return;
        }

        // String literal
        if (ch == '"') {
            colors[i++] = TEXT_SYNTAX_STRING;

            while (i < lineLen && line[i] != '"') {
                colors[i++] = TEXT_SYNTAX_STRING;
            }

            if (i < lineLen) {
                colors[i++] = TEXT_SYNTAX_STRING;
            }

            continue;
        }

        // Number
        if (isdigit((unsigned char)ch) || (ch == '&' && i + 1 < lineLen && (line[i + 1] == 'H' || line[i + 1] == 'h'))) {
            while (i < lineLen && (isxdigit((unsigned char)line[i]) || line[i] == '.' || line[i] == '&' || line[i] == 'H' || line[i] == 'h')) {
                colors[i++] = TEXT_SYNTAX_NUMBER;
            }

            continue;
        }

        // Identifier or keyword
        if (isalpha((unsigned char)ch) || ch == '_') {
            int32_t start = i;

            while (i < lineLen && (isalnum((unsigned char)line[i]) || line[i] == '_' || line[i] == '$' || line[i] == '%' || line[i] == '&' || line[i] == '!' || line[i] == '#')) {
                i++;
            }

            int32_t wordLen = i - start;

            // Check for REM
            if (wordLen == 3 && (line[start] == 'R' || line[start] == 'r') && (line[start + 1] == 'E' || line[start + 1] == 'e') && (line[start + 2] == 'M' || line[start + 2] == 'm')) {
                for (int32_t j = start; j < lineLen; j++) {
                    colors[j] = TEXT_SYNTAX_COMMENT;
                }

                return;
            }

            // Uppercase for comparison
            char upper[48];
            int32_t uLen = wordLen < 47 ? wordLen : 47;

            for (int32_t j = 0; j < uLen; j++) {
                upper[j] = (char)toupper((unsigned char)line[start + j]);
            }

            // Strip type suffix for matching
            while (uLen > 0 && (upper[uLen - 1] == '$' || upper[uLen - 1] == '%' || upper[uLen - 1] == '&' || upper[uLen - 1] == '!' || upper[uLen - 1] == '#')) {
                uLen--;
            }

            upper[uLen] = '\0';

            // Check keywords
            uint8_t c = TEXT_SYNTAX_DEFAULT;

            for (int32_t j = 0; sBasKeywords[j]; j++) {
                if (strcmp(upper, sBasKeywords[j]) == 0) {
                    c = TEXT_SYNTAX_KEYWORD;
                    break;
                }
            }

            if (c == TEXT_SYNTAX_DEFAULT) {
                for (int32_t j = 0; sBasTypes[j]; j++) {
                    if (strcmp(upper, sBasTypes[j]) == 0) {
                        c = TEXT_SYNTAX_TYPE;
                        break;
                    }
                }
            }

            for (int32_t j = start; j < i; j++) {
                colors[j] = c;
            }

            continue;
        }

        // Operator
        if (ch == '=' || ch == '<' || ch == '>' || ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '\\') {
            colors[i++] = TEXT_SYNTAX_OPERATOR;
            continue;
        }

        colors[i++] = TEXT_SYNTAX_DEFAULT;
    }
}


// BASIC wrapper: GetWordAtCursor returns the word as a string
static const char *basGetWordAtCursor(const WidgetT *w) {
    static char buf[256];
    wgtTextAreaGetWordAtCursor(w, buf, sizeof(buf));
    return buf;
}


// SetSyntaxMode method: activate a built-in colorizer
static void basSetSyntaxMode(WidgetT *w, const char *mode) {
    if (!mode || !*mode) {
        wgtTextAreaSetColorize(w, NULL, NULL);
        return;
    }

    if (strcasecmp(mode, "dhs") == 0 || strcasecmp(mode, "help") == 0) {
        wgtTextAreaSetColorize(w, dhsColorize, NULL);
    } else if (strcasecmp(mode, "bas") == 0 || strcasecmp(mode, "basic") == 0) {
        wgtTextAreaSetColorize(w, basColorize, NULL);
    } else {
        wgtTextAreaSetColorize(w, NULL, NULL);
    }
}


// .dhs help source colorizer
static void dhsColorize(const char *line, int32_t lineLen, uint8_t *colors, void *ctx) {
    (void)ctx;

    if (lineLen == 0) {
        return;
    }

    // Skip leading whitespace
    int32_t i = 0;

    while (i < lineLen && (line[i] == ' ' || line[i] == '\t')) {
        i++;
    }

    // Lines starting with . are directives
    if (i < lineLen && line[i] == '.') {
        int32_t dirStart = i;
        i++;

        // Directive name
        while (i < lineLen && line[i] != ' ' && line[i] != '\t') {
            i++;
        }

        // Classify the directive
        int32_t dirLen = i - dirStart;
        const char *dir = line + dirStart;

        // Block directives: .code, .endcode, .table, .endtable, .list, .endlist, .note, .endnote
        bool isBlock = false;

        if (dirLen >= 4 && (strncasecmp(dir, ".code", 5) == 0 || strncasecmp(dir, ".table", 6) == 0 || strncasecmp(dir, ".list", 5) == 0 || strncasecmp(dir, ".note", 5) == 0 || strncasecmp(dir, ".endcode", 8) == 0 || strncasecmp(dir, ".endtable", 9) == 0 || strncasecmp(dir, ".endlist", 8) == 0 || strncasecmp(dir, ".endnote", 8) == 0 || strncasecmp(dir, ".item", 5) == 0 || strncasecmp(dir, ".hr", 3) == 0)) {
            isBlock = true;
        }

        // Heading directives: .h1, .h2, .h3
        bool isHeading = (dirLen >= 3 && dir[0] == '.' && (dir[1] == 'h' || dir[1] == 'H') && dir[2] >= '1' && dir[2] <= '3');

        // Link directive: .link
        bool isLink = (dirLen >= 5 && strncasecmp(dir, ".link", 5) == 0);

        // Topic/index/toc/title directives
        bool isMeta = false;

        if (dirLen >= 4 && (strncasecmp(dir, ".topic", 6) == 0 || strncasecmp(dir, ".title", 6) == 0 || strncasecmp(dir, ".toc", 4) == 0 || strncasecmp(dir, ".index", 6) == 0 || strncasecmp(dir, ".default", 8) == 0 || strncasecmp(dir, ".section", 8) == 0 || strncasecmp(dir, ".image", 6) == 0)) {
            isMeta = true;
        }

        // Color the directive name
        uint8_t dirColor = 1; // keyword

        if (isHeading) {
            dirColor = 6; // type (stands out more)
        } else if (isLink) {
            dirColor = 5; // operator
        } else if (isMeta) {
            dirColor = 7; // reserved
        } else if (isBlock) {
            dirColor = 1; // keyword
        }

        for (int32_t j = dirStart; j < i; j++) {
            colors[j] = dirColor;
        }

        // Color the rest of the line as the directive's argument
        if (isHeading) {
            // Heading text gets heading color
            for (int32_t j = i; j < lineLen; j++) {
                colors[j] = 6;
            }
        } else if (isLink) {
            // .link topicId displayText -- topicId is string-colored, rest is default
            while (i < lineLen && (line[i] == ' ' || line[i] == '\t')) {
                i++;
            }

            int32_t idStart = i;

            while (i < lineLen && line[i] != ' ' && line[i] != '\t') {
                i++;
            }

            for (int32_t j = idStart; j < i; j++) {
                colors[j] = 2; // string
            }
        } else if (isMeta) {
            // Meta argument in string color
            for (int32_t j = i; j < lineLen; j++) {
                colors[j] = 2;
            }
        }

        return;
    }

    // Non-directive lines are body text (default color), no special highlighting
}


static bool maskCharValid(char slot, char ch) {
    switch (slot) {
        case '#':
            return ch >= '0' && ch <= '9';
        case 'A':
            return isalpha((unsigned char)ch);
        case '*':
            return ch >= 32 && ch < 127;
        default:
            return false;
    }
}


// Masked input key handling is entirely separate from the shared
// text editor because the editing semantics are fundamentally different:
// the buffer length is fixed (it's always maskLen), characters can
// only be placed in slot positions, and backspace clears a slot rather
// than removing a character. The cursor skips over literal characters
// when moving left/right. Cut clears slots to '_' rather than removing
// text. Paste fills consecutive slots, skipping non-matching clipboard
// characters.
static void maskedInputOnKey(WidgetT *w, int32_t key, int32_t mod) {
    TextInputDataT *ti = (TextInputDataT *)w->data;
    char       *buf     = ti->buf;
    const char *mask    = ti->mask;
    int32_t    *pCur    = &ti->cursorPos;
    int32_t     maskLen = ti->len;
    bool        shift  = (mod & KEY_MOD_SHIFT) != 0;

    (void)shift;

    // Ctrl+A  -- select all
    if (key == KEY_CTRL_A) {
        ti->selStart = 0;
        ti->selEnd   = maskLen;
        *pCur = maskLen;
        goto done;
    }

    // Ctrl+C  -- copy formatted text
    if (key == KEY_CTRL_C) {
        if (ti->selStart >= 0 && ti->selEnd >= 0 && ti->selStart != ti->selEnd) {
            int32_t selLo = ti->selStart < ti->selEnd ? ti->selStart : ti->selEnd;
            int32_t selHi = ti->selStart < ti->selEnd ? ti->selEnd : ti->selStart;

            if (selLo < 0) {
                selLo = 0;
            }

            if (selHi > maskLen) {
                selHi = maskLen;
            }

            if (selHi > selLo) {
                clipboardCopy(buf + selLo, selHi - selLo);
            }
        }

        return;
    }

    // Ctrl+V  -- paste valid chars into slots
    if (key == KEY_CTRL_V) {
        int32_t clipLen;
        const char *clip = clipboardGet(&clipLen);

        if (clipLen > 0) {
            if (ti->undoBuf) {
                textEditSaveUndo(buf, maskLen, *pCur, ti->undoBuf, &ti->undoLen, &ti->undoCursor, ti->bufSize);
            }

            int32_t slotPos = *pCur;
            bool changed = false;

            for (int32_t i = 0; i < clipLen && slotPos < maskLen; i++) {
                // Skip to next slot if not on one
                while (slotPos < maskLen && !maskIsSlot(mask[slotPos])) {
                    slotPos++;
                }

                if (slotPos >= maskLen) {
                    break;
                }

                // Skip non-matching clipboard chars
                if (maskCharValid(mask[slotPos], clip[i])) {
                    buf[slotPos] = clip[i];
                    slotPos = maskNextSlot(mask, slotPos);
                    changed = true;
                }
            }

            if (changed) {
                *pCur = slotPos <= maskLen ? slotPos : maskLen;
                ti->selStart = -1;
                ti->selEnd   = -1;

                if (w->onChange) {
                    w->onChange(w);
                }
            }
        }

        goto done;
    }

    // Ctrl+X  -- copy and clear selected slots
    if (key == KEY_CTRL_X) {
        if (ti->selStart >= 0 && ti->selEnd >= 0 && ti->selStart != ti->selEnd) {
            int32_t selLo = ti->selStart < ti->selEnd ? ti->selStart : ti->selEnd;
            int32_t selHi = ti->selStart < ti->selEnd ? ti->selEnd : ti->selStart;

            if (selLo < 0) {
                selLo = 0;
            }

            if (selHi > maskLen) {
                selHi = maskLen;
            }

            clipboardCopy(buf + selLo, selHi - selLo);

            if (ti->undoBuf) {
                textEditSaveUndo(buf, maskLen, *pCur, ti->undoBuf, &ti->undoLen, &ti->undoCursor, ti->bufSize);
            }

            for (int32_t i = selLo; i < selHi; i++) {
                if (maskIsSlot(mask[i])) {
                    buf[i] = '_';
                }
            }

            *pCur = selLo;
            ti->selStart = -1;
            ti->selEnd   = -1;

            if (w->onChange) {
                w->onChange(w);
            }
        }

        goto done;
    }

    // Ctrl+Z  -- undo
    if (key == KEY_CTRL_Z && ti->undoBuf) {
        char tmpBuf[256];
        int32_t tmpLen = maskLen + 1 < (int32_t)sizeof(tmpBuf) ? maskLen + 1 : (int32_t)sizeof(tmpBuf);
        int32_t tmpCursor = *pCur;
        memcpy(tmpBuf, buf, tmpLen);

        memcpy(buf, ti->undoBuf, maskLen + 1);
        *pCur = ti->undoCursor < maskLen ? ti->undoCursor : maskLen;

        memcpy(ti->undoBuf, tmpBuf, tmpLen);
        ti->undoCursor = tmpCursor;

        ti->selStart = -1;
        ti->selEnd   = -1;

        if (w->onChange) {
            w->onChange(w);
        }

        goto done;
    }

    if (key >= KEY_ASCII_PRINT_FIRST && key <= KEY_ASCII_PRINT_LAST) {
        // Printable character  -- place at current slot if valid
        if (*pCur < maskLen && maskIsSlot(mask[*pCur]) && maskCharValid(mask[*pCur], (char)key)) {
            if (ti->undoBuf) {
                textEditSaveUndo(buf, maskLen, *pCur, ti->undoBuf, &ti->undoLen, &ti->undoCursor, ti->bufSize);
            }

            buf[*pCur] = (char)key;
            *pCur = maskNextSlot(mask, *pCur);

            ti->selStart = -1;
            ti->selEnd   = -1;

            if (w->onChange) {
                w->onChange(w);
            }
        }
    } else if (key == KEY_BACKSPACE) {
        // Backspace  -- clear previous slot
        int32_t prev = maskPrevSlot(mask, *pCur);

        if (prev != *pCur) {
            if (ti->undoBuf) {
                textEditSaveUndo(buf, maskLen, *pCur, ti->undoBuf, &ti->undoLen, &ti->undoCursor, ti->bufSize);
            }

            buf[prev] = '_';
            *pCur = prev;

            ti->selStart = -1;
            ti->selEnd   = -1;

            if (w->onChange) {
                w->onChange(w);
            }
        }
    } else if (key == KEY_DELETE) {
        // Delete  -- clear current slot
        if (*pCur < maskLen && maskIsSlot(mask[*pCur])) {
            if (ti->undoBuf) {
                textEditSaveUndo(buf, maskLen, *pCur, ti->undoBuf, &ti->undoLen, &ti->undoCursor, ti->bufSize);
            }

            buf[*pCur] = '_';

            ti->selStart = -1;
            ti->selEnd   = -1;

            if (w->onChange) {
                w->onChange(w);
            }
        }
    } else if (key == KEY_LEFT) {
        // Left arrow  -- move to previous slot
        int32_t prev = maskPrevSlot(mask, *pCur);

        if (shift) {
            if (ti->selStart < 0) {
                ti->selStart = *pCur;
                ti->selEnd   = *pCur;
            }

            *pCur = prev;
            ti->selEnd = *pCur;
        } else {
            ti->selStart = -1;
            ti->selEnd   = -1;
            *pCur = prev;
        }
    } else if (key == KEY_RIGHT) {
        // Right arrow  -- move to next slot
        int32_t next = maskNextSlot(mask, *pCur);

        if (shift) {
            if (ti->selStart < 0) {
                ti->selStart = *pCur;
                ti->selEnd   = *pCur;
            }

            *pCur = next;
            ti->selEnd = *pCur;
        } else {
            ti->selStart = -1;
            ti->selEnd   = -1;
            *pCur = next;
        }
    } else if (key == KEY_HOME) {
        // Home  -- first slot
        if (shift) {
            if (ti->selStart < 0) {
                ti->selStart = *pCur;
                ti->selEnd   = *pCur;
            }

            *pCur = maskFirstSlot(mask);
            ti->selEnd = *pCur;
        } else {
            ti->selStart = -1;
            ti->selEnd   = -1;
            *pCur = maskFirstSlot(mask);
        }
    } else if (key == KEY_END) {
        // End  -- past last slot
        int32_t last = maskLen;

        if (shift) {
            if (ti->selStart < 0) {
                ti->selStart = *pCur;
                ti->selEnd   = *pCur;
            }

            *pCur = last;
            ti->selEnd = *pCur;
        } else {
            ti->selStart = -1;
            ti->selEnd   = -1;
            *pCur = last;
        }
    } else {
        return;
    }

done:
    // Adjust scroll
    {
        AppContextT *ctx = wgtGetContext(w);
        const BitmapFontT *font = &ctx->font;
        int32_t visibleChars = (w->w - TEXT_INPUT_PAD * 2) / font->charWidth;

        if (*pCur < ti->scrollOff) {
            ti->scrollOff = *pCur;
        }

        if (*pCur >= ti->scrollOff + visibleChars) {
            ti->scrollOff = *pCur - visibleChars + 1;
        }
    }

    wgtInvalidatePaint(w);
}


static int32_t maskFirstSlot(const char *mask) {
    for (int32_t i = 0; mask[i]; i++) {
        if (maskIsSlot(mask[i])) {
            return i;
        }
    }

    return 0;
}


static bool maskIsSlot(char ch) {
    return ch == '#' || ch == 'A' || ch == '*';
}


static int32_t maskNextSlot(const char *mask, int32_t pos) {
    for (int32_t i = pos + 1; mask[i]; i++) {
        if (maskIsSlot(mask[i])) {
            return i;
        }
    }

    return (int32_t)strlen(mask);
}


static int32_t maskPrevSlot(const char *mask, int32_t pos) {
    for (int32_t i = pos - 1; i >= 0; i--) {
        if (maskIsSlot(mask[i])) {
            return i;
        }
    }

    return pos;
}


// Compute the text area's visible-region geometry once. The horizontal
// scrollbar reservation depends on visCols (which depends on the gutter
// width), so the order here matters: gutter -> innerW -> visCols -> needHSb
// -> innerH -> visRows. Kept in one place so scroll, hit-test, and paint
// never disagree about the visible size (they had drifted before).
static void textAreaComputeGeom(WidgetT *w, const BitmapFontT *font, TextAreaGeomT *g) {
    g->gutterW = textAreaGutterWidth(w, font);
    g->innerW  = w->w - TEXTAREA_BORDER * 2 - TEXTAREA_PAD * 2 - TEXTAREA_SB_W - g->gutterW;
    g->visCols = g->innerW / font->charWidth;
    g->maxLL   = textAreaGetMaxLineLen(w);
    g->needHSb = (g->maxLL > g->visCols);
    g->innerH  = w->h - TEXTAREA_BORDER * 2 - (g->needHSb ? TEXTAREA_SB_W : 0);
    g->visRows = g->innerH / font->charHeight;
}


static inline void textAreaDirtyCache(WidgetT *w) {
    TextAreaDataT *ta = (TextAreaDataT *)w->data;
    textEditLineCacheDirty(&ta->te.lines);
    ta->cachedGutterW = 0;
}


static void textAreaEnsureVisible(WidgetT *w, int32_t visRows, int32_t visCols) {
    TextAreaDataT *ta = (TextAreaDataT *)w->data;
    textEditEnsureVisible(&ta->te.lines, ta->te.buf, ta->te.len, ta->te.cursorRow, ta->te.cursorCol, ta->tabWidth, visRows, visCols, &ta->te.scrollRow, &ta->te.scrollCol);
}


static int32_t textAreaGetLineCount(WidgetT *w) {
    TextAreaDataT *ta = (TextAreaDataT *)w->data;
    return textEditLineCount(&ta->te.lines, ta->te.buf, ta->te.len);
}


static int32_t textAreaGetMaxLineLen(WidgetT *w) {
    TextAreaDataT *ta = (TextAreaDataT *)w->data;
    return textEditMaxLineLen(&ta->te.lines, ta->te.buf, ta->te.len);
}


static int32_t textAreaGutterWidth(WidgetT *w, const BitmapFontT *font) {
    TextAreaDataT *ta = (TextAreaDataT *)w->data;

    if (!ta->showLineNumbers) {
        return 0;
    }

    int32_t totalLines = textAreaGetLineCount(w);

    if (ta->cachedGutterW > 0 && ta->cachedGutterLines == totalLines) {
        return ta->cachedGutterW;
    }

    int32_t digits = 1;
    int32_t temp   = totalLines;

    while (temp >= 10) {
        temp /= 10;
        digits++;
    }

    if (digits < 3) {
        digits = 3;
    }

    ta->cachedGutterW     = (digits + 1) * font->charWidth;
    ta->cachedGutterLines = totalLines;

    return ta->cachedGutterW;
}


WidgetT *wgtMaskedInput(WidgetT *parent, const char *mask) {
    if (!mask) {
        return NULL;
    }

    int32_t maskLen = (int32_t)strlen(mask);
    WidgetT *w = wgtTextInput(parent, maskLen);

    if (w) {
        TextInputDataT *ti = (TextInputDataT *)w->data;
        ti->inputMode = InputMaskedE;
        ti->mask      = mask;

        // Pre-fill buffer: literals copied as-is, slots filled with '_'
        for (int32_t i = 0; i < maskLen; i++) {
            char ch = mask[i];

            if (ch == '#' || ch == 'A' || ch == '*') {
                ti->buf[i] = '_';
            } else {
                ti->buf[i] = ch;
            }
        }

        ti->buf[maskLen] = '\0';
        ti->len          = maskLen;

        // Position cursor at first editable slot
        ti->cursorPos = 0;

        for (int32_t i = 0; mask[i]; i++) {
            char ch = mask[i];

            if (ch == '#' || ch == 'A' || ch == '*') {
                ti->cursorPos = i;
                break;
            }
        }
    }

    return w;
}


WidgetT *wgtPasswordInput(WidgetT *parent, int32_t maxLen) {
    WidgetT *w = wgtTextInput(parent, maxLen);

    if (w) {
        TextInputDataT *ti = (TextInputDataT *)w->data;
        ti->inputMode = InputPasswordE;
    }

    return w;
}


WidgetT *wgtTextArea(WidgetT *parent, int32_t maxLen) {
    WidgetT *w = widgetAlloc(parent, sTextAreaTypeId);

    if (w) {
        TextAreaDataT *ta = (TextAreaDataT *)calloc(1, sizeof(TextAreaDataT));

        if (!ta) {
            return w;
        }

        w->data = ta;
        ta->captureTabs = false; // default: Tab moves focus
        ta->useTabChar  = true;  // default: insert actual tab character
        ta->tabWidth    = 3;     // default: 3-space tab stops
        textEditMultiInit(&ta->te, maxLen, ta->tabWidth);

        // Pre-allocate paint buffers (avoids 3KB stack alloc per visible line per frame)
        ta->rawSyntax = (uint8_t *)malloc(MAX_COLORIZE_LEN);
        ta->expandBuf = (char *)malloc(MAX_COLORIZE_LEN);
        ta->syntaxBuf = (uint8_t *)malloc(MAX_COLORIZE_LEN);

        w->weight = WGT_WEIGHT_FILL;
    }

    return w;
}


void wgtTextAreaAppendText(WidgetT *w, const char *text) {
    if (!w || w->type != sTextAreaTypeId || !text) {
        return;
    }

    TextAreaDataT *ta = (TextAreaDataT *)w->data;

    if (!ta->te.buf) {
        return;
    }

    int32_t addLen = (int32_t)strlen(text);
    int32_t room   = ta->te.bufSize - 1 - ta->te.len;

    if (addLen > room) {
        addLen = room;
    }

    if (addLen <= 0) {
        return;
    }

    memcpy(ta->te.buf + ta->te.len, text, addLen);
    ta->te.len             += addLen;
    ta->te.buf[ta->te.len]     = '\0';
    textAreaDirtyCache(w);
    wgtInvalidatePaint(w);
}


// wgtTextAreaCursorToEnd -- place the cursor at the very end of the buffer
// (offset == len), past the last character.  A backward search anchored
// here scans every match including those on the final line, which a line-
// start anchor (e.g. wgtTextAreaGoToLine) would miss.
void wgtTextAreaCursorToEnd(WidgetT *w) {
    if (!w || w->type != sTextAreaTypeId) {
        return;
    }

    TextAreaDataT *ta = (TextAreaDataT *)w->data;

    textEditOffToRowCol(&ta->te.lines, ta->te.buf, ta->te.len, ta->te.len, &ta->te.cursorRow, &ta->te.cursorCol);
    ta->te.desiredCol = ta->te.cursorCol;
    ta->te.selAnchor  = -1;
    ta->te.selCursor  = -1;
}


bool wgtTextAreaFindNext(WidgetT *w, const char *needle, bool caseSensitive, bool forward) {
    if (!w || w->type != sTextAreaTypeId) {
        return false;
    }

    TextAreaDataT *ta = (TextAreaDataT *)w->data;
    bool found = textEditFindNext(&ta->te.lines, ta->te.buf, ta->te.len, needle, caseSensitive, forward, &ta->te.cursorRow, &ta->te.cursorCol, &ta->te.desiredCol, &ta->te.selAnchor, &ta->te.selCursor);

    if (found) {
        AppContextT *ctx = wgtGetContext(w);

        if (ctx) {
            const BitmapFontT *font = &ctx->font;
            TextAreaGeomT geom;
            textAreaComputeGeom(w, font, &geom);
            int32_t visCols = geom.visCols;
            int32_t visRows = geom.visRows;

            if (visCols < 1) {
                visCols = 1;
            }

            if (visRows < 1) {
                visRows = 1;
            }

            textAreaEnsureVisible(w, visRows, visCols);
        }

        wgtInvalidatePaint(w);
    }

    return found;
}


int32_t wgtTextAreaGetCursorLine(const WidgetT *w) {
    if (!w || w->type != sTextAreaTypeId) {
        return 1;
    }

    const TextAreaDataT *ta = (const TextAreaDataT *)w->data;
    return ta->te.cursorRow + 1; // 0-based to 1-based
}


int32_t wgtTextAreaGetWordAtCursor(const WidgetT *w, char *buf, int32_t bufSize) {
    if (!w || w->type != sTextAreaTypeId) {
        buf[0] = '\0';
        return 0;
    }

    TextAreaDataT *ta = (TextAreaDataT *)w->data;
    return textEditGetWordAtCursor(&ta->te.lines, ta->te.buf, ta->te.len, ta->te.cursorRow, ta->te.cursorCol, buf, bufSize);
}


void wgtTextAreaGoToLine(WidgetT *w, int32_t line) {
    if (!w || w->type != sTextAreaTypeId) {
        return;
    }

    TextAreaDataT *ta       = (TextAreaDataT *)w->data;
    AppContextT *ctx        = wgtGetContext(w);
    int32_t visRows         = 1;

    if (ctx) {
        const BitmapFontT *font = &ctx->font;
        TextAreaGeomT geom;
        textAreaComputeGeom(w, font, &geom);
        visRows = geom.visRows;

        if (visRows < 1) {
            visRows = 1;
        }
    }

    textEditGoToLine(&ta->te.lines, ta->te.buf, ta->te.len, line, visRows, &ta->te.cursorRow, &ta->te.cursorCol, &ta->te.desiredCol, &ta->te.scrollRow, &ta->te.scrollCol, &ta->te.selAnchor, &ta->te.selCursor);
    wgtInvalidatePaint(w);
}


int32_t wgtTextAreaReplaceAll(WidgetT *w, const char *needle, const char *replacement, bool caseSensitive) {
    if (!w || w->type != sTextAreaTypeId) {
        return 0;
    }

    TextAreaDataT *ta = (TextAreaDataT *)w->data;
    int32_t count     = textEditReplaceAll(&ta->te.lines, ta->te.buf, ta->te.bufSize, &ta->te.len, needle, replacement, caseSensitive, &ta->te.cursorRow, &ta->te.cursorCol, &ta->te.desiredCol, &ta->te.selAnchor, &ta->te.selCursor, ta->te.undoBuf, &ta->te.undoLen, &ta->te.undoCursor);

    if (count > 0) {
        ta->cachedGutterW = 0;
        wgtInvalidatePaint(w);

        if (w->onChange) {
            w->onChange(w);
        }
    }

    return count;
}


// wgtTextAreaReplaceSelection -- if the editor's current selection
// matches needle, replace it, fire onChange, and refresh the gutter;
// then advance to the next match in the requested direction.  Returns
// true if anything was replaced or a following match was found.
bool wgtTextAreaReplaceSelection(WidgetT *w, const char *needle, const char *replacement, bool caseSensitive, bool forward) {
    if (!w || w->type != sTextAreaTypeId) {
        return false;
    }

    TextAreaDataT *ta = (TextAreaDataT *)w->data;
    bool replaced     = textEditReplaceSelectionMulti(&ta->te.lines, ta->te.buf, ta->te.bufSize, &ta->te.len, needle, replacement, caseSensitive, forward, &ta->te.cursorRow, &ta->te.cursorCol, &ta->te.desiredCol, &ta->te.selAnchor, &ta->te.selCursor, ta->te.undoBuf, &ta->te.undoLen, &ta->te.undoCursor);

    if (replaced) {
        ta->cachedGutterW = 0;
        wgtInvalidatePaint(w);

        if (w->onChange) {
            w->onChange(w);
        }
    }

    bool found = wgtTextAreaFindNext(w, needle, caseSensitive, forward);

    return replaced || found;
}


void wgtTextAreaSetAutoIndent(WidgetT *w, bool enable) {
    if (!w || w->type != sTextAreaTypeId) {
        return;
    }

    TextAreaDataT *ta = (TextAreaDataT *)w->data;
    ta->autoIndent = enable;
}


void wgtTextAreaSetCaptureTabs(WidgetT *w, bool capture) {
    if (!w || w->type != sTextAreaTypeId) {
        return;
    }

    TextAreaDataT *ta = (TextAreaDataT *)w->data;
    ta->captureTabs = capture;
    w->swallowTab   = capture;
}


void wgtTextAreaSetColorize(WidgetT *w, void (*fn)(const char *, int32_t, uint8_t *, void *), void *ctx) {
    if (!w || w->type != sTextAreaTypeId) {
        return;
    }

    TextAreaDataT *ta = (TextAreaDataT *)w->data;
    ta->colorize    = fn;
    ta->colorizeCtx = ctx;
}


void wgtTextAreaSetGutterClickCallback(WidgetT *w, void (*fn)(WidgetT *, int32_t)) {
    if (!w || w->type != sTextAreaTypeId) {
        return;
    }

    TextAreaDataT *ta = (TextAreaDataT *)w->data;
    ta->onGutterClick = fn;
}


void wgtTextAreaSetLineDecorator(WidgetT *w, uint32_t (*fn)(int32_t, uint32_t *, void *), void *ctx) {
    if (!w || w->type != sTextAreaTypeId) {
        return;
    }

    TextAreaDataT *ta  = (TextAreaDataT *)w->data;
    ta->lineDecorator    = fn;
    ta->lineDecoratorCtx = ctx;
}


void wgtTextAreaSetShowLineNumbers(WidgetT *w, bool show) {
    if (!w || w->type != sTextAreaTypeId) {
        return;
    }

    TextAreaDataT *ta = (TextAreaDataT *)w->data;
    ta->showLineNumbers = show;
    wgtInvalidatePaint(w);
}


void wgtTextAreaSetSyntaxColors(WidgetT *w, const uint32_t *colors, int32_t count) {
    if (!w || w->type != sTextAreaTypeId) {
        return;
    }

    TextAreaDataT *ta = (TextAreaDataT *)w->data;
    memset(ta->customSyntaxColors, 0, sizeof(ta->customSyntaxColors));

    if (colors && count > 0) {
        if (count > TEXT_SYNTAX_MAX) {
            count = TEXT_SYNTAX_MAX;
        }

        memcpy(ta->customSyntaxColors, colors, count * sizeof(uint32_t));
    }

    wgtInvalidatePaint(w);
}


void wgtTextAreaSetTabWidth(WidgetT *w, int32_t width) {
    if (!w || w->type != sTextAreaTypeId) {
        return;
    }

    TextAreaDataT *ta = (TextAreaDataT *)w->data;
    ta->tabWidth = width > 0 ? width : 1;
    textEditLineCacheSetTabWidth(&ta->te.lines, ta->tabWidth);
}


void wgtTextAreaSetUseTabChar(WidgetT *w, bool useChar) {
    if (!w || w->type != sTextAreaTypeId) {
        return;
    }

    TextAreaDataT *ta = (TextAreaDataT *)w->data;
    ta->useTabChar = useChar;
}


WidgetT *wgtTextInput(WidgetT *parent, int32_t maxLen) {
    WidgetT *w = widgetAlloc(parent, sTextInputTypeId);

    if (w) {
        TextInputDataT *ti = (TextInputDataT *)calloc(1, sizeof(TextInputDataT));

        if (!ti) {
            return w;
        }

        w->data = ti;
        int32_t bufSize = maxLen > 0 ? maxLen + 1 : TEXTINPUT_DEFAULT_BUF;
        ti->buf     = (char *)malloc(bufSize);
        ti->bufSize = bufSize;

        if (ti->buf) {
            ti->buf[0] = '\0';
        }

        ti->undoBuf  = (char *)malloc(bufSize);

        // Zero the whole undo buffer so a Ctrl+Z before any edit copies a
        // defined (empty) buffer into the field instead of uninitialized
        // heap (the masked path memcpy's maskLen+1 bytes from it).
        if (ti->undoBuf) {
            memset(ti->undoBuf, 0, bufSize);
            ti->undoLen    = 0;
            ti->undoCursor = 0;
        }

        ti->selStart = -1;
        ti->selEnd   = -1;
        w->weight = WGT_WEIGHT_FILL;
    }

    return w;
}


void widgetTextAreaCalcMinSize(WidgetT *w, const BitmapFontT *font) {
    w->calcMinW = font->charWidth * TEXTAREA_MIN_COLS + TEXTAREA_PAD * 2 + TEXTAREA_BORDER * 2 + TEXTAREA_SB_W;
    w->calcMinH = font->charHeight * TEXTAREA_MIN_ROWS + TEXTAREA_BORDER * 2;
}


static bool widgetTextAreaClearSelection(WidgetT *w) {
    TextAreaDataT *ta = (TextAreaDataT *)w->data;

    if (ta->te.selAnchor >= 0 && ta->te.selCursor >= 0 && ta->te.selAnchor != ta->te.selCursor) {
        ta->te.selAnchor = -1;
        ta->te.selCursor = -1;
        return true;
    }

    return false;
}


void widgetTextAreaDestroy(WidgetT *w) {
    TextAreaDataT *ta = (TextAreaDataT *)w->data;

    if (ta) {
        textEditMultiFree(&ta->te);
        free(ta->rawSyntax);
        free(ta->expandBuf);
        free(ta->syntaxBuf);
        free(ta);
        w->data = NULL;
    }
}


static void widgetTextAreaDragSelect(WidgetT *w, WidgetT *root, int32_t vx, int32_t vy) {
    (void)root;
    TextAreaDataT *ta       = (TextAreaDataT *)w->data;
    AppContextT *ctx        = wgtGetContext(w);
    const BitmapFontT *font = &ctx->font;
    TextAreaGeomT geom;
    textAreaComputeGeom(w, font, &geom);
    int32_t textX   = w->x + TEXTAREA_BORDER + TEXTAREA_PAD + geom.gutterW;
    int32_t textY   = w->y + TEXTAREA_BORDER;
    int32_t visRows = geom.visRows;

    widgetTextEditMultiDragUpdateArea(&ta->te.lines, ta->te.buf, ta->te.len, vx, vy, textX, textY, font, &ta->te.scrollRow, ta->te.scrollCol, visRows, ta->tabWidth, &ta->te.cursorRow, &ta->te.cursorCol, &ta->te.desiredCol, &ta->te.selCursor);
}


const char *widgetTextAreaGetText(const WidgetT *w) {
    const TextAreaDataT *ta = (const TextAreaDataT *)w->data;
    return ta->te.buf ? ta->te.buf : "";
}


static void widgetTextAreaOnDragUpdate(WidgetT *w, WidgetT *root, int32_t x, int32_t y) {
    TextAreaDataT *ta = (TextAreaDataT *)w->data;

    if (ta->sbDragging) {
        widgetTextAreaScrollDragUpdate(w, ta->sbDragOrient, ta->sbDragOff, x, y);
    } else {
        widgetTextAreaDragSelect(w, root, x, y);
    }
}


// TextArea key handling is inline (not using widgetTextEditOnKey)
// because multi-line editing has fundamentally different cursor
// semantics: row/col instead of linear offset, desiredCol for
// vertical movement (so moving down from a long line to a short
// line remembers the original column), and Enter inserts newlines.
//
// The SEL_BEGIN/SEL_END/HAS_SEL macros factor out the repetitive
// selection-start/selection-extend pattern: SEL_BEGIN initializes
// the anchor at the current offset if Shift is held and no selection
// exists yet. SEL_END updates the selection cursor to the new
// position (or clears selection if Shift isn't held). This keeps
// the per-key handler code manageable despite the large number of
// key combinations.
//
// textAreaEnsureVisible() is called after every cursor movement to
// auto-scroll the viewport. It adjusts scrollRow/scrollCol so the
// cursor is within the visible range.
void widgetTextAreaOnKey(WidgetT *w, int32_t key, int32_t mod) {
    TextAreaDataT *ta = (TextAreaDataT *)w->data;

    if (!ta->te.buf) {
        return;
    }

    clearOtherSelections(w);

    AppContextT *ctx        = wgtGetContext(w);
    const BitmapFontT *font = &ctx->font;
    TextAreaGeomT geom;
    textAreaComputeGeom(w, font, &geom);
    int32_t visCols = geom.visCols;
    int32_t visRows = geom.visRows;

    if (visRows < 1) {
        visRows = 1;
    }

    if (visCols < 1) {
        visCols = 1;
    }

    TextEditMultiOptionsT opts = {
        .autoIndent  = ta->autoIndent,
        .captureTabs = ta->captureTabs,
        .useTabChar  = ta->useTabChar,
        .tabWidth    = ta->tabWidth,
        .readOnly    = w->readOnly,
    };

    widgetTextEditMultiOnKey(w, key, mod, &ta->te.lines, ta->te.buf, ta->te.bufSize, &ta->te.len, &ta->te.cursorRow, &ta->te.cursorCol, &ta->te.desiredCol, &ta->te.scrollRow, &ta->te.scrollCol, &ta->te.selAnchor, &ta->te.selCursor, ta->te.undoBuf, &ta->te.undoLen, &ta->te.undoCursor, visRows, visCols, &opts);

    // Gutter cache may be stale after edits that change line count
    ta->cachedGutterW = 0;
}


// Mouse handling: scrollbar clicks (both V and H), then content area
// clicks. Content clicks convert pixel coordinates to row/col using
// font metrics and scroll offset. Multi-click: double-click selects
// word, triple-click selects entire line. Single click starts a
// drag-select (sets sDragWidget which the event loop monitors
// on mouse-move to extend the selection). The drag-select global
// is cleared on double/triple click since the selection is already
// complete.
void widgetTextAreaOnMouse(WidgetT *w, WidgetT *root, int32_t vx, int32_t vy) {
    TextAreaDataT *ta = (TextAreaDataT *)w->data;
    sFocusedWidget = w;
    clearOtherSelections(w);

    AppContextT *ctx = (AppContextT *)root->userData;
    const BitmapFontT *font = &ctx->font;

    TextAreaGeomT geom;
    textAreaComputeGeom(w, font, &geom);
    int32_t gutterW = geom.gutterW;
    int32_t innerX  = w->x + TEXTAREA_BORDER + TEXTAREA_PAD + gutterW;
    int32_t innerY  = w->y + TEXTAREA_BORDER;
    int32_t visCols = geom.visCols;
    int32_t maxLL   = geom.maxLL;
    bool    needHSb = geom.needHSb;
    int32_t innerH  = geom.innerH;
    int32_t visRows = geom.visRows;

    if (visRows < 1) {
        visRows = 1;
    }

    if (visCols < 1) {
        visCols = 1;
    }

    int32_t totalLines = textAreaGetLineCount(w);
    int32_t maxScroll  = totalLines - visRows;

    if (maxScroll < 0) {
        maxScroll = 0;
    }

    ta->te.scrollRow = clampInt(ta->te.scrollRow, 0, maxScroll);

    int32_t maxHScroll = maxLL - visCols;

    if (maxHScroll < 0) {
        maxHScroll = 0;
    }

    ta->te.scrollCol = clampInt(ta->te.scrollCol, 0, maxHScroll);

    if (needHSb) {
        int32_t hsbX = w->x + TEXTAREA_BORDER;
        int32_t hsbY = w->y + w->h - TEXTAREA_BORDER - TEXTAREA_SB_W;
        int32_t hsbW = w->w - TEXTAREA_BORDER * 2 - TEXTAREA_SB_W;

        if (vy >= hsbY && vx < hsbX + hsbW) {
            int32_t dragOff = 0;
            int32_t hit     = widgetTextScrollbarHitTest(false, vx, vy, hsbX, hsbY, TEXTAREA_SB_W, hsbW, maxLL, visCols, ta->te.scrollCol, &dragOff);

            switch (hit) {
                case TEXT_SB_HIT_UP:
                    if (ta->te.scrollCol > 0) {
                        ta->te.scrollCol--;
                    }
                    break;
                case TEXT_SB_HIT_DOWN:
                    if (ta->te.scrollCol < maxHScroll) {
                        ta->te.scrollCol++;
                    }
                    break;
                case TEXT_SB_HIT_PAGE_UP:
                    ta->te.scrollCol = clampInt(ta->te.scrollCol - visCols, 0, maxHScroll);
                    break;
                case TEXT_SB_HIT_PAGE_DOWN:
                    ta->te.scrollCol = clampInt(ta->te.scrollCol + visCols, 0, maxHScroll);
                    break;
                case TEXT_SB_HIT_THUMB:
                    sDragWidget      = w;
                    ta->sbDragOrient = 1;
                    ta->sbDragging   = true;
                    ta->sbDragOff    = dragOff;
                    return;
            }

            return;
        }
    }

    int32_t sbX = w->x + w->w - TEXTAREA_BORDER - TEXTAREA_SB_W;
    int32_t sbY = w->y + TEXTAREA_BORDER;

    if (vx >= sbX) {
        int32_t dragOff = 0;
        int32_t hit     = widgetTextScrollbarHitTest(true, vx, vy, sbX, sbY, TEXTAREA_SB_W, innerH, totalLines, visRows, ta->te.scrollRow, &dragOff);

        switch (hit) {
            case TEXT_SB_HIT_UP:
                if (ta->te.scrollRow > 0) {
                    ta->te.scrollRow--;
                }
                break;
            case TEXT_SB_HIT_DOWN:
                if (ta->te.scrollRow < maxScroll) {
                    ta->te.scrollRow++;
                }
                break;
            case TEXT_SB_HIT_PAGE_UP:
                ta->te.scrollRow = clampInt(ta->te.scrollRow - visRows, 0, maxScroll);
                break;
            case TEXT_SB_HIT_PAGE_DOWN:
                ta->te.scrollRow = clampInt(ta->te.scrollRow + visRows, 0, maxScroll);
                break;
            case TEXT_SB_HIT_THUMB:
                sDragWidget      = w;
                ta->sbDragOrient = 0;
                ta->sbDragging   = true;
                ta->sbDragOff    = dragOff;
                return;
        }

        return;
    }

    // Click on gutter — toggle breakpoint
    if (gutterW > 0 && vx < innerX && ta->onGutterClick) {
        int32_t relY     = vy - innerY;
        int32_t clickRow = ta->te.scrollRow + relY / font->charHeight;

        if (clickRow >= 0 && clickRow < totalLines) {
            ta->onGutterClick(w, clickRow + 1); // 1-based line number
        }

        wgtInvalidatePaint(w);
        return;
    }

    widgetTextEditMultiMouseClick(w, &ta->te.lines, ta->te.buf, ta->te.len, vx, vy, innerX, innerY, font, ta->te.scrollRow, ta->te.scrollCol, ta->tabWidth, &ta->te.cursorRow, &ta->te.cursorCol, &ta->te.desiredCol, &ta->te.selAnchor, &ta->te.selCursor);
    ta->sbDragging = false;
}


// TextArea paint uses an optimized incremental line-offset approach:
// instead of calling textAreaLineStart() for each visible row (which
// would re-scan from the buffer start each time), we compute the
// starting offset of the first visible line once, then advance it
// line by line. This makes the paint cost O(visRows * maxLineLen)
// rather than O(visRows * totalLines).
//
// Each line is drawn in up to 3 runs (before-selection, selection,
// after-selection) to avoid overdraw. Selection highlighting that
// extends past the end of a line (the newline itself is "selected")
// is rendered as a highlight-colored rectFill past the text.
//
// Scrollbars are drawn inline (not using the shared scrollbar
// functions) because TextArea scrolling is in rows/cols (logical
// units) rather than pixels, so the thumb calculation parameters
// differ. The dead corner between scrollbars is filled with
// windowFace color.
void widgetTextAreaPaint(WidgetT *w, DisplayT *d, const BlitOpsT *ops, const BitmapFontT *font, const ColorSchemeT *colors) {
    TextAreaDataT *ta = (TextAreaDataT *)w->data;
    uint32_t fg = w->fgColor ? w->fgColor : colors->contentFg;
    uint32_t bg = w->bgColor ? w->bgColor : colors->contentBg;

    TextAreaGeomT geom;
    textAreaComputeGeom(w, font, &geom);
    int32_t gutterW    = geom.gutterW;
    int32_t innerW     = geom.innerW;
    int32_t visCols    = geom.visCols;
    int32_t maxLL      = geom.maxLL;
    bool    needHSb    = geom.needHSb;
    int32_t innerH     = geom.innerH;
    int32_t visRows    = geom.visRows;
    int32_t totalLines = textAreaGetLineCount(w);
    bool    needVSb    = (totalLines > visRows);

    // Sunken border
    BevelStyleT bevel = BEVEL_SUNKEN(colors, bg, 2);
    drawBevel(d, ops, w->x, w->y, w->w, w->h, &bevel);

    int32_t maxScroll = totalLines - visRows;

    if (maxScroll < 0) {
        maxScroll = 0;
    }

    ta->te.scrollRow = clampInt(ta->te.scrollRow, 0, maxScroll);

    int32_t maxHScroll = maxLL - visCols;

    if (maxHScroll < 0) {
        maxHScroll = 0;
    }

    ta->te.scrollCol = clampInt(ta->te.scrollCol, 0, maxHScroll);

    int32_t gutterX = w->x + TEXTAREA_BORDER + TEXTAREA_PAD;
    int32_t textX   = gutterX + gutterW;
    int32_t textY   = w->y + TEXTAREA_BORDER;

    if (gutterW > 0) {
        rectFill(d, ops, gutterX, textY, gutterW, innerH, colors->windowFace);
        drawVLine(d, ops, gutterX + gutterW - 1, textY, innerH, colors->windowShadow);

        for (int32_t i = 0; i < visRows; i++) {
            int32_t row = ta->te.scrollRow + i;

            if (row >= totalLines) {
                break;
            }

            int32_t drawY       = textY + i * font->charHeight;
            uint32_t gutterColor = 0;

            if (ta->lineDecorator) {
                ta->lineDecorator(row + 1, &gutterColor, ta->lineDecoratorCtx);
            }

            if (gutterColor) {
                // Draw a filled circle as 7 scanlines. Radius 3 gives
                // a clean 7x7 circle at any font size.
                int32_t cx = gutterX + font->charWidth / 2 + 1;
                int32_t cy = drawY + font->charHeight / 2;
                static const int32_t hw[] = { 1, 2, 3, 3, 3, 2, 1 };

                for (int32_t dy = -3; dy <= 3; dy++) {
                    int32_t hwVal = hw[dy + 3];
                    rectFill(d, ops, cx - hwVal, cy + dy, hwVal * 2 + 1, 1, gutterColor);
                }
            }

            char numBuf[12];
            int32_t numLen = snprintf(numBuf, sizeof(numBuf), "%d", (int)(row + 1));
            int32_t numX   = gutterX + gutterW - (numLen + 1) * font->charWidth;
            drawTextN(d, ops, font, numX, drawY, numBuf, numLen, colors->windowShadow, colors->windowFace, true);
        }
    }

    TextEditPaintHooksT hooks = {
        .colorize           = ta->colorize,
        .colorizeCtx        = ta->colorizeCtx,
        .lineDecorator      = ta->lineDecorator,
        .lineDecoratorCtx   = ta->lineDecoratorCtx,
        .rawSyntax          = ta->rawSyntax,
        .expandBuf          = ta->expandBuf,
        .syntaxBuf          = ta->syntaxBuf,
        .scratchLen         = MAX_COLORIZE_LEN,
        .customSyntaxColors = ta->customSyntaxColors,
    };

    int32_t tabW       = ta->tabWidth > 0 ? ta->tabWidth : 3;
    bool    showCursor = (w == sFocusedWidget && sCursorBlinkOn);

    widgetTextEditMultiPaintArea(d, ops, font, colors, &ta->te.lines, ta->te.buf, ta->te.len, textX, textY, innerW, visCols, visRows, ta->te.scrollRow, ta->te.scrollCol, ta->te.cursorRow, ta->te.cursorCol, ta->te.selAnchor, ta->te.selCursor, tabW, fg, bg, showCursor, &hooks);

    if (needVSb) {
        int32_t sbX = w->x + w->w - TEXTAREA_BORDER - TEXTAREA_SB_W;
        int32_t sbY = w->y + TEXTAREA_BORDER;
        widgetTextScrollbarDraw(d, ops, colors, true, sbX, sbY, TEXTAREA_SB_W, innerH, totalLines, visRows, ta->te.scrollRow);
    }

    if (needHSb) {
        int32_t hsbX = w->x + TEXTAREA_BORDER;
        int32_t hsbY = w->y + w->h - TEXTAREA_BORDER - TEXTAREA_SB_W;
        int32_t hsbW = w->w - TEXTAREA_BORDER * 2 - TEXTAREA_SB_W;
        widgetTextScrollbarDraw(d, ops, colors, false, hsbX, hsbY, TEXTAREA_SB_W, hsbW, maxLL, visCols, ta->te.scrollCol);

        if (needVSb) {
            int32_t cornerX = w->x + w->w - TEXTAREA_BORDER - TEXTAREA_SB_W;
            rectFill(d, ops, cornerX, hsbY, TEXTAREA_SB_W, TEXTAREA_SB_W, colors->windowFace);
        }
    }

    if (w == sFocusedWidget) {
        drawFocusRect(d, ops, w->x + 1, w->y + 1, w->w - 2, w->h - 2, fg);
    }
}


static void widgetTextAreaScrollDragUpdate(WidgetT *w, int32_t orient, int32_t dragOff, int32_t mouseX, int32_t mouseY) {
    TextAreaDataT     *ta   = (TextAreaDataT *)w->data;
    AppContextT       *ctx  = wgtGetContext(w);
    const BitmapFontT *font = &ctx->font;
    TextAreaGeomT geom;
    textAreaComputeGeom(w, font, &geom);
    int32_t innerH  = geom.innerH;
    int32_t visCols = geom.visCols;
    int32_t maxLL   = geom.maxLL;
    int32_t visRows = geom.visRows;

    if (visRows < 1) {
        visRows = 1;
    }

    if (visCols < 1) {
        visCols = 1;
    }

    if (orient == 0) {
        int32_t totalLines = textAreaGetLineCount(w);
        int32_t sbY        = w->y + TEXTAREA_BORDER;
        ta->te.scrollRow = widgetTextScrollbarDragToScroll(true, mouseY, sbY, TEXTAREA_SB_W, innerH, totalLines, visRows, dragOff);
    } else if (orient == 1) {
        int32_t hsbW = w->w - TEXTAREA_BORDER * 2 - TEXTAREA_SB_W;
        int32_t sbX  = w->x + TEXTAREA_BORDER;
        ta->te.scrollCol = widgetTextScrollbarDragToScroll(false, mouseX, sbX, TEXTAREA_SB_W, hsbW, maxLL, visCols, dragOff);
    }
}


void widgetTextAreaSetText(WidgetT *w, const char *text) {
    TextAreaDataT *ta = (TextAreaDataT *)w->data;

    if (ta->te.buf) {
        strncpy(ta->te.buf, text, ta->te.bufSize - 1);
        ta->te.buf[ta->te.bufSize - 1] = '\0';
        ta->te.len        = (int32_t)strlen(ta->te.buf);
        ta->te.cursorRow  = 0;
        ta->te.cursorCol  = 0;
        ta->te.scrollRow  = 0;
        ta->te.scrollCol  = 0;
        ta->te.desiredCol = 0;
        ta->te.selAnchor  = -1;
        ta->te.selCursor  = -1;
        textAreaDirtyCache(w);
    }
}


void widgetTextInputCalcMinSize(WidgetT *w, const BitmapFontT *font) {
    w->calcMinW = font->charWidth * 8 + TEXT_INPUT_PAD * 2;
    w->calcMinH = font->charHeight + TEXT_INPUT_PAD * 2;
}


static bool widgetTextInputClearSelection(WidgetT *w) {
    TextInputDataT *ti = (TextInputDataT *)w->data;

    if (ti->selStart >= 0 && ti->selEnd >= 0 && ti->selStart != ti->selEnd) {
        ti->selStart = -1;
        ti->selEnd   = -1;
        return true;
    }

    return false;
}


void widgetTextInputDestroy(WidgetT *w) {
    TextInputDataT *ti = (TextInputDataT *)w->data;

    if (ti) {
        free(ti->buf);
        free(ti->undoBuf);
        free(ti);
        w->data = NULL;
    }
}


const char *widgetTextInputGetText(const WidgetT *w) {
    const TextInputDataT *ti = (const TextInputDataT *)w->data;
    return ti->buf ? ti->buf : "";
}


static void widgetTextInputOnDragUpdate(WidgetT *w, WidgetT *root, int32_t vx, int32_t vy) {
    (void)root;
    (void)vy;
    TextInputDataT *ti = (TextInputDataT *)w->data;
    AppContextT *ctx   = wgtGetContext(w);
    int32_t maxChars   = (w->w - TEXT_INPUT_PAD * 2) / ctx->font.charWidth;

    widgetTextEditDragUpdateLine(vx, w->x + TEXT_INPUT_PAD, maxChars, &ctx->font, ti->len, &ti->cursorPos, &ti->scrollOff, &ti->selEnd);
}


// TextInput key handling delegates to the shared widgetTextEditOnKey
// engine, passing pointers to its state fields. Masked input mode
// gets its own handler since the editing semantics are completely
// different. Password mode blocks copy/cut at this level before
// reaching the shared engine.
void widgetTextInputOnKey(WidgetT *w, int32_t key, int32_t mod) {
    TextInputDataT *ti = (TextInputDataT *)w->data;

    if (!ti->buf) {
        return;
    }

    clearOtherSelections(w);

    if (ti->inputMode == InputMaskedE) {
        maskedInputOnKey(w, key, mod);
        return;
    }

    // Password mode: block copy (Ctrl+C) and cut (Ctrl+X)
    if (ti->inputMode == InputPasswordE) {
        if (key == KEY_CTRL_C || key == KEY_CTRL_X) {
            return;
        }
    }

    widgetTextEditOnKey(w, key, mod, ti->buf, ti->bufSize,
                        &ti->len, &ti->cursorPos,
                        &ti->scrollOff,
                        &ti->selStart, &ti->selEnd,
                        ti->undoBuf, &ti->undoLen,
                        &ti->undoCursor,
                        w->w - TEXT_INPUT_PAD * 2);
}


// Mouse handling for single-line input. Cursor position is computed
// from pixel offset using the fixed-width font (relX / charWidth +
// scrollOff). Multi-click: double-click selects word (using
// wordStart/wordEnd), triple-click selects all. Single click starts
// drag-select by setting both selStart and selEnd to the click
// position and registering sDragWidget.
void widgetTextInputOnMouse(WidgetT *w, WidgetT *root, int32_t vx, int32_t vy) {
    TextInputDataT *ti = (TextInputDataT *)w->data;
    sFocusedWidget = w;
    clearOtherSelections(w);

    AppContextT *ctx = (AppContextT *)root->userData;
    widgetTextEditMouseClick(w, vx, vy, w->x + TEXT_INPUT_PAD, &ctx->font, ti->buf, ti->len, ti->scrollOff, &ti->cursorPos, &ti->selStart, &ti->selEnd, true, true);
}


// TextInput paint: sunken 2px bevel, then text with optional selection
// highlighting, then cursor line. Text is drawn from a display buffer
// that may be either the actual text or bullets (password mode, using
// CP437 character 0xF9 which renders as a small centered dot).
//
// The 3-run approach (before/during/after selection) draws text in a
// single pass without overdraw. The scroll offset ensures only the
// visible portion of the text is drawn. The cursor is a 1px-wide
// vertical line drawn at the character boundary.
void widgetTextInputPaint(WidgetT *w, DisplayT *d, const BlitOpsT *ops, const BitmapFontT *font, const ColorSchemeT *colors) {
    TextInputDataT *ti = (TextInputDataT *)w->data;
    uint32_t fg = w->enabled ? (w->fgColor ? w->fgColor : colors->contentFg) : colors->windowShadow;
    uint32_t bg = w->bgColor ? w->bgColor : colors->contentBg;

    // Sunken border
    BevelStyleT bevel;
    bevel.highlight = colors->windowShadow;
    bevel.shadow    = colors->windowHighlight;
    bevel.face      = bg;
    bevel.width     = 2;
    drawBevel(d, ops, w->x, w->y, w->w, w->h, &bevel);

    // Draw text
    if (ti->buf) {
        int32_t textX    = w->x + TEXT_INPUT_PAD;
        int32_t textY    = w->y + (w->h - font->charHeight) / 2;
        int32_t maxChars = (w->w - TEXT_INPUT_PAD * 2) / font->charWidth;
        int32_t off      = ti->scrollOff;
        int32_t len      = ti->len - off;

        if (len > maxChars) {
            len = maxChars;
        }

        bool isPassword = (ti->inputMode == InputPasswordE);

        // Build display buffer (password masking)
        char dispBuf[256];
        int32_t dispLen = len > 255 ? 255 : len;

        if (isPassword) {
            memset(dispBuf, '\xF9', dispLen); // CP437 bullet
        } else {
            memcpy(dispBuf, ti->buf + off, dispLen);
        }

        widgetTextEditPaintLine(d, ops, font, colors, textX, textY, dispBuf, dispLen, off, ti->cursorPos, ti->selStart, ti->selEnd, fg, bg, w == sFocusedWidget && w->enabled, w->x + TEXT_INPUT_PAD, w->x + w->w - TEXT_INPUT_PAD);
    }
}


void widgetTextInputSetText(WidgetT *w, const char *text) {
    TextInputDataT *ti = (TextInputDataT *)w->data;

    if (ti->buf) {
        strncpy(ti->buf, text, ti->bufSize - 1);
        ti->buf[ti->bufSize - 1] = '\0';
        ti->len       = (int32_t)strlen(ti->buf);
        ti->cursorPos = ti->len;
        ti->scrollOff = 0;
        ti->selStart  = -1;
        ti->selEnd    = -1;
    }
}


static const WidgetClassT sClassTextInput = {
    .version = WGT_CLASS_VERSION,
    .flags   = WCLASS_FOCUSABLE,
    .handlers = {
        [WGT_METHOD_PAINT]           = (void *)widgetTextInputPaint,
        [WGT_METHOD_CALC_MIN_SIZE]   = (void *)widgetTextInputCalcMinSize,
        [WGT_METHOD_ON_MOUSE]        = (void *)widgetTextInputOnMouse,
        [WGT_METHOD_ON_KEY]          = (void *)widgetTextInputOnKey,
        [WGT_METHOD_DESTROY]         = (void *)widgetTextInputDestroy,
        [WGT_METHOD_GET_TEXT]        = (void *)widgetTextInputGetText,
        [WGT_METHOD_SET_TEXT]        = (void *)widgetTextInputSetText,
        [WGT_METHOD_CLEAR_SELECTION] = (void *)widgetTextInputClearSelection,
        [WGT_METHOD_ON_DRAG_UPDATE]  = (void *)widgetTextInputOnDragUpdate,
    }
};

static const WidgetClassT sClassTextArea = {
    .version = WGT_CLASS_VERSION,
    .flags   = WCLASS_FOCUSABLE | WCLASS_SCROLLABLE,
    .handlers = {
        [WGT_METHOD_PAINT]           = (void *)widgetTextAreaPaint,
        [WGT_METHOD_CALC_MIN_SIZE]   = (void *)widgetTextAreaCalcMinSize,
        [WGT_METHOD_ON_MOUSE]        = (void *)widgetTextAreaOnMouse,
        [WGT_METHOD_ON_KEY]          = (void *)widgetTextAreaOnKey,
        [WGT_METHOD_DESTROY]         = (void *)widgetTextAreaDestroy,
        [WGT_METHOD_GET_TEXT]        = (void *)widgetTextAreaGetText,
        [WGT_METHOD_SET_TEXT]        = (void *)widgetTextAreaSetText,
        [WGT_METHOD_CLEAR_SELECTION] = (void *)widgetTextAreaClearSelection,
        [WGT_METHOD_ON_DRAG_UPDATE]  = (void *)widgetTextAreaOnDragUpdate,
    }
};


static const struct {
    WidgetT *(*create)(WidgetT *parent, int32_t maxLen);
    WidgetT *(*password)(WidgetT *parent, int32_t maxLen);
    WidgetT *(*masked)(WidgetT *parent, const char *mask);
    WidgetT *(*textArea)(WidgetT *parent, int32_t maxLen);
    void     (*setColorize)(WidgetT *w, void (*fn)(const char *, int32_t, uint8_t *, void *), void *ctx);
    void     (*goToLine)(WidgetT *w, int32_t line);
    void     (*setAutoIndent)(WidgetT *w, bool enable);
    void     (*setShowLineNumbers)(WidgetT *w, bool show);
    void     (*setCaptureTabs)(WidgetT *w, bool capture);
    void     (*setTabWidth)(WidgetT *w, int32_t width);
    void     (*setUseTabChar)(WidgetT *w, bool useChar);
    bool     (*findNext)(WidgetT *w, const char *needle, bool caseSensitive, bool forward);
    int32_t  (*replaceAll)(WidgetT *w, const char *needle, const char *replacement, bool caseSensitive);
    bool     (*replaceSelection)(WidgetT *w, const char *needle, const char *replacement, bool caseSensitive, bool forward);
    void     (*setLineDecorator)(WidgetT *w, uint32_t (*fn)(int32_t, uint32_t *, void *), void *ctx);
    int32_t  (*getCursorLine)(const WidgetT *w);
    void     (*setGutterClick)(WidgetT *w, void (*fn)(WidgetT *, int32_t));
    int32_t  (*getWordAtCursor)(const WidgetT *w, char *buf, int32_t bufSize);
    void     (*setSyntaxColors)(WidgetT *w, const uint32_t *colors, int32_t count);
    void     (*cursorToEnd)(WidgetT *w);
} sApi = {
    .create             = wgtTextInput,
    .password           = wgtPasswordInput,
    .masked             = wgtMaskedInput,
    .textArea           = wgtTextArea,
    .setColorize        = wgtTextAreaSetColorize,
    .goToLine           = wgtTextAreaGoToLine,
    .setAutoIndent      = wgtTextAreaSetAutoIndent,
    .setShowLineNumbers = wgtTextAreaSetShowLineNumbers,
    .setCaptureTabs     = wgtTextAreaSetCaptureTabs,
    .setTabWidth        = wgtTextAreaSetTabWidth,
    .setUseTabChar      = wgtTextAreaSetUseTabChar,
    .findNext           = wgtTextAreaFindNext,
    .replaceAll         = wgtTextAreaReplaceAll,
    .replaceSelection   = wgtTextAreaReplaceSelection,
    .setLineDecorator   = wgtTextAreaSetLineDecorator,
    .getCursorLine      = wgtTextAreaGetCursorLine,
    .setGutterClick     = wgtTextAreaSetGutterClickCallback,
    .getWordAtCursor    = wgtTextAreaGetWordAtCursor,
    .setSyntaxColors    = wgtTextAreaSetSyntaxColors,
    .cursorToEnd        = wgtTextAreaCursorToEnd
};

// Per-type APIs for the designer
static const struct { WidgetT *(*create)(WidgetT *, int32_t); } sTextInputApi = { .create = wgtTextInput };
static const struct { WidgetT *(*create)(WidgetT *, int32_t); } sTextAreaApi  = { .create = wgtTextArea };


// TextArea BASIC interface
static const WgtPropDescT sTextAreaProps[] = {
    { "CursorLine",      WGT_IFACE_INT, (void *)wgtTextAreaGetCursorLine, NULL, NULL }
};

static const WgtMethodDescT sTextAreaMethods[] = {
    { "AppendText",         WGT_SIG_STR,            (void *)wgtTextAreaAppendText },
    { "FindNext",           WGT_SIG_STR_BOOL_BOOL, (void *)wgtTextAreaFindNext },
    { "GetWordAtCursor",    WGT_SIG_RET_STR,       (void *)basGetWordAtCursor },
    { "GoToLine",           WGT_SIG_INT,            (void *)wgtTextAreaGoToLine },
    { "ReplaceAll",         WGT_SIG_STR_STR_BOOL,   (void *)wgtTextAreaReplaceAll },
    { "SetAutoIndent",      WGT_SIG_BOOL,           (void *)wgtTextAreaSetAutoIndent },
    { "SetCaptureTabs",     WGT_SIG_BOOL,           (void *)wgtTextAreaSetCaptureTabs },
    { "SetShowLineNumbers", WGT_SIG_BOOL,           (void *)wgtTextAreaSetShowLineNumbers },
    { "SetSyntaxMode",      WGT_SIG_STR,            (void *)basSetSyntaxMode },
    { "SetTabWidth",        WGT_SIG_INT,             (void *)wgtTextAreaSetTabWidth },
    { "SetUseTabChar",      WGT_SIG_BOOL,            (void *)wgtTextAreaSetUseTabChar },
};

static const WgtIfaceT sIfaceTextInput = {
    .basName      = "TextBox",
    .props        = NULL,
    .propCount    = 0,
    .methods      = NULL,
    .methodCount  = 0,
    .events       = NULL,
    .eventCount   = 0,
    .createSig    = WGT_CREATE_PARENT_INT,
    .createArgs   = { TEXTINPUT_DEFAULT_BUF },
    .defaultEvent = "Change"
};

static const WgtIfaceT sIfaceTextArea = {
    .basName      = "TextArea",
    .props        = sTextAreaProps,
    .propCount    = sizeof(sTextAreaProps) / sizeof(sTextAreaProps[0]),
    .methods      = sTextAreaMethods,
    .methodCount  = sizeof(sTextAreaMethods) / sizeof(sTextAreaMethods[0]),
    .events       = NULL,
    .eventCount   = 0,
    .createSig    = WGT_CREATE_PARENT_INT,
    .createArgs   = { TEXTAREA_DEFAULT_BUF },
    .defaultEvent = "Change"
};

void wgtRegister(void) {
    sTextInputTypeId = wgtRegisterClass(&sClassTextInput);
    sTextAreaTypeId  = wgtRegisterClass(&sClassTextArea);

    // Original combined API (for widgetTextInput.h compatibility)
    wgtRegisterApi("textinput", &sApi);

    // Per-type APIs and ifaces (for designer/toolbox)
    wgtRegisterApi("textbox", &sTextInputApi);
    wgtRegisterIface("textbox", &sIfaceTextInput);

    wgtRegisterApi("textarea", &sTextAreaApi);
    wgtRegisterIface("textarea", &sIfaceTextArea);
}
