import { customElement, noShadowDOM } from "solid-element";
import {createEffect, onCleanup} from "solid-js";
import { resolvePath } from "./utils/path";

export interface BgProps {
  fit?: 'cover' | 'contain' | 'fill' | 'none' | 'scale-down';
}

customElement("md-bg", { fit: "cover" }, (props, { element }) => {
  noShadowDOM();

  // 从 element 的 textContent 获取图片路径
  const rawSrc = element?.textContent?.trim() || '';

  // 隐藏原始文本内容
  if (element) {
    element.textContent = "";
  }

  // 从父节点 article 的 data-src 获取当前 markdown 文件完整路径
  const articleEl = element?.closest('article') as HTMLElement;
  const articlePath = articleEl?.getAttribute('data-src') || '';

  // 解析相对路径
  const resolvedSrc = resolvePath(articlePath, rawSrc);

  createEffect(() => {
    if(!articleEl) return;
    articleEl.dataset.mdbg = resolvedSrc;
    articleEl.style.backgroundImage = `url(${resolvedSrc})`;
    articleEl.style.backgroundSize = props.fit || 'cover';
    articleEl.style.backgroundPosition = 'center';
    articleEl.style.backgroundRepeat = 'no-repeat';
  });
  
  onCleanup(() => {
      if(articleEl?.dataset?.mdbg !== resolvedSrc)
          return;
      articleEl.style.backgroundImage = '';
  });

  return null;
});
