#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#define MAX_QUESTS 16

typedef struct Node {
    char        name[16];
    struct Node *next;
    int          active;
    int          pad;
} Node;

Node  pool[MAX_QUESTS];
Node *head = NULL;

void setup(void) {
    setvbuf(stdin,  NULL, _IONBF, 0);
    setvbuf(stdout, NULL, _IONBF, 0);
    setvbuf(stderr, NULL, _IONBF, 0);
}

static void banner(void) {
    puts("");
    puts("  +----------------------------------------------------+");
    puts("  |         Steve's Quest Log  [No-Heap Edition]       |");
    puts("  |  [Grass][Stone][Iron][Gold][Diamond][Emerald][Air] |");
    puts("  |                                                    |");
    puts("  |             \"Heap? Never heard of it!              |");
    puts("  |             linked lists is out way.\" -- Steve     |");
    puts("  +----------------------------------------------------+");
    puts("");
}

static Node *alloc_node(void) {
    for (int i = 0; i < MAX_QUESTS; i++) {
        if (!pool[i].active) {
            pool[i].active = 1;
            return &pool[i];
        }
    }
    return NULL;
}

static void add_quest(void) {
    Node *n = alloc_node();
    if (!n) {
        puts("Quest log is full!");
        return;
    }
    printf("Quest name: ");
    read(0, n->name, 15);
    n->name[strcspn(n->name, "\n")] = 0;
    n->next = head;
    head = n;
    puts("Quest added to your log!");
}

static void show_quests(void) {
    Node *curr = head;
    int i = 0;
    puts("=== Active Quests ===");
    while (curr) {
        printf("[%d] %s\n", i++, curr->name);
        curr = curr->next;
    }
    puts("=====================");
}

static void edit_quest(void) {
    char buf[16];
    printf("Quest index: ");
    read(0, buf, 15);
    int idx = atoi(buf);

    Node *curr = head;
    for (int i = 0; i < idx; i++) {
        if (!curr) break;
        curr = curr->next;
    }

    if (!curr) {
        puts("Quest not found!");
        return;
    }

    printf("New name: ");
    read(0, curr->name, 32);
    puts("Quest updated!");
}

static void menu(void) {
    puts("1. Add Quest");
    puts("2. Show Quests");
    puts("3. Edit Quest");
    puts("4. Exit");
    printf("> ");
}

int main(void) {
    setup();
    banner();

    char buf[16];
    while (1) {
        menu();
        read(0, buf, 15);
        int choice = atoi(buf);
        switch (choice) {
            case 1: add_quest();   break;
            case 2: show_quests(); break;
            case 3: edit_quest();  break;
            case 4: exit(0);
            default: puts("Unknown command!");
        }
    }
    return 0;
}
