<?php

namespace Sitecake\Content;

/**
 * Minimal Collection — replaces Cake\Collection\Collection for ElementList.
 *
 * Provides: filter(), first(), last(), toArray(), count(), Iterator support.
 */
class Collection implements \Iterator, \Countable
{
    protected array $items;
    protected int $position = 0;

    public function __construct(array $items = [])
    {
        $this->items    = array_values($items);
        $this->position = 0;
    }

    // ── Iterator ────────────────────────────────────────────────────────────

    public function current(): mixed
    {
        return $this->items[$this->position];
    }

    public function key(): int
    {
        return $this->position;
    }

    public function next(): void
    {
        $this->position++;
    }

    public function rewind(): void
    {
        $this->position = 0;
    }

    public function valid(): bool
    {
        return isset($this->items[$this->position]);
    }

    /**
     * Returns an ArrayIterator (Countable) — used by ElementList::count().
     */
    public function getInnerIterator(): \ArrayIterator
    {
        return new \ArrayIterator($this->items);
    }

    // ── Functional helpers ───────────────────────────────────────────────────

    /**
     * Filter elements. Callback receives ($value, $key).
     *
     * @param callable $callback
     * @return static
     */
    public function filter(callable $callback): static
    {
        $filtered = [];
        foreach ($this->items as $key => $item) {
            if ($callback($item, $key)) {
                $filtered[] = $item;
            }
        }
        return new static($filtered);
    }

    /** Returns first element, or null when empty. */
    public function first(): mixed
    {
        return $this->items[0] ?? null;
    }

    /** Returns last element, or null when empty. */
    public function last(): mixed
    {
        if (empty($this->items)) {
            return null;
        }
        return $this->items[count($this->items) - 1];
    }

    /** Returns all elements as a plain array. */
    public function toArray(): array
    {
        return $this->items;
    }

    // ── Countable ────────────────────────────────────────────────────────────

    public function count(): int
    {
        return count($this->items);
    }
}
