;; Layer effect - composite overlay over background at position
;; Streaming-compatible: frame is background, overlay is foreground
;; Usage: (layer background overlay :x 10 :y 20 :opacity 0.8)
;;
;; Params:
;;   overlay - frame to composite on top
;;   x, y - position to place overlay
;;   opacity - blend amount (0-1)
;;   mode - blend mode (alpha, multiply, screen, etc.)

(require-primitives "image" "blending" "core")

(define-effect layer
  :params (
    (overlay :type frame :default nil)
    (x :type int :default 0)
    (y :type int :default 0)
    (opacity :type float :default 1.0)
    (mode :type string :default "alpha")
  )
  (if (core:is-nil overlay)
    frame
    (let [bg (copy frame)
          fg overlay
          fg-w (image:width fg)
          fg-h (image:height fg)]
      (if (= opacity 1.0)
        ;; Simple paste
        (paste bg fg x y)
        ;; Blend with opacity
        (let [blended (if (= mode "alpha")
                        (blending:blend-images (image:crop bg x y fg-w fg-h) fg opacity)
                        (blending:blend-images (image:crop bg x y fg-w fg-h)
                                     (blending:blend-mode (image:crop bg x y fg-w fg-h) fg mode)
                                     opacity))]
          (paste bg blended x y))))))
