<!-- #region AssistantClarificationCard [C:3] [TYPE Component] [SEMANTICS assistant, clarification, question, answer, dataset-review] -->
<!-- @BRIEF Component component: lib/components/assistant/AssistantClarificationCard.svelte -->
<!-- @LAYER UI -->
<!-- @SEMANTICS: assistant, clarification, dataset-review, mixed-initiative, resumable -->
<!-- @PURPOSE: Render the active dataset-review clarification queue inside AssistantChatPanel so users can answer, skip, defer, and resume questions without leaving the assistant workspace. -->
<!-- @LAYER UI -->
<!-- @RELATION CALLS ->[EXT:frontend:api_module] -->
<!-- @RELATION BINDS_TO ->[EXT:frontend:AssistantChatPanel] -->
<!-- @RELATION BINDS_TO ->[DatasetReviewWorkspace] -->
<!-- @PRE: sessionId belongs to the current dataset review workspace and the assistant drawer is open for session-scoped work. -->
<!-- @POST: Clarification queue state is readable in-chat and answer mutations refresh the active question state without requiring a dedicated dialog. -->
<!-- @SIDE_EFFECT: Reads and mutates clarification state through dataset orchestration APIs. -->
<!-- @DATA_CONTRACT: Input[{sessionId, disabled}] -> Output[{clarification_state|clarification_session|current_question|session}] via onupdated callback. -->
<!-- @UX_STATE: Loading -> Clarification queue state is being fetched for the active review session. -->
<!-- @UX_STATE: Question -> One focused question, current guess, and answer actions stay visible inside the assistant drawer. -->
<!-- @UX_STATE: Completed -> No active question remains and resume plus feedback actions stay available. -->
<!-- @UX_FEEDBACK: Save, skip, resume, and feedback results surface inline without hiding the queue context. -->
<!-- @UX_RECOVERY: Users can resume the queue, provide a custom answer, or mark the item for expert review from the same assistant surface. -->
<!-- @UX_REACTIVITY: Uses $props, $state, $derived, and $effect only; no legacy reactive syntax. -->
<script lang="ts">
  import { t } from "$lib/i18n/index.svelte.js";
  import { api, requestApi } from "$lib/api.js";

  let {
    sessionId = "",
    disabled = false,
    visible = true,
    onupdated = () => {},
    onfocus = () => {},
  } = $props();

  let clarificationState = $state(null);
  let loadingState = $state(false);
  let isSaving = $state(false);
  let selectedOptionValue = $state("");
  let customAnswerValue = $state("");
  let localMessage = $state("");
  let localStatus = $state("");
  let lastQuestionId = $state("");
  let feedbackQuestionId = $state("");
  let feedbackQuestionText = $state("");
  let feedbackSaving = $state("");
  let loadVersion = $state(0);
  let lastLoadedKey = $state("");

  const clarificationSession = $derived(clarificationState?.clarification_session || null);
  const currentQuestion = $derived(clarificationState?.current_question || null);
  const hasQuestion = $derived(Boolean(currentQuestion?.question_id));
  const cardState = $derived(
    loadingState ? "Loading" : isSaving ? "Saving" : hasQuestion ? "Question" : clarificationSession ? "Completed" : "Idle",
  );
  const progressLabel = $derived(
    clarificationSession
      ? `${clarificationSession.resolved_count} / ${clarificationSession.resolved_count + clarificationSession.remaining_count}`
      : "0 / 0",
  );
  const fatigueHint = $derived(
    clarificationSession?.remaining_count > 3
      ? "Очередь уточнений длинная: отвечайте по одному вопросу и возвращайтесь к спорным пунктам позже."
      : clarificationSession?.remaining_count > 0
        ? "Следующий вопрос уже приоритизирован. После ответа статус workspace обновится автоматически."
        : "Активных вопросов нет. При необходимости можно возобновить сессию уточнений из ассистента.",
  );

  async function loadClarificationState() {
    if (!sessionId || !visible || loadingState) {
      return;
    }

    const requestVersion = ++loadVersion;
    loadingState = true;

    try {
      const result = await api.fetchApi(`/dataset-orchestration/sessions/${sessionId}/clarification`);
      if (requestVersion !== loadVersion) {
        return;
      }
      clarificationState = result;
      localStatus = "";
      localMessage = "";
    } catch (error) {
      if (requestVersion !== loadVersion) {
        return;
      }
      clarificationState = null;
      localStatus = "error";
      localMessage = error?.message || $t.dataset_review?.clarification?.messages?.resume_failed || $t.common?.error;
    } finally {
      if (requestVersion === loadVersion) {
        loadingState = false;
      }
    }
  }

  function normalizeAnswerValue(answerKind) {
    if (answerKind === "selected") {
      return selectedOptionValue || null;
    }
    if (answerKind === "custom") {
      return customAnswerValue.trim() || null;
    }
    return null;
  }

  function updateClarificationState(result) {
    if (!result) {
      return;
    }

    if (result.clarification_state) {
      clarificationState = result.clarification_state;
    } else if (result.clarification_session || result.current_question !== undefined) {
      clarificationState = result;
    }

    onupdated(result);
  }

  async function submitAnswer(answerKind) {
    if (!sessionId || !currentQuestion?.question_id || isSaving) {
      return;
    }

    const answerValue = normalizeAnswerValue(answerKind);
    if (answerKind === "selected" && !answerValue) {
      localStatus = "error";
      localMessage = $t.dataset_review?.clarification?.messages?.option_required || "Choose one of the suggested answers first.";
      return;
    }
    if (answerKind === "custom" && !answerValue) {
      localStatus = "error";
      localMessage = $t.dataset_review?.clarification?.messages?.custom_required || "Provide a custom answer before saving.";
      return;
    }

    isSaving = true;
    localStatus = "saving";
    localMessage = "";

    try {
      const answeredQuestionId = currentQuestion.question_id;
      const answeredQuestionText = currentQuestion.question_text;
      const result = await requestApi(
        `/dataset-orchestration/sessions/${sessionId}/clarification/answers`,
        "POST",
        {
          question_id: answeredQuestionId,
          answer_kind: answerKind,
          answer_value: answerValue,
        },
      );

      feedbackQuestionId = answeredQuestionId;
      feedbackQuestionText = answeredQuestionText;
      localStatus = "success";
      localMessage =
        answerKind === "skipped"
          ? $t.dataset_review?.clarification?.messages?.skipped || "Clarification question skipped."
          : answerKind === "expert_review"
            ? $t.dataset_review?.clarification?.messages?.expert_review_requested || "Marked for expert review."
            : $t.dataset_review?.clarification?.messages?.saved || "Clarification answer saved.";
      updateClarificationState(result);
    } catch (error) {
      localStatus = "error";
      localMessage = error?.message || $t.dataset_review?.clarification?.messages?.save_failed || $t.common?.error;
    } finally {
      isSaving = false;
    }
  }

  async function resumeClarification() {
    if (!sessionId || isSaving) {
      return;
    }

    isSaving = true;
    localStatus = "saving";
    localMessage = "";

    try {
      const result = await requestApi(
        `/dataset-orchestration/sessions/${sessionId}/clarification/resume`,
        "POST",
      );
      localStatus = "success";
      localMessage = $t.dataset_review?.clarification?.messages?.resumed || "Clarification queue resumed.";
      updateClarificationState(result);
    } catch (error) {
      localStatus = "error";
      localMessage = error?.message || $t.dataset_review?.clarification?.messages?.resume_failed || $t.common?.error;
    } finally {
      isSaving = false;
    }
  }

  async function recordClarificationFeedback(feedback) {
    if (!sessionId || !feedbackQuestionId || isSaving || feedbackSaving) {
      return;
    }

    feedbackSaving = feedback;
    localStatus = "saving";
    localMessage = "";

    try {
      await requestApi(
        `/dataset-orchestration/sessions/${sessionId}/clarification/questions/${feedbackQuestionId}/feedback`,
        "POST",
        { feedback },
      );
      localStatus = "success";
      localMessage =
        feedback === "up"
          ? $t.dataset_review?.clarification?.messages?.feedback_up || "Positive clarification feedback recorded."
          : $t.dataset_review?.clarification?.messages?.feedback_down || "Negative clarification feedback recorded.";
    } catch (error) {
      localStatus = "error";
      localMessage = error?.message || $t.dataset_review?.clarification?.messages?.feedback_failed || $t.common?.error;
    } finally {
      feedbackSaving = "";
    }
  }

  $effect(() => {
    if (!sessionId || !visible) {
      clarificationState = null;
      loadingState = false;
      lastLoadedKey = "";
      return;
    }

    const nextKey = `${sessionId}:${visible}`;
    if (nextKey === lastLoadedKey) {
      return;
    }
    lastLoadedKey = nextKey;
    void loadClarificationState();
  });

  $effect(() => {
    const questionId = currentQuestion?.question_id || "";
    if (questionId === lastQuestionId) {
      return;
    }

    lastQuestionId = questionId;
    if (!questionId) {
      selectedOptionValue = "";
      customAnswerValue = "";
      onfocus({ target: "clarification", source: "assistant_clarification" });
      return;
    }

    const recommendedOption = (currentQuestion?.options || []).find((option) => option.is_recommended);
    selectedOptionValue = recommendedOption?.value || "";
    customAnswerValue = "";
    onfocus({ target: `clarification:${questionId}`, source: "assistant_clarification" });
  });
</script>

{#if visible && sessionId}
  <section class="mx-3 mt-3 rounded-2xl border border-violet-200 bg-violet-50 p-3 text-xs text-violet-900">
    <div class="flex items-start justify-between gap-3">
      <div>
        <div class="font-semibold">{$t.dataset_review?.clarification?.title || "Clarification queue"}</div>
        <div class="mt-1 text-violet-700">{fatigueHint}</div>
      </div>
      <div class="rounded-xl border border-violet-200 bg-white px-2.5 py-1.5 text-right">
        <div class="uppercase tracking-wide text-[10px] text-violet-500">
          {$t.dataset_review?.clarification?.progress_label || "Progress"}
        </div>
        <div class="mt-1 text-[11px] font-semibold text-slate-900">{progressLabel}</div>
        <div class="mt-1 text-[10px] text-violet-700">{cardState}</div>
      </div>
    </div>

    {#if loadingState}
      <div class="mt-3 rounded-xl border border-violet-200 bg-white px-3 py-3 text-violet-700">
        {$t.dataset_review?.clarification?.messages?.saving || "Loading clarification state..."}
      </div>
    {:else if hasQuestion}
      <div
        class="mt-3 rounded-xl border border-violet-200 bg-white p-3"
        data-focus-target={`clarification:${currentQuestion.question_id}`}
      >
        <div class="text-[11px] font-semibold uppercase tracking-wide text-violet-600">
          {$t.dataset_review?.clarification?.active_question_label || "Active question"}
        </div>
        <div class="mt-1 text-sm font-semibold text-slate-900">{currentQuestion.question_text}</div>

        <div class="mt-3 rounded-xl border border-slate-200 bg-slate-50 p-3 text-slate-700">
          <div class="text-[10px] uppercase tracking-wide text-slate-500">
            {$t.dataset_review?.clarification?.why_it_matters_label || "Why it matters"}
          </div>
          <div class="mt-1 text-xs leading-5">{currentQuestion.why_it_matters}</div>
        </div>

        <div class="mt-3 grid gap-3 sm:grid-cols-2">
          <div class="rounded-xl border border-slate-200 bg-slate-50 p-3 text-slate-700">
            <div class="text-[10px] uppercase tracking-wide text-slate-500">
              {$t.dataset_review?.clarification?.current_guess_label || "Current guess"}
            </div>
            <div class="mt-1 text-xs leading-5">
              {currentQuestion.current_guess || $t.dataset_review?.clarification?.current_guess_empty || "No current guess"}
            </div>
          </div>
          <div class="rounded-xl border border-slate-200 bg-slate-50 p-3 text-slate-700">
            <div class="text-[10px] uppercase tracking-wide text-slate-500">
              {$t.dataset_review?.clarification?.topic_label || "Topic"}
            </div>
            <div class="mt-1 text-xs leading-5">{currentQuestion.topic_ref}</div>
          </div>
        </div>

        <div class="mt-3 space-y-2">
          {#each currentQuestion.options || [] as option}
            <label class={`flex cursor-pointer items-start gap-2 rounded-xl border px-3 py-2 transition ${selectedOptionValue === option.value ? "border-violet-300 bg-violet-50 text-slate-900" : "border-slate-200 bg-white text-slate-700"}`}>
              <input
                type="radio"
                name="assistant-clarification-option"
                value={option.value}
                checked={selectedOptionValue === option.value}
                onchange={() => {
                  selectedOptionValue = option.value;
                  localMessage = "";
                  localStatus = "";
                }}
                disabled={disabled || isSaving}
              />
              <div class="min-w-0 flex-1">
                <div class="flex flex-wrap items-center gap-2">
                  <span class="text-xs font-medium">{option.label}</span>
                  {#if option.is_recommended}
                    <span class="rounded-full bg-violet-100 px-2 py-0.5 text-[10px] text-violet-700">
                      {$t.dataset_review?.clarification?.recommended_badge || "Recommended"}
                    </span>
                  {/if}
                </div>
                <div class="mt-1 text-[11px] text-slate-500">{option.value}</div>
              </div>
            </label>
          {/each}
        </div>

        <label class="mt-3 block space-y-1">
          <span class="text-xs font-medium text-slate-700">
            {$t.dataset_review?.clarification?.custom_answer_label || "Custom answer"}
          </span>
          <textarea
            class="min-h-20 w-full rounded-xl border border-slate-300 bg-white px-3 py-2 text-xs text-slate-900 shadow-sm outline-none transition focus:border-violet-500 focus:ring-2 focus:ring-violet-200"
            bind:value={customAnswerValue}
            disabled={disabled || isSaving}
          ></textarea>
        </label>

        <div class="mt-3 grid grid-cols-2 gap-2">
          <button type="button" class="rounded-xl bg-violet-600 px-3 py-2 text-xs font-medium text-white transition hover:bg-violet-700 disabled:cursor-not-allowed disabled:bg-slate-300" onclick={() => submitAnswer("selected")} disabled={disabled || isSaving}>
            {$t.dataset_review?.clarification?.answer_action || "Answer"}
          </button>
          <button type="button" class="rounded-xl border border-slate-300 bg-white px-3 py-2 text-xs font-medium text-slate-700 transition hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-50" onclick={() => submitAnswer("custom")} disabled={disabled || isSaving}>
            {$t.dataset_review?.clarification?.custom_answer_action || "Use custom answer"}
          </button>
          <button type="button" class="rounded-xl border border-slate-300 bg-white px-3 py-2 text-xs font-medium text-slate-700 transition hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-50" onclick={() => submitAnswer("skipped")} disabled={disabled || isSaving}>
            {$t.dataset_review?.clarification?.skip_action || "Skip"}
          </button>
          <button type="button" class="rounded-xl border border-amber-300 bg-white px-3 py-2 text-xs font-medium text-amber-800 transition hover:bg-amber-50 disabled:cursor-not-allowed disabled:opacity-50" onclick={() => submitAnswer("expert_review")} disabled={disabled || isSaving}>
            {$t.dataset_review?.clarification?.expert_review_action || "Expert review"}
          </button>
        </div>
      </div>
    {:else if clarificationSession}
      <div class="mt-3 rounded-xl border border-emerald-200 bg-white px-3 py-3 text-emerald-800" data-focus-target="clarification">
        <div class="text-sm font-semibold">{$t.dataset_review?.clarification?.completed || "No active clarification question remains."}</div>
        <div class="mt-2 flex flex-wrap gap-2">
          <button type="button" class="rounded-xl border border-slate-300 bg-white px-3 py-2 text-xs font-medium text-slate-700 transition hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-50" onclick={resumeClarification} disabled={disabled || isSaving}>
            {$t.dataset_review?.clarification?.resume_action || "Resume clarification"}
          </button>
        </div>
      </div>
    {/if}

    {#if feedbackQuestionId}
      <div class="mt-3 rounded-xl border border-slate-200 bg-white p-3 text-slate-700">
        <div class="text-[10px] uppercase tracking-wide text-slate-500">
          {$t.dataset_review?.clarification?.feedback_label || "Feedback"}
        </div>
        <div class="mt-1 text-xs leading-5">
          {feedbackQuestionText || $t.dataset_review?.clarification?.feedback_prompt || "Record whether the clarification result was useful."}
        </div>
        <div class="mt-3 grid grid-cols-2 gap-2">
          <button type="button" class="rounded-xl border border-slate-300 bg-white px-3 py-2 text-xs font-medium text-slate-700 transition hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-50" onclick={() => recordClarificationFeedback("up")} disabled={disabled || isSaving || Boolean(feedbackSaving)}>
            {$t.dataset_review?.clarification?.feedback_up_action || "Thumbs up"}
          </button>
          <button type="button" class="rounded-xl border border-slate-300 bg-white px-3 py-2 text-xs font-medium text-slate-700 transition hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-50" onclick={() => recordClarificationFeedback("down")} disabled={disabled || isSaving || Boolean(feedbackSaving)}>
            {$t.dataset_review?.clarification?.feedback_down_action || "Thumbs down"}
          </button>
        </div>
      </div>
    {/if}

    {#if localMessage || localStatus === "saving"}
      <div class={`mt-3 rounded-xl px-3 py-3 ${localStatus === "error" ? "border border-destructive-light bg-destructive-light text-red-700" : localStatus === "saving" ? "border border-violet-200 bg-violet-100 text-violet-700" : "border border-emerald-200 bg-emerald-50 text-emerald-800"}`}>
        {localStatus === "saving" ? $t.dataset_review?.clarification?.messages?.saving || "Saving clarification answer..." : localMessage}
      </div>
    {/if}
  </section>
{/if}

<!-- #endregion AssistantClarificationCard -->
