<?php

namespace MintyPHP\Module\Bookmarks\Providers;

use MintyPHP\App\AppContainer;
use MintyPHP\App\Module\Contracts\LayoutContextProvider;
use MintyPHP\Http\Request;
use MintyPHP\Module\Bookmarks\Support\BookmarkUrlNormalizer;

final class BookmarksLayoutProvider implements LayoutContextProvider
{
    public function provide(array $session, AppContainer $container): array
    {
        $grouped = is_array($session['module.bookmarks.grouped'] ?? null)
            ? $session['module.bookmarks.grouped']
            : ['groups' => [], 'ungrouped' => []];

        $requestUri = '/' . ltrim(Request::pathWithQuery(), '/');
        $localePath = (string) (parse_url(localeBase(), PHP_URL_PATH) ?? '/');
        $localePath = Request::stripBasePath($localePath);
        $localeBasePath = '/' . trim($localePath, '/');
        if ($localeBasePath !== '/') {
            $localeBasePath .= '/';
        }

        $currentPath = BookmarkUrlNormalizer::canonicalizeRequestUri($requestUri, $localeBasePath);

        return [
            'bookmarks.nav' => [
                'grouped' => $grouped,
                'current_path' => $currentPath,
            ],
        ];
    }
}
