CC      = gcc
CFLAGS  = -Wall -Wextra -std=c11 -O2
TARGET  = seabattle

# Source files — adjust if your src layout differs
SRCS    = $(wildcard src/*.c)
OBJS    = $(SRCS:.c=.o)

# ---------------------------------------------------------------------------
# raylib detection
# Try pkg-config first (works when libraylib-dev is installed via apt).
# If pkg-config doesn't know about raylib, fall back to a local build.
# ---------------------------------------------------------------------------
RAYLIB_FLAGS := $(shell pkg-config --cflags raylib 2>/dev/null)
RAYLIB_LIBS  := $(shell pkg-config --libs   raylib 2>/dev/null)

ifeq ($(RAYLIB_LIBS),)
    # pkg-config didn't find raylib → use local copy built from source
    RAYLIB_DIR   = libs/raylib
    RAYLIB_FLAGS = -I$(RAYLIB_DIR)/src
    RAYLIB_LIBS  = $(RAYLIB_DIR)/src/libraylib.a
    NEED_LOCAL_RAYLIB = 1
endif

# Linux system libraries required by raylib
SYS_LIBS = -lGL -lm -lpthread -ldl -lrt -lX11

CFLAGS  += $(RAYLIB_FLAGS)
LDFLAGS  = $(RAYLIB_LIBS) $(SYS_LIBS)

# ---------------------------------------------------------------------------
# Targets
# ---------------------------------------------------------------------------
.PHONY: all run clean raylib_local

all: $(TARGET)

$(TARGET): $(OBJS)
ifdef NEED_LOCAL_RAYLIB
	$(MAKE) raylib_local
endif
	$(CC) $(OBJS) -o $@ $(LDFLAGS)

src/%.o: src/%.c
	$(CC) $(CFLAGS) -c $< -o $@

run: all
	./$(TARGET)

# Build raylib from source into libs/raylib (used only when apt package absent)
raylib_local:
	@echo "raylib not found via pkg-config — building from source..."
	@if [ ! -d "$(RAYLIB_DIR)" ]; then \
	    mkdir -p libs && \
	    git clone --depth 1 https://github.com/raysan5/raylib.git $(RAYLIB_DIR); \
	fi
	$(MAKE) -C $(RAYLIB_DIR)/src PLATFORM=PLATFORM_DESKTOP

clean:
	rm -f $(OBJS) $(TARGET)
