# Architecture Diagrams - HTML Chess Game

## System Architecture

### High-Level Component Overview

```mermaid
graph TB
    UI[User Interface Layer]
    GAME[Game Logic Layer]
    DATA[Data Layer]

    UI --> GAME
    GAME --> DATA

    subgraph "UI Layer"
        RENDERER[BoardRenderer]
        DRAGDROP[DragDropHandler]
        UICTRL[UIController]
    end

    subgraph "Game Layer"
        CHESS[ChessGame]
        VALIDATOR[MoveValidator]
        SPECIAL[SpecialMoves]
    end

    subgraph "Data Layer"
        BOARD[Board]
        STATE[GameState]
        PIECES[Pieces]
    end

    RENDERER --> CHESS
    DRAGDROP --> CHESS
    UICTRL --> CHESS

    CHESS --> BOARD
    CHESS --> STATE
    CHESS --> VALIDATOR

    VALIDATOR --> PIECES
    SPECIAL --> BOARD
```

---

## Detailed Component Diagram

```mermaid
classDiagram
    class ChessGame {
        +Board board
        +GameState gameState
        +string currentTurn
        +string status
        +makeMove(from, to)
        +newGame()
        +undo()
        +redo()
        +getLegalMoves(piece)
        +isInCheck(color)
        +resign()
    }

    class Board {
        +Piece[][] grid
        +getPiece(row, col)
        +setPiece(row, col, piece)
        +movePiece(from, to)
        +clone()
        +toFEN()
        +fromFEN(fen)
        +setupInitialPosition()
    }

    class GameState {
        +Move[] moveHistory
        +int currentMove
        +CapturedPieces captured
        +string status
        +Position enPassantTarget
        +int halfMoveClock
        +int fullMoveNumber
        +recordMove(move)
        +undo()
        +redo()
        +toFEN()
        +toPGN()
    }

    class Piece {
        <<abstract>>
        +string color
        +Position position
        +string type
        +bool hasMoved
        +getValidMoves(board)*
        +isValidMove(board, to)*
        +clone()
    }

    class Pawn {
        +getValidMoves(board)
    }

    class Knight {
        +getValidMoves(board)
    }

    class Bishop {
        +getValidMoves(board)
    }

    class Rook {
        +getValidMoves(board)
    }

    class Queen {
        +getValidMoves(board)
    }

    class King {
        +getValidMoves(board)
        +canCastle(board, side)
    }

    class MoveValidator {
        <<static>>
        +isMoveLegal(board, piece, to, state)
        +isKingInCheck(board, color)
        +isCheckmate(board, color)
        +isStalemate(board, color)
        +hasAnyLegalMove(board, color)
    }

    class SpecialMoves {
        <<static>>
        +canCastle(board, king, rook)
        +executeCastle(board, king, rook)
        +canEnPassant(board, pawn, target, state)
        +executeEnPassant(board, pawn, target)
        +canPromote(pawn)
        +promote(board, pawn, pieceType)
    }

    class BoardRenderer {
        +HTMLElement boardElement
        +renderBoard(board, state)
        +highlightMoves(moves)
        +clearHighlights()
        +selectSquare(row, col)
        +updateSquare(row, col, piece)
    }

    class DragDropHandler {
        +ChessGame game
        +BoardRenderer renderer
        +setupEventListeners()
        +onDragStart(event)
        +onDrop(event)
        +enable()
        +disable()
    }

    class UIController {
        +ChessGame game
        +BoardRenderer renderer
        +DragDropHandler dragDrop
        +init()
        +updateGameStatus(status)
        +showPromotionDialog(callback)
        +updateMoveHistory(moves)
    }

    ChessGame --> Board
    ChessGame --> GameState
    ChessGame --> MoveValidator

    Board --> Piece

    Piece <|-- Pawn
    Piece <|-- Knight
    Piece <|-- Bishop
    Piece <|-- Rook
    Piece <|-- Queen
    Piece <|-- King

    MoveValidator --> Piece
    SpecialMoves --> Board

    UIController --> ChessGame
    UIController --> BoardRenderer
    UIController --> DragDropHandler

    BoardRenderer --> Board
    DragDropHandler --> ChessGame
```

---

## Move Validation Flow

```mermaid
flowchart TD
    START([User Makes Move])
    GET_PIECE{Piece at source?}
    CHECK_TURN{Correct turn?}
    VALID_MOVE{Valid for piece?}
    SIMULATE[Simulate Move]
    CHECK_CHECK{Leaves king in check?}
    EXECUTE[Execute Move]
    UPDATE_STATE[Update Game State]
    SWITCH_TURN[Switch Turn]
    CHECK_STATUS[Check Game Status]
    END([Move Complete])
    ERROR([Return Error])

    START --> GET_PIECE
    GET_PIECE -->|No| ERROR
    GET_PIECE -->|Yes| CHECK_TURN
    CHECK_TURN -->|No| ERROR
    CHECK_TURN -->|Yes| VALID_MOVE
    VALID_MOVE -->|No| ERROR
    VALID_MOVE -->|Yes| SIMULATE
    SIMULATE --> CHECK_CHECK
    CHECK_CHECK -->|Yes| ERROR
    CHECK_CHECK -->|No| EXECUTE
    EXECUTE --> UPDATE_STATE
    UPDATE_STATE --> SWITCH_TURN
    SWITCH_TURN --> CHECK_STATUS
    CHECK_STATUS --> END

    style START fill:#90EE90
    style END fill:#90EE90
    style ERROR fill:#FFB6C1
    style EXECUTE fill:#87CEEB
```

---

## Check Detection Algorithm

```mermaid
flowchart TD
    START([Is King In Check?])
    FIND_KING[Find King Position]
    LOOP_START{For each square}
    GET_PIECE[Get Piece]
    IS_OPPONENT{Opponent piece?}
    GET_MOVES[Get Valid Moves]
    CAN_ATTACK{Can attack king?}
    RETURN_TRUE([Return TRUE])
    RETURN_FALSE([Return FALSE])
    NEXT[Next Square]

    START --> FIND_KING
    FIND_KING --> LOOP_START
    LOOP_START -->|Yes| GET_PIECE
    LOOP_START -->|No| RETURN_FALSE
    GET_PIECE --> IS_OPPONENT
    IS_OPPONENT -->|No| NEXT
    IS_OPPONENT -->|Yes| GET_MOVES
    GET_MOVES --> CAN_ATTACK
    CAN_ATTACK -->|Yes| RETURN_TRUE
    CAN_ATTACK -->|No| NEXT
    NEXT --> LOOP_START

    style RETURN_TRUE fill:#FFB6C1
    style RETURN_FALSE fill:#90EE90
```

---

## Castling Validation Flow

```mermaid
flowchart TD
    START([Can Castle?])
    MOVED{King or Rook moved?}
    CLEAR{Path clear?}
    IN_CHECK{King in check?}
    THROUGH_CHECK{Passes through check?}
    CAN_CASTLE([Can Castle])
    CANNOT([Cannot Castle])

    START --> MOVED
    MOVED -->|Yes| CANNOT
    MOVED -->|No| CLEAR
    CLEAR -->|No| CANNOT
    CLEAR -->|Yes| IN_CHECK
    IN_CHECK -->|Yes| CANNOT
    IN_CHECK -->|No| THROUGH_CHECK
    THROUGH_CHECK -->|Yes| CANNOT
    THROUGH_CHECK -->|No| CAN_CASTLE

    style CAN_CASTLE fill:#90EE90
    style CANNOT fill:#FFB6C1
```

---

## UI Event Flow

```mermaid
sequenceDiagram
    participant User
    participant DOM
    participant DragDrop
    participant ChessGame
    participant Board
    participant Renderer

    User->>DOM: Drag piece
    DOM->>DragDrop: dragstart event
    DragDrop->>ChessGame: getLegalMoves(piece)
    ChessGame->>Board: getPiece(row, col)
    Board-->>ChessGame: piece
    ChessGame-->>DragDrop: legal moves
    DragDrop->>Renderer: highlightMoves(moves)
    Renderer->>DOM: Add CSS classes

    User->>DOM: Drop piece
    DOM->>DragDrop: drop event
    DragDrop->>ChessGame: makeMove(from, to)
    ChessGame->>Board: movePiece(from, to)
    Board-->>ChessGame: result
    ChessGame->>Renderer: renderBoard(board)
    Renderer->>DOM: Update squares

    ChessGame->>DragDrop: move result
    DragDrop->>Renderer: clearHighlights()
```

---

## Data Flow Diagram

```mermaid
flowchart LR
    USER[User Input]
    UI[UI Layer]
    GAME[Game Logic]
    DATA[Data Layer]
    STORAGE[LocalStorage]

    USER -->|Click/Drag| UI
    UI -->|makeMove| GAME
    GAME -->|Update| DATA
    DATA -->|Notify| GAME
    GAME -->|Render| UI
    UI -->|Display| USER

    GAME <-->|Save/Load| STORAGE

    style USER fill:#87CEEB
    style UI fill:#90EE90
    style GAME fill:#FFD700
    style DATA fill:#FFA07A
    style STORAGE fill:#DDA0DD
```

---

## State Machine Diagram

```mermaid
stateDiagram-v2
    [*] --> Active: New Game

    Active --> Check: King Attacked
    Check --> Active: King Safe
    Check --> Checkmate: No Legal Moves

    Active --> Stalemate: No Legal Moves (Not in Check)
    Active --> Draw: Draw Condition Met
    Active --> Resigned: Player Resigns

    Checkmate --> [*]
    Stalemate --> [*]
    Draw --> [*]
    Resigned --> [*]

    Active --> Active: Valid Move
    Check --> Check: Valid Move
```

---

## Piece Inheritance Hierarchy

```mermaid
graph TD
    PIECE[Piece Abstract Class]
    PAWN[Pawn]
    KNIGHT[Knight]
    BISHOP[Bishop]
    ROOK[Rook]
    QUEEN[Queen]
    KING[King]

    PIECE --> PAWN
    PIECE --> KNIGHT
    PIECE --> BISHOP
    PIECE --> ROOK
    PIECE --> QUEEN
    PIECE --> KING

    style PIECE fill:#FFD700
    style PAWN fill:#90EE90
    style KNIGHT fill:#90EE90
    style BISHOP fill:#90EE90
    style ROOK fill:#90EE90
    style QUEEN fill:#90EE90
    style KING fill:#87CEEB
```

---

## Module Dependency Graph

```mermaid
graph TD
    MAIN[main.js]
    GAME[ChessGame]
    BOARD[Board]
    STATE[GameState]
    PIECES[Pieces/*]
    VALIDATOR[MoveValidator]
    SPECIAL[SpecialMoves]
    RENDERER[BoardRenderer]
    DRAGDROP[DragDropHandler]
    UICTRL[UIController]
    NOTATION[notation.js]
    STORAGE[storage.js]
    HELPERS[helpers.js]

    MAIN --> GAME
    MAIN --> UICTRL

    GAME --> BOARD
    GAME --> STATE
    GAME --> VALIDATOR

    BOARD --> PIECES

    VALIDATOR --> PIECES
    VALIDATOR --> SPECIAL

    SPECIAL --> BOARD

    UICTRL --> GAME
    UICTRL --> RENDERER
    UICTRL --> DRAGDROP

    RENDERER --> BOARD
    DRAGDROP --> GAME

    STATE --> NOTATION
    UICTRL --> STORAGE

    GAME --> HELPERS
    BOARD --> HELPERS

    style MAIN fill:#FFD700
    style GAME fill:#87CEEB
    style UICTRL fill:#90EE90
```

---

## FEN Parsing Flow

```mermaid
flowchart TD
    START([FEN String])
    SPLIT[Split by Space]
    POSITION[Parse Position]
    TURN[Parse Turn]
    CASTLE[Parse Castling Rights]
    ENPASSANT[Parse En Passant]
    CLOCKS[Parse Clocks]

    CLEAR_BOARD[Clear Board]
    PARSE_RANKS[Parse Ranks]
    PLACE_PIECES[Place Pieces]
    SET_STATE[Set Game State]

    END([Board Configured])

    START --> SPLIT
    SPLIT --> POSITION
    SPLIT --> TURN
    SPLIT --> CASTLE
    SPLIT --> ENPASSANT
    SPLIT --> CLOCKS

    POSITION --> CLEAR_BOARD
    CLEAR_BOARD --> PARSE_RANKS
    PARSE_RANKS --> PLACE_PIECES

    PLACE_PIECES --> SET_STATE
    TURN --> SET_STATE
    CASTLE --> SET_STATE
    ENPASSANT --> SET_STATE
    CLOCKS --> SET_STATE

    SET_STATE --> END

    style START fill:#90EE90
    style END fill:#90EE90
```

---

## Render Cycle

```mermaid
flowchart TD
    TRIGGER[Trigger Render]
    CLEAR[Clear Previous Highlights]
    LOOP[For Each Square]
    CREATE_SQUARE[Create Square Element]
    STYLE_SQUARE[Apply Light/Dark Style]
    GET_PIECE{Has Piece?}
    CREATE_PIECE[Create Piece Element]
    APPEND_PIECE[Append to Square]
    APPEND_SQUARE[Append to Board]
    DONE{All Squares?}
    ATTACH[Attach to DOM]
    END([Render Complete])

    TRIGGER --> CLEAR
    CLEAR --> LOOP
    LOOP --> CREATE_SQUARE
    CREATE_SQUARE --> STYLE_SQUARE
    STYLE_SQUARE --> GET_PIECE
    GET_PIECE -->|Yes| CREATE_PIECE
    CREATE_PIECE --> APPEND_PIECE
    APPEND_PIECE --> APPEND_SQUARE
    GET_PIECE -->|No| APPEND_SQUARE
    APPEND_SQUARE --> DONE
    DONE -->|No| LOOP
    DONE -->|Yes| ATTACH
    ATTACH --> END

    style END fill:#90EE90
```

---

## Performance Optimization Points

```mermaid
graph LR
    INPUT[User Input]
    CACHE1{Move Cache Valid?}
    CALC1[Calculate Moves]
    STORE1[Store in Cache]
    VALIDATE[Validate Move]

    RENDER[Render Board]
    CACHE2{DOM Unchanged?}
    UPDATE[Update DOM]
    BATCH[Batch Updates]
    FRAGMENT[Document Fragment]
    ATTACH[Single Attach]

    INPUT --> CACHE1
    CACHE1 -->|No| CALC1
    CALC1 --> STORE1
    STORE1 --> VALIDATE
    CACHE1 -->|Yes| VALIDATE

    VALIDATE --> RENDER
    RENDER --> CACHE2
    CACHE2 -->|No| UPDATE
    UPDATE --> BATCH
    BATCH --> FRAGMENT
    FRAGMENT --> ATTACH

    style CACHE1 fill:#FFD700
    style CACHE2 fill:#FFD700
    style FRAGMENT fill:#90EE90
```

---

## Error Handling Flow

```mermaid
flowchart TD
    ACTION[User Action]
    TRY[Try Execute]
    ERROR{Error?}
    TYPE{Error Type}

    INVALID_MOVE[Invalid Move]
    WRONG_TURN[Wrong Turn]
    NO_PIECE[No Piece]
    IN_CHECK[Leaves Check]

    LOG[Log Error]
    NOTIFY[Notify User]
    HIGHLIGHT[Highlight Issue]
    ROLLBACK[Rollback State]

    SUCCESS[Execute Success]
    UPDATE[Update UI]
    END([Complete])

    ACTION --> TRY
    TRY --> ERROR
    ERROR -->|Yes| TYPE
    ERROR -->|No| SUCCESS

    TYPE -->|Invalid| INVALID_MOVE
    TYPE -->|Turn| WRONG_TURN
    TYPE -->|Missing| NO_PIECE
    TYPE -->|Check| IN_CHECK

    INVALID_MOVE --> LOG
    WRONG_TURN --> LOG
    NO_PIECE --> LOG
    IN_CHECK --> LOG

    LOG --> NOTIFY
    NOTIFY --> HIGHLIGHT
    HIGHLIGHT --> ROLLBACK
    ROLLBACK --> END

    SUCCESS --> UPDATE
    UPDATE --> END

    style ERROR fill:#FFB6C1
    style SUCCESS fill:#90EE90
```

---

## Testing Strategy Diagram

```mermaid
graph TB
    CODE[Application Code]

    UNIT[Unit Tests]
    INTEGRATION[Integration Tests]
    E2E[Manual Testing]

    PIECES[Piece Movement]
    VALIDATION[Move Validation]
    SPECIAL[Special Moves]

    SCENARIOS[Game Scenarios]
    STATE[State Management]

    BROWSER[Browser Testing]
    PERF[Performance]
    ACCESS[Accessibility]

    CODE --> UNIT
    CODE --> INTEGRATION
    CODE --> E2E

    UNIT --> PIECES
    UNIT --> VALIDATION
    UNIT --> SPECIAL

    INTEGRATION --> SCENARIOS
    INTEGRATION --> STATE

    E2E --> BROWSER
    E2E --> PERF
    E2E --> ACCESS

    style CODE fill:#FFD700
    style UNIT fill:#90EE90
    style INTEGRATION fill:#87CEEB
    style E2E fill:#FFA07A
```

---

## Deployment Pipeline

```mermaid
flowchart LR
    DEV[Development]
    TEST[Run Tests]
    LINT[Lint Code]
    BUILD[Build]
    OPTIMIZE[Optimize]
    DEPLOY[Deploy]
    VERIFY[Verify]

    DEV --> TEST
    TEST --> LINT
    LINT --> BUILD
    BUILD --> OPTIMIZE
    OPTIMIZE --> DEPLOY
    DEPLOY --> VERIFY

    style DEV fill:#87CEEB
    style TEST fill:#FFD700
    style DEPLOY fill:#90EE90
    style VERIFY fill:#90EE90
```

---

These diagrams provide visual representations of:

1. **System Architecture** - Overall structure
2. **Component Relationships** - Class diagram
3. **Move Validation** - Flow logic
4. **Check Detection** - Algorithm flow
5. **Castling** - Special move validation
6. **UI Events** - Sequence diagram
7. **Data Flow** - Information movement
8. **State Machine** - Game states
9. **Inheritance** - Piece hierarchy
10. **Dependencies** - Module imports
11. **FEN Parsing** - Data import
12. **Rendering** - UI update cycle
13. **Performance** - Optimization points
14. **Error Handling** - Error flow
15. **Testing** - Test strategy
16. **Deployment** - Release pipeline

Use these diagrams as reference during implementation to understand component relationships and data flow.
