{#- Advanced Clock Domain Crossing Module Template -#}
{{ header | safe }}

`default_nettype none

{# Ensure required context variables are defined with fallbacks #}
{% if not device_config is defined %}
{% set device_config = {} %}
{% endif %}

{% if not board_config is defined %}
{% set board_config = {} %}
{% endif %}

module advanced_clock_crossing #(
    parameter DATA_WIDTH = 32,
    parameter SYNC_STAGES = 3
) (
    input wire src_clk,
    input wire dst_clk,
    input wire reset_n,
    input wire [DATA_WIDTH-1:0] src_data,
    input wire src_valid,
    output logic src_ready,
    output logic [DATA_WIDTH-1:0] dst_data,
    output logic dst_valid,
    input wire dst_ready
);

    // Implementation of advanced clock domain crossing with variance compensation
    logic [SYNC_STAGES-1:0] sync_reg;
    logic [DATA_WIDTH-1:0] data_reg;
    logic valid_reg;

    // Source domain logic
    always_ff @(posedge src_clk or negedge reset_n) begin
        if (!reset_n) begin
            data_reg <= '0;
            valid_reg <= 1'b0;
        end else if (src_valid && src_ready) begin
            data_reg <= src_data;
            valid_reg <= 1'b1;
        end else if (sync_reg[SYNC_STAGES-1]) begin
            valid_reg <= 1'b0;
        end
    end

    // Destination domain synchronizer
    always_ff @(posedge dst_clk or negedge reset_n) begin
        if (!reset_n) begin
            sync_reg <= '0;
        end else begin
            sync_reg <= {sync_reg[SYNC_STAGES-2:0], valid_reg};
        end
    end

    assign src_ready = !valid_reg || sync_reg[SYNC_STAGES-1];
    assign dst_data = data_reg;
    assign dst_valid = sync_reg[SYNC_STAGES-1] && dst_ready;

endmodule

`default_nettype wire