package fr.bglands.client.protocol;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/** Pure layout helpers shared by the renderer and unit tests. */
public final class UiLayout {
    private UiLayout() {
    }

    public static List<UiSceneWidget> orderedWidgets(UiScene scene) {
        var indexed = new ArrayList<IndexedWidget>(scene.widgets().size());
        for (int index = 0; index < scene.widgets().size(); index++) {
            indexed.add(new IndexedWidget(index, scene.widgets().get(index)));
        }
        indexed.sort(Comparator.comparingInt((IndexedWidget value) -> value.widget().z())
                .thenComparingInt(IndexedWidget::index));
        return indexed.stream().map(IndexedWidget::widget).toList();
    }

    public static int pageCount(int itemCount, int pageSize) {
        if (itemCount < 0 || pageSize < 1) {
            throw new IllegalArgumentException("Invalid pagination bounds");
        }
        return Math.max(1, (itemCount + pageSize - 1) / pageSize);
    }

    public static int clampPage(int page, int itemCount, int pageSize) {
        return Math.max(0, Math.min(page, pageCount(itemCount, pageSize) - 1));
    }

    public static int pageStart(int page, int itemCount, int pageSize) {
        return clampPage(page, itemCount, pageSize) * pageSize;
    }

    public static int pageEnd(int page, int itemCount, int pageSize) {
        return Math.min(itemCount, pageStart(page, itemCount, pageSize) + pageSize);
    }

    private record IndexedWidget(int index, UiSceneWidget widget) {
    }
}
