`timescale 1ns/1ps
module tb_gs_lpddr_color_blend;
  logic clk=0,rst_n=0; always #5 clk=~clk;
  logic iv,ir; logic [31:0] ia,ic; logic [16:0] ialpha; logic [3:0] ibe;
  logic ov,or_; logic [31:0] oa,oc; logic idle;
  logic [31:0] araddr; logic [7:0] arlen; logic [2:0] arsize; logic [1:0] arburst; logic arvalid,arready;
  logic [255:0] rdata; logic [1:0] rresp; logic rlast,rvalid,rready;
  gs_lpddr_color_blend dut(.*,.in_valid(iv),.in_ready(ir),.in_addr(ia),.in_color(ic),.in_alpha(ialpha),.in_be(ibe),.out_valid(ov),.out_ready(or_),.out_addr(oa),.out_color(oc));
  initial begin
    iv=0; ia=0; ic=0; ialpha=0; ibe=4'hF; or_=1; arready=0; rdata=0; rresp=0; rlast=0; rvalid=0;
    repeat(2) @(posedge clk); rst_n=1;
    // A=0 B=2(0) C=2(FIX=0x80) D=1(Cd): result Cd-Cs, saturating.
    @(negedge clk); iv=1; ia=32'h14; ic=32'h80402010; ialpha={1'b1,2'd2,2'd0,2'd2,2'd1,8'h80};
    @(negedge clk); iv=0;
    wait(arvalid); @(negedge clk); arready=1; @(negedge clk); arready=0;
    wait(rready); rdata[191:160]=32'h40203020; rlast=1; rvalid=1; @(negedge clk); rvalid=0; rlast=0;
    wait(ov); if(oa!==32'h14 || oc!==32'h80001010) $fatal(1,"blend got addr=%h color=%h",oa,oc);
    repeat(2) @(posedge clk); if(!idle) $fatal(1,"stage did not return idle");

    // Authentic SH3 destination-darken equation (ALPHA=0x46):
    // (ZERO-Cd)*As/128 + Cd.  Black source RGB is intentional; only
    // source alpha supplies the coefficient.  Cd=0x80604020, As=0x50
    // gives floor(Cd*48/128) = 0x24180c in BGR byte order.
    @(negedge clk); iv=1; ia=32'h08; ic=32'h50000000; ibe=4'b0111;
    ialpha={1'b1,2'd2,2'd1,2'd0,2'd1,8'h80};
    @(negedge clk); iv=0;
    wait(arvalid); @(negedge clk); arready=1; @(negedge clk); arready=0;
    wait(rready); rdata[95:64]=32'h80604020; rlast=1; rvalid=1; @(negedge clk); rvalid=0; rlast=0;
    wait(ov); if(oa!==32'h08 || oc!==32'h8024180c) $fatal(1,"masked darken got addr=%h color=%h",oa,oc);
    repeat(2) @(posedge clk); if(!idle) $fatal(1,"darken stage did not return idle");
    $display("[tb_gs_lpddr_color_blend] PASS color=%08x",oc); $finish;
  end
  initial #1000 $fatal(1,"timeout");
endmodule
