#include "input.h"
#include "game.h"
#include <stdlib.h>   // für rand(), srand()
#include <time.h>     // für time()
#include <string.h>   // für strlen()

#define EMPTY_CHAR 0
#define MAX_RAND_TRIES_PER_WORD 10

int createWordSalad(char salad[MAX_SEARCH_FIELD_LEN][MAX_SEARCH_FIELD_LEN], unsigned int searchFieldLen, const char words[][MAX_WORD_LEN], unsigned int wordCount)
{
    srand(time(NULL));
    int placedWords = 0;

    // Initialisiere das Feld mit 0 (leere Zeichen)
    for (unsigned int i = 0; i < searchFieldLen; i++) {
        for (unsigned int j = 0; j < searchFieldLen; j++) {
            salad[i][j] = EMPTY_CHAR;
        }
    }

    for (unsigned int w = 0; w < wordCount; w++) {
        const char* word = words[w];
        size_t len = strlen(word);
        int placed = 0;

        for (int tries = 0; tries < MAX_RAND_TRIES_PER_WORD && !placed; tries++) {
            int direction = rand() % 2; // 0 = horizontal, 1 = vertical
            int row = rand() % searchFieldLen;
            int col = rand() % searchFieldLen;

            if (direction == 0) { // horizontal
                if (col + len > searchFieldLen) continue;

                int fits = 1;
                for (size_t i = 0; i < len; i++) {
                    if (salad[row][col + i] != EMPTY_CHAR && salad[row][col + i] != word[i]) {
                        fits = 0;
                        break;
                    }
                }

                if (fits) {
                    for (size_t i = 0; i < len; i++) {
                        salad[row][col + i] = word[i];
                    }
                    placed = 1;
                }
            } else { // vertical
                if (row + len > searchFieldLen) continue;

                int fits = 1;
                for (size_t i = 0; i < len; i++) {
                    if (salad[row + i][col] != EMPTY_CHAR && salad[row + i][col] != word[i]) {
                        fits = 0;
                        break;
                    }
                }

                if (fits) {
                    for (size_t i = 0; i < len; i++) {
                        salad[row + i][col] = word[i];
                    }
                    placed = 1;
                }
            }
        }

        if (placed) {
            placedWords++;
        }
    }

    // Fülle leere Felder mit zufälligen Buchstaben
    for (unsigned int i = 0; i < searchFieldLen; i++) {
        for (unsigned int j = 0; j < searchFieldLen; j++) {
            if (salad[i][j] == EMPTY_CHAR) {
                salad[i][j] = 'A' + rand() % 26;
            }
        }
    }

    return placedWords;
}
