<script setup>
import { DottedMenu } from "@/Utilities/Icons";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/Components/ui/dialog";
import {
  AlertDialog,
  AlertDialogContent,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogFooter,
} from "@/Components/ui/alert-dialog";
import { computed, onMounted, ref, watch, nextTick } from "vue";
import { router, useForm } from "@inertiajs/vue3";
import InputLabel from "@/Components/InputLabel.vue";
import { Input } from "@/Components/ui/input";
import { Checkbox } from "@/Components/ui/checkbox";
import {
  Select,
  SelectTrigger,
  SelectValue,
  SelectContent,
  SelectItem,
} from "@/Components/ui/select";
import AppCombobox from "@/Components/app/ui/AppCombobox.vue";
import AppMultiSelect from "@/Components/app/ui/AppMultiSelect.vue";
import { Button } from "@/Components/ui/button";
import DataTableNew2 from "@/Components/DataTable/DataTableNew2.vue";
import InlineColorPicker from "@/Components/InlineColorPicker.vue";
import Dropdown from "@/Components/Dropdown.vue";
import AppPopover from "@/Components/app/ui/AppPopover.vue";
import {
  FilterIcon,
  MoreHorizontal,
  Pencil,
  Plus,
  Trash,
  Trash2,
  X,
} from "lucide-vue-next";
import { Switch } from "@/Components/ui/switch";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/Components/ui/dropdown-menu";

const props = defineProps({
  decisions: Array,
  actions: Array,
  emailTemplates: { type: Array, default: () => [] },
  availableEvents: { type: Array, default: () => [] },
  segments: { type: Array, default: () => [] },
  archiveSettings: { type: Array, default: () => [] },
  conditionFields: { type: Array, default: () => [] },
  conditionOperators: { type: Object, default: () => ({}) },
});

const drawerEdit = ref(false);
const drawerCreate = ref(false);
const showDelete = ref(false);
const toDelete = ref(null);

const search = ref("");
const selectedTemplateId = ref(null);
const onlyAutoMail = ref(false);
// Filter: selected events (multi-select)
const selectedEvents = ref([]);

const actionOptions = ref([]);

const columns = [
  { key: "id", label: "#", sortable: true },
  { key: "name", label: "Ime", sortable: true },
  { key: "color_tag", label: "Barva", sortable: false },
  { key: "events", label: "Dogodki", sortable: false },
  { key: "belongs", label: "Pripada akcijam", sortable: false },
  { key: "auto_mail", label: "Auto mail", sortable: false },
  { key: "actions", label: "", sortable: false, class: "w-12" },
];

const form = useForm({
  id: 0,
  name: "",
  color_tag: "",
  actions: [],
  auto_mail: false,
  email_template_id: null,
  events: [],
});

const createForm = useForm({
  name: "",
  color_tag: "",
  actions: [],
  auto_mail: false,
  email_template_id: null,
  events: [],
});

// When auto mail is disabled, also detach email template selection (edit form)
watch(
  () => form.auto_mail,
  (enabled) => {
    if (!enabled) {
      form.email_template_id = null;
    }
  }
);

// Same behavior for create form for consistency
watch(
  () => createForm.auto_mail,
  (enabled) => {
    if (!enabled) {
      createForm.email_template_id = null;
    }
  }
);

const openEditDrawer = (item) => {
  form.actions = [];
  form.id = item.id;
  form.name = item.name;
  form.color_tag = item.color_tag;
  form.auto_mail = !!item.auto_mail;
  form.email_template_id = item.email_template_id || null;
  form.events = (item.events || []).map((ev) => {
    let cfgObj = {};
    const pCfg = ev.pivot?.config;
    if (typeof pCfg === "string" && pCfg.trim() !== "") {
      try {
        cfgObj = JSON.parse(pCfg);
      } catch (e) {
        cfgObj = {};
      }
    } else if (typeof pCfg === "object" && pCfg !== null) {
      cfgObj = pCfg;
    }
    return {
      id: ev.id,
      key: ev.key,
      name: ev.name,
      active: ev.pivot?.active ?? true,
      run_order: ev.pivot?.run_order ?? null,
      config: cfgObj,
    };
  });
  drawerEdit.value = true;

  form.actions = item.actions.map((a) => a.id);
};

const closeEditDrawer = () => {
  drawerEdit.value = false;
  form.reset();
};

const openCreateDrawer = () => {
  createForm.reset();
  drawerCreate.value = true;
};

const closeCreateDrawer = () => {
  drawerCreate.value = false;
  createForm.reset();
};

onMounted(() => {
  props.actions.forEach((a) => {
    actionOptions.value.push({
      label: a.name,
      value: a.id,
    });
  });
});

function eventById(id) {
  return (props.availableEvents || []).find((e) => Number(e.id) === Number(id));
}

function eventKey(ev) {
  const id = ev?.id;
  const found = eventById(id);
  return (found?.key || ev?.key || "").toString();
}

function defaultConfigForKey(key) {
  switch (key) {
    case "add_segment":
      return { segment_id: null, deactivate_previous: true };
    case "archive_contract":
      return { archive_setting_id: null, reactivate: false };
    case "end_field_job":
      return {};
    case "add_call_later":
      return {};
    default:
      return {};
  }
}

function adoptKeyAndName(ev) {
  const found = eventById(ev.id);
  if (found) {
    ev.key = found.key;
    ev.name = found.name;
  }
}

function onEventChange(ev) {
  adoptKeyAndName(ev);
  const key = eventKey(ev);
  // Reset config to sensible defaults for the new key
  ev.config = defaultConfigForKey(key);
  // Clear any raw JSON cache
  if (ev.__rawJson !== undefined) delete ev.__rawJson;
}

function defaultEventPayload() {
  const first = (props.availableEvents || [])[0] || { id: null, key: null, name: null };
  return {
    id: first.id || null,
    key: first.key || null,
    name: first.name || null,
    active: true,
    run_order: null,
    config: defaultConfigForKey(first.key || ""),
  };
}

function operatorsForField(fieldKey) {
  const field = (props.conditionFields || []).find((f) => f.key === fieldKey);
  if (!field) {
    return props.conditionOperators?.numeric ?? [];
  }
  return props.conditionOperators?.[field.type] ?? [];
}

function addCondition(ev) {
  if (!Array.isArray(ev.config.conditions)) {
    ev.config.conditions = [];
  }
  const firstField = (props.conditionFields || [])[0];
  const firstOperator = firstField
    ? operatorsForField(firstField.key)[0]?.key ?? "="
    : "=";
  ev.config.conditions.push({
    field: firstField?.key ?? "",
    operator: firstOperator,
    value: "",
  });
}

function removeCondition(ev, idx) {
  ev.config.conditions.splice(idx, 1);
}

function onConditionFieldChange(condition) {
  const ops = operatorsForField(condition.field);
  condition.operator = ops[0]?.key ?? "=";
  condition.value = "";
}

function tryAdoptRaw(ev) {
  try {
    const obj = JSON.parse(ev.__rawJson || "{}");
    if (obj && typeof obj === "object") {
      ev.config = obj;
    }
  } catch (e) {
    // ignore parse error, leave raw as-is
  }
}

const filtered = computed(() => {
  const term = search.value?.toLowerCase() ?? "";
  const tplId = selectedTemplateId.value ? Number(selectedTemplateId.value) : null;
  const evIdSet = new Set((selectedEvents.value || []).map((e) => Number(e)));
  return (props.decisions || []).filter((d) => {
    const matchesSearch =
      !term ||
      d.name?.toLowerCase().includes(term) ||
      d.color_tag?.toLowerCase().includes(term);
    const matchesAuto = !onlyAutoMail.value || !!d.auto_mail;
    const matchesTemplate = !tplId || Number(d.email_template_id || 0) === tplId;
    const rowEvents = Array.isArray(d.events) ? d.events : [];
    const matchesEvents =
      evIdSet.size === 0 || rowEvents.some((ev) => evIdSet.has(Number(ev.id)));
    return matchesSearch && matchesAuto && matchesTemplate && matchesEvents;
  });
});

const update = () => {
  const clientErrors = validateEventsClientSide(form.events || []);
  if (Object.keys(clientErrors).length > 0) {
    // attach errors to form for display
    form.setErrors(clientErrors);
    scrollToFirstEventError(clientErrors, "edit");
    return;
  }

  // Transform actions from array of IDs to array of objects
  const actionsPayload = form.actions
    .map((id) => {
      const action = props.actions.find((a) => a.id === Number(id) || a.id === id);
      if (!action) {
        console.warn("Action not found for id:", id);
        return null;
      }
      return { id: action.id, name: action.name };
    })
    .filter(Boolean); // Remove null entries

  form
    .transform((data) => ({
      ...data,
      actions: actionsPayload,
    }))
    .put(route("settings.decisions.update", { id: form.id }), {
      onSuccess: () => {
        closeEditDrawer();
      },
      onError: (errors) => {
        // preserve server errors for display
        scrollToFirstEventError(form.errors, "edit");
      },
    });
};

const store = () => {
  const clientErrors = validateEventsClientSide(createForm.events || []);
  if (Object.keys(clientErrors).length > 0) {
    createForm.setErrors(clientErrors);
    scrollToFirstEventError(clientErrors, "create");
    return;
  }

  // Transform actions from array of IDs to array of objects
  const actionsPayload = createForm.actions
    .map((id) => {
      const action = props.actions.find((a) => a.id === Number(id) || a.id === id);
      if (!action) {
        console.warn("Action not found for id:", id);
        return null;
      }
      return { id: action.id, name: action.name };
    })
    .filter(Boolean); // Remove null entries

  createForm
    .transform((data) => ({
      ...data,
      actions: actionsPayload,
    }))
    .post(route("settings.decisions.store"), {
      onSuccess: () => {
        closeCreateDrawer();
      },
      onError: () => {
        scrollToFirstEventError(createForm.errors, "create");
      },
    });
};

function validateEventsClientSide(events) {
  const errors = {};
  (events || []).forEach((ev, idx) => {
    const key = eventKey(ev);
    if (key === "add_segment") {
      if (!ev.config || !ev.config.segment_id) {
        errors[`events.${idx}.config.segment_id`] = "Izberite segment.";
      }
    } else if (key === "archive_contract") {
      if (!ev.config || !ev.config.archive_setting_id) {
        errors[`events.${idx}.config.archive_setting_id`] = "Izberite nastavitve arhiva.";
      }
    }
  });
  return errors;
}

function scrollToFirstEventError(errorsBag, mode /* 'edit' | 'create' */) {
  const keys = Object.keys(errorsBag || {});
  // find first event-related error key
  const first = keys.find((k) =>
    /^events\.\d+\.config\.(segment_id|archive_setting_id)$/.test(k)
  );
  if (!first) return;
  const match = first.match(/^events\.(\d+)\.config\.(segment_id|archive_setting_id)$/);
  if (!match) return;
  const idx = Number(match[1]);
  const field = match[2];
  let targetId = null;
  if (field === "segment_id") {
    targetId = mode === "create" ? `cseg-${idx}` : `seg-${idx}`;
  } else if (field === "archive_setting_id") {
    targetId = mode === "create" ? `cas-${idx}` : `as-${idx}`;
  }
  if (!targetId) return;
  nextTick(() => {
    const el = document.getElementById(targetId);
    if (el && "scrollIntoView" in el) {
      el.scrollIntoView({ behavior: "smooth", block: "center" });
      // also focus the control for accessibility
      if ("focus" in el) {
        try {
          el.focus();
        } catch (e) {
          /* noop */
        }
      }
    }
  });
}

const eventsValidEdit = computed(() => {
  const errs = validateEventsClientSide(form.events || []);
  return Object.keys(errs).length === 0;
});

const eventsValidCreate = computed(() => {
  const errs = validateEventsClientSide(createForm.events || []);
  return Object.keys(errs).length === 0;
});

const confirmDelete = (decision) => {
  toDelete.value = decision;
  showDelete.value = true;
};

const cancelDelete = () => {
  toDelete.value = null;
  showDelete.value = false;
};

const destroyDecision = () => {
  if (!toDelete.value) return;
  router.delete(route("settings.decisions.destroy", { id: toDelete.value.id }), {
    preserveScroll: true,
    onFinish: () => cancelDelete(),
  });
};
</script>
<template>
  <div class="p-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
    <div class="flex gap-3 items-center">
      <AppPopover align="start" side="bottom" content-class="w-96">
        <template #trigger>
          <Button variant="outline" size="sm">
            <FilterIcon class="w-4 h-4 mr-2" />
            Filtri
          </Button>
        </template>
        <div class="space-y-3 p-1">
          <div>
            <InputLabel for="searchFilter" value="Iskanje" class="mb-1" />
            <Input
              id="searchFilter"
              v-model="search"
              placeholder="Iskanje..."
              class="w-full"
            />
          </div>
          <div>
            <InputLabel for="templateFilter" value="Email predloga" class="mb-1" />
            <Select v-model="selectedTemplateId">
              <SelectTrigger id="templateFilter" class="w-full">
                <SelectValue placeholder="Vse predloge" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem :value="null">Vse predloge</SelectItem>
                <SelectItem v-for="t in emailTemplates" :key="t.id" :value="t.id">
                  {{ t.name }}
                </SelectItem>
              </SelectContent>
            </Select>
          </div>
          <div>
            <InputLabel for="eventsFilter" value="Dogodki" class="mb-1" />
            <AppMultiSelect
              id="eventsFilter"
              v-model="selectedEvents"
              :items="availableEvents.map((e) => ({ value: e.id, label: e.name }))"
              placeholder="Filtriraj po dogodkih"
              class="w-full"
            />
          </div>
          <div class="flex items-center gap-2">
            <Checkbox id="onlyAutoMailFilter" v-model="onlyAutoMail" />
            <InputLabel
              for="onlyAutoMailFilter"
              class="text-sm font-normal cursor-pointer"
            >
              Samo auto mail
            </InputLabel>
          </div>
        </div>
      </AppPopover>
    </div>
    <div class="shrink-0">
      <Button @click="openCreateDrawer">+ Dodaj odločitev</Button>
    </div>
  </div>
  <div>
    <DataTableNew2
      :columns="columns"
      :data="filtered"
      :pageSize="25"
      :showToolbar="false"
      :showPagination="true"
    >
      <template #cell-color_tag="{ row }">
        <div class="flex items-center gap-2">
          <span
            v-if="row.color_tag"
            class="inline-block h-4 w-4 rounded"
            :style="{ backgroundColor: row.color_tag }"
          ></span>
          <span>{{ row.color_tag || "" }}</span>
        </div>
      </template>
      <template #cell-belongs="{ row }">
        {{ row.actions?.length ?? 0 }}
      </template>
      <template #cell-events="{ row }">
        <div class="flex items-center gap-2">
          <Dropdown align="left" width="64" :close-on-content-click="false">
            <template #trigger>
              <button
                type="button"
                class="p-1 rounded hover:bg-gray-100 border border-transparent hover:border-gray-200"
              >
                {{ row.events?.length ?? 0 }}
              </button>
            </template>
            <template #content>
              <div class="py-2">
                <div
                  v-if="!row.events || row.events.length === 0"
                  class="px-3 py-1 text-sm text-gray-500"
                >
                  Ni dogodkov
                </div>
                <ul v-else class="max-h-64 overflow-auto">
                  <li
                    v-for="(ev, i) in row.events"
                    :key="ev.id"
                    class="px-3 py-1 text-sm flex items-center gap-2"
                  >
                    <span
                      class="inline-flex items-center justify-center w-2 h-2 rounded-full"
                      :class="ev.pivot?.active === false ? 'bg-gray-300' : 'bg-green-500'"
                    ></span>
                    <span
                      class="text-gray-800"
                      :class="
                        ev.pivot?.active === false ? 'line-through text-gray-400' : ''
                      "
                    >
                      {{ ev.pivot?.run_order ?? i + 1 }}.
                      {{ ev.name || ev.key || "#" + ev.id }}
                    </span>
                  </li>
                </ul>
              </div>
            </template>
          </Dropdown>
        </div>
      </template>
      <template #cell-auto_mail="{ row }">
        <div class="flex flex-col text-sm">
          <span :class="row.auto_mail ? 'text-green-700' : 'text-gray-500'">{{
            row.auto_mail ? "Vključeno" : "Izključeno"
          }}</span>
          <span v-if="row.auto_mail && row.email_template_id" class="text-gray-600">
            Template:
            {{ emailTemplates.find((t) => t.id === row.email_template_id)?.name || "—" }}
          </span>
        </div>
      </template>
      <template #cell-actions="{ row }">
        <DropdownMenu>
          <DropdownMenuTrigger as-child>
            <Button variant="ghost" size="icon">
              <MoreHorizontal class="w-4 h-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem @click="openEditDrawer(row)">
              <Pencil class="w-4 h-4 mr-2" />
              Uredi
            </DropdownMenuItem>
            <DropdownMenuItem
              :disabled="(row.activities_count ?? 0) > 0"
              @click="confirmDelete(row)"
              class="text-red-600 focus:text-red-600"
            >
              <Trash class="w-4 h-4 mr-2" />
              Izbriši
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </template>
    </DataTableNew2>
  </div>
  <Dialog v-model:open="drawerEdit">
    <DialogContent class="max-w-2xl max-h-[90vh] overflow-y-auto">
      <DialogHeader>
        <DialogTitle>Uredi odločitev</DialogTitle>
      </DialogHeader>
      <div class="space-y-4">
        <div>
          <InputLabel for="name">Ime</InputLabel>
          <Input id="name" v-model="form.name" type="text" />
        </div>

        <div class="mt-4 flex items-center gap-2">
          <Checkbox id="autoMailEdit" v-model="form.auto_mail" />
          <InputLabel for="autoMailEdit" class="text-sm font-normal cursor-pointer">
            Samodejna pošta (auto mail)
          </InputLabel>
        </div>

        <div class="col-span-6 sm:col-span-4 mt-2">
          <InputLabel for="emailTemplateEdit" value="Email predloga" />
          <Select v-model="form.email_template_id" :disabled="!form.auto_mail">
            <SelectTrigger id="emailTemplateEdit" class="w-full">
              <SelectValue placeholder="— Brez —" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem :value="null">— Brez —</SelectItem>
              <SelectItem v-for="t in emailTemplates" :key="t.id" :value="t.id">
                {{ t.name }}
              </SelectItem>
            </SelectContent>
          </Select>
          <p v-if="form.email_template_id" class="text-xs text-gray-500 mt-1">
            <span
              v-if="
                (
                  emailTemplates.find((t) => t.id === form.email_template_id)
                    ?.entity_types || []
                ).includes('contract')
              "
              >Ta predloga zahteva pogodbo.</span
            >
          </p>
        </div>
        <div class="col-span-6 sm:col-span-4">
          <InputLabel for="colorTag" value="Barva" />
          <div class="mt-1">
            <InlineColorPicker v-model="form.color_tag" />
          </div>
        </div>

        <div class="col-span-6 sm:col-span-4">
          <InputLabel for="actionsSelect" value="Akcije" />
          <AppMultiSelect
            id="actionsSelect"
            v-model="form.actions"
            :items="actionOptions"
            placeholder="Dodaj akcijo"
          />
        </div>

        <!-- Quick JSON event config editor -->
        <div class="mt-6">
          <h3 class="text-md font-semibold mb-2">Dogodki odločitve</h3>
          <div class="space-y-4">
            <div v-for="(ev, idx) in form.events" :key="idx" class="border rounded p-3">
              <div class="flex flex-col sm:flex-row gap-3">
                <div class="flex-1">
                  <InputLabel :for="`event-${idx}`" value="Dogodek" />
                  <Select v-model="ev.id" @update:model-value="onEventChange(ev)">
                    <SelectTrigger :id="`event-${idx}`" class="w-full">
                      <SelectValue placeholder="— Izberi —" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem :value="null">— Izberi —</SelectItem>
                      <SelectItem
                        v-for="opt in availableEvents"
                        :key="opt.id"
                        :value="opt.id"
                      >
                        {{ opt.name || opt.key || `#${opt.id}` }}
                      </SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div class="w-36">
                  <InputLabel :for="`order-${idx}`">Vrstni red</InputLabel>
                  <Input
                    :id="`order-${idx}`"
                    v-model.number="ev.run_order"
                    type="number"
                    class="w-full"
                  />
                </div>
                <div class="flex items-center gap-2 self-end">
                  <label
                    class="flex items-center gap-2 text-sm cursor-pointer select-none"
                  >
                    <Switch v-model="ev.active" />
                    <span
                      :class="
                        ev.active ? 'text-green-700 font-medium' : 'text-muted-foreground'
                      "
                      >{{ ev.active ? "Aktivno" : "Neaktivno" }}</span
                    >
                  </label>
                  <Button
                    variant="ghost"
                    size="icon"
                    class="text-red-600 hover:text-red-700 hover:bg-red-50"
                    @click="form.events.splice(idx, 1)"
                  >
                    <Trash2 class="w-4 h-4" />
                  </Button>
                </div>
              </div>
              <div class="mt-3">
                <template v-if="eventKey(ev) === 'add_segment'">
                  <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                    <div>
                      <InputLabel :for="`seg-${idx}`" value="Segment" />
                      <Select v-model="ev.config.segment_id">
                        <SelectTrigger :id="`seg-${idx}`" class="w-full">
                          <SelectValue placeholder="— Izberi segment —" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem :value="null">— Izberi segment —</SelectItem>
                          <SelectItem v-for="s in segments" :key="s.id" :value="s.id">
                            {{ s.name }}
                          </SelectItem>
                        </SelectContent>
                      </Select>
                      <p
                        v-if="form.errors[`events.${idx}.config.segment_id`]"
                        class="text-xs text-red-600 mt-1"
                      >
                        {{ form.errors[`events.${idx}.config.segment_id`] }}
                      </p>
                    </div>
                    <div class="flex items-end">
                      <label class="flex items-center gap-2 text-sm mt-6">
                        <Checkbox v-model="ev.config.deactivate_previous" />
                        Deaktiviraj prejšnje
                      </label>
                    </div>
                  </div>
                </template>
                <template v-else-if="eventKey(ev) === 'archive_contract'">
                  <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                    <div>
                      <InputLabel :for="`as-${idx}`" value="Nastavitev arhiva" />
                      <Select v-model="ev.config.archive_setting_id">
                        <SelectTrigger :id="`as-${idx}`" class="w-full">
                          <SelectValue placeholder="— Izberi nastavitev —" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem :value="null">— Izberi nastavitev —</SelectItem>
                          <SelectItem
                            v-for="a in archiveSettings"
                            :key="a.id"
                            :value="a.id"
                          >
                            {{ a.name }}
                          </SelectItem>
                        </SelectContent>
                      </Select>
                      <p
                        v-if="form.errors[`events.${idx}.config.archive_setting_id`]"
                        class="text-xs text-red-600 mt-1"
                      >
                        {{ form.errors[`events.${idx}.config.archive_setting_id`] }}
                      </p>
                    </div>
                    <div class="flex items-end">
                      <label
                        class="flex items-center gap-2 text-sm mt-6 cursor-pointer select-none"
                      >
                        <Switch
                          :model-value="ev.config.reactivate"
                          v-model:checked="ev.config.reactivate"
                        />
                        Reaktiviraj namesto arhiviranja
                      </label>
                    </div>
                  </div>
                </template>
                <template v-else-if="eventKey(ev) === 'end_field_job'">
                  <p class="text-sm text-gray-600">
                    Ta dogodek nima dodatnih nastavitev.
                  </p>
                </template>
                <template v-else-if="eventKey(ev) === 'add_call_later'">
                  <p class="text-sm text-muted-foreground">
                    Datum in ura povratnega klica se vneseta ob ustvarjanju aktivnosti.
                  </p>
                </template>
                <template v-else>
                  <!-- Rezervni urejevalnik za neznane ključe dogodkov -->
                  <InputLabel :for="`cfg-${idx}`" value="Napredna nastavitev (JSON)" />
                  <textarea
                    :id="`cfg-${idx}`"
                    v-model="ev.__rawJson"
                    @focus="
                      ev.__rawJson =
                        ev.__rawJson ?? JSON.stringify(ev.config || {}, null, 2)
                    "
                    @change="tryAdoptRaw(ev)"
                    class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 text-sm font-mono"
                    rows="6"
                    placeholder="{ }"
                  ></textarea>
                </template>
              </div>

              <!-- Conditions -->
              <div v-if="conditionFields.length" class="mt-3 border-t pt-3">
                <div class="flex items-center justify-between mb-2">
                  <span
                    class="text-xs font-semibold text-muted-foreground uppercase tracking-wide"
                    >Pogoji za izvajanje</span
                  >
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    class="h-7 gap-1 text-xs"
                    @click="addCondition(ev)"
                  >
                    <Plus class="w-3 h-3" />
                    Dodaj pogoj
                  </Button>
                </div>
                <p
                  v-if="!ev.config.conditions?.length"
                  class="text-xs text-muted-foreground italic"
                >
                  Brez pogojev — dogodek se vedno izvede.
                </p>
                <div
                  v-for="(cond, cidx) in ev.config.conditions"
                  :key="cidx"
                  class="flex items-center gap-2 mt-1"
                >
                  <Select
                    v-model="cond.field"
                    @update:model-value="onConditionFieldChange(cond)"
                    class="w-48"
                  >
                    <SelectTrigger class="h-8 text-xs">
                      <SelectValue placeholder="Polje" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem
                        v-for="f in conditionFields"
                        :key="f.key"
                        :value="f.key"
                        class="text-xs"
                      >
                        {{ f.label }}
                      </SelectItem>
                    </SelectContent>
                  </Select>
                  <Select v-model="cond.operator" class="w-36">
                    <SelectTrigger class="h-8 text-xs">
                      <SelectValue placeholder="Operator" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem
                        v-for="op in operatorsForField(cond.field)"
                        :key="op.key"
                        :value="op.key"
                        class="text-xs"
                      >
                        {{ op.label }}
                      </SelectItem>
                    </SelectContent>
                  </Select>
                  <template
                    v-if="
                      conditionFields.find((f) => f.key === cond.field)?.type ===
                      'boolean'
                    "
                  >
                    <Select v-model="cond.value" class="w-24">
                      <SelectTrigger class="h-8 text-xs">
                        <SelectValue placeholder="Vrednost" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="1" class="text-xs">Da</SelectItem>
                        <SelectItem value="0" class="text-xs">Ne</SelectItem>
                      </SelectContent>
                    </Select>
                  </template>
                  <template v-else>
                    <Input
                      v-model="cond.value"
                      class="h-8 text-xs w-28"
                      placeholder="Vrednost"
                    />
                  </template>
                  <Button
                    type="button"
                    variant="ghost"
                    size="icon"
                    class="h-7 w-7 text-red-500 hover:text-red-700"
                    @click="removeCondition(ev, cidx)"
                  >
                    <X class="w-3 h-3" />
                  </Button>
                </div>
              </div>
            </div>
            <div>
              <Button
                type="button"
                variant="outline"
                @click="form.events.push(defaultEventPayload())"
                >+ Dodaj dogodek</Button
              >
            </div>
          </div>
        </div>

        <div v-if="form.recentlySuccessful" class="text-sm text-green-600">
          Shranjuje.
        </div>
      </div>
      <DialogFooter>
        <Button variant="outline" @click="closeEditDrawer">Prekliči</Button>
        <Button @click="update" :disabled="form.processing || !eventsValidEdit"
          >Shrani</Button
        >
      </DialogFooter>
    </DialogContent>
  </Dialog>

  <Dialog v-model:open="drawerCreate">
    <DialogContent class="max-w-2xl max-h-[90vh] overflow-y-auto">
      <DialogHeader>
        <DialogTitle>Dodaj odločitev</DialogTitle>
      </DialogHeader>
      <div class="space-y-4">
        <div>
          <InputLabel for="nameCreate">Ime</InputLabel>
          <Input id="nameCreate" v-model="createForm.name" type="text" />
        </div>

        <div class="mt-4 flex items-center gap-2">
          <Checkbox id="autoMailCreate" v-model="createForm.auto_mail" />
          <InputLabel for="autoMailCreate" class="text-sm font-normal cursor-pointer">
            Samodejna pošta (auto mail)
          </InputLabel>
        </div>

        <div class="col-span-6 sm:col-span-4 mt-2">
          <InputLabel for="emailTemplateCreate" value="Email predloga" />
          <Select
            v-model="createForm.email_template_id"
            :disabled="!createForm.auto_mail"
          >
            <SelectTrigger id="emailTemplateCreate" class="w-full">
              <SelectValue placeholder="— Brez —" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem :value="null">— Brez —</SelectItem>
              <SelectItem v-for="t in emailTemplates" :key="t.id" :value="t.id">
                {{ t.name }}
              </SelectItem>
            </SelectContent>
          </Select>
          <p v-if="createForm.email_template_id" class="text-xs text-gray-500 mt-1">
            <span
              v-if="
                (
                  emailTemplates.find((t) => t.id === createForm.email_template_id)
                    ?.entity_types || []
                ).includes('contract')
              "
              >Ta predloga zahteva pogodbo.</span
            >
          </p>
        </div>
        <div class="col-span-6 sm:col-span-4">
          <InputLabel for="colorTagCreate" value="Barva" />
          <div class="mt-1">
            <InlineColorPicker v-model="createForm.color_tag" />
          </div>
        </div>

        <div class="col-span-6 sm:col-span-4">
          <InputLabel for="actionsCreate" value="Akcije" />
          <AppMultiSelect
            id="actionsCreate"
            v-model="createForm.actions"
            :items="actionOptions"
            placeholder="Dodaj akcijo"
          />
        </div>

        <!-- Create: Decision events editor -->
        <div class="mt-6">
          <h3 class="text-md font-semibold mb-2">Dogodki odločitve</h3>
          <div class="space-y-4">
            <div
              v-for="(ev, idx) in createForm.events"
              :key="`c-${idx}`"
              class="border rounded p-3"
            >
              <div class="flex flex-col sm:flex-row gap-3">
                <div class="flex-1">
                  <InputLabel :for="`cevent-${idx}`" value="Dogodek" />
                  <Select v-model="ev.id" @update:model-value="onEventChange(ev)">
                    <SelectTrigger :id="`cevent-${idx}`" class="w-full">
                      <SelectValue placeholder="— Izberi —" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem :value="null">— Izberi —</SelectItem>
                      <SelectItem
                        v-for="opt in availableEvents"
                        :key="opt.id"
                        :value="opt.id"
                      >
                        {{ opt.name || opt.key || `#${opt.id}` }}
                      </SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div class="w-36">
                  <InputLabel :for="`corder-${idx}`">Vrstni red</InputLabel>
                  <Input
                    :id="`corder-${idx}`"
                    v-model.number="ev.run_order"
                    type="number"
                    class="w-full"
                  />
                </div>
                <div class="flex items-center gap-2 self-end">
                  <label
                    class="flex items-center gap-2 text-sm cursor-pointer select-none"
                  >
                    <Switch v-model="ev.active" />
                    <span
                      :class="
                        ev.active ? 'text-green-700 font-medium' : 'text-muted-foreground'
                      "
                      >{{ ev.active ? "Aktivno" : "Neaktivno" }}</span
                    >
                  </label>
                  <Button
                    variant="ghost"
                    size="icon"
                    class="text-red-600 hover:text-red-700 hover:bg-red-50"
                    @click="createForm.events.splice(idx, 1)"
                  >
                    <Trash2 class="w-4 h-4" />
                  </Button>
                </div>
              </div>
              <div class="mt-3">
                <template v-if="eventKey(ev) === 'add_segment'">
                  <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                    <div>
                      <InputLabel :for="`cseg-${idx}`" value="Segment" />
                      <Select v-model="ev.config.segment_id">
                        <SelectTrigger :id="`cseg-${idx}`" class="w-full">
                          <SelectValue placeholder="— Izberi segment —" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem :value="null">— Izberi segment —</SelectItem>
                          <SelectItem v-for="s in segments" :key="s.id" :value="s.id">
                            {{ s.name }}
                          </SelectItem>
                        </SelectContent>
                      </Select>
                      <p
                        v-if="createForm.errors[`events.${idx}.config.segment_id`]"
                        class="text-xs text-red-600 mt-1"
                      >
                        {{ createForm.errors[`events.${idx}.config.segment_id`] }}
                      </p>
                    </div>
                    <div class="flex items-end">
                      <label class="flex items-center gap-2 text-sm mt-6">
                        <Checkbox v-model:checked="ev.config.deactivate_previous" />
                        Deaktiviraj prejšnje
                      </label>
                    </div>
                  </div>
                </template>
                <template v-else-if="eventKey(ev) === 'archive_contract'">
                  <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                    <div>
                      <InputLabel :for="`cas-${idx}`" value="Nastavitev arhiva" />
                      <Select v-model="ev.config.archive_setting_id">
                        <SelectTrigger :id="`cas-${idx}`" class="w-full">
                          <SelectValue placeholder="— Izberi nastavitev —" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem :value="null">— Izberi nastavitev —</SelectItem>
                          <SelectItem
                            v-for="a in archiveSettings"
                            :key="a.id"
                            :value="a.id"
                          >
                            {{ a.name }}
                          </SelectItem>
                        </SelectContent>
                      </Select>
                      <p
                        v-if="
                          createForm.errors[`events.${idx}.config.archive_setting_id`]
                        "
                        class="text-xs text-red-600 mt-1"
                      >
                        {{ createForm.errors[`events.${idx}.config.archive_setting_id`] }}
                      </p>
                    </div>
                    <div class="flex items-end">
                      <label
                        class="flex items-center gap-2 text-sm mt-6 cursor-pointer select-none"
                      >
                        <Switch
                          :model-value="ev.config.reactivate"
                          v-model:checked="ev.config.reactivate"
                        />
                        Reaktiviraj namesto arhiviranja
                      </label>
                    </div>
                  </div>
                </template>
                <template v-else-if="eventKey(ev) === 'end_field_job'">
                  <p class="text-sm text-gray-600">
                    Ta dogodek nima dodatnih nastavitev.
                  </p>
                </template>
                <template v-else-if="eventKey(ev) === 'add_call_later'">
                  <p class="text-sm text-muted-foreground">
                    Datum in ura povratnega klica se vneseta ob ustvarjanju aktivnosti.
                  </p>
                </template>
                <template v-else>
                  <InputLabel :for="`ccfg-${idx}`" value="Napredna nastavitev (JSON)" />
                  <textarea
                    :id="`ccfg-${idx}`"
                    v-model="ev.__rawJson"
                    @focus="
                      ev.__rawJson =
                        ev.__rawJson ?? JSON.stringify(ev.config || {}, null, 2)
                    "
                    @change="tryAdoptRaw(ev)"
                    class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 text-sm font-mono"
                    rows="6"
                    placeholder="{ }"
                  ></textarea>
                </template>
              </div>

              <!-- Conditions -->
              <div v-if="conditionFields.length" class="mt-3 border-t pt-3">
                <div class="flex items-center justify-between mb-2">
                  <span
                    class="text-xs font-semibold text-muted-foreground uppercase tracking-wide"
                    >Pogoji za izvajanje</span
                  >
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    class="h-7 gap-1 text-xs"
                    @click="addCondition(ev)"
                  >
                    <Plus class="w-3 h-3" />
                    Dodaj pogoj
                  </Button>
                </div>
                <p
                  v-if="!ev.config.conditions?.length"
                  class="text-xs text-muted-foreground italic"
                >
                  Brez pogojev — dogodek se vedno izvede.
                </p>
                <div
                  v-for="(cond, cidx) in ev.config.conditions"
                  :key="cidx"
                  class="flex items-center gap-2 mt-1"
                >
                  <Select
                    v-model="cond.field"
                    @update:model-value="onConditionFieldChange(cond)"
                    class="w-48"
                  >
                    <SelectTrigger class="h-8 text-xs">
                      <SelectValue placeholder="Polje" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem
                        v-for="f in conditionFields"
                        :key="f.key"
                        :value="f.key"
                        class="text-xs"
                      >
                        {{ f.label }}
                      </SelectItem>
                    </SelectContent>
                  </Select>
                  <Select v-model="cond.operator" class="w-36">
                    <SelectTrigger class="h-8 text-xs">
                      <SelectValue placeholder="Operator" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem
                        v-for="op in operatorsForField(cond.field)"
                        :key="op.key"
                        :value="op.key"
                        class="text-xs"
                      >
                        {{ op.label }}
                      </SelectItem>
                    </SelectContent>
                  </Select>
                  <template
                    v-if="
                      conditionFields.find((f) => f.key === cond.field)?.type ===
                      'boolean'
                    "
                  >
                    <Select v-model="cond.value" class="w-24">
                      <SelectTrigger class="h-8 text-xs">
                        <SelectValue placeholder="Vrednost" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="1" class="text-xs">Da</SelectItem>
                        <SelectItem value="0" class="text-xs">Ne</SelectItem>
                      </SelectContent>
                    </Select>
                  </template>
                  <template v-else>
                    <Input
                      v-model="cond.value"
                      class="h-8 text-xs w-28"
                      placeholder="Vrednost"
                    />
                  </template>
                  <Button
                    type="button"
                    variant="ghost"
                    size="icon"
                    class="h-7 w-7 text-red-500 hover:text-red-700"
                    @click="removeCondition(ev, cidx)"
                  >
                    <X class="w-3 h-3" />
                  </Button>
                </div>
              </div>
            </div>
            <div>
              <Button
                type="button"
                variant="outline"
                @click="createForm.events.push(defaultEventPayload())"
                >+ Dodaj dogodek</Button
              >
            </div>
          </div>
        </div>

        <div v-if="createForm.recentlySuccessful" class="text-sm text-green-600">
          Shranjuje.
        </div>
      </div>
      <DialogFooter>
        <Button variant="outline" @click="closeCreateDrawer">Prekliči</Button>
        <Button @click="store" :disabled="createForm.processing || !eventsValidCreate"
          >Dodaj</Button
        >
      </DialogFooter>
    </DialogContent>
  </Dialog>

  <AlertDialog v-model:open="showDelete">
    <AlertDialogContent>
      <AlertDialogHeader>
        <AlertDialogTitle>Zbriši odločitev</AlertDialogTitle>
      </AlertDialogHeader>
      <div class="text-sm text-muted-foreground">
        Ali ste prepričani, da želite zbrisati odločitev "{{ toDelete?.name }}"? Tega
        dejanja ni mogoče razveljaviti.
      </div>
      <AlertDialogFooter>
        <Button variant="outline" @click="cancelDelete">Prekliči</Button>
        <Button variant="destructive" @click="destroyDecision">Zbriši</Button>
      </AlertDialogFooter>
    </AlertDialogContent>
  </AlertDialog>
</template>
