<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\PageBuilder\Builder;

use CpCreation\VitiCore\PageBuilder\Model\PageSection;

final readonly class BuilderUi
{
    public function __construct(
        private ?PageSection $section = null,
        private ?string $locale = null,
    ) {
    }

    public function class(string $key, string $default = ''): string
    {
        $override = $this->nodeOverride($key);
        $class = $this->stringOrNull($override['class'] ?? null);

        return $class ?? $default;
    }

    public function text(string $key, string $default = ''): string
    {
        $content = $this->localizedContentOverride($key);
        $text = $this->stringOrNull($content['text'] ?? null);
        if (null !== $text) {
            return $text;
        }

        $override = $this->nodeOverride($key);
        $text = $this->stringOrNull($override['text'] ?? null);

        return $text ?? $default;
    }

    public function attr(string $key, string $name, string $default = ''): string
    {
        $content = $this->localizedContentOverride($key);
        $value = $this->stringOrNull($content[$name] ?? ($content['attributes'][$name] ?? null));
        if (null !== $value) {
            return $value;
        }

        $override = $this->nodeOverride($key);
        $value = $this->stringOrNull($override[$name] ?? ($override['attributes'][$name] ?? null));

        return $value ?? $default;
    }

    /**
     * @return array<string, mixed>
     */
    private function nodeOverride(string $key): array
    {
        $overrides = $this->section?->getSetting('overrides', []);

        return \is_array($overrides) && \is_array($overrides[$key] ?? null) ? $overrides[$key] : [];
    }

    /**
     * @return array<string, mixed>
     */
    private function localizedContentOverride(string $key): array
    {
        if (null === $this->locale) {
            return [];
        }

        $byLocale = $this->section?->getSetting('contentOverridesByLocale', []);
        if (!\is_array($byLocale) || !\is_array($byLocale[$this->locale] ?? null)) {
            return [];
        }

        $content = $byLocale[$this->locale];

        return \is_array($content[$key] ?? null) ? $content[$key] : [];
    }

    private function stringOrNull(mixed $value): ?string
    {
        if (null === $value) {
            return null;
        }

        $value = trim((string) $value);

        return '' === $value ? null : $value;
    }
}
