<script lang="ts">
  import { invalidateAll } from "$app/navigation";
  import EmailText from "../../../../components/EmailText.svelte";
  import CreateCredentialModal from "../../../../components/CreateCredentialModal.svelte";
  import { credential as credentialApi } from "$lib/optima-api/modules/credentials";
  import type { Credential } from "$lib/optima-api/modules/credentials";
  import type {
    CredentialType,
    CredentialTypeField,
  } from "$lib/optima-api/modules/credentialTypes";
  import type { PermissionMap } from "$lib/permissions";
  import { formatDate } from "../types";
  import { onMount } from "svelte";
  import { clientFetch } from "$lib/client-fetch";

  export let companyId: string;
  export let credentials: Credential[];
  export let credentialTypes: CredentialType[];
  export let accessToken: string | null;
  export let permissions: PermissionMap;
  export let isMobile: boolean;
  export let isCreateCredentialOpen: boolean;

  // Credential actions state
  let openCredMenuId: string | null = null;
  let credToDelete: Credential | null = null;
  let isDeleting = false;
  let deleteError = "";

  // Edit mode state
  let isEditingCredential = false;
  let editCredName = "";
  let editCredNotes = "";
  let editCredFields: Record<string, string> = {};
  let isSavingCredential = false;
  let saveCredError = "";

  // Credentials split-view state
  let selectedCredential: Credential | null = null;
  let credFadeKey = 0;
  let revealedCredFields: Record<string, boolean> = {};
  let loadingCredFields: Record<string, boolean> = {};
  let fetchedSecureValues: Record<string, string> = {};
  let credFieldTimers: Record<string, ReturnType<typeof setTimeout>> = {};

  // Sub-credentials state
  let subCredentials: Credential[] = [];
  let isLoadingSubCreds = false;
  let addingSubCred: string | null = null;
  let newSubCredName = "";
  let newSubCredFields: Record<string, string> = {};
  let isSubmittingSubCred = false;
  let subCredError = "";
  let deletingSubCredId: string | null = null;

  function toggleCredMenu(id: string) {
    openCredMenuId = openCredMenuId === id ? null : id;
  }

  function handleEditCredential(cred: Credential | null) {
    if (!cred) return;
    openCredMenuId = null;
    if (selectedCredential?.id !== cred.id) {
      selectedCredential = cred;
      credFadeKey++;
      revealedCredFields = {};
      loadingCredFields = {};
    }
    editCredName = cred.name;
    editCredNotes = cred.notes ?? "";
    const newFields: Record<string, string> = {};
    cred.fields.forEach((f) => {
      newFields[f.id] = f.secure ? "" : (f.value ?? "");
    });
    editCredFields = newFields;
    saveCredError = "";
    isEditingCredential = true;
  }

  function cancelEditCredential() {
    isEditingCredential = false;
    editCredName = "";
    editCredNotes = "";
    editCredFields = {};
    saveCredError = "";
  }

  async function saveEditCredential() {
    if (!selectedCredential || !accessToken) return;
    isSavingCredential = true;
    saveCredError = "";
    try {
      const updates: { name?: string; notes?: string } = {};
      if (editCredName.trim() !== selectedCredential.name) {
        updates.name = editCredName.trim();
      }
      if (editCredNotes !== (selectedCredential.notes ?? "")) {
        updates.notes = editCredNotes;
      }
      if (Object.keys(updates).length > 0) {
        await credentialApi.update(accessToken, selectedCredential.id, updates);
      }
      const fieldsToUpdate = selectedCredential.fields
        .filter((f) => {
          const newVal = editCredFields[f.id];
          if (f.secure)
            return typeof newVal === "string" && newVal.trim().length > 0;
          return true;
        })
        .map((f) => ({
          fieldId: f.id,
          value: editCredFields[f.id] ?? "",
        }));

      if (fieldsToUpdate.length > 0) {
        await credentialApi.updateFields(
          accessToken,
          selectedCredential.id,
          fieldsToUpdate as unknown as import("$lib/optima-api/modules/credentials").CredentialField[],
        );
      }
      isEditingCredential = false;
      revealedCredFields = {};
      fetchedSecureValues = {};
      await invalidateAll();
      const updated = credentials.find((c) => c.id === selectedCredential?.id);
      if (updated) {
        selectedCredential = updated;
        credFadeKey++;
      }
    } catch (err) {
      saveCredError =
        err instanceof Error ? err.message : "Failed to save changes";
      console.error("Failed to save credential:", err);
    } finally {
      isSavingCredential = false;
    }
  }

  function handleDeleteCredential(cred: Credential | null) {
    if (!cred) return;
    openCredMenuId = null;
    credToDelete = cred;
    deleteError = "";
  }

  function cancelDelete() {
    credToDelete = null;
    deleteError = "";
  }

  async function confirmDelete() {
    if (!credToDelete || !accessToken) return;
    isDeleting = true;
    deleteError = "";
    try {
      await credentialApi.delete(accessToken, credToDelete.id);
      if (selectedCredential?.id === credToDelete.id) {
        selectedCredential = null;
      }
      credToDelete = null;
      await invalidateAll();
    } catch (err) {
      deleteError =
        err instanceof Error ? err.message : "Failed to delete credential";
      console.error("Failed to delete credential:", err);
    } finally {
      isDeleting = false;
    }
  }

  function selectCredential(cred: Credential) {
    if (selectedCredential?.id === cred.id) {
      selectedCredential = null;
      isEditingCredential = false;
      subCredentials = [];
    } else {
      selectedCredential = cred;
      credFadeKey++;
      revealedCredFields = {};
      loadingCredFields = {};
      isEditingCredential = false;
      subCredentials = [];
      cancelAddSubCred();
      Object.values(credFieldTimers).forEach(clearTimeout);
      credFieldTimers = {};
      const hasMultiCredFields = getMultiCredFields(cred).length > 0;
      if (hasMultiCredFields) {
        loadSubCredentials(cred.id);
      }
    }
  }

  function getMultiCredFields(cred: Credential): CredentialTypeField[] {
    const ct = credentialTypes.find((t) => t.id === cred.typeId);
    if (!ct) return [];
    return ct.fields.filter((f) => f.valueType === "multi_credential");
  }

  function subCredKey(subCredId: string, fieldId: string): string {
    return `sc:${subCredId}:${fieldId}`;
  }

  function autoHideCredField(fieldId: string) {
    if (credFieldTimers[fieldId]) clearTimeout(credFieldTimers[fieldId]);
    credFieldTimers[fieldId] = setTimeout(() => {
      revealedCredFields[fieldId] = false;
      revealedCredFields = revealedCredFields;
      delete fetchedSecureValues[fieldId];
      fetchedSecureValues = fetchedSecureValues;
      delete credFieldTimers[fieldId];
    }, 30_000);
  }

  async function toggleCredField(
    credentialId: string,
    fieldId: string,
    isSecure: boolean,
    plaintextValue?: string,
    stateKey?: string,
  ) {
    const key = stateKey ?? fieldId;
    if (revealedCredFields[key]) {
      revealedCredFields[key] = false;
      revealedCredFields = revealedCredFields;
      delete fetchedSecureValues[key];
      fetchedSecureValues = fetchedSecureValues;
      if (credFieldTimers[key]) {
        clearTimeout(credFieldTimers[key]);
        delete credFieldTimers[key];
      }
      return;
    }
    loadingCredFields[key] = true;
    loadingCredFields = loadingCredFields;
    const minDelay = new Promise((r) => setTimeout(r, 500));
    try {
      if (isSecure) {
        const [result] = await Promise.all([
          clientFetch<{ data?: { value?: string } }>(
            `/companies/${companyId}/secure-value?credentialId=${encodeURIComponent(credentialId)}&fieldId=${encodeURIComponent(fieldId)}`,
          ),
          minDelay,
        ]);
        fetchedSecureValues[key] = result?.data?.value ?? "";
      } else {
        await minDelay;
        fetchedSecureValues[key] = plaintextValue ?? "";
      }
      fetchedSecureValues = fetchedSecureValues;
      revealedCredFields[key] = true;
      revealedCredFields = revealedCredFields;
      autoHideCredField(key);
    } catch (err) {
      console.error("Failed to fetch secure value:", err);
      fetchedSecureValues[key] = "Error loading value";
      fetchedSecureValues = fetchedSecureValues;
      revealedCredFields[key] = true;
      revealedCredFields = revealedCredFields;
    } finally {
      loadingCredFields[key] = false;
      loadingCredFields = loadingCredFields;
    }
  }

  async function loadSubCredentials(credentialId: string) {
    if (!accessToken) return;
    isLoadingSubCreds = true;
    try {
      const result = await credentialApi.fetchSubCredentials(
        accessToken,
        credentialId,
      );
      subCredentials = result?.data ?? [];
    } catch (err) {
      console.error("Failed to fetch sub-credentials:", err);
      subCredentials = [];
    } finally {
      isLoadingSubCreds = false;
    }
  }

  function openAddSubCred(fieldId: string, subFields: CredentialTypeField[]) {
    addingSubCred = fieldId;
    newSubCredName = "";
    newSubCredFields = {};
    subCredError = "";
    (subFields ?? []).forEach((sf) => {
      newSubCredFields[sf.id] = "";
    });
  }

  function cancelAddSubCred() {
    addingSubCred = null;
    newSubCredName = "";
    newSubCredFields = {};
    subCredError = "";
  }

  async function submitSubCred(fieldId: string) {
    if (!selectedCredential || !accessToken || !newSubCredName.trim()) return;
    isSubmittingSubCred = true;
    subCredError = "";
    try {
      await credentialApi.addSubCredential(accessToken, selectedCredential.id, {
        fieldId,
        name: newSubCredName.trim(),
        fields: Object.entries(newSubCredFields).map(([fid, val]) => ({
          fieldId: fid,
          value: val,
        })),
      });
      cancelAddSubCred();
      await loadSubCredentials(selectedCredential.id);
    } catch (err) {
      subCredError =
        err instanceof Error ? err.message : "Failed to add sub-credential";
      console.error("Failed to add sub-credential:", err);
    } finally {
      isSubmittingSubCred = false;
    }
  }

  async function deleteSubCred(subId: string) {
    if (!selectedCredential || !accessToken) return;
    deletingSubCredId = subId;
    try {
      await credentialApi.removeSubCredential(
        accessToken,
        selectedCredential.id,
        subId,
      );
      await loadSubCredentials(selectedCredential.id);
    } catch (err) {
      console.error("Failed to delete sub-credential:", err);
    } finally {
      deletingSubCredId = null;
    }
  }
</script>

<svelte:window
  on:click={() => {
    openCredMenuId = null;
  }}
/>

<CreateCredentialModal
  bind:isOpen={isCreateCredentialOpen}
  {companyId}
  accessToken={accessToken ?? ""}
  {credentialTypes}
  onSuccess={() => {
    isCreateCredentialOpen = false;
    invalidateAll();
  }}
/>

<!-- Delete confirmation dialog -->
{#if credToDelete}
  <!-- svelte-ignore a11y_no_static_element_interactions -->
  <!-- svelte-ignore a11y_click_events_have_key_events -->
  <div class="delete-overlay" on:click={cancelDelete}>
    <!-- svelte-ignore a11y_no_static_element_interactions -->
    <!-- svelte-ignore a11y_click_events_have_key_events -->
    <div class="delete-dialog" on:click|stopPropagation>
      <div class="delete-dialog-icon">
        <svg
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="2"
          width="28"
          height="28"
        >
          <polyline points="3 6 5 6 21 6" />
          <path d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6" />
          <path d="M10 11v6M14 11v6" />
          <path d="M9 6V4a1 1 0 011-1h4a1 1 0 011 1v2" />
        </svg>
      </div>
      <h3 class="delete-dialog-title">Delete Credential</h3>
      <p class="delete-dialog-msg">
        Are you sure you want to delete
        <strong>{credToDelete.name}</strong>? This action cannot be undone.
      </p>
      {#if deleteError}
        <p class="delete-dialog-error">{deleteError}</p>
      {/if}
      <div class="delete-dialog-actions">
        <button
          type="button"
          class="delete-dialog-btn cancel"
          on:click={cancelDelete}
          disabled={isDeleting}
        >
          Cancel
        </button>
        <button
          type="button"
          class="delete-dialog-btn confirm"
          on:click={confirmDelete}
          disabled={isDeleting}
        >
          {#if isDeleting}
            Deleting…
          {:else}
            Delete
          {/if}
        </button>
      </div>
    </div>
  </div>
{/if}

{#if credentials.length === 0}
  <div class="tab-empty">
    <svg
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      stroke-width="1.5"
      class="tab-empty-icon"
    >
      <rect x="3" y="11" width="18" height="11" rx="2" ry="2" />
      <path d="M7 11V7a5 5 0 0 1 10 0v4" />
    </svg>
    <p>No credentials found for this company</p>
    <button
      type="button"
      class="create-credential-btn"
      on:click={() => (isCreateCredentialOpen = true)}
    >
      <svg
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="2"
        width="14"
        height="14"
      >
        <line x1="12" y1="5" x2="12" y2="19" />
        <line x1="5" y1="12" x2="19" y2="12" />
      </svg>
      Create Credential
    </button>
  </div>
{:else}
  <div
    class="config-split"
    class:expanded={selectedCredential !== null && !isMobile}
  >
    <!-- Left side: credential buttons -->
    <div
      class="config-list"
      class:collapsed={selectedCredential !== null && !isMobile}
    >
      {#each credentials as cred (cred.id)}
        <!-- svelte-ignore a11y_no_static_element_interactions -->
        <div
          class="config-item"
          class:selected={selectedCredential?.id === cred.id}
          on:click={() => selectCredential(cred)}
          on:keydown={(e) => e.key === "Enter" && selectCredential(cred)}
          role="button"
          tabindex="0"
        >
          <div class="config-item-header">
            <div class="config-name-group">
              <span class="config-status-dot dot-active" title="Active"></span>
              <span class="config-name">{cred.name}</span>
            </div>
            <div class="config-header-badges">
              {#if cred.type?.name && (!selectedCredential || isMobile)}
                <span class="config-type-badge">{cred.type.name}</span>
              {/if}
              {#if !selectedCredential || isMobile}
                <div class="cred-menu-wrap">
                  <button
                    type="button"
                    class="cred-menu-btn"
                    aria-label="Credential actions"
                    on:click|stopPropagation={() => toggleCredMenu(cred.id)}
                  >
                    <svg
                      viewBox="0 0 16 16"
                      fill="currentColor"
                      width="14"
                      height="14"
                    >
                      <circle cx="8" cy="2.5" r="1.5" />
                      <circle cx="8" cy="8" r="1.5" />
                      <circle cx="8" cy="13.5" r="1.5" />
                    </svg>
                  </button>
                  {#if openCredMenuId === cred.id}
                    <!-- svelte-ignore a11y_no_static_element_interactions -->
                    <!-- svelte-ignore a11y_click_events_have_key_events -->
                    <div class="cred-dropdown-menu" on:click|stopPropagation>
                      <button
                        type="button"
                        class="cred-dropdown-item"
                        on:click|stopPropagation={() =>
                          handleEditCredential(cred)}
                      >
                        <svg
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                          width="13"
                          height="13"
                        >
                          <path
                            d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"
                          />
                          <path
                            d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z"
                          />
                        </svg>
                        Edit
                      </button>
                      <div class="cred-dropdown-sep"></div>
                      <button
                        type="button"
                        class="cred-dropdown-item cred-dropdown-item-danger"
                        on:click|stopPropagation={() =>
                          handleDeleteCredential(cred)}
                      >
                        <svg
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                          width="13"
                          height="13"
                        >
                          <polyline points="3 6 5 6 21 6" />
                          <path
                            d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6"
                          />
                          <path d="M10 11v6M14 11v6" />
                          <path d="M9 6V4a1 1 0 011-1h4a1 1 0 011 1v2" />
                        </svg>
                        Delete
                      </button>
                    </div>
                  {/if}
                </div>
              {/if}
            </div>
          </div>
          {#if !selectedCredential || isMobile}
            {#if cred.type?.name}
              <p class="config-description">{cred.type.name}</p>
            {/if}
            {#if cred.fields.length > 0}
              <span class="config-date">
                {cred.fields.length} field{cred.fields.length === 1 ? "" : "s"}
              </span>
            {/if}
            {#if formatDate(cred.updatedAt) || formatDate(cred.createdAt)}
              <span class="config-date">
                {#if formatDate(cred.updatedAt)}
                  Updated {formatDate(cred.updatedAt)}
                {:else}
                  Created {formatDate(cred.createdAt)}
                {/if}
              </span>
            {/if}
          {/if}
        </div>
      {/each}
    </div>

    <!-- Right side: credential detail panel -->
    {#if selectedCredential}
      <!-- svelte-ignore a11y_no_static_element_interactions -->
      <!-- svelte-ignore a11y_click_events_have_key_events -->
      <div
        class="bottom-sheet-overlay"
        class:active={selectedCredential !== null}
        on:click={() => {
          selectedCredential = null;
          isEditingCredential = false;
        }}
      >
        <!-- svelte-ignore a11y_no_static_element_interactions -->
        <!-- svelte-ignore a11y_click_events_have_key_events -->
        <div class="bottom-sheet-panel" on:click|stopPropagation>
          <div class="bottom-sheet-handle"></div>
          <div class="bottom-sheet-body">
            <div class="config-detail-panel">
              {#key credFadeKey}
                <div class="config-detail-content">
                  <div class="config-detail-header">
                    <div class="config-detail-header-left">
                      {#if isEditingCredential}
                        <input
                          class="cred-edit-name-input"
                          type="text"
                          bind:value={editCredName}
                          placeholder="Credential name"
                        />
                      {:else}
                        <h3 class="config-detail-title">
                          {selectedCredential.name}
                        </h3>
                      {/if}
                      <div class="config-detail-meta-badges">
                        {#if selectedCredential.type?.name}
                          <span class="config-badge type">
                            {selectedCredential.type.name}
                          </span>
                        {/if}
                      </div>
                    </div>
                    <div class="config-detail-header-actions">
                      {#if isEditingCredential}
                        <button
                          class="cred-action-btn cred-action-save"
                          on:click={saveEditCredential}
                          disabled={isSavingCredential || !editCredName.trim()}
                          aria-label="Save changes"
                          type="button"
                          title="Save changes"
                        >
                          {#if isSavingCredential}
                            <svg
                              viewBox="0 0 24 24"
                              width="14"
                              height="14"
                              class="spin-icon"
                            >
                              <circle
                                cx="12"
                                cy="12"
                                r="10"
                                stroke="currentColor"
                                stroke-width="3"
                                fill="none"
                                opacity="0.25"
                              />
                              <path
                                d="M12 2a10 10 0 0 1 10 10"
                                stroke="currentColor"
                                stroke-width="3"
                                fill="none"
                                stroke-linecap="round"
                              />
                            </svg>
                          {:else}
                            <svg
                              viewBox="0 0 24 24"
                              fill="none"
                              stroke="currentColor"
                              stroke-width="2"
                              width="14"
                              height="14"
                            >
                              <polyline points="20 6 9 17 4 12" />
                            </svg>
                          {/if}
                        </button>
                      {:else}
                        <button
                          class="cred-action-btn cred-action-edit"
                          on:click={() =>
                            handleEditCredential(selectedCredential)}
                          aria-label="Edit credential"
                          type="button"
                          title="Edit credential"
                        >
                          <svg
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            stroke-width="2"
                            width="14"
                            height="14"
                          >
                            <path
                              d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"
                            />
                            <path
                              d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z"
                            />
                          </svg>
                        </button>
                        <button
                          class="cred-action-btn cred-action-delete"
                          on:click={() =>
                            handleDeleteCredential(selectedCredential)}
                          aria-label="Delete credential"
                          type="button"
                          title="Delete credential"
                        >
                          <svg
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            stroke-width="2"
                            width="14"
                            height="14"
                          >
                            <polyline points="3 6 5 6 21 6" />
                            <path
                              d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6"
                            />
                            <path d="M10 11v6M14 11v6" />
                            <path d="M9 6V4a1 1 0 011-1h4a1 1 0 011 1v2" />
                          </svg>
                        </button>
                      {/if}
                      <button
                        class="config-detail-close"
                        on:click={() => {
                          if (isEditingCredential) {
                            cancelEditCredential();
                          } else {
                            selectedCredential = null;
                          }
                        }}
                        aria-label={isEditingCredential
                          ? "Cancel editing"
                          : "Close detail view"}
                        type="button"
                      >
                        <svg
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                          width="16"
                          height="16"
                        >
                          <path d="M18 6L6 18M6 6l12 12" />
                        </svg>
                      </button>
                    </div>
                  </div>

                  <!-- Credential fields -->
                  {#if (selectedCredential.fields && selectedCredential.fields.length > 0) || isEditingCredential || selectedCredential.notes}
                    <div class="config-questions">
                      <!-- Notes -->
                      {#if isEditingCredential || selectedCredential.notes}
                        <div class="cred-notes-section">
                          <h4 class="config-section-title">
                            <svg
                              viewBox="0 0 24 24"
                              fill="none"
                              stroke="currentColor"
                              stroke-width="2"
                              width="16"
                              height="16"
                            >
                              <path
                                d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"
                              />
                              <polyline points="14 2 14 8 20 8" />
                              <line x1="16" y1="13" x2="8" y2="13" />
                              <line x1="16" y1="17" x2="8" y2="17" />
                              <polyline points="10 9 9 9 8 9" />
                            </svg>
                            Notes
                          </h4>
                          {#if isEditingCredential}
                            <textarea
                              class="cred-edit-notes-input"
                              bind:value={editCredNotes}
                              placeholder="Add notes…"
                              rows="3"
                            ></textarea>
                          {:else}
                            <p class="cred-notes-text">
                              {selectedCredential.notes}
                            </p>
                          {/if}
                        </div>
                      {/if}
                      <h4 class="config-section-title">
                        <svg
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                          width="16"
                          height="16"
                        >
                          <path
                            d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2"
                          />
                          <rect x="9" y="3" width="6" height="4" rx="1" />
                        </svg>
                        Credential Fields
                      </h4>
                      <div class="questions-grid">
                        {#each selectedCredential.fields as field (field.id)}
                          {#if field.valueType === "multi_credential"}
                            <!-- Skip multi_credential fields in the regular grid -->
                          {:else}
                            <div
                              class="question-row"
                              class:has-answer={!!field.value}
                            >
                              <div class="cred-field-label-row">
                                <span class="question-label">{field.name}</span>
                                {#if field.required && isEditingCredential}
                                  <span
                                    class="cred-required-star"
                                    title="Required">*</span
                                  >
                                {/if}
                                {#if field.secure}
                                  <svg
                                    class="cred-lock-icon"
                                    viewBox="0 0 24 24"
                                    fill="none"
                                    stroke="currentColor"
                                    stroke-width="2"
                                    width="11"
                                    height="11"
                                    aria-label="Secure"
                                  >
                                    <title>Secure</title>
                                    <rect
                                      x="3"
                                      y="11"
                                      width="18"
                                      height="11"
                                      rx="2"
                                      ry="2"
                                    />
                                    <path d="M7 11V7a5 5 0 0 1 10 0v4" />
                                  </svg>
                                {/if}
                              </div>
                              <div class="question-value-wrap">
                                {#if isEditingCredential}
                                  <input
                                    class="cred-edit-field-input"
                                    type={field.valueType === "email"
                                      ? "email"
                                      : field.valueType === "url"
                                        ? "url"
                                        : "text"}
                                    bind:value={editCredFields[field.id]}
                                    placeholder={field.secure
                                      ? "Leave blank to keep existing"
                                      : `Enter ${field.name}`}
                                  />
                                {:else if field.secure || field.valueType === "password" || field.valueType === "generic_secret" || field.valueType === "bitlocker_key"}
                                  <span class="question-value password-value">
                                    {#if loadingCredFields[field.id]}
                                      <span
                                        class="cred-secure-spinner"
                                        aria-label="Loading"
                                      >
                                        <svg
                                          viewBox="0 0 24 24"
                                          width="14"
                                          height="14"
                                          class="spin-icon"
                                        >
                                          <circle
                                            cx="12"
                                            cy="12"
                                            r="10"
                                            stroke="currentColor"
                                            stroke-width="3"
                                            fill="none"
                                            opacity="0.25"
                                          />
                                          <path
                                            d="M12 2a10 10 0 0 1 10 10"
                                            stroke="currentColor"
                                            stroke-width="3"
                                            fill="none"
                                            stroke-linecap="round"
                                          />
                                        </svg>
                                      </span>
                                    {:else if revealedCredFields[field.id]}
                                      <span
                                        class="cred-revealed-value {field.valueType ===
                                          'bitlocker_key' ||
                                        field.valueType === 'license_key'
                                          ? 'mono'
                                          : ''}"
                                      >
                                        {fetchedSecureValues[field.id] ||
                                          "—"}</span
                                      >
                                    {:else}
                                      ••••••••
                                    {/if}
                                  </span>
                                  {#if (!field.secure || permissions["credential.secure_values.read"]) && !loadingCredFields[field.id]}
                                    {#if revealedCredFields[field.id]}
                                      <span
                                        class="cred-countdown-wrap"
                                        title="Auto-hides in 30 seconds"
                                      >
                                        <svg
                                          class="cred-countdown-ring"
                                          viewBox="0 0 20 20"
                                          width="20"
                                          height="20"
                                        >
                                          <circle
                                            cx="10"
                                            cy="10"
                                            r="8"
                                            fill="none"
                                            stroke="currentColor"
                                            stroke-width="2"
                                            opacity="0.1"
                                          />
                                          <circle
                                            cx="10"
                                            cy="10"
                                            r="8"
                                            fill="none"
                                            stroke="currentColor"
                                            stroke-width="2"
                                            stroke-linecap="round"
                                            stroke-dasharray="50.265"
                                            stroke-dashoffset="0"
                                            class="cred-countdown-arc"
                                          />
                                        </svg>
                                      </span>
                                    {/if}
                                    <button
                                      class="password-toggle"
                                      on:click={() =>
                                        toggleCredField(
                                          selectedCredential?.id ?? "",
                                          field.id,
                                          field.secure,
                                          field.value,
                                        )}
                                      type="button"
                                      aria-label={revealedCredFields[field.id]
                                        ? "Hide value"
                                        : "Show value"}
                                    >
                                      {#if revealedCredFields[field.id]}
                                        <svg
                                          viewBox="0 0 24 24"
                                          fill="none"
                                          stroke="currentColor"
                                          stroke-width="2"
                                          width="14"
                                          height="14"
                                        >
                                          <path
                                            d="M17.94 17.94A10.07 10.07 0 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94"
                                          />
                                          <path
                                            d="M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19"
                                          />
                                          <path
                                            d="M14.12 14.12a3 3 0 11-4.24-4.24"
                                          />
                                          <line x1="1" y1="1" x2="23" y2="23" />
                                        </svg>
                                      {:else}
                                        <svg
                                          viewBox="0 0 24 24"
                                          fill="none"
                                          stroke="currentColor"
                                          stroke-width="2"
                                          width="14"
                                          height="14"
                                        >
                                          <path
                                            d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"
                                          />
                                          <circle cx="12" cy="12" r="3" />
                                        </svg>
                                      {/if}
                                    </button>
                                  {/if}
                                {:else if field.valueType === "url" && field.value}
                                  <a
                                    class="question-value cred-url-value"
                                    href={field.value}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    on:click|stopPropagation
                                  >
                                    {field.value}
                                  </a>
                                {:else if field.valueType === "email" && field.value}
                                  <EmailText email={field.value} />
                                {:else if field.valueType === "ip_address" && field.value}
                                  <span class="question-value mono"
                                    >{field.value}</span
                                  >
                                {:else if field.valueType === "license_key" && field.value}
                                  <span class="question-value mono"
                                    >{field.value}</span
                                  >
                                {:else}
                                  <span class="question-value"
                                    >{field.value || "—"}</span
                                  >
                                {/if}
                              </div>
                            </div>
                          {/if}
                        {/each}
                      </div>

                      <!-- Sub-credentials for multi_credential fields -->
                      {#if selectedCredential && getMultiCredFields(selectedCredential).length > 0}
                        {#each getMultiCredFields(selectedCredential) as mcField (mcField.id)}
                          <div class="sub-creds-section">
                            <div class="sub-creds-header">
                              <h4 class="sub-creds-title">
                                <svg
                                  viewBox="0 0 24 24"
                                  fill="none"
                                  stroke="currentColor"
                                  stroke-width="2"
                                  width="14"
                                  height="14"
                                >
                                  <rect
                                    x="2"
                                    y="3"
                                    width="20"
                                    height="6"
                                    rx="1"
                                  />
                                  <rect
                                    x="2"
                                    y="15"
                                    width="20"
                                    height="6"
                                    rx="1"
                                  />
                                  <path d="M12 9v6" />
                                </svg>
                                {mcField.name}
                                {#if subCredentials.length > 0}
                                  <span class="sub-creds-count"
                                    >{subCredentials.length}</span
                                  >
                                {/if}
                              </h4>
                              {#if !isEditingCredential && addingSubCred !== mcField.id}
                                <button
                                  type="button"
                                  class="sub-cred-add-btn"
                                  on:click={() =>
                                    openAddSubCred(
                                      mcField.id,
                                      mcField.subFields ?? [],
                                    )}
                                >
                                  <svg
                                    viewBox="0 0 24 24"
                                    fill="none"
                                    stroke="currentColor"
                                    stroke-width="2"
                                    width="12"
                                    height="12"
                                  >
                                    <line x1="12" y1="5" x2="12" y2="19" /><line
                                      x1="5"
                                      y1="12"
                                      x2="19"
                                      y2="12"
                                    />
                                  </svg>
                                  Add
                                </button>
                              {/if}
                            </div>

                            {#if isLoadingSubCreds}
                              <div class="sub-creds-loading">
                                <svg
                                  viewBox="0 0 24 24"
                                  width="14"
                                  height="14"
                                  class="spin-icon"
                                >
                                  <circle
                                    cx="12"
                                    cy="12"
                                    r="10"
                                    stroke="currentColor"
                                    stroke-width="3"
                                    fill="none"
                                    opacity="0.25"
                                  />
                                  <path
                                    d="M12 2a10 10 0 0 1 10 10"
                                    stroke="currentColor"
                                    stroke-width="3"
                                    fill="none"
                                    stroke-linecap="round"
                                  />
                                </svg>
                                <span>Loading…</span>
                              </div>
                            {:else if subCredentials.length === 0 && addingSubCred !== mcField.id}
                              <p class="sub-creds-empty">No entries yet.</p>
                            {:else}
                              <table class="sub-creds-table">
                                <thead>
                                  <tr>
                                    <th>Name</th>
                                    {#each mcField.subFields ?? [] as sf (sf.id)}
                                      <th>
                                        {sf.name}
                                        {#if sf.secure}
                                          <svg
                                            class="cred-lock-icon"
                                            viewBox="0 0 24 24"
                                            fill="none"
                                            stroke="currentColor"
                                            stroke-width="2"
                                            width="9"
                                            height="9"
                                          >
                                            <rect
                                              x="3"
                                              y="11"
                                              width="18"
                                              height="11"
                                              rx="2"
                                              ry="2"
                                            />
                                            <path
                                              d="M7 11V7a5 5 0 0 1 10 0v4"
                                            />
                                          </svg>
                                        {/if}
                                      </th>
                                    {/each}
                                    {#if !isEditingCredential}
                                      <th class="sub-creds-th-actions"></th>
                                    {/if}
                                  </tr>
                                </thead>
                                <tbody>
                                  {#each subCredentials as subCred (subCred.id)}
                                    <tr class="sub-cred-row">
                                      <td class="sub-cred-name-cell"
                                        >{subCred.name}</td
                                      >
                                      {#each subCred.fields as sf (sf.id)}
                                        <td
                                          class:mono={sf.valueType ===
                                            "ip_address" ||
                                            sf.valueType === "license_key"}
                                        >
                                          {#if sf.secure}
                                            <span class="sub-cred-secure-cell">
                                              {#if loadingCredFields[subCredKey(subCred.id, sf.id)]}
                                                <svg
                                                  viewBox="0 0 24 24"
                                                  width="12"
                                                  height="12"
                                                  class="spin-icon sub-cred-spinner"
                                                >
                                                  <circle
                                                    cx="12"
                                                    cy="12"
                                                    r="10"
                                                    stroke="currentColor"
                                                    stroke-width="3"
                                                    fill="none"
                                                    opacity="0.25"
                                                  />
                                                  <path
                                                    d="M12 2a10 10 0 0 1 10 10"
                                                    stroke="currentColor"
                                                    stroke-width="3"
                                                    fill="none"
                                                    stroke-linecap="round"
                                                  />
                                                </svg>
                                              {:else if revealedCredFields[subCredKey(subCred.id, sf.id)]}
                                                <span class="sub-cred-revealed"
                                                  >{fetchedSecureValues[
                                                    subCredKey(
                                                      subCred.id,
                                                      sf.id,
                                                    )
                                                  ] || "—"}</span
                                                >
                                              {:else}
                                                <span class="sub-cred-masked"
                                                  >••••••••</span
                                                >
                                              {/if}
                                              {#if permissions["credential.secure_values.read"] && !loadingCredFields[subCredKey(subCred.id, sf.id)]}
                                                {#if revealedCredFields[subCredKey(subCred.id, sf.id)]}
                                                  <span
                                                    class="cred-countdown-wrap"
                                                    title="Auto-hides in 30 seconds"
                                                  >
                                                    <svg
                                                      class="cred-countdown-ring"
                                                      viewBox="0 0 20 20"
                                                      width="16"
                                                      height="16"
                                                    >
                                                      <circle
                                                        cx="10"
                                                        cy="10"
                                                        r="8"
                                                        fill="none"
                                                        stroke="currentColor"
                                                        stroke-width="2"
                                                        opacity="0.1"
                                                      />
                                                      <circle
                                                        cx="10"
                                                        cy="10"
                                                        r="8"
                                                        fill="none"
                                                        stroke="currentColor"
                                                        stroke-width="2"
                                                        stroke-linecap="round"
                                                        stroke-dasharray="50.265"
                                                        stroke-dashoffset="0"
                                                        class="cred-countdown-arc"
                                                      />
                                                    </svg>
                                                  </span>
                                                {/if}
                                                <button
                                                  type="button"
                                                  class="sub-cred-eye-btn"
                                                  on:click|stopPropagation={() =>
                                                    toggleCredField(
                                                      subCred.id,
                                                      sf.id,
                                                      true,
                                                      undefined,
                                                      subCredKey(
                                                        subCred.id,
                                                        sf.id,
                                                      ),
                                                    )}
                                                  aria-label={revealedCredFields[
                                                    subCredKey(
                                                      subCred.id,
                                                      sf.id,
                                                    )
                                                  ]
                                                    ? "Hide value"
                                                    : "Show value"}
                                                  title={revealedCredFields[
                                                    subCredKey(
                                                      subCred.id,
                                                      sf.id,
                                                    )
                                                  ]
                                                    ? "Hide"
                                                    : "Reveal"}
                                                >
                                                  {#if revealedCredFields[subCredKey(subCred.id, sf.id)]}
                                                    <svg
                                                      viewBox="0 0 24 24"
                                                      fill="none"
                                                      stroke="currentColor"
                                                      stroke-width="2"
                                                      width="13"
                                                      height="13"
                                                    >
                                                      <path
                                                        d="M17.94 17.94A10.07 10.07 0 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94"
                                                      />
                                                      <path
                                                        d="M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19"
                                                      />
                                                      <path
                                                        d="M14.12 14.12a3 3 0 11-4.24-4.24"
                                                      />
                                                      <line
                                                        x1="1"
                                                        y1="1"
                                                        x2="23"
                                                        y2="23"
                                                      />
                                                    </svg>
                                                  {:else}
                                                    <svg
                                                      viewBox="0 0 24 24"
                                                      fill="none"
                                                      stroke="currentColor"
                                                      stroke-width="2"
                                                      width="13"
                                                      height="13"
                                                    >
                                                      <path
                                                        d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"
                                                      />
                                                      <circle
                                                        cx="12"
                                                        cy="12"
                                                        r="3"
                                                      />
                                                    </svg>
                                                  {/if}
                                                </button>
                                              {/if}
                                            </span>
                                          {:else}
                                            {sf.value || "—"}
                                          {/if}
                                        </td>
                                      {/each}
                                      {#if !isEditingCredential}
                                        <td class="sub-cred-actions-cell">
                                          <button
                                            type="button"
                                            class="sub-cred-remove-btn"
                                            on:click|stopPropagation={() =>
                                              deleteSubCred(subCred.id)}
                                            disabled={deletingSubCredId ===
                                              subCred.id}
                                            aria-label="Remove"
                                            title="Remove"
                                          >
                                            {#if deletingSubCredId === subCred.id}
                                              <svg
                                                viewBox="0 0 24 24"
                                                width="12"
                                                height="12"
                                                class="spin-icon"
                                              >
                                                <circle
                                                  cx="12"
                                                  cy="12"
                                                  r="10"
                                                  stroke="currentColor"
                                                  stroke-width="3"
                                                  fill="none"
                                                  opacity="0.25"
                                                />
                                                <path
                                                  d="M12 2a10 10 0 0 1 10 10"
                                                  stroke="currentColor"
                                                  stroke-width="3"
                                                  fill="none"
                                                  stroke-linecap="round"
                                                />
                                              </svg>
                                            {:else}
                                              <svg
                                                viewBox="0 0 24 24"
                                                fill="none"
                                                stroke="currentColor"
                                                stroke-width="2"
                                                width="12"
                                                height="12"
                                              >
                                                <polyline
                                                  points="3 6 5 6 21 6"
                                                />
                                                <path
                                                  d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6"
                                                />
                                                <path d="M10 11v6M14 11v6" />
                                                <path
                                                  d="M9 6V4a1 1 0 011-1h4a1 1 0 011 1v2"
                                                />
                                              </svg>
                                            {/if}
                                          </button>
                                        </td>
                                      {/if}
                                    </tr>
                                  {/each}
                                </tbody>
                              </table>
                            {/if}

                            <!-- Inline add form -->
                            {#if addingSubCred === mcField.id}
                              <div class="sub-cred-add-row">
                                <div class="sub-cred-add-row-fields">
                                  <input
                                    type="text"
                                    class="sub-cred-add-input"
                                    bind:value={newSubCredName}
                                    placeholder="Name"
                                    disabled={isSubmittingSubCred}
                                  />
                                  {#each mcField.subFields ?? [] as sf (sf.id)}
                                    <input
                                      type="text"
                                      class="sub-cred-add-input"
                                      bind:value={newSubCredFields[sf.id]}
                                      placeholder={sf.name}
                                      disabled={isSubmittingSubCred}
                                    />
                                  {/each}
                                </div>
                                <div class="sub-cred-add-row-actions">
                                  {#if subCredError}
                                    <span
                                      class="sub-cred-add-error"
                                      title={subCredError}
                                    >
                                      <svg
                                        viewBox="0 0 24 24"
                                        fill="none"
                                        stroke="currentColor"
                                        stroke-width="2"
                                        width="13"
                                        height="13"
                                      >
                                        <circle cx="12" cy="12" r="10" /><line
                                          x1="12"
                                          y1="8"
                                          x2="12"
                                          y2="12"
                                        /><line
                                          x1="12"
                                          y1="16"
                                          x2="12.01"
                                          y2="16"
                                        />
                                      </svg>
                                    </span>
                                  {/if}
                                  <button
                                    type="button"
                                    class="sub-cred-btn-save"
                                    on:click={() => submitSubCred(mcField.id)}
                                    disabled={isSubmittingSubCred ||
                                      !newSubCredName.trim()}
                                  >
                                    {isSubmittingSubCred ? "…" : "Add"}
                                  </button>
                                  <button
                                    type="button"
                                    class="sub-cred-btn-cancel"
                                    on:click={cancelAddSubCred}
                                    disabled={isSubmittingSubCred}
                                  >
                                    Cancel
                                  </button>
                                </div>
                              </div>
                            {/if}
                          </div>
                        {/each}
                      {/if}

                      {#if isEditingCredential && saveCredError}
                        <div class="cred-edit-error">
                          <svg
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            stroke-width="2"
                            width="14"
                            height="14"
                          >
                            <circle cx="12" cy="12" r="10" />
                            <line x1="12" y1="8" x2="12" y2="12" />
                            <line x1="12" y1="16" x2="12.01" y2="16" />
                          </svg>
                          {saveCredError}
                        </div>
                      {/if}
                    </div>
                  {:else}
                    <div class="config-no-questions">
                      <svg
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        stroke-width="1.5"
                        width="32"
                        height="32"
                      >
                        <circle cx="12" cy="12" r="10" />
                        <path d="M9.09 9a3 3 0 015.83 1c0 2-3 3-3 3" />
                        <line x1="12" y1="17" x2="12.01" y2="17" />
                      </svg>
                      <p>No credential fields available</p>
                    </div>
                  {/if}

                  <!-- Footer metadata -->
                  <div class="config-info-footer">
                    {#if formatDate(selectedCredential.createdAt)}
                      <div class="config-info-item">
                        <svg
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                          width="13"
                          height="13"
                        >
                          <path d="M12 5v14M5 12h14" />
                        </svg>
                        Created on {formatDate(selectedCredential.createdAt)}
                      </div>
                    {/if}
                    {#if formatDate(selectedCredential.updatedAt)}
                      <div class="config-info-item">
                        <svg
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                          width="13"
                          height="13"
                        >
                          <circle cx="12" cy="12" r="10" />
                          <polyline points="12 6 12 12 16 14" />
                        </svg>
                        Updated on {formatDate(selectedCredential.updatedAt)}
                      </div>
                    {/if}
                  </div>
                </div>
              {/key}
            </div>
          </div>
        </div>
      </div>
    {/if}
  </div>
{/if}
