module round_robin_arbiter (
    input  wire       clk,
    input  wire       rst,
    input  wire [7:0] req,
    input  wire       grant_ready,
    output reg        grant_valid,
    output reg [2:0]  grant_idx
);
    reg [2:0] rr_start;
    reg       found;
    reg [2:0] candidate;
    integer   offset;

    always @(*) begin
        grant_valid = 1'b0;
        grant_idx = 3'd0;
        found = 1'b0;
        candidate = 3'd0;

        if (!rst) begin
            for (offset = 0; offset < 8; offset = offset + 1) begin
                candidate = rr_start + offset;
                if (!found && req[candidate]) begin
                    grant_valid = 1'b1;
                    grant_idx = candidate;
                    found = 1'b1;
                end
            end
        end
    end

    always @(posedge clk) begin
        if (rst) begin
            rr_start <= 3'd0;
        end else if (grant_valid && grant_ready) begin
            rr_start <= grant_idx + 3'd1;
        end
    end
endmodule
