name: Frontend Tests

on:
  push:
    branches: [master, main]
  pull_request:
    branches: [master, main]

jobs:
  test:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        # Do NOT use submodules: recursive — the submodule pointers in this repo
        # are stale and predate package.json. We clone the libs fresh below.

      - name: Setup Node.js 22
        uses: actions/setup-node@v4
        with:
          node-version: '22'

      # Clone wokwi-libs fresh (stale submodule pointers can't be used)
      - name: Clone wokwi-libs
        run: |
          git clone --depth=1 https://github.com/wokwi/avr8js.git wokwi-libs/avr8js
          git clone --depth=1 https://github.com/wokwi/rp2040js.git wokwi-libs/rp2040js
          git clone --depth=1 https://github.com/wokwi/wokwi-elements.git wokwi-libs/wokwi-elements

      # Cache wokwi-libs node_modules to speed up repeated runs
      - name: Cache wokwi-libs node_modules
        uses: actions/cache@v4
        with:
          path: |
            wokwi-libs/avr8js/node_modules
            wokwi-libs/rp2040js/node_modules
            wokwi-libs/wokwi-elements/node_modules
          key: wokwi-libs-${{ hashFiles('wokwi-libs/avr8js/package-lock.json', 'wokwi-libs/rp2040js/package-lock.json', 'wokwi-libs/wokwi-elements/package-lock.json') }}

      # Cache frontend node_modules
      - name: Cache frontend node_modules
        uses: actions/cache@v4
        with:
          path: frontend/node_modules
          key: frontend-${{ hashFiles('frontend/package-lock.json') }}

      # Build avr8js (referenced as file: dep in frontend/package.json)
      - name: Build avr8js
        run: cd wokwi-libs/avr8js && npm install && npm run build

      # Build rp2040js (referenced via vite alias to dist/esm)
      - name: Build rp2040js
        run: cd wokwi-libs/rp2040js && npm install && npm run build

      # Build wokwi-elements (referenced as file: dep in frontend/package.json)
      - name: Build wokwi-elements
        run: cd wokwi-libs/wokwi-elements && npm install && npm run build

      # Install frontend deps (picks up file: references to avr8js and wokwi-elements)
      - name: Install frontend dependencies
        run: cd frontend && npm ci

      # Run all vitest tests
      - name: Run tests
        run: cd frontend && npm test
