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

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

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

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

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

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

  // 加载图片
  const loadImage = (src: string): Promise<HTMLImageElement> => {
    return new Promise((resolve, reject) => {
      const img = new Image();
      img.onload = () => resolve(img);
      img.onerror = reject;
      img.src = src;
    });
  };

  const [image] = createResource(resolvedSrc, loadImage);

  createEffect(() => {
    // 图片加载完成后，将背景图片设置到 article 元素
      console.log(resolvedSrc, image(), articleEl);
    if (image() && articleEl) {
      articleEl.style.backgroundImage = `url(${resolvedSrc})`;
      articleEl.style.backgroundSize = 'cover';
      articleEl.style.backgroundPosition = 'center';
      articleEl.style.backgroundRepeat = 'no-repeat';
    }
  });

  return null;
});
