import { css } from "@linaria/core";
import { defineComponent } from "vue";
import { string } from "vue-types";
import { useEditor } from "../../..";
import { Transfer } from "./Transfer";

export const View = defineComponent({
  props: {
    compId: string().isRequired,
  },
  emits: ["dblclick"],
  setup(props, { slots, emit }) {
    const { store, actions, helper } = useEditor();

    return () => {
      const comp = helper.findComp(props.compId);
      if (!comp) return store.isEditMode ? <div>无效组件</div> : null;

      const isSelected = store.currCompId === props.compId;
      return (
        <div
          class={[
            viewStyle,
            store.isEditMode && viewEditStyle,
            isSelected && viewSelectedStyle,
          ]}
          style={helper.createStyle(comp.layout)}
          onClick={(e) => {
            e.stopPropagation();
            if (!isSelected) {
              actions.pickComp(props.compId as string);
            }
          }}
          onDblclick={() => emit("dblclick")}
        >
          {slots.default?.()}
          {isSelected && <Transfer compId={props.compId} />}
        </div>
      );
    };
  },
});

const viewStyle = css`
  position: relative;
  font-size: 0;
  z-index: 1;

  > :first-child {
    width: 100%;
    height: 100%;
  }
`;

const viewEditStyle = css`
  &:hover {
    outline: 2px dashed @inf-primary-color;
  }
`;

const viewSelectedStyle = css`
  z-index: 2;
`;
