// Brass & Sigil -- first-join welcome grant
//
// Gives each new player exactly 1 Waystone + 1 Patchouli manual on
// first login. Gated by a per-player persistent flag so it fires once
// even if the player relogs.
//
// The manual is a Patchouli book ("patchouli:manual") shipped in the
// pack's root patchouli_books/ folder (the modpack-author path that
// Patchouli's docs recommend for non-mod books).
// Folder layout:
//   patchouli_books/manual/book.json
//   patchouli_books/manual/en_us/categories/<name>.json
//   patchouli_books/manual/en_us/entries/<name>.json
// Namespace defaults to "patchouli" in this mode -- the book id is
// "patchouli:manual".

const WELCOME_FLAG = 'bnsWelcomeGranted';

function giveManual(player) {
    // Patchouli's guide_book uses the "patchouli:book" data component
    // (1.21 component system) to identify which book to open. Plain
    // resource location string is the expected value type.
    const book = Item.of('patchouli:guide_book');
    book.set('patchouli:book', 'patchouli:manual');
    player.give(book);
}

function giveStarterWaystone(player) {
    player.give(Item.of('waystones:waystone'));
}

PlayerEvents.loggedIn(event => {
    const player = event.player;
    const data = player.persistentData;
    if (data.getBoolean(WELCOME_FLAG)) return;

    try {
        giveStarterWaystone(player);
        giveManual(player);
        data.putBoolean(WELCOME_FLAG, true);
        player.tell(Text.gold('Welcome to Brass & Sigil. Check your inventory for a Waystone and the server manual.'));
        console.info(`[bns/welcome] granted starter packet to ${player.username}`);
    } catch (e) {
        // If something goes wrong, don't set the flag -- player gets another chance.
        console.error(`[bns/welcome] failed for ${player.username}: ${e}`);
    }
});
