<script setup>
import { computed, provide } from "vue";
import { useNamespace } from "@yh-ui/hooks";
import { useComponentTheme } from "@yh-ui/theme";
defineOptions({ name: "YhGrid" });
const props = defineProps({
  cols: { type: [Number, String], required: false, default: 12 },
  colGap: { type: [Number, String], required: false, default: 0 },
  rowGap: { type: [Number, String], required: false, default: 0 },
  gap: { type: [Number, String, Array], required: false, default: 0 },
  collapsed: { type: Boolean, required: false, default: false },
  collapsedRows: { type: Number, required: false, default: 1 },
  justifyItems: { type: String, required: false },
  alignItems: { type: String, required: false },
  responsive: { type: String, required: false },
  themeOverrides: { type: null, required: false }
});
const ns = useNamespace("grid");
const { themeStyle } = useComponentTheme(
  "grid",
  computed(() => props.themeOverrides)
);
function resolveGap(val) {
  return typeof val === "number" ? `${val}px` : val;
}
const computedCols = computed(() => {
  const cols = props.cols;
  if (cols !== "" && cols !== null && cols !== void 0) {
    const num = Number(cols);
    if (!isNaN(num) && num > 0) return `repeat(${num}, minmax(0, 1fr))`;
  }
  return cols;
});
const gridStyle = computed(() => {
  const style = {
    ...themeStyle.value,
    display: "grid",
    gridTemplateColumns: computedCols.value
  };
  if (Array.isArray(props.gap)) {
    style.columnGap = resolveGap(props.gap[0]);
    style.rowGap = resolveGap(props.gap[1]);
  } else if (props.gap) {
    style.gap = resolveGap(props.gap);
  } else {
    if (props.colGap) style.columnGap = resolveGap(props.colGap);
    if (props.rowGap) style.rowGap = resolveGap(props.rowGap);
  }
  if (props.justifyItems) style.justifyItems = props.justifyItems;
  if (props.alignItems) style.alignItems = props.alignItems;
  return style;
});
provide(
  "yh-grid",
  computed(() => ({
    cols: typeof props.cols === "number" ? props.cols : 12,
    collapsed: props.collapsed,
    collapsedRows: props.collapsedRows
  }))
);
</script>

<template>
  <div :class="ns.b()" :style="gridStyle">
    <slot />
  </div>
</template>

<style>
@charset "UTF-8";
/**
 * YH-UI Sass Variables
 * 原具体的 CSS 变量输出规则 (:root, html.dark 等) 已移至 root.scss，以防止各组件样式编译时产生重复的全局变量 CSS 冗余。
 */
.yh-grid {
  display: grid;
  width: 100%;
  box-sizing: border-box;
  gap: var(--yh-grid-gap, 0);
  column-gap: var(--yh-grid-col-gap, var(--yh-grid-gap, 0));
  row-gap: var(--yh-grid-row-gap, var(--yh-grid-gap, 0));
}

.yh-grid-item {
  box-sizing: border-box;
  min-width: 0;
  padding: var(--yh-grid-item-padding, 0);
}
.yh-grid-item.is-suffix {
  justify-self: end;
}
</style>
