<?php
declare(strict_types=1);

namespace PpPhp\Core\Designer\Layout;

final class DesignerGridColumn
{
    public function __construct(
        private readonly string $columnId,
        private readonly int $span = 12,
        private readonly int $offset = 0,
        private readonly array $components = [],
        private readonly array $responsive = [],
        private readonly array $style = []
    ) {}

    public static function create(string $columnId, int $span = 12, int $offset = 0, array $components = []): self
    {
        $span = self::clampSpan($span);
        return new self($columnId, $span, max(0, min(11, $offset)), $components, [
            'xs' => 12, 'sm' => 12, 'md' => $span, 'lg' => $span, 'xl' => $span,
        ]);
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['columnId'] ?? $data['id'] ?? 'col'),
            self::clampSpan((int) ($data['span'] ?? 12)),
            max(0, min(11, (int) ($data['offset'] ?? 0))),
            (array) ($data['components'] ?? []),
            (array) ($data['responsive'] ?? []),
            (array) ($data['style'] ?? [])
        );
    }

    public function columnId(): string { return $this->columnId; }
    public function span(): int { return $this->span; }
    public function components(): array { return $this->components; }

    public function resized(int $span): self
    {
        $span = self::clampSpan($span);
        return new self($this->columnId, $span, $this->offset, $this->components, array_replace($this->responsive, [
            'md' => $span, 'lg' => $span, 'xl' => $span,
        ]), $this->style);
    }

    public function withComponents(array $components): self
    {
        return new self($this->columnId, $this->span, $this->offset, $components, $this->responsive, $this->style);
    }

    public function toArray(): array
    {
        return [
            'columnId' => $this->columnId,
            'id' => $this->columnId,
            'span' => $this->span,
            'offset' => $this->offset,
            'components' => $this->components,
            'responsive' => $this->responsive,
            'style' => $this->style,
        ];
    }

    private static function clampSpan(int $span): int
    {
        return max(1, min(12, $span));
    }
}
