import { watch } from "vue";
import { string } from "vue-types";
import { useCompData, useCreateChild } from ".";
import { useEditor } from "../../../../..";
import { Image, Text } from "../../../basicUI";
import { createUIComp } from "../../../defines/createUIComp";

export const Component = createUIComp({
  props: {
    compId: string().isRequired,
  },
  setup(props) {
    const { helper } = useEditor();
    const { value, children } = useCompData(props.compId);
    const createList = useCreateChild("list");

    watch(
      () => [value.total],
      () => {
        const { total } = value;
        const offset = total - children.list.length;
        if (offset > 0) {
          children.list.push(...createList(offset));
        } else {
          children.list.splice(total, offset * -1);
        }
      }
    );

    return () => (
      <div
        class="grid px-10px pt-15px"
        style={{
          gridTemplateColumns: `repeat(${value.columns}, 1fr)`,
          gridGap: helper.designToNaturalSize(value.gap),
        }}
      >
        {children.list.map((d, i) => (
          <div key={i}>
            <Image.Component
              class="overflow-hidden"
              style={{ height: helper.designToNaturalSize(value.imgHeight) }}
              compId={d.img}
            />
            {value.showDesc && <Text.Component compId={d.desc} />}
          </div>
        ))}
      </div>
    );
  },
});
