<?php

declare(strict_types=1);

namespace App\Framework\LiveComponents\ValueObjects;

use App\Framework\StateManagement\SerializableState;

/**
 * Value Object representing the state of a LiveComponent
 *
 * Implements SerializableState for integration with StateManager infrastructure.
 * This enables ComponentState to be persisted via CacheBasedStateManager or other
 * StateManager implementations while maintaining type safety.
 */
final readonly class ComponentState implements SerializableState
{
    /**
     * @param array<string, mixed> $data The component's state data
     */
    public function __construct(
        public array $data = []
    ) {
    }

    /**
     * Create a new state with updated data
     */
    public function with(string $key, mixed $value): self
    {
        return new self([...$this->data, $key => $value]);
    }

    /**
     * Get a value from state
     */
    public function get(string $key, mixed $default = null): mixed
    {
        return $this->data[$key] ?? $default;
    }

    /**
     * Check if key exists in state
     */
    public function has(string $key): bool
    {
        return array_key_exists($key, $this->data);
    }

    /**
     * Merge with another state
     */
    public function merge(self $other): self
    {
        return new self([...$this->data, ...$other->data]);
    }

    /**
     * Create from array
     */
    public static function fromArray(array $data): self
    {
        return new self($data);
    }

    /**
     * Convert to array
     */
    public function toArray(): array
    {
        return $this->data;
    }

    /**
     * Create empty state
     */
    public static function empty(): self
    {
        return new self([]);
    }
}
