<?php

declare(strict_types=1);

namespace Atdt\Screens;

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

/**
 * Last callers (SPEC §10.6): the last 10 completed-or-current calls from
 * call_log, with their summaries. Also renders as a post-login step.
 */
final class LastCallersScreen implements Screen
{
    public function describe(): string
    {
        return 'Reading the last callers';
    }

    public function enter(Ctx $c): array
    {
        $o = $c->out()->cls()->txt(self::renderBody($c, 2));
        $o->at(21, 1)->txt($c->center($c->tstr('nua.press_any_key')));
        return [$c->ansi($o->str()), $c->hotkey()];
    }

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

    /** The table itself, reusable by the post-login sequence step. */
    public static function renderBody(Ctx $c, int $top): string
    {
        $rows = $c->db()->all(
            'SELECT * FROM call_log WHERE user_id IS NOT NULL ORDER BY id DESC LIMIT 10'
        );
        $o = Ansi::make();
        $o->at($top, 1)->txt($c->center($c->tstr('callers.title')));
        $o->at($top + 1, 1)->fg(8)->txt($c->center(str_repeat('─', 50)))->reset();
        $o->at($top + 3, 6)->txt($c->tstr('callers.columns'));
        $row = $top + 5;
        foreach ($rows as $log) {
            $on = $c->localStamp((string)$log['on_at'], 'm-d H:i');
            $off = $log['off_at'] === null ? '|10on now|07 ' : '|08' . $c->localStamp((string)$log['off_at'], 'H:i');
            $o->at($row++, 6)->txt($c->pipe(sprintf(
                '|15%-18s |03%2d  |07%s %s  |08%s',
                Pipe::escape(mb_strimwidth((string)$log['handle'], 0, 18)),
                (int)$log['node'],
                $on,
                $off,
                Pipe::escape(mb_strimwidth((string)($log['summary'] ?? ''), 0, 22))
            )));
        }
        if ($rows === []) {
            $o->at($top + 6, 1)->txt($c->center($c->tstr('callers.empty')));
        }
        return $o->reset()->str();
    }
}
