import {createMemo, For} from 'solid-js';
import { marked } from '../../markdown';
import { getLayerStyle } from './hooks/dimensions';
import type { CardData } from './types';
import {DeckStore} from "./hooks/deckStore";
import {processVariables} from "../utils/csv-loader";

export interface CardLayerProps {
  cardData: CardData;
  store: DeckStore;
}

export function CardLayer(props: CardLayerProps) {
  const layers = createMemo(() => props.store.state.layerConfigs.filter((l) => l.visible));
  const dimensions = () => props.store.state.dimensions!;
  const showBounds = () => props.store.state.isEditing;
  
  function renderLayerContent(content: string) {
    return marked.parse(processVariables(content, props.cardData, props.store.state.cards)) as string;
  }
  return (
    <For each={layers()}>
      {(layer) => {
        return (
          <>
            <article
              class="absolute flex items-center justify-center text-center prose prose-sm"
              style={{
                ...getLayerStyle(layer, dimensions()),
                'font-size': `${layer.fontSize || 3}mm`
              }}
              innerHTML={renderLayerContent(props.cardData[layer.prop])}
            />
            {showBounds() && (
              <div
                class="absolute border-2 border-blue-500/50 pointer-events-none select-none"
                style={{
                  left: `${(layer.x1 - 1) * dimensions().cellWidth}mm`,
                  top: `${(layer.y1 - 1) * dimensions().cellHeight}mm`,
                  width: `${(layer.x2 - layer.x1 + 1) * dimensions().cellWidth}mm`,
                  height: `${(layer.y2 - layer.y1 + 1) * dimensions().cellHeight}mm`
                }}
              />
            )}
          </>
        );
      }}
    </For>
  );
}
