#import <Cocoa/Cocoa.h>
#import <ImageIO/ImageIO.h>
#import <Carbon/Carbon.h>
#import <ScreenCaptureKit/ScreenCaptureKit.h>
#import <math.h>
#import <pwd.h>
#import <unistd.h>

static const CGFloat PAD_LEFT  = 42.0;
static const CGFloat PAD_RITE  = 12.0;
static const CGFloat PAD_TOP_  = 48.0;
static const CGFloat PAD_BOTM  = 12.0;
static const CGFloat MIN_HOLE  = 32.0;
static const CGFloat MAX_HOLE  = 16384.0;
static const CGFloat MIN_BAR_W = 340.0;

typedef struct {
    int hole_x, hole_y, hole_w, hole_h;
    int locked, res_mult, clip, grid;
    int pre_w[5], pre_h[5];
    char prefix[64];
} WdvPxCfg;

static BOOL isSandboxed(void) {
    return (NSProcessInfo.processInfo.environment[@"APP_SANDBOX_CONTAINER_ID"] != nil);
}

static NSURL *realUserDesktopURL(void) {
    struct passwd *pw = getpwuid(getuid());
    if (pw && pw->pw_dir) {
        NSString *home = [NSString stringWithUTF8String:pw->pw_dir];
        return [NSURL fileURLWithPath:[home stringByAppendingPathComponent:@"Desktop"] isDirectory:YES];
    }
    return [NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Desktop"] isDirectory:YES];
}

static CGFloat primaryScreenHeight(void) {
    NSArray<NSScreen *> *screens = [NSScreen screens];
    return (screens.count > 0) ? screens[0].frame.size.height : 1080.0;
}

static void cfgDefaults(WdvPxCfg *c) {
    c->hole_x = 200; c->hole_y = 200;
    c->hole_w = 400; c->hole_h = 300;
    c->locked = 0;   c->res_mult = 2; c->clip = 0; c->grid = 0;
    // Base 1X logical sizes: at default 2X these yield 100x100, 512x512, 800x600, 1280x720, 1920x1080 px
    int dw[5] = { 50, 256, 400, 640, 960 };
    int dh[5] = { 50, 256, 300, 360, 540 };
    for (int i = 0; i < 5; i++) { c->pre_w[i] = dw[i]; c->pre_h[i] = dh[i]; }
    strlcpy(c->prefix, "wdv-px", sizeof(c->prefix));
}

static int clampHoleDim(int v) {
    if (v < (int)MIN_HOLE) return (int)MIN_HOLE;
    if (v > (int)MAX_HOLE) return (int)MAX_HOLE;
    return v;
}

static void cfgLoad(WdvPxCfg *c) {
    cfgDefaults(c);
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    if ([ud objectForKey:@"hole_x"])   c->hole_x   = (int)[ud integerForKey:@"hole_x"];
    if ([ud objectForKey:@"hole_y"])   c->hole_y   = (int)[ud integerForKey:@"hole_y"];
    if ([ud objectForKey:@"hole_w"])   c->hole_w   = clampHoleDim((int)[ud integerForKey:@"hole_w"]);
    if ([ud objectForKey:@"hole_h"])   c->hole_h   = clampHoleDim((int)[ud integerForKey:@"hole_h"]);
    if ([ud objectForKey:@"locked"])   c->locked   = [ud boolForKey:@"locked"] ? 1 : 0;
    if ([ud objectForKey:@"res_mult"]) c->res_mult = ([ud integerForKey:@"res_mult"] == 1) ? 1 : 2;
    if ([ud objectForKey:@"clip"])     c->clip     = [ud boolForKey:@"clip"] ? 1 : 0;
    if ([ud objectForKey:@"grid"])     c->grid     = [ud boolForKey:@"grid"] ? 1 : 0;
    NSString *pfx = [ud stringForKey:@"prefix"];
    if (pfx.length > 0) strlcpy(c->prefix, pfx.UTF8String, sizeof(c->prefix));

    for (int i = 0; i < 5; i++) {
        NSString *pk = [NSString stringWithFormat:@"preset%d", i + 1];
        NSString *pv = [ud stringForKey:pk];
        int pw = 0, ph = 0;
        if (pv && sscanf(pv.UTF8String, "%dx%d", &pw, &ph) == 2) {
            c->pre_w[i] = clampHoleDim(pw);
            c->pre_h[i] = clampHoleDim(ph);
        }
    }
}

static void cfgSave(const WdvPxCfg *c) {
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    [ud setInteger:c->hole_x   forKey:@"hole_x"];
    [ud setInteger:c->hole_y   forKey:@"hole_y"];
    [ud setInteger:c->hole_w   forKey:@"hole_w"];
    [ud setInteger:c->hole_h   forKey:@"hole_h"];
    [ud setBool:(c->locked != 0) forKey:@"locked"];
    [ud setInteger:c->res_mult forKey:@"res_mult"];
    [ud setBool:(c->clip != 0)   forKey:@"clip"];
    [ud setBool:(c->grid != 0)   forKey:@"grid"];
    [ud setObject:[NSString stringWithUTF8String:c->prefix] forKey:@"prefix"];
    for (int i = 0; i < 5; i++) {
        NSString *pk = [NSString stringWithFormat:@"preset%d", i + 1];
        NSString *pv = [NSString stringWithFormat:@"%dx%d", c->pre_w[i], c->pre_h[i]];
        [ud setObject:pv forKey:pk];
    }
    [ud synchronize];
}

static BOOL writeCroppedScaledPNG(CGImageRef srcImg, CGRect cropPx,
                                  int targetW, int targetH, int resMult,
                                  NSURL *outURL, NSData **outPngData) {
    if (!srcImg || targetW <= 0 || targetH <= 0) return NO;
    size_t srcW = CGImageGetWidth(srcImg);
    size_t srcH = CGImageGetHeight(srcImg);
    CGRect bounds = CGRectMake(0, 0, (CGFloat)srcW, (CGFloat)srcH);
    CGRect clamped = CGRectIntersection(bounds, cropPx);
    if (CGRectIsEmpty(clamped) || clamped.size.width < 1.0 || clamped.size.height < 1.0) {
        return NO;
    }

    CGImageRef cropped = CGImageCreateWithImageInRect(srcImg, clamped);
    if (!cropped) return NO;

    CGImageRef finalImg = NULL;
    if (CGImageGetWidth(cropped) == (size_t)targetW && CGImageGetHeight(cropped) == (size_t)targetH) {
        finalImg = CGImageRetain(cropped);
    } else {
        CGColorSpaceRef srcCS = CGImageGetColorSpace(cropped);
        CGColorSpaceRef cs = NULL;
        if (srcCS && CGColorSpaceGetModel(srcCS) == kCGColorSpaceModelRGB) {
            cs = CGColorSpaceRetain(srcCS);
        } else {
            cs = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
        }
        CGContextRef ctx = CGBitmapContextCreate(NULL, (size_t)targetW, (size_t)targetH,
                                                 8, 0, cs, (CGBitmapInfo)kCGImageAlphaPremultipliedLast);
        CGColorSpaceRelease(cs);
        if (ctx) {
            CGContextSetInterpolationQuality(ctx, kCGInterpolationHigh);
            CGContextDrawImage(ctx, CGRectMake(0, 0, (CGFloat)targetW, (CGFloat)targetH), cropped);
            finalImg = CGBitmapContextCreateImage(ctx);
            CGContextRelease(ctx);
        }
    }
    CGImageRelease(cropped);
    if (!finalImg) return NO;

    NSMutableData *buf = [NSMutableData data];
    CGImageDestinationRef dst = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)buf,
                                                                 CFSTR("public.png"), 1, NULL);
    if (!dst) {
        CGImageRelease(finalImg);
        return NO;
    }
    NSDictionary *props = @{
        (__bridge NSString *)kCGImagePropertyDPIWidth:  @(72 * resMult),
        (__bridge NSString *)kCGImagePropertyDPIHeight: @(72 * resMult)
    };
    CGImageDestinationAddImage(dst, finalImg, (__bridge CFDictionaryRef)props);
    BOOL encoded = CGImageDestinationFinalize(dst);
    CFRelease(dst);
    CGImageRelease(finalImg);
    if (!encoded) return NO;

    BOOL written = [buf writeToURL:outURL atomically:YES];
    if (written && outPngData) *outPngData = buf;
    return written;
}

typedef enum { DRAG_NONE = 0, DRAG_MOVE, DRAG_RITE, DRAG_BOTM, DRAG_CORN } DragMode;
typedef enum { BTN_NONE = 0, BTN_SNAP, BTN_LOCK, BTN_RES, BTN_GRID, BTN_CLIP } BtnId;

@class WdvPxWindow;

@interface CrosshairView : NSView
@property (nonatomic, assign) WdvPxCfg *cfg;
@property (nonatomic, assign) BOOL cursorInside;
@property (nonatomic, assign) CGFloat curX;
@property (nonatomic, assign) CGFloat curY;
@end

@implementation CrosshairView
- (void)drawRect:(NSRect)dirtyRect {
    (void)dirtyRect;
    NSRect b = self.bounds;
    [[NSColor clearColor] set];
    NSRectFillUsingOperation(b, NSCompositingOperationClear);
    if (!self.cfg || !self.cfg->grid) return;

    CGFloat w = b.size.width;
    CGFloat h = b.size.height;

    if (!self.cursorInside) {
        CGFloat cx = floor(w * 0.5) + 0.5;
        CGFloat cy = floor(h * 0.5) + 0.5;
        [[NSColor colorWithCalibratedWhite:0.0 alpha:0.35] setStroke];
        [NSBezierPath setDefaultLineWidth:2.0];
        [NSBezierPath strokeLineFromPoint:NSMakePoint(cx - 8, cy) toPoint:NSMakePoint(cx + 8, cy)];
        [NSBezierPath strokeLineFromPoint:NSMakePoint(cx, cy - 8) toPoint:NSMakePoint(cx, cy + 8)];

        [[NSColor colorWithCalibratedRed:0.36 green:0.90 blue:0.70 alpha:0.65] setStroke];
        [NSBezierPath setDefaultLineWidth:1.0];
        [NSBezierPath strokeLineFromPoint:NSMakePoint(cx - 7, cy) toPoint:NSMakePoint(cx + 7, cy)];
        [NSBezierPath strokeLineFromPoint:NSMakePoint(cx, cy - 7) toPoint:NSMakePoint(cx, cy + 7)];
        return;
    }

    CGFloat x = floor(self.curX) + 0.5;
    CGFloat y = floor(h - self.curY) - 0.5;

    NSBezierPath *linePath = [NSBezierPath bezierPath];
    [linePath moveToPoint:NSMakePoint(x, 0)];
    [linePath lineToPoint:NSMakePoint(x, h)];
    [linePath moveToPoint:NSMakePoint(0, y)];
    [linePath lineToPoint:NSMakePoint(w, y)];

    CGFloat dash[2] = { 4.0, 3.0 };
    [linePath setLineDash:dash count:2 phase:0.0];

    [[NSColor colorWithCalibratedWhite:0.0 alpha:0.42] setStroke];
    [linePath setLineWidth:2.0];
    [linePath stroke];

    [[NSColor colorWithCalibratedRed:0.36 green:0.92 blue:0.72 alpha:0.86] setStroke];
    [linePath setLineWidth:1.0];
    [linePath stroke];

    int mult = self.cfg->res_mult;
    int pxX = (int)lround(self.curX) * mult;
    int pxY = (int)lround(self.curY) * mult;
    NSString *hud = [NSString stringWithFormat:@"%d, %d px", pxX, pxY];
    NSDictionary *attr = @{
        NSFontAttributeName: [NSFont monospacedDigitSystemFontOfSize:9.5 weight:NSFontWeightMedium],
        NSForegroundColorAttributeName: [NSColor colorWithCalibratedWhite:0.95 alpha:1.0]
    };
    NSSize sz = [hud sizeWithAttributes:attr];
    CGFloat pw = sz.width + 12.0;
    CGFloat ph = 18.0;
    CGFloat bx = (x + 10.0 + pw <= w - 4.0) ? (x + 10.0) : MAX(4.0, x - pw - 10.0);
    CGFloat by = (y - 10.0 - ph >= 4.0)     ? (y - 10.0 - ph) : MIN(h - ph - 4.0, y + 10.0);
    NSRect pill = NSMakeRect(bx, by, pw, ph);

    NSBezierPath *pp = [NSBezierPath bezierPathWithRoundedRect:pill xRadius:ph * 0.5 yRadius:ph * 0.5];
    [[NSColor colorWithCalibratedRed:0.08 green:0.10 blue:0.13 alpha:0.86] setFill];
    [pp fill];
    [[NSColor colorWithCalibratedRed:0.36 green:0.92 blue:0.72 alpha:0.55] setStroke];
    [pp setLineWidth:0.85];
    [pp stroke];

    [hud drawAtPoint:NSMakePoint(pill.origin.x + 6.0, pill.origin.y + (ph - sz.height) * 0.5)
      withAttributes:attr];
}
@end

@interface RulerView : NSView
@property (nonatomic, assign) WdvPxCfg *cfg;
@property (nonatomic, copy) NSString *flashMsg;
@property (nonatomic, weak) WdvPxWindow *hostWin;
@property (nonatomic, assign) BOOL cursorInHole;
@property (nonatomic, assign) CGFloat cursorHoleX;
@property (nonatomic, assign) CGFloat cursorHoleY;
@property (nonatomic, assign) BOOL shutterPulse;
@end

@interface WdvPxWindow : NSWindow
@property (nonatomic, assign) WdvPxCfg cfg;
@property (nonatomic, strong) RulerView *rulerView;
@property (nonatomic, strong) NSWindow *overlayWin;
@property (nonatomic, strong) CrosshairView *crossView;
@property (nonatomic, assign) NSInteger flashSeq;
@property (nonatomic, assign) BOOL capturing;
- (WdvPxCfg *)cfgPtr;
- (void)applyFrameFromCfg;
- (void)clampVisibleOnLaunch;
- (void)captureNow;
- (void)chooseSaveFolderWithCompletion:(void (^)(NSURL * _Nullable folderURL))done;
- (void)revealSaveFolderInFinder;
- (void)applyPresetIndex:(int)idx;
- (void)toggleLock;
- (void)toggleRes;
- (void)toggleGrid;
- (void)toggleClip;
- (void)updateCrosshairFromScreenPoint:(NSPoint)pt;
- (void)showFlash:(NSString *)msg seconds:(double)sec;
@end

@implementation RulerView {
    DragMode _dragMode;
    NSPoint  _dragMouse0;
    int      _dragHoleX0, _dragHoleY0, _dragHoleW0, _dragHoleH0;
    BtnId    _hoverBtn;
    BtnId    _pressBtn;
    NSTrackingArea *_trackArea;
}

- (BOOL)acceptsFirstMouse:(NSEvent *)event {
    (void)event;
    return YES;
}

- (void)updateTrackingAreas {
    [super updateTrackingAreas];
    if (_trackArea) [self removeTrackingArea:_trackArea];
    _trackArea = [[NSTrackingArea alloc]
        initWithRect:self.bounds
             options:(NSTrackingMouseMoved | NSTrackingMouseEnteredAndExited |
                      NSTrackingActiveAlways | NSTrackingInVisibleRect)
               owner:self
            userInfo:nil];
    [self addTrackingArea:_trackArea];
}

- (NSRect)btnRectFor:(BtnId)bid {
    CGFloat y = self.bounds.size.height - 23.0;
    CGFloat h = 19.0;
    switch (bid) {
        case BTN_SNAP: return NSMakeRect(8.0,   y, 46.0, h);
        case BTN_LOCK: return NSMakeRect(60.0,  y, 46.0, h);
        case BTN_RES:  return NSMakeRect(112.0, y, 32.0, h);
        case BTN_GRID: return NSMakeRect(150.0, y, 44.0, h);
        case BTN_CLIP: return NSMakeRect(200.0, y, 42.0, h);
        default:       return NSZeroRect;
    }
}

- (BtnId)hitTestBtn:(NSPoint)p {
    for (int i = BTN_SNAP; i <= BTN_CLIP; i++) {
        if (NSPointInRect(p, [self btnRectFor:(BtnId)i])) return (BtnId)i;
    }
    return BTN_NONE;
}

- (void)drawPillButton:(NSRect)r title:(NSString *)t
                topCol:(NSColor *)topCol botCol:(NSColor *)botCol
                rimCol:(NSColor *)rimCol hovered:(BOOL)hov pressed:(BOOL)prs {
    NSRect dr = prs ? NSOffsetRect(r, 0.0, -0.5) : r;
    CGFloat rad = dr.size.height * 0.5;
    NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect:dr xRadius:rad yRadius:rad];

    [NSGraphicsContext saveGraphicsState];
    NSShadow *sh = [[NSShadow alloc] init];
    sh.shadowOffset = NSMakeSize(0, -1.0);
    sh.shadowBlurRadius = prs ? 1.0 : 2.5;
    sh.shadowColor = [NSColor colorWithCalibratedWhite:0.0 alpha:(prs ? 0.30 : 0.48)];
    [sh set];
    [botCol setFill];
    [path fill];
    [NSGraphicsContext restoreGraphicsState];

    NSColor *cTop = topCol;
    NSColor *cBot = botCol;
    if (prs) {
        cTop = [topCol blendedColorWithFraction:0.18 ofColor:[NSColor blackColor]];
        cBot = [botCol blendedColorWithFraction:0.12 ofColor:[NSColor blackColor]];
    } else if (hov) {
        cTop = [topCol blendedColorWithFraction:0.14 ofColor:[NSColor whiteColor]];
        cBot = [botCol blendedColorWithFraction:0.10 ofColor:[NSColor whiteColor]];
    }
    NSGradient *grad = [[NSGradient alloc] initWithStartingColor:cTop endingColor:cBot];
    [grad drawInBezierPath:path angle:-90.0];

    [[NSColor colorWithCalibratedWhite:0.0 alpha:0.35] setStroke];
    [path setLineWidth:0.8];
    [path stroke];

    NSRect inR = NSInsetRect(dr, 0.85, 0.85);
    NSBezierPath *inPath = [NSBezierPath bezierPathWithRoundedRect:inR
                                                           xRadius:inR.size.height * 0.5
                                                           yRadius:inR.size.height * 0.5];
    [(hov ? [rimCol blendedColorWithFraction:0.25 ofColor:[NSColor whiteColor]] : rimCol) setStroke];
    [inPath setLineWidth:0.75];
    [inPath stroke];

    NSDictionary *attr = @{
        NSFontAttributeName: [NSFont systemFontOfSize:10.0 weight:NSFontWeightSemibold],
        NSForegroundColorAttributeName: [NSColor colorWithCalibratedWhite:(prs ? 0.86 : 0.96) alpha:1.0]
    };
    NSSize sz = [t sizeWithAttributes:attr];
    [t drawAtPoint:NSMakePoint(dr.origin.x + (dr.size.width - sz.width) * 0.5,
                               dr.origin.y + (dr.size.height - sz.height) * 0.5 + 0.5)
    withAttributes:attr];
}

- (void)drawRect:(NSRect)dirtyRect {
    (void)dirtyRect;
    NSRect b = self.bounds;
    [[NSColor clearColor] set];
    NSRectFillUsingOperation(b, NSCompositingOperationClear);
    if (!self.cfg) return;

    CGFloat hx = PAD_LEFT;
    CGFloat hyBot = PAD_BOTM;
    CGFloat hw = (CGFloat)self.cfg->hole_w;
    CGFloat hh = (CGFloat)self.cfg->hole_h;
    CGFloat hyTop = hyBot + hh;
    CGFloat frameW = hx + hw + PAD_RITE;
    CGFloat topBarW = b.size.width;

    NSRect topBar = NSMakeRect(0, hyTop, topBarW, PAD_TOP_);
    NSBezierPath *barPath = [NSBezierPath bezierPathWithRoundedRect:topBar xRadius:7.0 yRadius:7.0];
    [barPath appendBezierPathWithRect:NSMakeRect(0, hyTop, MIN(frameW, topBarW), 8.0)];
    NSGradient *barGrad = [[NSGradient alloc]
        initWithStartingColor:[NSColor colorWithCalibratedRed:0.14 green:0.16 blue:0.20 alpha:0.92]
                  endingColor:[NSColor colorWithCalibratedRed:0.08 green:0.09 blue:0.12 alpha:0.90]];
    [barGrad drawInBezierPath:barPath angle:-90.0];

    [[NSColor colorWithCalibratedWhite:1.0 alpha:0.07] setStroke];
    [NSBezierPath setDefaultLineWidth:1.0];
    [NSBezierPath strokeLineFromPoint:NSMakePoint(6.0, hyTop + 21.5)
                              toPoint:NSMakePoint(topBarW - 6.0, hyTop + 21.5)];

    [[NSColor colorWithCalibratedRed:0.08 green:0.09 blue:0.12 alpha:0.88] setFill];
    NSRectFill(NSMakeRect(0, 0, frameW, PAD_BOTM));
    NSRectFill(NSMakeRect(0, hyBot, PAD_LEFT, hh));
    NSRectFill(NSMakeRect(hx + hw, hyBot, PAD_RITE, hh));

    [[NSColor colorWithCalibratedWhite:1.0 alpha:0.12] setStroke];
    NSBezierPath *topRim = [NSBezierPath bezierPathWithRoundedRect:NSInsetRect(topBar, 0.5, 0.5)
                                                           xRadius:6.5 yRadius:6.5];
    [topRim setLineWidth:0.8];
    [topRim stroke];

    NSColor *accent = self.shutterPulse
        ? [NSColor colorWithCalibratedRed:0.95 green:1.00 blue:0.98 alpha:1.0]
        : (self.cfg->locked
            ? [NSColor colorWithCalibratedRed:0.94 green:0.68 blue:0.24 alpha:0.95]
            : [NSColor colorWithCalibratedRed:0.32 green:0.88 blue:0.64 alpha:0.92]);
    [accent setStroke];
    [NSBezierPath setDefaultLineWidth:(self.shutterPulse ? 2.0 : 1.0)];
    [NSBezierPath strokeRect:NSMakeRect(hx - 0.5, hyBot - 0.5, hw + 1.0, hh + 1.0)];

    if (!self.cfg->locked) {
        [[NSColor colorWithCalibratedWhite:0.78 alpha:0.65] setStroke];
        [NSBezierPath setDefaultLineWidth:1.0];
        [NSBezierPath strokeLineFromPoint:NSMakePoint(frameW - 9.5, 2.5)
                                  toPoint:NSMakePoint(frameW - 2.5, 9.5)];
        [NSBezierPath strokeLineFromPoint:NSMakePoint(frameW - 5.5, 2.5)
                                  toPoint:NSMakePoint(frameW - 2.5, 5.5)];
    }

    int mult = self.cfg->res_mult;
    NSDictionary *tickAttr = @{
        NSFontAttributeName: [NSFont monospacedDigitSystemFontOfSize:8.5 weight:NSFontWeightRegular],
        NSForegroundColorAttributeName: [NSColor colorWithCalibratedWhite:0.80 alpha:0.92]
    };
    [[NSColor colorWithCalibratedWhite:0.66 alpha:0.82] setStroke];
    [NSBezierPath setDefaultLineWidth:1.0];

    for (int d = 0; d <= (int)hw; d += 5) {
        CGFloat x = hx + d + 0.5;
        CGFloat len = (d % 50 == 0) ? 8.0
                    : ((mult == 2 && d % 25 == 0) ? 6.0
                    : ((d % 10 == 0) ? 4.5 : 2.5));
        [NSBezierPath strokeLineFromPoint:NSMakePoint(x, hyTop) toPoint:NSMakePoint(x, hyTop + len)];
        if (d % 50 == 0 && d < (int)hw - 14) {
            NSString *lbl = [NSString stringWithFormat:@"%d", d * mult];
            [lbl drawAtPoint:NSMakePoint(x + 2.5, hyTop + 7.5) withAttributes:tickAttr];
        }
    }
    for (int d = 0; d <= (int)hh; d += 5) {
        CGFloat y = hyTop - d - 0.5;
        CGFloat len = (d % 50 == 0) ? 8.0
                    : ((mult == 2 && d % 25 == 0) ? 6.0
                    : ((d % 10 == 0) ? 4.5 : 2.5));
        [NSBezierPath strokeLineFromPoint:NSMakePoint(hx, y) toPoint:NSMakePoint(hx - len, y)];
        if (d % 50 == 0 && d > 0 && d < (int)hh - 8) {
            NSString *lbl = [NSString stringWithFormat:@"%d", d * mult];
            NSSize sz = [lbl sizeWithAttributes:tickAttr];
            [lbl drawAtPoint:NSMakePoint(hx - len - sz.width - 2.5, y - sz.height * 0.5)
              withAttributes:tickAttr];
        }
    }

    if (self.cfg->grid && self.cursorInHole) {
        CGFloat mx = hx + floor(self.cursorHoleX) + 0.5;
        CGFloat my = hyTop - floor(self.cursorHoleY) - 0.5;
        [[NSColor colorWithCalibratedRed:0.36 green:0.92 blue:0.72 alpha:0.95] setFill];
        NSBezierPath *triTop = [NSBezierPath bezierPath];
        [triTop moveToPoint:NSMakePoint(mx, hyTop)];
        [triTop lineToPoint:NSMakePoint(mx - 3.5, hyTop + 5.5)];
        [triTop lineToPoint:NSMakePoint(mx + 3.5, hyTop + 5.5)];
        [triTop closePath];
        [triTop fill];

        NSBezierPath *triLeft = [NSBezierPath bezierPath];
        [triLeft moveToPoint:NSMakePoint(hx, my)];
        [triLeft lineToPoint:NSMakePoint(hx - 5.5, my + 3.5)];
        [triLeft lineToPoint:NSMakePoint(hx - 5.5, my - 3.5)];
        [triLeft closePath];
        [triLeft fill];
    }

    NSColor *smokeTop = [NSColor colorWithCalibratedRed:0.26 green:0.29 blue:0.34 alpha:0.92];
    NSColor *smokeBot = [NSColor colorWithCalibratedRed:0.17 green:0.19 blue:0.23 alpha:0.94];
    NSColor *smokeRim = [NSColor colorWithCalibratedWhite:1.0 alpha:0.18];

    [self drawPillButton:[self btnRectFor:BTN_SNAP] title:@"Shot"
                  topCol:[NSColor colorWithCalibratedRed:0.20 green:0.54 blue:0.84 alpha:0.95]
                  botCol:[NSColor colorWithCalibratedRed:0.13 green:0.38 blue:0.64 alpha:0.96]
                  rimCol:[NSColor colorWithCalibratedRed:0.62 green:0.86 blue:1.00 alpha:0.42]
                 hovered:(_hoverBtn == BTN_SNAP) pressed:(_pressBtn == BTN_SNAP)];

    [self drawPillButton:[self btnRectFor:BTN_LOCK]
                   title:(self.cfg->locked ? @"Lock" : @"Free")
                  topCol:(self.cfg->locked ? [NSColor colorWithCalibratedRed:0.78 green:0.52 blue:0.14 alpha:0.95] : smokeTop)
                  botCol:(self.cfg->locked ? [NSColor colorWithCalibratedRed:0.56 green:0.35 blue:0.08 alpha:0.96] : smokeBot)
                  rimCol:(self.cfg->locked ? [NSColor colorWithCalibratedRed:1.00 green:0.84 blue:0.48 alpha:0.42] : smokeRim)
                 hovered:(_hoverBtn == BTN_LOCK) pressed:(_pressBtn == BTN_LOCK)];

    [self drawPillButton:[self btnRectFor:BTN_RES]
                   title:(mult == 2 ? @"2X" : @"1X")
                  topCol:(mult == 2 ? [NSColor colorWithCalibratedRed:0.16 green:0.54 blue:0.58 alpha:0.95] : smokeTop)
                  botCol:(mult == 2 ? [NSColor colorWithCalibratedRed:0.10 green:0.38 blue:0.42 alpha:0.96] : smokeBot)
                  rimCol:(mult == 2 ? [NSColor colorWithCalibratedRed:0.55 green:0.92 blue:0.94 alpha:0.38] : smokeRim)
                 hovered:(_hoverBtn == BTN_RES) pressed:(_pressBtn == BTN_RES)];

    [self drawPillButton:[self btnRectFor:BTN_GRID] title:@"Grid"
                  topCol:(self.cfg->grid ? [NSColor colorWithCalibratedRed:0.20 green:0.56 blue:0.46 alpha:0.95] : smokeTop)
                  botCol:(self.cfg->grid ? [NSColor colorWithCalibratedRed:0.13 green:0.40 blue:0.32 alpha:0.96] : smokeBot)
                  rimCol:(self.cfg->grid ? [NSColor colorWithCalibratedRed:0.56 green:0.96 blue:0.80 alpha:0.38] : smokeRim)
                 hovered:(_hoverBtn == BTN_GRID) pressed:(_pressBtn == BTN_GRID)];

    [self drawPillButton:[self btnRectFor:BTN_CLIP] title:@"Clip"
                  topCol:(self.cfg->clip ? [NSColor colorWithCalibratedRed:0.22 green:0.58 blue:0.36 alpha:0.95] : smokeTop)
                  botCol:(self.cfg->clip ? [NSColor colorWithCalibratedRed:0.14 green:0.42 blue:0.24 alpha:0.96] : smokeBot)
                  rimCol:(self.cfg->clip ? [NSColor colorWithCalibratedRed:0.58 green:0.96 blue:0.70 alpha:0.38] : smokeRim)
                 hovered:(_hoverBtn == BTN_CLIP) pressed:(_pressBtn == BTN_CLIP)];

    CGFloat avail = topBarW - 252.0 - 10.0;
    NSString *info = self.flashMsg;
    if (!info) {
        if (avail >= 165.0) {
            info = [NSString stringWithFormat:@"(%d,%d) %dx%d px",
                    self.cfg->hole_x * mult, self.cfg->hole_y * mult,
                    self.cfg->hole_w * mult, self.cfg->hole_h * mult];
        } else {
            info = [NSString stringWithFormat:@"%dx%d px",
                    self.cfg->hole_w * mult, self.cfg->hole_h * mult];
        }
    }
    NSDictionary *infoAttr = @{
        NSFontAttributeName: [NSFont monospacedDigitSystemFontOfSize:10.0 weight:NSFontWeightMedium],
        NSForegroundColorAttributeName: self.flashMsg
            ? [NSColor colorWithCalibratedRed:0.44 green:0.95 blue:0.68 alpha:1.0]
            : [NSColor colorWithCalibratedWhite:0.86 alpha:0.94]
    };
    NSSize infoSz = [info sizeWithAttributes:infoAttr];
    CGFloat ix = MAX(250.0, topBarW - 10.0 - infoSz.width);
    [info drawAtPoint:NSMakePoint(ix, b.size.height - 20.5) withAttributes:infoAttr];
}

- (void)updateCursorForPoint:(NSPoint)p {
    if (!self.cfg) return;
    BtnId bid = [self hitTestBtn:p];
    if (bid != BTN_NONE) {
        [[NSCursor pointingHandCursor] set];
        return;
    }
    CGFloat frameW = PAD_LEFT + (CGFloat)self.cfg->hole_w + PAD_RITE;
    CGFloat hyTop  = PAD_BOTM + (CGFloat)self.cfg->hole_h;
    BOOL inFrameBody = (p.x <= frameW && p.y <= hyTop);
    BOOL onRite = inFrameBody && (p.x >= frameW - PAD_RITE - 4.0);
    BOOL onBotm = inFrameBody && (p.y <= PAD_BOTM + 4.0);

    if (!self.cfg->locked && onRite && onBotm) [[NSCursor crosshairCursor] set];
    else if (!self.cfg->locked && onRite)      [[NSCursor resizeLeftRightCursor] set];
    else if (!self.cfg->locked && onBotm)      [[NSCursor resizeUpDownCursor] set];
    else                                       [[NSCursor openHandCursor] set];
}

- (void)mouseMoved:(NSEvent *)event {
    NSPoint p = [self convertPoint:event.locationInWindow fromView:nil];
    BtnId newHover = [self hitTestBtn:p];
    if (newHover != _hoverBtn) {
        _hoverBtn = newHover;
        [self setNeedsDisplay:YES];
    }
    [self updateCursorForPoint:p];
}

- (void)mouseExited:(NSEvent *)event {
    (void)event;
    if (_hoverBtn != BTN_NONE) {
        _hoverBtn = BTN_NONE;
        [self setNeedsDisplay:YES];
    }
    [[NSCursor arrowCursor] set];
}

- (void)mouseDown:(NSEvent *)event {
    NSPoint p = [self convertPoint:event.locationInWindow fromView:nil];
    BtnId bid = [self hitTestBtn:p];
    if (bid != BTN_NONE) {
        _pressBtn = bid;
        [self setNeedsDisplay:YES];
        return;
    }

    _dragMouse0 = [NSEvent mouseLocation];
    _dragHoleX0 = self.cfg->hole_x;
    _dragHoleY0 = self.cfg->hole_y;
    _dragHoleW0 = self.cfg->hole_w;
    _dragHoleH0 = self.cfg->hole_h;

    CGFloat frameW = PAD_LEFT + (CGFloat)self.cfg->hole_w + PAD_RITE;
    CGFloat hyTop  = PAD_BOTM + (CGFloat)self.cfg->hole_h;
    BOOL inFrameBody = (p.x <= frameW && p.y <= hyTop);
    BOOL onRite = inFrameBody && (p.x >= frameW - PAD_RITE - 4.0);
    BOOL onBotm = inFrameBody && (p.y <= PAD_BOTM + 4.0);

    if (!self.cfg->locked && onRite && onBotm) _dragMode = DRAG_CORN;
    else if (!self.cfg->locked && onRite)      _dragMode = DRAG_RITE;
    else if (!self.cfg->locked && onBotm)      _dragMode = DRAG_BOTM;
    else {
        _dragMode = DRAG_MOVE;
        [[NSCursor closedHandCursor] set];
    }
}

- (void)mouseDragged:(NSEvent *)event {
    if (_pressBtn != BTN_NONE) {
        NSPoint p = [self convertPoint:event.locationInWindow fromView:nil];
        BtnId over = [self hitTestBtn:p];
        _hoverBtn = (over == _pressBtn) ? _pressBtn : BTN_NONE;
        [self setNeedsDisplay:YES];
        return;
    }
    if (_dragMode == DRAG_NONE) return;

    NSPoint cur = [NSEvent mouseLocation];
    int dx = (int)lround(cur.x - _dragMouse0.x);
    int dy = (int)lround(cur.y - _dragMouse0.y);

    if (_dragMode == DRAG_MOVE) {
        self.cfg->hole_x = _dragHoleX0 + dx;
        self.cfg->hole_y = _dragHoleY0 - dy;
    } else {
        if (_dragMode == DRAG_RITE || _dragMode == DRAG_CORN) {
            self.cfg->hole_w = clampHoleDim(_dragHoleW0 + dx);
        }
        if (_dragMode == DRAG_BOTM || _dragMode == DRAG_CORN) {
            self.cfg->hole_h = clampHoleDim(_dragHoleH0 - dy);
        }
    }
    [self.hostWin applyFrameFromCfg];
}

- (void)mouseUp:(NSEvent *)event {
    NSPoint p = [self convertPoint:event.locationInWindow fromView:nil];
    if (_pressBtn != BTN_NONE) {
        BtnId fired = ([self hitTestBtn:p] == _pressBtn) ? _pressBtn : BTN_NONE;
        _pressBtn = BTN_NONE;
        [self setNeedsDisplay:YES];
        switch (fired) {
            case BTN_SNAP: [self.hostWin captureNow]; break;
            case BTN_LOCK: [self.hostWin toggleLock]; break;
            case BTN_RES:  [self.hostWin toggleRes];  break;
            case BTN_GRID: [self.hostWin toggleGrid]; break;
            case BTN_CLIP: [self.hostWin toggleClip]; break;
            default: break;
        }
        return;
    }
    if (_dragMode != DRAG_NONE) {
        _dragMode = DRAG_NONE;
        cfgSave(self.cfg);
        [self updateCursorForPoint:p];
    }
}
@end

@implementation WdvPxWindow

- (BOOL)canBecomeKeyWindow  { return YES; }
- (BOOL)canBecomeMainWindow { return YES; }
- (WdvPxCfg *)cfgPtr        { return &_cfg; }

- (void)applyFrameFromCfg {
    CGFloat primH = primaryScreenHeight();
    CGFloat winW = MAX((CGFloat)_cfg.hole_w + PAD_LEFT + PAD_RITE, MIN_BAR_W);
    CGFloat winH = (CGFloat)_cfg.hole_h + PAD_TOP_ + PAD_BOTM;
    CGFloat winX = (CGFloat)_cfg.hole_x - PAD_LEFT;
    CGFloat winY = (primH - (CGFloat)_cfg.hole_y + PAD_TOP_) - winH;
    [self setFrame:NSMakeRect(winX, winY, winW, winH) display:YES];
    [self.rulerView setNeedsDisplay:YES];

    if (self.overlayWin) {
        NSRect holeRect = NSMakeRect(winX + PAD_LEFT, winY + PAD_BOTM,
                                     (CGFloat)_cfg.hole_w, (CGFloat)_cfg.hole_h);
        [self.overlayWin setFrame:holeRect display:YES];
        if (_cfg.grid && self.isVisible) {
            [self.overlayWin orderFront:nil];
            [self.crossView setNeedsDisplay:YES];
        } else {
            [self.overlayWin orderOut:nil];
        }
    }
}

- (void)clampVisibleOnLaunch {
    [self applyFrameFromCfg];
    NSRect barRect = NSMakeRect(self.frame.origin.x,
                                self.frame.origin.y + self.frame.size.height - PAD_TOP_,
                                self.frame.size.width, PAD_TOP_);
    BOOL onAnyScreen = NO;
    for (NSScreen *scr in [NSScreen screens]) {
        if (!NSIsEmptyRect(NSIntersectionRect(barRect, scr.visibleFrame))) {
            onAnyScreen = YES;
            break;
        }
    }
    if (!onAnyScreen) {
        _cfg.hole_x = 120;
        _cfg.hole_y = 120;
        cfgSave(&_cfg);
        [self applyFrameFromCfg];
    }
}

- (void)updateCrosshairFromScreenPoint:(NSPoint)pt {
    if (!_cfg.grid || !self.overlayWin || self.capturing) return;
    NSRect hr = self.overlayWin.frame;
    CGFloat lx = pt.x - hr.origin.x;
    CGFloat ly = (hr.origin.y + hr.size.height) - pt.y;
    BOOL inside = (lx >= 0.0 && lx <= hr.size.width && ly >= 0.0 && ly <= hr.size.height);

    if (inside || self.crossView.cursorInside) {
        self.crossView.cursorInside = inside;
        self.crossView.curX = lx;
        self.crossView.curY = ly;
        [self.crossView setNeedsDisplay:YES];

        self.rulerView.cursorInHole = inside;
        self.rulerView.cursorHoleX = lx;
        self.rulerView.cursorHoleY = ly;
        [self.rulerView setNeedsDisplay:YES];
    }
}

- (void)toggleLock {
    _cfg.locked = !_cfg.locked;
    cfgSave(&_cfg);
    [self.rulerView setNeedsDisplay:YES];
}

- (void)toggleRes {
    _cfg.res_mult = (_cfg.res_mult == 2) ? 1 : 2;
    cfgSave(&_cfg);
    [self.rulerView setNeedsDisplay:YES];
    [self.crossView setNeedsDisplay:YES];
}

- (void)toggleGrid {
    _cfg.grid = !_cfg.grid;
    cfgSave(&_cfg);
    if (!_cfg.grid) {
        self.crossView.cursorInside = NO;
        self.rulerView.cursorInHole = NO;
    }
    [self applyFrameFromCfg];
    if (_cfg.grid) [self updateCrosshairFromScreenPoint:[NSEvent mouseLocation]];
}

- (void)toggleClip {
    _cfg.clip = !_cfg.clip;
    cfgSave(&_cfg);
    [self.rulerView setNeedsDisplay:YES];
}

- (void)applyPresetIndex:(int)idx {
    if (idx < 0 || idx >= 5) return;
    _cfg.hole_w = _cfg.pre_w[idx];
    _cfg.hole_h = _cfg.pre_h[idx];
    [self applyFrameFromCfg];
    cfgSave(&_cfg);
    [self showFlash:[NSString stringWithFormat:@"P%d %dx%d px",
                     idx + 1, _cfg.hole_w * _cfg.res_mult,
                     _cfg.hole_h * _cfg.res_mult] seconds:1.2];
}

- (void)showFlash:(NSString *)msg seconds:(double)sec {
    NSInteger seq = ++self.flashSeq;
    self.rulerView.flashMsg = msg;
    [self.rulerView setNeedsDisplay:YES];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(sec * NSEC_PER_SEC)),
                   dispatch_get_main_queue(), ^{
        if (self.flashSeq == seq) {
            self.rulerView.flashMsg = nil;
            [self.rulerView setNeedsDisplay:YES];
        }
    });
}

- (void)pulseShutterBorder {
    self.rulerView.shutterPulse = YES;
    [self.rulerView setNeedsDisplay:YES];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 110 * NSEC_PER_MSEC),
                   dispatch_get_main_queue(), ^{
        self.rulerView.shutterPulse = NO;
        [self.rulerView setNeedsDisplay:YES];
    });
}

- (NSURL *)resolveSavedFolderURL:(BOOL *)needsSecurityScope {
    if (needsSecurityScope) *needsSecurityScope = NO;
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSData *bm = [ud dataForKey:@"outDirBookmark"];
    if (bm) {
        BOOL stale = NO;
        NSURLBookmarkResolutionOptions opts = isSandboxed()
            ? NSURLBookmarkResolutionWithSecurityScope
            : 0;
        NSURL *url = [NSURL URLByResolvingBookmarkData:bm options:opts
                                         relativeToURL:nil
                                   bookmarkDataIsStale:&stale error:nil];
        if (url) {
            if (needsSecurityScope) *needsSecurityScope = isSandboxed();
            if (stale) {
                BOOL started = isSandboxed() ? [url startAccessingSecurityScopedResource] : NO;
                NSData *fresh = [url bookmarkDataWithOptions:(isSandboxed() ? NSURLBookmarkCreationWithSecurityScope : 0)
                                  includingResourceValuesForKeys:nil relativeToURL:nil error:nil];
                if (fresh) [ud setObject:fresh forKey:@"outDirBookmark"];
                if (started) [url stopAccessingSecurityScopedResource];
            }
            return url;
        }
    }
    if (!isSandboxed()) {
        NSString *p = [ud stringForKey:@"outDirPath"];
        if (p.length > 0) return [NSURL fileURLWithPath:p isDirectory:YES];
        return realUserDesktopURL();
    }
    return nil;
}

- (void)chooseSaveFolderWithCompletion:(void (^)(NSURL * _Nullable folderURL))done {
    NSOpenPanel *panel = [NSOpenPanel openPanel];
    panel.title = @"Choose wdv-px Save Folder";
    panel.message = @"Select the folder where wdv-px saves PNG screenshots (remembered across sessions).";
    panel.prompt = @"Select Folder";
    panel.canChooseFiles = NO;
    panel.canChooseDirectories = YES;
    panel.canCreateDirectories = YES;
    panel.allowsMultipleSelection = NO;
    panel.directoryURL = realUserDesktopURL();
    panel.level = NSFloatingWindowLevel + 1;

    [NSApp activateIgnoringOtherApps:YES];
    NSModalResponse resp = [panel runModal];
    if (resp == NSModalResponseOK && panel.URL) {
        NSURL *url = panel.URL;
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        NSData *bm = [url bookmarkDataWithOptions:(isSandboxed() ? NSURLBookmarkCreationWithSecurityScope : 0)
                       includingResourceValuesForKeys:nil relativeToURL:nil error:nil];
        if (!bm) {
            bm = [url bookmarkDataWithOptions:0 includingResourceValuesForKeys:nil
                                relativeToURL:nil error:nil];
        }
        if (bm) [ud setObject:bm forKey:@"outDirBookmark"];
        [ud setObject:url.path forKey:@"outDirPath"];
        [ud synchronize];
        [self showFlash:[NSString stringWithFormat:@"Folder: %@", url.lastPathComponent] seconds:1.5];
        if (done) done(url);
    } else {
        if (done) done(nil);
    }
}

- (void)revealSaveFolderInFinder {
    BOOL scoped = NO;
    NSURL *folder = [self resolveSavedFolderURL:&scoped];
    if (!folder) {
        [self chooseSaveFolderWithCompletion:^(NSURL *chosen) {
            if (chosen) [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs:@[chosen]];
        }];
        return;
    }
    BOOL started = scoped ? [folder startAccessingSecurityScopedResource] : NO;
    [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs:@[folder]];
    if (started) [folder stopAccessingSecurityScopedResource];
}

- (void)performScreenCaptureToFolder:(NSURL *)folderURL securityScoped:(BOOL)scoped {
    if (@available(macOS 14.0, *)) {
        self.capturing = YES;
        cfgSave(&_cfg);

        int holeX = _cfg.hole_x;
        int holeY = _cfg.hole_y;
        int holeW = _cfg.hole_w;
        int holeH = _cfg.hole_h;
        int resMult = _cfg.res_mult;
        int targetW = holeW * resMult;
        int targetH = holeH * resMult;
        int wantClip = _cfg.clip;
        NSString *prefix = [NSString stringWithUTF8String:_cfg.prefix];
        CGWindowID ownWinID = (self.windowNumber > 0) ? (CGWindowID)self.windowNumber : kCGNullWindowID;
        CGWindowID ovWinID  = (self.overlayWin && self.overlayWin.windowNumber > 0)
                            ? (CGWindowID)self.overlayWin.windowNumber : kCGNullWindowID;

        [SCShareableContent getShareableContentExcludingDesktopWindows:NO
                                                   onScreenWindowsOnly:YES
                                                     completionHandler:^(SCShareableContent * _Nullable content,
                                                                         NSError * _Nullable err) {
            if (err || !content || content.displays.count == 0) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.capturing = NO;
                    [self showFlash:@"Grant Screen Recording (Help menu)" seconds:3.2];
                });
                return;
            }

            // Pick the display containing the capture center (or largest overlap)
            CGRect holeCG = CGRectMake(holeX, holeY, holeW, holeH);
            CGPoint center = CGPointMake(CGRectGetMidX(holeCG), CGRectGetMidY(holeCG));
            SCDisplay *targetDisp = nil;
            for (SCDisplay *d in content.displays) {
                if (CGRectContainsPoint(d.frame, center)) { targetDisp = d; break; }
            }
            if (!targetDisp) {
                CGFloat bestArea = -1.0;
                for (SCDisplay *d in content.displays) {
                    CGRect inter = CGRectIntersection(d.frame, holeCG);
                    CGFloat area = CGRectIsEmpty(inter) ? 0.0 : (inter.size.width * inter.size.height);
                    if (area > bestArea) { bestArea = area; targetDisp = d; }
                }
            }
            if (!targetDisp) targetDisp = content.displays.firstObject;

            CGFloat nativeScale = 2.0;
            for (NSScreen *scr in [NSScreen screens]) {
                NSNumber *num = scr.deviceDescription[@"NSScreenNumber"];
                if (num && (CGDirectDisplayID)num.unsignedIntValue == targetDisp.displayID) {
                    nativeScale = (scr.backingScaleFactor > 0.0) ? scr.backingScaleFactor : 2.0;
                    break;
                }
            }

            NSMutableArray<SCWindow *> *excluded = [NSMutableArray array];
            for (SCWindow *w in content.windows) {
                if ((ownWinID != kCGNullWindowID && w.windowID == ownWinID) ||
                    (ovWinID  != kCGNullWindowID && w.windowID == ovWinID)) {
                    [excluded addObject:w];
                }
            }

            SCContentFilter *filter = [[SCContentFilter alloc] initWithDisplay:targetDisp
                                                              excludingWindows:excluded];
            SCStreamConfiguration *scfg = [[SCStreamConfiguration alloc] init];
            scfg.width  = (size_t)lround(targetDisp.frame.size.width  * nativeScale);
            scfg.height = (size_t)lround(targetDisp.frame.size.height * nativeScale);
            scfg.showsCursor = NO;
            scfg.scalesToFit = NO;

            [SCScreenshotManager captureImageWithFilter:filter
                                          configuration:scfg
                                      completionHandler:^(CGImageRef _Nullable fullImg,
                                                          NSError * _Nullable capErr) {
                BOOL ok = NO;
                NSData *pngData = nil;
                NSString *errLabel = @"Capture failed";

                if (!capErr && fullImg) {
                    size_t imgW = CGImageGetWidth(fullImg);
                    size_t imgH = CGImageGetHeight(fullImg);
                    CGFloat sx = (targetDisp.frame.size.width  > 0) ? ((CGFloat)imgW / targetDisp.frame.size.width)  : nativeScale;
                    CGFloat sy = (targetDisp.frame.size.height > 0) ? ((CGFloat)imgH / targetDisp.frame.size.height) : nativeScale;

                    CGRect cropPx = CGRectMake(round((holeX - targetDisp.frame.origin.x) * sx),
                                               round((holeY - targetDisp.frame.origin.y) * sy),
                                               round(holeW * sx),
                                               round(holeH * sy));

                    NSDateFormatter *df = [[NSDateFormatter alloc] init];
                    df.dateFormat = @"yyyyMMdd_HHmmss_SSS";
                    NSString *fname = [NSString stringWithFormat:@"%@_%@.png",
                                       prefix, [df stringFromDate:[NSDate date]]];
                    NSURL *outURL = [folderURL URLByAppendingPathComponent:fname];

                    BOOL started = scoped ? [folderURL startAccessingSecurityScopedResource] : NO;
                    ok = writeCroppedScaledPNG(fullImg, cropPx, targetW, targetH, resMult, outURL, &pngData);
                    if (started) [folderURL stopAccessingSecurityScopedResource];
                    if (!ok) errLabel = @"Write failed (re-choose folder)";
                } else {
                    errLabel = @"Grant Screen Recording (Help menu)";
                }

                dispatch_async(dispatch_get_main_queue(), ^{
                    self.capturing = NO;
                    if (ok) {
                        if (wantClip && pngData) {
                            NSPasteboard *pb = [NSPasteboard generalPasteboard];
                            [pb clearContents];
                            [pb setData:pngData forType:NSPasteboardTypePNG];
                        }
                        [self pulseShutterBorder];
                        [self showFlash:[NSString stringWithFormat:@"Saved %dx%d px", targetW, targetH]
                                seconds:1.4];
                    } else {
                        [self showFlash:errLabel seconds:3.0];
                    }
                });
            }];
        }];
    } else {
        [self showFlash:@"Requires macOS 14.0+" seconds:3.0];
    }
}

- (void)captureNow {
    if (self.capturing) return;
    BOOL scoped = NO;
    NSURL *folder = [self resolveSavedFolderURL:&scoped];
    if (!folder) {
        [self chooseSaveFolderWithCompletion:^(NSURL *chosen) {
            if (chosen) {
                [self performScreenCaptureToFolder:chosen securityScoped:isSandboxed()];
            }
        }];
        return;
    }
    [self performScreenCaptureToFolder:folder securityScoped:scoped];
}

- (BOOL)performKeyEquivalent:(NSEvent *)event {
    if ((event.modifierFlags & NSEventModifierFlagCommand) &&
        [[event.charactersIgnoringModifiers lowercaseString] isEqualToString:@"q"]) {
        [NSApp terminate:nil];
        return YES;
    }
    return [super performKeyEquivalent:event];
}

- (void)keyDown:(NSEvent *)event {
    unsigned short kc = event.keyCode;
    NSEventModifierFlags mod = event.modifierFlags;
    int step = (mod & NSEventModifierFlagShift) ? 10 : 1;
    BOOL resize = (mod & NSEventModifierFlagOption) != 0;

    if (kc == 49 || kc == 36 || kc == 76) { [self captureNow]; return; }

    if (kc >= 123 && kc <= 126) {
        if (resize) {
            if (!_cfg.locked) {
                if (kc == 123) _cfg.hole_w = clampHoleDim(_cfg.hole_w - step);
                if (kc == 124) _cfg.hole_w = clampHoleDim(_cfg.hole_w + step);
                if (kc == 126) _cfg.hole_h = clampHoleDim(_cfg.hole_h - step);
                if (kc == 125) _cfg.hole_h = clampHoleDim(_cfg.hole_h + step);
            }
        } else {
            if (kc == 123) _cfg.hole_x -= step;
            if (kc == 124) _cfg.hole_x += step;
            if (kc == 126) _cfg.hole_y -= step;
            if (kc == 125) _cfg.hole_y += step;
        }
        [self applyFrameFromCfg];
        cfgSave(&_cfg);
        return;
    }

    NSString *ch = [event.charactersIgnoringModifiers lowercaseString];
    if ([ch isEqualToString:@"l"])      [self toggleLock];
    else if ([ch isEqualToString:@"x"]) [self toggleRes];
    else if ([ch isEqualToString:@"g"]) [self toggleGrid];
    else if ([ch isEqualToString:@"c"]) [self toggleClip];
    else if ([ch isEqualToString:@"q"] || kc == 53) [NSApp terminate:nil];
    else if (ch.length == 1) {
        unichar u = [ch characterAtIndex:0];
        if (u >= '1' && u <= '5') [self applyPresetIndex:(int)(u - '1')];
    }
}
@end

static OSStatus globalHotKeyHandler(EventHandlerCallRef nextHandler, EventRef theEvent, void *userData) {
    (void)nextHandler;
    (void)theEvent;
    WdvPxWindow *win = (__bridge WdvPxWindow *)userData;
    dispatch_async(dispatch_get_main_queue(), ^{
        [win captureNow];
    });
    return noErr;
}

@interface AppDelegate : NSObject <NSApplicationDelegate>
@property (nonatomic, strong) WdvPxWindow *win;
@property (nonatomic, strong) NSMutableArray<NSURL *> *pendingURLs;
@end

@implementation AppDelegate {
    EventHotKeyRef _hotKeyRef;
    id _globalMoveMon;
    id _localMoveMon;
}

- (void)buildMenuBar {
    NSMenu *mainMenu = [[NSMenu alloc] init];

    // 1. Application Menu
    NSMenuItem *appItem = [[NSMenuItem alloc] init];
    [mainMenu addItem:appItem];
    NSMenu *appMenu = [[NSMenu alloc] initWithTitle:@"wdv-px"];

    NSMenuItem *aboutItem = [[NSMenuItem alloc] initWithTitle:@"About wdv-px"
                                                       action:@selector(showAbout:)
                                                keyEquivalent:@""];
    aboutItem.target = self;
    [appMenu addItem:aboutItem];
    [appMenu addItem:[NSMenuItem separatorItem]];

    NSMenuItem *hideItem = [[NSMenuItem alloc] initWithTitle:@"Hide wdv-px"
                                                      action:@selector(hide:)
                                               keyEquivalent:@"h"];
    hideItem.target = NSApp;
    [appMenu addItem:hideItem];

    NSMenuItem *hideOthers = [[NSMenuItem alloc] initWithTitle:@"Hide Others"
                                                        action:@selector(hideOtherApplications:)
                                                 keyEquivalent:@"h"];
    hideOthers.keyEquivalentModifierMask = NSEventModifierFlagCommand | NSEventModifierFlagOption;
    hideOthers.target = NSApp;
    [appMenu addItem:hideOthers];

    NSMenuItem *showAll = [[NSMenuItem alloc] initWithTitle:@"Show All"
                                                     action:@selector(unhideAllApplications:)
                                              keyEquivalent:@""];
    showAll.target = NSApp;
    [appMenu addItem:showAll];
    [appMenu addItem:[NSMenuItem separatorItem]];

    NSMenuItem *quitItem = [[NSMenuItem alloc] initWithTitle:@"Quit wdv-px"
                                                      action:@selector(terminate:)
                                               keyEquivalent:@"q"];
    quitItem.target = NSApp;
    [appMenu addItem:quitItem];
    appItem.submenu = appMenu;

    // 2. File & Capture Menu
    NSMenuItem *fileItem = [[NSMenuItem alloc] init];
    [mainMenu addItem:fileItem];
    NSMenu *fileMenu = [[NSMenu alloc] initWithTitle:@"File"];

    NSMenuItem *shotItem = [[NSMenuItem alloc] initWithTitle:@"Capture Now (Shift+Cmd+6)"
                                                      action:@selector(menuShot:)
                                               keyEquivalent:@""];
    shotItem.target = self;
    [fileMenu addItem:shotItem];

    NSMenuItem *folderItem = [[NSMenuItem alloc] initWithTitle:@"Choose Save Folder..."
                                                        action:@selector(menuFolder:)
                                                 keyEquivalent:@"o"];
    folderItem.target = self;
    [fileMenu addItem:folderItem];

    NSMenuItem *revealItem = [[NSMenuItem alloc] initWithTitle:@"Reveal Save Folder in Finder"
                                                        action:@selector(menuReveal:)
                                                 keyEquivalent:@""];
    revealItem.target = self;
    [fileMenu addItem:revealItem];
    [fileMenu addItem:[NSMenuItem separatorItem]];

    NSMenuItem *lockItem = [[NSMenuItem alloc] initWithTitle:@"Toggle Lock (L)"
                                                      action:@selector(menuLock:)
                                               keyEquivalent:@""];
    lockItem.target = self;
    [fileMenu addItem:lockItem];

    NSMenuItem *resItem = [[NSMenuItem alloc] initWithTitle:@"Toggle 2X / 1X (X)"
                                                     action:@selector(menuRes:)
                                              keyEquivalent:@""];
    resItem.target = self;
    [fileMenu addItem:resItem];

    NSMenuItem *gridItem = [[NSMenuItem alloc] initWithTitle:@"Toggle Crosshair Grid (G)"
                                                      action:@selector(menuGrid:)
                                               keyEquivalent:@""];
    gridItem.target = self;
    [fileMenu addItem:gridItem];

    NSMenuItem *clipItem = [[NSMenuItem alloc] initWithTitle:@"Toggle Clipboard Copy (C)"
                                                      action:@selector(menuClip:)
                                               keyEquivalent:@""];
    clipItem.target = self;
    [fileMenu addItem:clipItem];
    fileItem.submenu = fileMenu;

    // 3. Presets Menu
    NSMenuItem *preItem = [[NSMenuItem alloc] init];
    [mainMenu addItem:preItem];
    NSMenu *preMenu = [[NSMenu alloc] initWithTitle:@"Presets"];
    NSArray<NSString *> *labels = @[
        @"Preset 1 (100x100 px @ 2X)",
        @"Preset 2 (512x512 px @ 2X)",
        @"Preset 3 (800x600 px @ 2X)",
        @"Preset 4 (1280x720 px @ 2X)",
        @"Preset 5 (1920x1080 px @ 2X)"
    ];
    for (int i = 0; i < 5; i++) {
        NSMenuItem *pi = [[NSMenuItem alloc] initWithTitle:labels[(NSUInteger)i]
                                                    action:@selector(menuPreset:)
                                             keyEquivalent:@""];
        pi.tag = i;
        pi.target = self;
        [preMenu addItem:pi];
    }
    preItem.submenu = preMenu;

    // 4. Help Menu
    NSMenuItem *helpItem = [[NSMenuItem alloc] init];
    [mainMenu addItem:helpItem];
    NSMenu *helpMenu = [[NSMenu alloc] initWithTitle:@"Help"];

    NSMenuItem *permItem = [[NSMenuItem alloc] initWithTitle:@"Screen Recording Permission..."
                                                      action:@selector(menuScreenPerm:)
                                               keyEquivalent:@""];
    permItem.target = self;
    [helpMenu addItem:permItem];

    NSMenuItem *webItem = [[NSMenuItem alloc] initWithTitle:@"wdv-px Website (wdv.com)"
                                                     action:@selector(menuWebsite:)
                                              keyEquivalent:@""];
    webItem.target = self;
    [helpMenu addItem:webItem];
    helpItem.submenu = helpMenu;

    NSApp.mainMenu = mainMenu;
}

- (void)menuShot:(id)sender   { (void)sender; [self.win captureNow]; }
- (void)menuFolder:(id)sender { (void)sender; [self.win chooseSaveFolderWithCompletion:nil]; }
- (void)menuReveal:(id)sender { (void)sender; [self.win revealSaveFolderInFinder]; }
- (void)menuLock:(id)sender   { (void)sender; [self.win toggleLock]; }
- (void)menuRes:(id)sender    { (void)sender; [self.win toggleRes];  }
- (void)menuGrid:(id)sender   { (void)sender; [self.win toggleGrid]; }
- (void)menuClip:(id)sender   { (void)sender; [self.win toggleClip]; }
- (void)menuPreset:(id)sender {
    NSMenuItem *mi = (NSMenuItem *)sender;
    [self.win applyPresetIndex:(int)mi.tag];
}
- (void)menuScreenPerm:(id)sender {
    (void)sender;
    NSURL *u = [NSURL URLWithString:@"x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture"];
    if (u) [[NSWorkspace sharedWorkspace] openURL:u];
}
- (void)menuWebsite:(id)sender {
    (void)sender;
    NSURL *u = [NSURL URLWithString:@"https://wdv.com/wdv-px/"];
    if (u) [[NSWorkspace sharedWorkspace] openURL:u];
}

- (void)showAbout:(id)sender {
    (void)sender;
    NSMutableParagraphStyle *ps = [[NSMutableParagraphStyle alloc] init];
    ps.alignment = NSTextAlignmentCenter;
    NSAttributedString *credits = [[NSAttributedString alloc]
        initWithString:@"L Van Warren 2026 + Neon High"
            attributes:@{
                NSFontAttributeName: [NSFont systemFontOfSize:12 weight:NSFontWeightMedium],
                NSForegroundColorAttributeName: [NSColor labelColor],
                NSParagraphStyleAttributeName: ps
            }];
    [NSApp activateIgnoringOtherApps:YES];
    [NSApp orderFrontStandardAboutPanelWithOptions:@{
        NSAboutPanelOptionApplicationName: @"wdv-px",
        NSAboutPanelOptionApplicationVersion: @"1.0.0",
        NSAboutPanelOptionVersion: @"1",
        NSAboutPanelOptionCredits: credits
    }];
    for (NSWindow *w in NSApp.windows) {
        if (w != self.win && w != self.win.overlayWin && w.isVisible) {
            w.level = NSFloatingWindowLevel + 1;
            [w center];
            [w makeKeyAndOrderFront:nil];
        }
    }
}

- (void)handleControlURL:(NSURL *)url {
    if (!self.win || !url) return;
    NSURLComponents *uc = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];
    NSString *cmd = [uc.host lowercaseString];
    if ([cmd isEqualToString:@"quit"]) {
        [NSApp terminate:nil];
        return;
    }
    if ([cmd isEqualToString:@"folder"]) {
        [self.win chooseSaveFolderWithCompletion:nil];
        return;
    }
    if ([cmd isEqualToString:@"snap"] || [cmd isEqualToString:@"shot"]) {
        [self.win captureNow];
        return;
    }
    if ([cmd isEqualToString:@"set"]) {
        WdvPxCfg *c = [self.win cfgPtr];
        int reqW = -1, reqH = -1, reqX = INT_MIN, reqY = INT_MIN;
        BOOL fireShot = NO;
        for (NSURLQueryItem *qi in uc.queryItems) {
            NSString *k = qi.name.lowercaseString;
            NSString *v = qi.value ?: @"";
            if ([k isEqualToString:@"res"])       c->res_mult = (v.intValue == 1) ? 1 : 2;
            else if ([k isEqualToString:@"lock"]) c->locked   = (v.intValue != 0) ? 1 : 0;
            else if ([k isEqualToString:@"grid"]) c->grid     = (v.intValue != 0) ? 1 : 0;
            else if ([k isEqualToString:@"clip"]) c->clip     = (v.intValue != 0) ? 1 : 0;
            else if ([k isEqualToString:@"w"])    reqW        = v.intValue;
            else if ([k isEqualToString:@"h"])    reqH        = v.intValue;
            else if ([k isEqualToString:@"x"])    reqX        = v.intValue;
            else if ([k isEqualToString:@"y"])    reqY        = v.intValue;
            else if ([k isEqualToString:@"shot"] || [k isEqualToString:@"snap"]) fireShot = (v.intValue != 0);
        }
        int mult = c->res_mult;
        if (reqW > 0)       c->hole_w = clampHoleDim((int)lround((double)reqW / mult));
        if (reqH > 0)       c->hole_h = clampHoleDim((int)lround((double)reqH / mult));
        if (reqX != INT_MIN) c->hole_x = (int)lround((double)reqX / mult);
        if (reqY != INT_MIN) c->hole_y = (int)lround((double)reqY / mult);
        cfgSave(c);
        [self.win applyFrameFromCfg];
        [self.win makeKeyAndOrderFront:nil];
        [NSApp activateIgnoringOtherApps:YES];
        if (fireShot) [self.win captureNow];
    }
}

- (void)application:(NSApplication *)application openURLs:(NSArray<NSURL *> *)urls {
    (void)application;
    if (!self.win) {
        if (!self.pendingURLs) self.pendingURLs = [NSMutableArray array];
        [self.pendingURLs addObjectsFromArray:urls];
        return;
    }
    for (NSURL *u in urls) [self handleControlURL:u];
}

- (void)applicationDidFinishLaunching:(NSNotification *)note {
    (void)note;
    [self buildMenuBar];

    WdvPxCfg cfg;
    cfgLoad(&cfg);

    self.win = [[WdvPxWindow alloc] initWithContentRect:NSMakeRect(0, 0, 400, 300)
                                              styleMask:NSWindowStyleMaskBorderless
                                                backing:NSBackingStoreBuffered
                                                  defer:NO];
    self.win.cfg = cfg;
    self.win.opaque = NO;
    self.win.backgroundColor = [NSColor clearColor];
    self.win.hasShadow = NO;
    self.win.level = NSFloatingWindowLevel;
    self.win.collectionBehavior = NSWindowCollectionBehaviorCanJoinAllSpaces |
                                  NSWindowCollectionBehaviorFullScreenAuxiliary;

    RulerView *rv = [[RulerView alloc] initWithFrame:self.win.contentView.bounds];
    rv.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
    rv.cfg = [self.win cfgPtr];
    rv.hostWin = self.win;
    self.win.rulerView = rv;
    self.win.contentView = rv;

    NSWindow *ov = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 100, 100)
                                               styleMask:NSWindowStyleMaskBorderless
                                                 backing:NSBackingStoreBuffered
                                                   defer:NO];
    ov.opaque = NO;
    ov.backgroundColor = [NSColor clearColor];
    ov.hasShadow = NO;
    ov.ignoresMouseEvents = YES;
    ov.level = NSFloatingWindowLevel;
    ov.collectionBehavior = NSWindowCollectionBehaviorCanJoinAllSpaces |
                            NSWindowCollectionBehaviorFullScreenAuxiliary;

    CrosshairView *cv = [[CrosshairView alloc] initWithFrame:ov.contentView.bounds];
    cv.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
    cv.cfg = [self.win cfgPtr];
    ov.contentView = cv;
    self.win.overlayWin = ov;
    self.win.crossView = cv;

    EventTypeSpec et = { kEventClassKeyboard, kEventHotKeyPressed };
    InstallApplicationEventHandler(&globalHotKeyHandler, 1, &et, (__bridge void *)self.win, NULL);
    EventHotKeyID hkID = { 0x57565058u, 1u }; // 'WVPX'
    RegisterEventHotKey(kVK_ANSI_6, cmdKey | shiftKey, hkID,
                        GetApplicationEventTarget(), 0, &_hotKeyRef);

    __weak WdvPxWindow *weakWin = self.win;
    NSEventMask moveMask = NSEventMaskMouseMoved | NSEventMaskLeftMouseDragged;
    _globalMoveMon = [NSEvent addGlobalMonitorForEventsMatchingMask:moveMask handler:^(NSEvent *e) {
        (void)e;
        [weakWin updateCrosshairFromScreenPoint:[NSEvent mouseLocation]];
    }];
    _localMoveMon = [NSEvent addLocalMonitorForEventsMatchingMask:moveMask handler:^NSEvent *(NSEvent *e) {
        [weakWin updateCrosshairFromScreenPoint:[NSEvent mouseLocation]];
        return e;
    }];

    [self.win clampVisibleOnLaunch];
    [self.win makeKeyAndOrderFront:nil];
    if (cfg.grid) [self.win.overlayWin orderFront:nil];
    [NSApp activateIgnoringOtherApps:YES];

    if (self.pendingURLs.count > 0) {
        NSArray<NSURL *> *queued = [self.pendingURLs copy];
        [self.pendingURLs removeAllObjects];
        for (NSURL *u in queued) [self handleControlURL:u];
    }
}

- (void)applicationWillTerminate:(NSNotification *)note {
    (void)note;
    if (_hotKeyRef) UnregisterEventHotKey(_hotKeyRef);
    if (_globalMoveMon) [NSEvent removeMonitor:_globalMoveMon];
    if (_localMoveMon)  [NSEvent removeMonitor:_localMoveMon];
    cfgSave([self.win cfgPtr]);
}
@end

int main(int argc, const char *argv[]) {
    (void)argc; (void)argv;
    @autoreleasepool {
        NSApplication *app = [NSApplication sharedApplication];
        [app setActivationPolicy:NSApplicationActivationPolicyRegular];
        AppDelegate *del = [[AppDelegate alloc] init];
        app.delegate = del;
        [app run];
    }
    return 0;
}
