<?php

declare(strict_types=1);

final class Toast
{
    public static function success(string $message): void
    {
        $_SESSION['toast'] = ['type' => 'success', 'message' => $message];
    }

    public static function error(string $message): void
    {
        $_SESSION['toast'] = ['type' => 'error', 'message' => $message];
    }

    public static function consume(): ?array
    {
        if (!isset($_SESSION['toast'])) {
            return null;
        }

        $toast = $_SESSION['toast'];
        unset($_SESSION['toast']);

        return is_array($toast) ? $toast : null;
    }

    public static function render(): string
    {
        $toast = self::consume();
        if (!$toast) {
            return '';
        }

        $type = (string)($toast['type'] ?? 'success');
        $message = (string)($toast['message'] ?? '');

        $classes = $type === 'error'
            ? 'border-red-200 bg-red-50 text-red-700'
            : 'border-green-200 bg-green-50 text-green-800';

        ob_start();
        ?>
        <div class="rounded-lg border px-3 py-2 text-sm <?= e($classes) ?>">
            <?= e($message) ?>
        </div>
        <?php
        return (string)ob_get_clean();
    }
}
