<?php

declare(strict_types=1);

namespace CliqThemes\StoreLocator\Layouts;

defined('ABSPATH') || exit;


/**
 * The locator this plugin ships, assembled from the Settings screen.
 *
 * There is exactly one, because it is built from the site's settings rather than
 * stored as a row — so resolving it IS the lookup, and the id simply identifies
 * it. A negative id keeps it clear of any database-backed design.
 */
final class BundledLocatorLayouts implements LocatorLayoutSource
{
    private ?array $resolved = null;

    /** @return array<int, array{id: int, name: string}> */
    public function all(): array
    {
        $layout = $this->layout();

        return [[
            'id' => (int) $layout['id'],
            'name' => (string) $layout['name'],
        ]];
    }

    /** @return array<string, mixed>|null */
    public function find(int $id): ?array
    {
        $layout = $this->layout();

        return (int) $layout['id'] === $id ? $layout : null;
    }

    public function defaultId(): int
    {
        return BundledLocatorPreset::TEMPLATE_ID;
    }

    /** @return array<string, mixed>|null */
    public function detailModel(): ?array
    {
        $detail = $this->layout()['designs'][(string) BundledLocatorPreset::DETAIL_ID]['model'] ?? null;

        return is_array($detail) && isset($detail['rows']) ? $detail : null;
    }

    /**
     * Resolved once per request: a result page asks for the same layout many
     * times and rebuilding it from settings each time is wasted work.
     *
     * @return array<string, mixed>
     */
    private function layout(): array
    {
        return $this->resolved ??= (new BundledLocatorBuilder())->resolve();
    }
}
