<script setup>
import { Effect } from "effect";
import { computed } from "vue";
import { useI18n } from "vue-i18n";
import { cel as _rawCel } from "../../../../../utils/cel";
import { celBindings, injectCELContext } from "../../../../../utils/cel-context";
import { getLocalizedText } from "../../../../../share/locale";
import { Switch } from "../../../../ui/switch";
import { useFieldValue } from "../../../../form/utils/field-value";
defineOptions({ name: "ShwfedTableSwitchRendererRuntime" });
const props = defineProps({
  column: { type: null, required: true },
  ctx: { type: Object, required: true }
});
const { locale } = useI18n();
const inherited = injectCELContext();
const $cel = (expression, context) => _rawCel(expression, { ...celBindings(inherited), ...context });
function evalBool(expression, label) {
  if (!expression) return false;
  try {
    return Effect.runSync($cel(expression)) === true;
  } catch (e) {
    console.error(`[shwfed-table] switch ${label} failed`, e);
    return false;
  }
}
const isHidden = computed(() => evalBool(props.column.hidden, "hidden"));
const isDisabled = computed(() => evalBool(props.column.disabled, "disabled"));
const isReadonly = computed(() => evalBool(props.column.readonly, "readonly"));
const effectiveReadonly = computed(
  () => isReadonly.value || props.column.derived?.mode === "formula"
);
const trueText = computed(
  () => getLocalizedText(props.column.trueLabel, locale.value) || "\u662F"
);
const falseText = computed(
  () => getLocalizedText(props.column.falseLabel, locale.value) || "\u5426"
);
const { draft, commit } = useFieldValue({
  binding: () => props.column.binding,
  fromState: (raw) => raw === true,
  toState: (next) => next === true
});
function onUpdate(next) {
  draft.value = next;
  commit();
}
</script>

<template>
  <!--
    Row budget matches the editable text/number cells: 2px outer inset around
    an `h-7` (28px) row — 32px total. The switch is centered inside that row;
    `sm` size (h-3.5) keeps it visually compact against the surrounding cells.
    Every branch (hidden / readonly / editable) is sized identically so rows
    do not jump when a CEL condition flips.
  -->
  <div class="p-[0.125rem] w-full">
    <span
      v-if="isHidden"
      class="block h-7 w-full"
    />
    <span
      v-else-if="effectiveReadonly"
      class="flex items-center justify-center h-7 w-full px-2 text-[0.75rem] text-zinc-700 truncate"
    >
      {{ draft ? trueText : falseText }}
    </span>
    <span
      v-else
      class="flex items-center justify-center h-7 w-full"
    >
      <Switch
        size="sm"
        :model-value="draft"
        :disabled="isDisabled"
        @update:model-value="onUpdate"
      />
    </span>
  </div>
</template>
