#ifndef HUSH_HITTEST_H
#define HUSH_HITTEST_H

#include "layout_cache.h"
#include "document.h"
#include "fonts.h"
#include "clay.h"

typedef struct {
    int blockIndex;
    int offset;
} HitResult;

/* Maps a screen-space point to the nearest (block, byte offset), using the Clay element
   positions computed for the layout built during the previous frame. */
HitResult hittest_point(LayoutCache *cache, Document *doc, SDL2_Font *fonts, Clay_Vector2 point);

typedef struct {
    int found;
    int blockIndex;
    int offset;
} VerticalMoveResult;

/* Moves the cursor to the visual line above (dir<0) or below (dir>0), trying to land as
   close as possible to `preferredX` (screen-space x). */
VerticalMoveResult hittest_vertical(LayoutCache *cache, Document *doc, SDL2_Font *fonts, int blockIndex, int offset, float preferredX, int dir);

/* Resolves screen-space x to a byte offset within `blockIndex`'s *first* registered visual line
   (a table cell's own vertical-nav jump lands here -- equal-width narrow columns wrap more
   readily than most block types, so not preserving exact wrapped-row position across a jump to
   a different cell is a deliberate simplification). Returns 0 if the block has no registered
   line yet (e.g. very first frame). */
int hittest_offset_for_block_x(LayoutCache *cache, Document *doc, SDL2_Font *fonts, int blockIndex, float targetX);

/* Fills the caret's screen box for (blockIndex, offset). Returns 0 if the layout has no
   matching entry yet (e.g. very first frame). */
int hittest_caret(LayoutCache *cache, Document *doc, SDL2_Font *fonts, int blockIndex, int offset, float *outX, float *outY, float *outHeight);

/* Fills the screen-space box covering [rangeStart, rangeEnd) (byte offsets within the line's
   block) as visible on visual line `lineIdx`, clamped to that line's own byte range. Returns 0
   if the range doesn't intersect the line or the layout has no matching entry yet. Used to draw
   the selection highlight, one rectangle per intersected visual line. */
int hittest_line_range_box(LayoutCache *cache, Document *doc, SDL2_Font *fonts, int lineIdx,
                            int rangeStart, int rangeEnd, float *outX, float *outY, float *outW, float *outHeight);

#endif
