<?php

namespace PHPNative\Tailwind\Style;

class Gap implements Style
{
    public int $x;
    public int $y;

    public function __construct(int $x = 0, int $y = 0)
    {
        $this->x = $x;
        $this->y = $y;
    }

    public static function parse(string $class): null|self
    {
        // gap-{n} - both x and y
        if (preg_match('/^gap-(\d+)$/', $class, $matches)) {
            $value = (int) $matches[1] * 4; // Tailwind uses 4px units
            return new self($value, $value);
        }

        // gap-x-{n}
        if (preg_match('/^gap-x-(\d+)$/', $class, $matches)) {
            $value = (int) $matches[1] * 4;
            return new self($value, 0);
        }

        // gap-y-{n}
        if (preg_match('/^gap-y-(\d+)$/', $class, $matches)) {
            $value = (int) $matches[1] * 4;
            return new self(0, $value);
        }

        return null;
    }

    public function merge(Style $other): Style
    {
        if (!($other instanceof self)) {
            return $this;
        }

        return new self(
            $other->x !== 0 ? $other->x : $this->x,
            $other->y !== 0 ? $other->y : $this->y,
        );
    }
}
