// SPDX-License-Identifier: MIT
// A small finite-state machine. Each tick advances the light state.
module traffic_light_fsm (
    input wire clk,
    input wire rst,
    output reg red,
    output reg yellow,
    output reg green
);
    localparam S_RED    = 2'd0;
    localparam S_GREEN  = 2'd1;
    localparam S_YELLOW = 2'd2;

    reg [1:0] state;
    reg [3:0] timer;

    always @(posedge clk) begin
        if (rst) begin
            state <= S_RED;
            timer <= 4'd0;
        end else begin
            timer <= timer + 1'b1;

            case (state)
            S_RED:
                if (timer == 4'd4) begin
                    state <= S_GREEN;
                    timer <= 4'd0;
                end
            S_GREEN:
                if (timer == 4'd7) begin
                    state <= S_YELLOW;
                    timer <= 4'd0;
                end
            S_YELLOW:
                if (timer == 4'd2) begin
                    state <= S_RED;
                    timer <= 4'd0;
                end
            default: begin
                state <= S_RED;
                timer <= 4'd0;
            end
            endcase
        end
    end

    always @(*) begin
        red = 1'b0;
        yellow = 1'b0;
        green = 1'b0;

        case (state)
        S_RED: red = 1'b1;
        S_GREEN: green = 1'b1;
        S_YELLOW: yellow = 1'b1;
        default: red = 1'b1;
        endcase
    end
endmodule
