<script setup lang="ts">
import { computed } from "vue";
import DynamicField from "./DynamicField.vue";
import { usePermissions } from "../composables/usePermissions";

type Field = {
  name: string;
  label: string;
  component: string;
  rules: string[];
  default: unknown;
  hint: string | null;
  readonly: boolean;
  viewPermission: string | null;
  updatePermission: string | null;
  translatable: boolean;
  generateFrom: string | null;
  visibleWhen?: { field: string; value: unknown } | null;
};

type Section = {
  key: string;
  label: string;
  description: string | null;
  fields: Field[];
  updatePermission: string | null;
};

const props = defineProps<{
  section: Section;
  form: Record<string, unknown>;
  errors: Record<string, string>;
  currentLocale: string | null;
  sidebar?: boolean;
}>();

defineEmits<{
  "update:field": [name: string, value: unknown];
}>();

const { can } = usePermissions();

function fieldError(fieldName: string): string | undefined {
  if (props.errors[fieldName]) return props.errors[fieldName];
  const nested = Object.keys(props.errors).find((k) =>
    k.startsWith(fieldName + "."),
  );
  return nested ? props.errors[nested] : undefined;
}

const hasTranslatableFields = computed(() =>
  props.section.fields.some((f) => f.translatable),
);

const visibleFields = computed(() =>
  props.section.fields.filter((f) => {
    if (!can(f.viewPermission)) return false;
    if (
      f.visibleWhen &&
      props.form[f.visibleWhen.field] !== f.visibleWhen.value
    )
      return false;
    return true;
  }),
);
</script>

<template>
  <!-- Header: main section style (locale badge inline) -->
  <template v-if="!sidebar">
    <div
      v-if="section.label || (currentLocale && hasTranslatableFields)"
      class="flex items-center justify-between gap-4 mb-4"
    >
      <div>
        <h3 v-if="section.label" class="font-medium text-foreground">
          {{ section.label }}
        </h3>
        <p
          v-if="section.description"
          class="mt-1 text-sm text-muted-foreground"
        >
          {{ section.description }}
        </p>
      </div>
      <span
        v-if="currentLocale && hasTranslatableFields"
        class="shrink-0 rounded px-2 py-0.5 text-xs font-medium uppercase tracking-wide bg-primary/10 text-primary"
      >
        {{ currentLocale }}
      </span>
    </div>
  </template>

  <!-- Header: sidebar section style (description below header) -->
  <template v-else>
    <div
      v-if="section.label"
      class="flex items-center justify-between gap-4 mb-4"
    >
      <h3 class="font-medium text-foreground">{{ section.label }}</h3>
    </div>
    <p v-if="section.description" class="mb-4 text-sm text-muted-foreground">
      {{ section.description }}
    </p>
  </template>

  <div class="space-y-4">
    <DynamicField
      v-for="field in visibleFields"
      :key="field.name"
      :field="{
        ...field,
        readonly:
          field.readonly ||
          !can(field.updatePermission) ||
          !can(section.updatePermission),
      }"
      :model-value="form[field.name]"
      :error="fieldError(field.name)"
      :current-locale="currentLocale"
      @update:model-value="$emit('update:field', field.name, $event)"
    />
  </div>
</template>
