<script setup>
import { computed } from "vue";
import { Effect } from "effect";
import { Icon } from "@iconify/vue";
import { cel as $cel } from "../../../../../utils/cel";
import { celBindings, injectCELContext } from "../../../../../utils/cel-context";
import { cn } from "../../../../../utils/cn";
defineOptions({ name: "ShwfedTableSelectRendererRuntime" });
const props = defineProps({
  column: { type: null, required: true },
  ctx: { type: Object, required: true }
});
const celContext = injectCELContext();
function evalPredicate(expression, fallback) {
  try {
    return Boolean(Effect.runSync($cel(expression, celBindings(celContext))));
  } catch (e) {
    console.error("[shwfed-table] row-selection predicate failed", e);
    return fallback;
  }
}
const canSelect = computed(() => {
  if (props.column.enableRowSelection && !evalPredicate(props.column.enableRowSelection, true)) {
    return false;
  }
  if (props.column.mode === "checkbox" && props.column.enableMultiRowSelection && !evalPredicate(props.column.enableMultiRowSelection, true)) {
    return false;
  }
  return true;
});
function onCheckboxClick(e) {
  if (!canSelect.value) return;
  const { row, table } = props.ctx;
  if (e.shiftKey) {
    const rows = table.getRowModel().rows;
    const i = rows.findIndex((r) => r.id === row.id);
    if (i >= 0) {
      let anchor = -1;
      for (let d = 1; d < rows.length; d++) {
        const up = rows[i - d];
        if (up?.getIsSelected()) {
          anchor = i - d;
          break;
        }
        const dn = rows[i + d];
        if (dn?.getIsSelected()) {
          anchor = i + d;
          break;
        }
      }
      if (anchor >= 0) {
        const [lo, hi] = anchor <= i ? [anchor, i] : [i, anchor];
        const updates = {};
        for (let j = lo; j <= hi; j++) {
          const r = rows[j];
          if (r && r.getCanSelect() && r.getCanMultiSelect()) {
            updates[r.id] = true;
          }
        }
        table.setRowSelection((prev) => ({ ...prev, ...updates }));
        return;
      }
    }
  }
  row.toggleSelected(!row.getIsSelected());
}
</script>

<template>
  <div class="w-full h-full flex items-center justify-center">
    <button
      v-if="column.mode === 'radio'"
      type="button"
      role="radio"
      :aria-checked="ctx.row.getIsSelected()"
      :disabled="!canSelect"
      :class="[
  'size-4 shrink-0 rounded-full border shadow-xs outline-none transition-shadow',
  'flex items-center justify-center',
  ctx.row.getIsSelected() ? 'bg-(--primary) border-(--primary)' : 'border-zinc-200 hover:shadow',
  !canSelect ? 'cursor-not-allowed opacity-50' : 'cursor-pointer'
]"
      @click="ctx.table.setRowSelection({ [ctx.row.id]: true })"
    >
      <span
        v-if="ctx.row.getIsSelected()"
        class="size-1.5 rounded-full bg-white"
      />
    </button>
    <button
      v-else
      :id="`${ctx.column.id}-${ctx.row.id}`"
      type="button"
      role="checkbox"
      :aria-checked="ctx.row.getIsSelected()"
      :disabled="!canSelect"
      :data-state="ctx.row.getIsSelected() ? 'checked' : 'unchecked'"
      :class="cn(
  'peer flex items-center justify-center border-zinc-200',
  'data-[state=checked]:bg-(--primary) data-[state=checked]:text-white data-[state=checked]:border-(--primary)',
  'aria-invalid:border-red-400',
  'size-4 shrink-0 rounded border shadow-xs hover:shadow transition-shadow outline-none',
  'disabled:cursor-not-allowed disabled:opacity-50',
  canSelect ? 'cursor-pointer' : 'cursor-not-allowed'
)"
      @click="onCheckboxClick"
    >
      <span class="grid h-full w-full place-content-center transition-none text-xs">
        <Icon
          v-if="ctx.row.getIsSelected()"
          icon="fluent:checkmark-20-filled"
        />
      </span>
    </button>
  </div>
</template>
