<?php

declare(strict_types=1);

namespace Atdt\Screens;

use Atdt\Ctx;
use Atdt\In;
use Atdt\Pipe;
use Atdt\Screen;

/**
 * Board stats (SPEC §10.6): total calls, calls today, total users, total
 * posts, top 5 posters, board founded date.
 */
final class StatsScreen implements Screen
{
    public function describe(): string
    {
        return 'Reading the board stats';
    }

    public function enter(Ctx $c): array
    {
        $db = $c->db();
        $vars = $c->mciVars(); // CA total calls, CT today, UT users
        $posts = (int)$db->val('SELECT COALESCE(SUM(posts), 0) FROM users');
        $top = $db->all("SELECT handle, posts FROM users WHERE posts > 0 AND status = 'active' ORDER BY posts DESC, handle LIMIT 5");

        $o = $c->out()->cls();
        $o->at(2, 1)->txt($c->center($c->tstr('stats.title')));
        $o->at(3, 1)->fg(8)->txt($c->center(str_repeat('─', 44)))->reset();
        $row = 6;
        foreach ([
            ['stats.row_founded', ['SV' => (string)($c->settings()->get('board_founded', '?') ?? '?')]],
            ['stats.row_calls', ['SV' => (string)$vars['CA']]],
            ['stats.row_today', ['SV' => (string)$vars['CT']]],
            ['stats.row_users', ['SV' => (string)$vars['UT']]],
            ['stats.row_posts', ['SV' => (string)$posts]],
        ] as [$key, $kv]) {
            $o->at($row++, 24)->txt($c->tstr($key, $kv));
        }
        $o->at(13, 8)->txt($c->tstr('stats.top_title'));
        $row = 15;
        $rank = 1;
        foreach ($top as $poster) {
            $o->at($row++, 6)->txt($c->pipe(sprintf(
                '|14%d. |15%-18s |07%d',
                $rank++,
                Pipe::escape(mb_strimwidth((string)$poster['handle'], 0, 18)),
                (int)$poster['posts']
            )));
        }
        if ($top === []) {
            $o->at(15, 6)->txt($c->pipe('|08Nobody has posted yet.'));
        }

        // Door champions (§13.4 award()): total points across every door.
        $scores = $db->all("SELECT k, v FROM door_kv WHERE door_slug = '_scores'");
        $byUser = [];
        foreach ($scores as $s) {
            $uid = (int)substr((string)$s['k'], (int)strpos((string)$s['k'], ':') + 1);
            $byUser[$uid] = ($byUser[$uid] ?? 0) + (int)$s['v'];
        }
        arsort($byUser);
        $o->at(13, 46)->txt($c->pipe('|03DOOR CHAMPIONS'));
        $row = 15;
        $rank = 1;
        foreach (array_slice($byUser, 0, 5, true) as $uid => $points) {
            $handle = (string)($db->val('SELECT handle FROM users WHERE id = ?', [$uid]) ?? 'caller');
            $o->at($row++, 44)->txt($c->pipe(sprintf(
                '|14%d. |15%-18s |11%d',
                $rank++,
                Pipe::escape(mb_strimwidth($handle, 0, 18)),
                $points
            )));
        }
        if ($byUser === []) {
            $o->at(15, 44)->txt($c->pipe('|08The doors await a champion.'));
        }
        $o->at(22, 1)->txt($c->center($c->tstr('nua.press_any_key')));
        return [$c->ansi($o->reset()->str()), $c->hotkey()];
    }

    public function input(Ctx $c, In $in): array
    {
        if ($in->kind !== 'key') {
            return [$c->bell()];
        }
        return $c->pop();
    }
}
