import { h, render } from 'https://unpkg.com/preact?module';

function players(range) {
    if (range[0] === range[1]) {
        if (range[0] === 1) {
            return "1 player";
        }
        return `${range[0]} players`;
    }
    return `${range[0]} to ${range[1]} players`;
}

function time(minutes) {
    const hours = Math.floor(minutes / 60);
    minutes -= hours * 60;
    const out = [];
    if (hours === 1) {
        out.push(`1 hour`);
    } else if (hours > 1){
        out.push(`${hours} hours`);
    }

    if (minutes === 1) {
        out.push(`1 minute`);
    } else if (minutes > 1){
        out.push(`${minutes} minutes`);
    }

    return out.join(" ");
}

function weight_to_percent(weight) {
    return Math.round(((weight - 1) / 4) * 100);
}

export function boardgame(game) {
    return h('div', { class: 'boardgame' }, [
        h('h2', { class: 'title' }, game.title),
        h('img', {src: `./cache/${game.id}.jpg`}),
        h('div', { class: 'weight stat' }, `${weight_to_percent(game.weight)}%`),
        h('div', { class: 'time stat' }, time(game.time)),
        h('div', { class: 'players stat' }, players(game.player_range)),
        h('div', { class: 'description' }, game.description.slice(0, 400) + "..."),
        h('div', { class: 'mechanics' }, game.mechanics.slice(0,3).join(" • "))
    ]);
}

function boardgames(games) {
    return h('div', { class: "boardgames" }, games.map(boardgame));
}

function nav_list() {
    return h('ul', null, [
        h('li', null, h('a', { href: "?all" }, "All")),
        h('li', null, h('a', { href: "?two-player" }, "Two Player")),
        h('li', null, h('a', { href: "?multi" }, "Multiplayer"))
    ]);
}

export function app(games, nav) {
    if (nav === null) {
        return nav_list();
    } else if (nav === "all") {
        return boardgames(games);
    } else if (nav === "two-player") {
        return boardgames(games.filter(g => g.player_range[0] === 2 && g.player_range[1] === 2));
    } else if (nav === "multi") {
        return boardgames(games.filter(g => g.player_range[0] !== 2 || g.player_range[1] !== 2));
    }
}
