<script setup>
import { computed } from "vue";
import { Icon } from "@iconify/vue";
import { Effect } from "effect";
import { cel as $cel } from "../../../../../utils/cel";
import { useI18n } from "vue-i18n";
import { getLocalizedText } from "../../../../../share/locale";
import { Button } from "../../../../ui/button";
import { Markdown } from "../../../../ui/markdown";
import { JUSTIFY_CLASS, interpolateMarkdown } from "../../../utils/runtime";
import { celBindings, injectCELContext } from "../../../../../utils/cel-context";
defineOptions({ name: "ShwfedTableMarkdownRendererRuntime" });
const props = defineProps({
  column: { type: null, required: true },
  ctx: { type: Object, required: true }
});
const { locale } = useI18n();
const celContext = injectCELContext();
const rendered = computed(() => {
  const source = getLocalizedText(props.column.markdown, locale.value) ?? "";
  if (!source) return "";
  return interpolateMarkdown(source, $cel, celBindings(celContext));
});
const isEmpty = computed(() => rendered.value.trim().length === 0);
const align = computed(() => isEmpty.value ? "center" : props.column.align ?? "left");
const justifyClass = computed(() => JUSTIFY_CLASS[align.value] ?? JUSTIFY_CLASS.left);
const copyText = computed(() => {
  const { copyExpression } = props.column;
  if (!copyExpression) return void 0;
  try {
    const value = Effect.runSync($cel(copyExpression, celBindings(celContext)));
    return value === void 0 || value === null ? void 0 : String(value);
  } catch (e) {
    console.error("[shwfed-table] markdown copy expression failed", e);
    return void 0;
  }
});
const showCopy = computed(() => copyText.value !== void 0 && !isEmpty.value);
const onCopy = async () => {
  const text = copyText.value;
  if (text === void 0) return;
  try {
    await navigator.clipboard.writeText(text);
  } catch (e) {
    console.error("[shwfed-table] markdown copy failed", e);
  }
};
</script>

<template>
  <div
    :class="[
  'relative w-full py-2 px-1 flex items-center text-xs group',
  justifyClass,
  isEmpty ? 'text-zinc-300 select-none' : 'text-zinc-600'
]"
  >
    <template v-if="isEmpty">
      -
    </template>
    <Markdown
      v-else
      :source="rendered"
      block
      class="prose prose-zinc text-xs"
    />
    <Button
      v-if="showCopy"
      aria-label="Copy"
      class="p-1 w-6 h-6 flex items-center justify-center right-1 top-1/2 -translate-y-1/2 transform-3d group-hover:opacity-100 opacity-0 absolute transition-opacity duration-180"
      size="xs"
      @click="onCopy"
    >
      <Icon icon="fluent:copy-20-regular" />
    </Button>
  </div>
</template>
