<!-- [DEF:SemanticLayerReview:Component] -->
<!-- @COMPLEXITY: 4 -->
<!-- @SEMANTICS: dataset-review, semantic-layer, candidate-review, manual-override, field-lock -->
<!-- @PURPOSE: Surface field-level semantic decisions with provenance, confidence, candidate acceptance, and manual override safeguards for US2 review flow. -->
<!-- @LAYER: UI -->
<!-- @RELATION: [BINDS_TO] ->[api_module] -->
<!-- @RELATION: [BINDS_TO] ->[DatasetReviewWorkspace] -->
<!-- @PRE: Session id is available and semantic field entries come from the current ownership-scoped session detail payload. -->
<!-- @POST: Users can review the current semantic value, accept a candidate, apply manual override, and lock or unlock field state without violating backend provenance rules. -->
<!-- @SIDE_EFFECT: Persists semantic field decisions, lock state, and optional thumbs feedback through dataset orchestration endpoints. -->
<!-- @DATA_CONTRACT: Input -> Dataset review session detail { sessionId, fields[], semanticSources[] }; Output -> onupdated(updatedField | { fields: updatedFields }) refresh payload. -->
<!-- @UX_STATE: Conflicted -> Multiple candidates or review-needed fields remain visible with explicit acceptance actions. -->
<!-- @UX_STATE: Manual -> One field enters local draft mode and persists as locked manual override on save. -->
<!-- @UX_FEEDBACK: Save, lock, unlock, and feedback actions expose inline success or error state on the affected field. -->
<!-- @UX_RECOVERY: Users can cancel local edits, unlock a manual override for re-review, or retry failed mutations in place. -->
<!-- @UX_REACTIVITY: Uses $props, $state, and $derived only; no legacy reactive syntax. -->
<script>
  import { t } from "$lib/i18n";
  import { requestApi } from "$lib/api.js";

  let {
    sessionId = "",
    fields = [],
    semanticSources = [],
    disabled = false,
    onupdated = () => {},
  } = $props();

  let editingFieldId = $state("");
  let draftVerboseName = $state("");
  let draftDescription = $state("");
  let draftDisplayFormat = $state("");
  let savingFieldId = $state("");
  let batchSaving = $state(false);
  let fieldMessages = $state({});

  const sortedFields = $derived(
    [...(fields || [])].sort((left, right) => {
      const leftPriority = Number(Boolean(left?.needs_review)) + Number(Boolean(left?.has_conflict));
      const rightPriority =
        Number(Boolean(right?.needs_review)) + Number(Boolean(right?.has_conflict));
      if (leftPriority !== rightPriority) {
        return rightPriority - leftPriority;
      }
      return String(left?.field_name || "").localeCompare(String(right?.field_name || ""));
    }),
  );

  const activeFieldCount = $derived(sortedFields.length);

  function updateFieldMessage(fieldId, patch) {
    fieldMessages = {
      ...fieldMessages,
      [fieldId]: {
        ...(fieldMessages[fieldId] || {}),
        ...patch,
      },
    };
  }

  function resetFieldMessage(fieldId) {
    fieldMessages = {
      ...fieldMessages,
      [fieldId]: {
        status: "",
        text: "",
      },
    };
  }

  function startManualEdit(field) {
    editingFieldId = field.field_id;
    draftVerboseName = field.verbose_name || "";
    draftDescription = field.description || "";
    draftDisplayFormat = field.display_format || "";
    resetFieldMessage(field.field_id);
  }

  function cancelManualEdit(fieldId) {
    if (editingFieldId !== fieldId) {
      return;
    }
    editingFieldId = "";
    draftVerboseName = "";
    draftDescription = "";
    draftDisplayFormat = "";
    resetFieldMessage(fieldId);
  }

  function getSourceLabel(sourceId) {
    const source = (semanticSources || []).find((item) => item.source_id === sourceId);
    if (!source) {
      return $t.dataset_review?.semantics?.unknown_source;
    }
    return `${source.display_name} • ${source.source_version}`;
  }

  function getCandidateStatusLabel(status) {
    const normalized = String(status || "pending");
    return $t.dataset_review?.semantics?.candidate_status?.[normalized] || normalized;
  }

  function getProvenanceLabel(provenance) {
    const normalized = String(provenance || "unresolved");
    return $t.dataset_review?.semantics?.provenance?.[normalized] || normalized;
  }

  function getConfidenceLabel(rank) {
    if (rank === null || rank === undefined) {
      return $t.dataset_review?.semantics?.confidence_unset;
    }
    return `${$t.dataset_review?.semantics?.confidence_rank_label} #${rank}`;
  }

  function getCurrentValueSummary(field) {
    const parts = [
      field.verbose_name || $t.dataset_review?.semantics?.empty_value,
      field.description || "",
      field.display_format || "",
    ].filter(Boolean);
    return parts.join(" • ");
  }

  async function persistFieldSemantic(fieldId, payload, successKey) {
    if (!sessionId || !fieldId || savingFieldId) {
      return;
    }

    savingFieldId = fieldId;
    updateFieldMessage(fieldId, { status: "saving", text: "" });

    try {
      const updatedField = await requestApi(
        `/dataset-orchestration/sessions/${sessionId}/fields/${fieldId}/semantic`,
        "PATCH",
        payload,
      );
      updateFieldMessage(fieldId, {
        status: "success",
        text: $t.dataset_review?.semantics?.messages?.[successKey],
      });
      if (editingFieldId === fieldId) {
        editingFieldId = "";
      }
      onupdated(updatedField);
    } catch (error) {
      updateFieldMessage(fieldId, {
        status: "error",
        text:
          error?.message ||
          $t.dataset_review?.semantics?.messages?.save_failed ||
          $t.common?.error,
      });
    } finally {
      savingFieldId = "";
    }
  }

  async function acceptCandidate(field, candidateId, lockField) {
    await persistFieldSemantic(
      field.field_id,
      {
        candidate_id: candidateId,
        lock_field: lockField,
      },
      lockField ? "candidate_locked" : "candidate_applied",
    );
  }

  async function saveManualOverride(field) {
    const payload = {
      verbose_name: draftVerboseName.trim() || null,
      description: draftDescription.trim() || null,
      display_format: draftDisplayFormat.trim() || null,
      lock_field: true,
    };
    const hasManualValue =
      payload.verbose_name || payload.description || payload.display_format;

    if (!hasManualValue) {
      updateFieldMessage(field.field_id, {
        status: "error",
        text: $t.dataset_review?.semantics?.messages?.manual_override_required,
      });
      return;
    }

    await persistFieldSemantic(field.field_id, payload, "manual_saved");
  }

  async function mutateLock(field, action) {
    if (!sessionId || !field?.field_id || savingFieldId) {
      return;
    }

    savingFieldId = field.field_id;
    updateFieldMessage(field.field_id, { status: "saving", text: "" });

    try {
      const updatedField = await requestApi(
        `/dataset-orchestration/sessions/${sessionId}/fields/${field.field_id}/${action}`,
        "POST",
      );
      updateFieldMessage(field.field_id, {
        status: "success",
        text:
          action === "lock"
            ? $t.dataset_review?.semantics?.messages?.locked
            : $t.dataset_review?.semantics?.messages?.unlocked,
      });
      onupdated(updatedField);
    } catch (error) {
      updateFieldMessage(field.field_id, {
        status: "error",
        text:
          error?.message ||
          $t.dataset_review?.semantics?.messages?.save_failed ||
          $t.common?.error,
      });
    } finally {
      savingFieldId = "";
    }
  }

  async function approveAllCandidates() {
    if (!sessionId || batchSaving) {
      return;
    }

    const items = sortedFields
      .filter((field) => !field.is_locked && field.candidates?.length)
      .map((field) => ({
        field_id: field.field_id,
        candidate_id: field.candidates[0].candidate_id,
        lock_field: false,
      }));
    if (!items.length) {
      return;
    }

    batchSaving = true;
    try {
      const updatedFields = await requestApi(
        `/dataset-orchestration/sessions/${sessionId}/fields/semantic/approve-batch`,
        "POST",
        { items },
      );
      onupdated({ fields: updatedFields });
    } catch (error) {
      const message =
        error?.message ||
        $t.dataset_review?.semantics?.messages?.save_failed ||
        $t.common?.error;
      for (const item of items) {
        updateFieldMessage(item.field_id, { status: "error", text: message });
      }
    } finally {
      batchSaving = false;
    }
  }

  async function recordFeedback(fieldId, feedback) {
    if (!sessionId || !fieldId || savingFieldId) {
      return;
    }

    savingFieldId = fieldId;
    updateFieldMessage(fieldId, { status: "saving", text: "" });

    try {
      await requestApi(
        `/dataset-orchestration/sessions/${sessionId}/fields/${fieldId}/feedback`,
        "POST",
        { feedback },
      );
      updateFieldMessage(fieldId, {
        status: "success",
        text:
          feedback === "up"
            ? $t.dataset_review?.semantics?.messages?.feedback_up
            : $t.dataset_review?.semantics?.messages?.feedback_down,
      });
    } catch (error) {
      updateFieldMessage(fieldId, {
        status: "error",
        text:
          error?.message ||
          $t.dataset_review?.semantics?.messages?.save_failed ||
          $t.common?.error,
      });
    } finally {
      savingFieldId = "";
    }
  }
</script>

<section id="semantics" class="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm">
  <div class="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
    <div>
      <p class="text-xs font-semibold uppercase tracking-wide text-slate-500">
        {$t.dataset_review?.semantics?.eyebrow}
      </p>
      <h2 class="text-xl font-semibold text-slate-900">
        {$t.dataset_review?.semantics?.title}
      </h2>
      <p class="mt-1 max-w-3xl text-sm text-slate-600">
        {$t.dataset_review?.semantics?.description}
      </p>
    </div>

    <div class="flex flex-col items-end gap-2">
      <div class="rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-right">
        <div class="text-xs uppercase tracking-wide text-slate-500">
          {$t.dataset_review?.semantics?.field_count_label}
        </div>
        <div class="mt-1 text-sm font-medium text-slate-900">{activeFieldCount}</div>
      </div>
      <button
        type="button"
        class="inline-flex items-center justify-center rounded-xl border border-slate-300 px-4 py-2 text-sm font-medium text-slate-700 transition hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-50"
        onclick={approveAllCandidates}
        disabled={disabled || batchSaving || activeFieldCount === 0}
      >
        {$t.dataset_review?.semantics?.approve_all_action}
      </button>
    </div>
  </div>

  {#if activeFieldCount === 0}
    <div class="mt-5 rounded-xl border border-slate-200 bg-slate-50 px-4 py-4 text-sm text-slate-600">
      {$t.dataset_review?.semantics?.empty}
    </div>
  {:else}
    <div class="mt-5 space-y-4">
      {#each sortedFields as field}
        {@const message = fieldMessages[field.field_id] || { status: "", text: "" }}
        {@const isEditing = editingFieldId === field.field_id}
        {@const isSaving = savingFieldId === field.field_id}

        <article
          class={`rounded-2xl border p-4 shadow-sm ${
            field.has_conflict || field.needs_review
              ? "border-amber-200 bg-amber-50"
              : "border-slate-200 bg-white"
          }`}
        >
          <div class="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
            <div class="min-w-0 flex-1">
              <div class="flex flex-wrap items-center gap-2">
                <h3 class="text-base font-semibold text-slate-900">{field.field_name}</h3>
                <span class="rounded-full bg-slate-100 px-2 py-0.5 text-xs text-slate-700">
                  {field.field_kind}
                </span>
                <span
                  class={`rounded-full px-2 py-0.5 text-xs ${
                    field.is_locked
                      ? "bg-blue-100 text-blue-700"
                      : "bg-slate-100 text-slate-700"
                  }`}
                >
                  {field.is_locked
                    ? $t.dataset_review?.semantics?.locked_badge
                    : $t.dataset_review?.semantics?.unlocked_badge}
                </span>
                {#if field.has_conflict}
                  <span class="rounded-full bg-amber-100 px-2 py-0.5 text-xs text-amber-800">
                    {$t.dataset_review?.semantics?.conflict_badge}
                  </span>
                {/if}
                {#if field.needs_review}
                  <span class="rounded-full bg-amber-100 px-2 py-0.5 text-xs text-amber-800">
                    {$t.dataset_review?.semantics?.needs_review_badge}
                  </span>
                {/if}
              </div>

              <div class="mt-3 rounded-xl border border-slate-200 bg-slate-50 p-3">
                <div class="text-xs uppercase tracking-wide text-slate-500">
                  {$t.dataset_review?.semantics?.active_value_label}
                </div>
                <div class="mt-1 text-sm font-medium text-slate-900">
                  {getCurrentValueSummary(field)}
                </div>
                <div class="mt-2 flex flex-wrap gap-2 text-xs text-slate-600">
                  <span class="rounded-full bg-white px-2 py-1">
                    {$t.dataset_review?.semantics?.provenance_label}:
                    {getProvenanceLabel(field.provenance)}
                  </span>
                  <span class="rounded-full bg-white px-2 py-1">
                    {$t.dataset_review?.semantics?.confidence_label}:
                    {getConfidenceLabel(field.confidence_rank)}
                  </span>
                  {#if field.source_id}
                    <span class="rounded-full bg-white px-2 py-1">
                      {$t.dataset_review?.semantics?.source_label}: {getSourceLabel(field.source_id)}
                    </span>
                  {/if}
                  <span class="rounded-full bg-white px-2 py-1">
                    {$t.dataset_review?.semantics?.changed_by_label}: {field.last_changed_by}
                  </span>
                </div>
              </div>

              {#if isEditing}
                <div class="mt-4 grid gap-3">
                  <label class="space-y-1">
                    <span class="text-sm font-medium text-slate-700">
                      {$t.dataset_review?.semantics?.manual_verbose_name_label}
                    </span>
                    <input
                      class="w-full rounded-xl border border-slate-300 bg-white px-3 py-2 text-sm text-slate-900 shadow-sm outline-none transition focus:border-blue-500 focus:ring-2 focus:ring-blue-200"
                      bind:value={draftVerboseName}
                      disabled={isSaving || disabled}
                    />
                  </label>

                  <label class="space-y-1">
                    <span class="text-sm font-medium text-slate-700">
                      {$t.dataset_review?.semantics?.manual_description_label}
                    </span>
                    <textarea
                      class="min-h-24 w-full rounded-xl border border-slate-300 bg-white px-3 py-2 text-sm text-slate-900 shadow-sm outline-none transition focus:border-blue-500 focus:ring-2 focus:ring-blue-200"
                      bind:value={draftDescription}
                      disabled={isSaving || disabled}
                    ></textarea>
                  </label>

                  <label class="space-y-1">
                    <span class="text-sm font-medium text-slate-700">
                      {$t.dataset_review?.semantics?.manual_display_format_label}
                    </span>
                    <input
                      class="w-full rounded-xl border border-slate-300 bg-white px-3 py-2 text-sm text-slate-900 shadow-sm outline-none transition focus:border-blue-500 focus:ring-2 focus:ring-blue-200"
                      bind:value={draftDisplayFormat}
                      disabled={isSaving || disabled}
                    />
                  </label>

                  <div class="flex flex-wrap gap-2">
                    <button
                      type="button"
                      class="inline-flex items-center justify-center rounded-xl bg-blue-600 px-4 py-2 text-sm font-medium text-white transition hover:bg-blue-700 disabled:cursor-not-allowed disabled:bg-slate-300"
                      onclick={() => saveManualOverride(field)}
                      disabled={disabled || isSaving}
                    >
                      {$t.dataset_review?.semantics?.save_manual_action}
                    </button>
                    <button
                      type="button"
                      class="inline-flex items-center justify-center rounded-xl border border-slate-300 px-4 py-2 text-sm font-medium text-slate-700 transition hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-50"
                      onclick={() => cancelManualEdit(field.field_id)}
                      disabled={isSaving}
                    >
                      {$t.common?.cancel}
                    </button>
                  </div>
                </div>
              {/if}

              <div class="mt-4">
                <div class="flex items-center justify-between gap-2">
                  <h4 class="text-sm font-semibold text-slate-900">
                    {$t.dataset_review?.semantics?.candidates_title}
                  </h4>
                  <span class="rounded-full bg-slate-100 px-2.5 py-1 text-xs text-slate-700">
                    {field.candidates?.length || 0}
                  </span>
                </div>

                {#if !field.candidates?.length}
                  <p class="mt-2 text-sm text-slate-600">
                    {$t.dataset_review?.semantics?.candidates_empty}
                  </p>
                {:else}
                  <div class="mt-3 space-y-3">
                    {#each field.candidates as candidate}
                      <div class="rounded-xl border border-slate-200 bg-white p-3">
                        <div class="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
                          <div class="min-w-0 flex-1">
                            <div class="flex flex-wrap items-center gap-2">
                              <div class="text-sm font-medium text-slate-900">
                                {candidate.proposed_verbose_name ||
                                  $t.dataset_review?.semantics?.empty_value}
                              </div>
                              <span class="rounded-full bg-slate-100 px-2 py-0.5 text-xs text-slate-700">
                                {candidate.match_type}
                              </span>
                              <span class="rounded-full bg-slate-100 px-2 py-0.5 text-xs text-slate-700">
                                {$t.dataset_review?.semantics?.score_label}:
                                {candidate.confidence_score}
                              </span>
                              <span class="rounded-full bg-slate-100 px-2 py-0.5 text-xs text-slate-700">
                                {getCandidateStatusLabel(candidate.status)}
                              </span>
                            </div>

                            <p class="mt-2 text-sm text-slate-700">
                              {candidate.proposed_description ||
                                $t.dataset_review?.semantics?.candidate_description_empty}
                            </p>

                            {#if candidate.proposed_display_format}
                              <p class="mt-1 text-xs text-slate-500">
                                {$t.dataset_review?.semantics?.display_format_label}:
                                {candidate.proposed_display_format}
                              </p>
                            {/if}
                          </div>

                          <div class="flex shrink-0 flex-wrap gap-2">
                            <button
                              type="button"
                              class="inline-flex items-center justify-center rounded-lg border border-slate-300 px-3 py-2 text-sm font-medium text-slate-700 transition hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-50"
                              onclick={() => acceptCandidate(field, candidate.candidate_id, false)}
                              disabled={disabled || isSaving}
                            >
                              {$t.dataset_review?.semantics?.apply_candidate_action}
                            </button>
                            <button
                              type="button"
                              class="inline-flex items-center justify-center rounded-lg bg-blue-600 px-3 py-2 text-sm font-medium text-white transition hover:bg-blue-700 disabled:cursor-not-allowed disabled:bg-slate-300"
                              onclick={() => acceptCandidate(field, candidate.candidate_id, true)}
                              disabled={disabled || isSaving}
                            >
                              {$t.dataset_review?.semantics?.apply_and_lock_action}
                            </button>
                          </div>
                        </div>
                      </div>
                    {/each}
                  </div>
                {/if}
              </div>

              {#if message.text || message.status === "saving"}
                <div
                  class={`mt-4 rounded-xl px-3 py-3 text-sm ${
                    message.status === "error"
                      ? "border border-red-200 bg-red-50 text-red-700"
                      : message.status === "saving"
                        ? "border border-blue-200 bg-blue-50 text-blue-700"
                        : "border border-emerald-200 bg-emerald-50 text-emerald-800"
                  }`}
                >
                  {message.status === "saving"
                    ? $t.dataset_review?.semantics?.messages?.saving
                    : message.text}
                </div>
              {/if}
            </div>

            <div class="flex shrink-0 flex-wrap gap-2 lg:w-52 lg:flex-col">
              <button
                type="button"
                class="inline-flex items-center justify-center rounded-xl border border-slate-300 px-4 py-2 text-sm font-medium text-slate-700 transition hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-50"
                onclick={() => startManualEdit(field)}
                disabled={disabled || isSaving}
              >
                {$t.dataset_review?.semantics?.manual_override_action}
              </button>

              <button
                type="button"
                class="inline-flex items-center justify-center rounded-xl border border-slate-300 px-4 py-2 text-sm font-medium text-slate-700 transition hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-50"
                onclick={() => mutateLock(field, field.is_locked ? "unlock" : "lock")}
                disabled={disabled || isSaving}
              >
                {field.is_locked
                  ? $t.dataset_review?.semantics?.unlock_action
                  : $t.dataset_review?.semantics?.lock_action}
              </button>

              <div class="grid grid-cols-2 gap-2">
                <button
                  type="button"
                  class="inline-flex items-center justify-center rounded-xl border border-slate-300 px-3 py-2 text-sm font-medium text-slate-700 transition hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-50"
                  onclick={() => recordFeedback(field.field_id, 'up')}
                  disabled={disabled || isSaving}
                >
                  {$t.dataset_review?.semantics?.feedback_up_action}
                </button>
                <button
                  type="button"
                  class="inline-flex items-center justify-center rounded-xl border border-slate-300 px-3 py-2 text-sm font-medium text-slate-700 transition hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-50"
                  onclick={() => recordFeedback(field.field_id, 'down')}
                  disabled={disabled || isSaving}
                >
                  {$t.dataset_review?.semantics?.feedback_down_action}
                </button>
              </div>
            </div>
          </div>
        </article>
      {/each}
    </div>
  {/if}
</section>

<!-- [/DEF:SemanticLayerReview:Component] -->