<script setup>
import { Icon } from "@iconify/vue";
import { Effect } from "effect";
import { computed, nextTick, ref, watch } 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 {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList
} from "../../../../ui/command";
import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from "../../../../ui/input-group";
import { Markdown } from "../../../../ui/markdown";
import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from "../../../../ui/popover";
import { useFormState } from "../../../../form/utils/state";
import { interpolateMarkdown } from "../../../utils/runtime";
defineOptions({ name: "ShwfedTableComboboxSingleRendererRuntime" });
const props = defineProps({
  column: { type: null, required: true },
  ctx: { type: Object, required: true }
});
const { locale, t } = useI18n({
  inheritLocale: true,
  messages: {
    zh: {
      "combobox-single-placeholder": "\u8BF7\u9009\u62E9",
      "combobox-single-search-placeholder": "\u641C\u7D22\u2026",
      "combobox-single-empty": "\u65E0\u5339\u914D\u9879"
    },
    en: {
      "combobox-single-placeholder": "Select\u2026",
      "combobox-single-search-placeholder": "Search\u2026",
      "combobox-single-empty": "No matches"
    },
    ja: {
      "combobox-single-placeholder": "\u9078\u629E\u3057\u3066\u304F\u3060\u3055\u3044",
      "combobox-single-search-placeholder": "\u691C\u7D22\u2026",
      "combobox-single-empty": "\u4E00\u81F4\u306A\u3057"
    }
  }
});
const formState = useFormState();
const inherited = injectCELContext();
const $cel = (expression, context) => _rawCel(expression, { ...celBindings(inherited), ...context });
const placeholderText = computed(
  () => props.column.placeholder ? getLocalizedText(props.column.placeholder, locale.value) : t("combobox-single-placeholder")
);
function evalBool(expression, label) {
  if (!expression) return false;
  try {
    return Effect.runSync($cel(expression)) === true;
  } catch (e) {
    console.error(`[shwfed-table] combobox-single ${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"
);
function safeInterpolate(tpl) {
  try {
    return interpolateMarkdown(tpl, $cel, {});
  } catch (e) {
    console.error(`[shwfed-table] combobox-single label interpolation failed`, e);
    return tpl;
  }
}
const entries = computed(
  () => (props.column.items ?? []).map((item) => {
    const labelTpl = getLocalizedText(item.label, locale.value) ?? "";
    const tooltipTpl = item.tooltip ? getLocalizedText(item.tooltip, locale.value) : void 0;
    return {
      key: item.id,
      value: item.value.value,
      label: labelTpl ? safeInterpolate(labelTpl) : "",
      tooltip: tooltipTpl ? safeInterpolate(tooltipTpl) : void 0
    };
  })
);
const cellValue = computed(() => formState.getAt(props.column.binding));
function isEqual(a, b) {
  if (a === b) return true;
  if (a == null || b == null) return false;
  if (typeof a === "object" && typeof b === "object") {
    try {
      return JSON.stringify(a) === JSON.stringify(b);
    } catch {
      return false;
    }
  }
  return false;
}
const selectedEntry = computed(
  () => entries.value.find((entry) => isEqual(entry.value, cellValue.value))
);
const selectedKey = computed(() => selectedEntry.value?.key);
const selectedLabel = computed(() => selectedEntry.value?.label ?? "");
const open = ref(false);
function handleSelect(key) {
  if (typeof key !== "string") return;
  const entry = entries.value.find((e) => e.key === key);
  if (!entry) return;
  formState.setAt(props.column.binding, entry.value);
  void nextTick().then(() => {
    open.value = false;
  });
}
const showClear = computed(
  () => !isDisabled.value && selectedEntry.value !== void 0
);
function handleClear() {
  formState.setAt(props.column.binding, null);
  open.value = false;
}
const hoveredKey = ref(null);
watch(open, (isOpen) => {
  hoveredKey.value = isOpen ? entries.value[0]?.key ?? null : null;
});
const hoveredEntry = computed(
  () => entries.value.find((e) => e.key === hoveredKey.value)
);
const hoveredTooltip = computed(() => hoveredEntry.value?.tooltip);
const anyHasTooltip = computed(
  () => entries.value.some((e) => e.tooltip != null && e.tooltip.length > 0)
);
</script>

<template>
  <!--
    Row budget matches the text-input cell: 2px outer inset around an `h-7`
    (28px) trigger, total 32px. Every branch (hidden / readonly / editable)
    is sized identically so rows do not jump when a CEL condition flips.
    Trigger is a read-only `InputGroupInput` styled to read as editable — a
    faded border idle, snapping to full on hover/focus — and an `h-7` +
    `text-[0.75rem] md:text-[0.75rem]` override (both breakpoints, since
    `Input`'s default `md:text-sm` would beat an unprefixed override at md+).
  -->
  <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 h-7 w-full px-2 text-[0.75rem] text-zinc-700 truncate"
    >
      {{ selectedLabel || "\u2014" }}
    </span>
    <Popover
      v-else
      v-model:open="open"
    >
      <PopoverAnchor as-child>
        <InputGroup
          class="group/combobox-single h-7 rounded border-zinc-200/30 hover:border-zinc-200 focus-within:border-zinc-200 transition-colors ease-out duration-180"
          :data-disabled="isDisabled ? 'true' : void 0"
        >
          <PopoverTrigger as-child>
            <InputGroupInput
              :model-value="selectedLabel"
              :disabled="isDisabled"
              :placeholder="placeholderText"
              class="h-7 text-[0.75rem] md:text-[0.75rem] px-2 cursor-pointer text-left"
              readonly
            />
          </PopoverTrigger>
          <InputGroupAddon
            v-if="showClear"
            align="inline-end"
            class="[@media(hover:hover)]:opacity-0 transition-opacity group-hover/combobox-single:opacity-100 focus-within:opacity-100"
          >
            <InputGroupButton
              size="icon-xs"
              data-slot="combobox-single-clear"
              class="size-4 text-zinc-500 hover:text-zinc-700"
              tabindex="-1"
              @mousedown.prevent
              @click.stop="handleClear"
            >
              <Icon
                icon="fluent:dismiss-20-regular"
                class="size-3"
              />
            </InputGroupButton>
          </InputGroupAddon>
        </InputGroup>
      </PopoverAnchor>
      <PopoverContent
        class="w-auto p-0 [&_[data-slot=command-input-wrapper]]:h-7 [&_[data-slot=command-input-wrapper]]:px-2 [&_[data-slot=command-input-wrapper]_svg]:size-3 [&_[data-slot=command-input]]:h-7 [&_[data-slot=command-input]]:py-0 [&_[data-slot=command-input]]:text-[0.75rem] [&_[data-slot=command-item]]:px-2 [&_[data-slot=command-item]]:py-1 [&_[data-slot=command-item]]:text-[0.75rem]"
        :style="{ width: 'var(--reka-popover-trigger-width)' }"
      >
        <Command
          :model-value="selectedKey"
          :disabled="isDisabled"
          selection-behavior="toggle"
          @update:model-value="handleSelect"
        >
          <CommandInput :placeholder="t('combobox-single-search-placeholder')" />
          <CommandList>
            <CommandEmpty class="py-3 text-center text-[0.75rem] text-zinc-500">
              {{ t("combobox-single-empty") }}
            </CommandEmpty>
            <CommandGroup>
              <CommandItem
                v-for="entry in entries"
                :key="entry.key"
                :value="entry.key"
                @mouseenter="hoveredKey = entry.key"
                @focus="hoveredKey = entry.key"
              >
                {{ entry.label }}
              </CommandItem>
            </CommandGroup>
          </CommandList>
          <div
            v-if="anyHasTooltip && hoveredTooltip"
            class="border-t border-zinc-200 px-2 py-1.5"
          >
            <Markdown
              :source="hoveredTooltip"
              block
              class="prose prose-xs prose-zinc"
            />
          </div>
        </Command>
      </PopoverContent>
    </Popover>
  </div>
</template>
