<script lang="ts">
  import { enhance } from "$app/forms";
  import ModalShell from "./ModalShell.svelte";
  import type {
    CredentialType,
    CredentialTypeField,
  } from "$lib/optima-api/modules/credentialTypes";

  export let isOpen = false;
  export let typeToEdit: CredentialType | null = null;
  export let onClose: () => void = () => {};
  export let onSuccess: () => void = () => {};
  export let valueTypes: string[] = [];

  $: isEditMode = typeToEdit !== null;

  $: if (isOpen && typeToEdit) {
    name = typeToEdit.name;
    permissionScope = typeToEdit.permissionScope;
    icon = typeToEdit.icon ?? "";
    fields = typeToEdit.fields.map((f) => ({
      ...f,
      subFields: f.subFields?.map((sf) => ({ ...sf })),
    }));
  }

  let name = "";
  let permissionScope = "";
  let icon = "";
  let fields: Array<{
    id?: string;
    name: string;
    required: boolean;
    secure: boolean;
    valueType: string;
    subFields?: Array<{
      id?: string;
      name: string;
      required: boolean;
      secure: boolean;
      valueType: string;
    }>;
  }> = [];
  let isSubmitting = false;
  let submitError = "";
  let manualIdFields = new Set<number>();

  function toSnakeCase(str: string): string {
    return str
      .trim()
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, "_")
      .replace(/^_|_$/g, "");
  }

  function handleFieldNameInput(index: number) {
    if (manualIdFields.has(index)) return;
    const field = fields[index];
    field.id = toSnakeCase(field.name);
    fields = fields;
  }

  function handleFieldIdInput(index: number) {
    manualIdFields.add(index);
  }

  $: isValid =
    name.trim().length > 0 &&
    permissionScope.trim().length > 0 &&
    fields.every((f) => (f.id ?? "").trim().length > 0);

  function formatValueTypeLabel(vt: string): string {
    return vt
      .split("_")
      .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
      .join(" ");
  }

  $: valueTypeOptions = (
    valueTypes.length > 0 ? valueTypes : ["plain_text", "password"]
  ).map((vt) => ({ value: vt, label: formatValueTypeLabel(vt) }));

  $: subFieldValueTypeOptions = valueTypeOptions.filter(
    (opt) => opt.value !== "multi_credential",
  );

  let manualIdSubFields = new Map<number, Set<number>>();

  function handleValueTypeChange(index: number) {
    const field = fields[index];
    if (field.valueType === "multi_credential") {
      field.secure = false;
      if (!field.subFields) field.subFields = [];
    } else {
      field.subFields = undefined;
      manualIdSubFields.delete(index);
    }
    fields = fields;
  }

  function addSubField(parentIndex: number) {
    const field = fields[parentIndex];
    if (!field.subFields) field.subFields = [];
    field.subFields = [
      ...field.subFields,
      {
        id: "",
        name: "",
        required: false,
        secure: false,
        valueType: "plain_text",
      },
    ];
    fields = fields;
  }

  function removeSubField(parentIndex: number, subIndex: number) {
    const field = fields[parentIndex];
    if (!field.subFields) return;
    field.subFields = field.subFields.filter((_, i) => i !== subIndex);
    fields = fields;
    const parentSet = manualIdSubFields.get(parentIndex);
    if (parentSet) {
      const updated = new Set<number>();
      for (const i of parentSet) {
        if (i < subIndex) updated.add(i);
        else if (i > subIndex) updated.add(i - 1);
      }
      manualIdSubFields.set(parentIndex, updated);
    }
  }

  function handleSubFieldNameInput(parentIndex: number, subIndex: number) {
    const parentSet = manualIdSubFields.get(parentIndex);
    if (parentSet?.has(subIndex)) return;
    const subField = fields[parentIndex].subFields![subIndex];
    subField.id = toSnakeCase(subField.name);
    fields = fields;
  }

  function handleSubFieldIdInput(parentIndex: number, subIndex: number) {
    if (!manualIdSubFields.has(parentIndex)) {
      manualIdSubFields.set(parentIndex, new Set());
    }
    manualIdSubFields.get(parentIndex)!.add(subIndex);
  }

  function moveSubField(
    parentIndex: number,
    subIndex: number,
    direction: "up" | "down",
  ) {
    const subs = fields[parentIndex].subFields;
    if (!subs) return;
    const target = direction === "up" ? subIndex - 1 : subIndex + 1;
    if (target < 0 || target >= subs.length) return;
    const newSubs = [...subs];
    [newSubs[subIndex], newSubs[target]] = [newSubs[target], newSubs[subIndex]];
    fields[parentIndex].subFields = newSubs;
    fields = fields;
    const parentSet = manualIdSubFields.get(parentIndex);
    if (parentSet) {
      const hadIndex = parentSet.has(subIndex);
      const hadTarget = parentSet.has(target);
      if (hadIndex) parentSet.add(target);
      else parentSet.delete(target);
      if (hadTarget) parentSet.add(subIndex);
      else parentSet.delete(subIndex);
    }
  }

  function addField() {
    fields = [
      ...fields,
      {
        id: "",
        name: "",
        required: false,
        secure: false,
        valueType: "plain_text",
      },
    ];
  }

  function removeField(index: number) {
    fields = fields.filter((_, i) => i !== index);
    const updated = new Set<number>();
    for (const i of manualIdFields) {
      if (i < index) updated.add(i);
      else if (i > index) updated.add(i - 1);
    }
    manualIdFields = updated;
  }

  function moveField(index: number, direction: "up" | "down") {
    const newFields = [...fields];
    const target = direction === "up" ? index - 1 : index + 1;
    if (target < 0 || target >= newFields.length) return;
    [newFields[index], newFields[target]] = [
      newFields[target],
      newFields[index],
    ];
    fields = newFields;
    const hadIndex = manualIdFields.has(index);
    const hadTarget = manualIdFields.has(target);
    if (hadIndex) manualIdFields.add(target);
    else manualIdFields.delete(target);
    if (hadTarget) manualIdFields.add(index);
    else manualIdFields.delete(index);
    manualIdFields = manualIdFields;
  }

  function reset() {
    name = "";
    permissionScope = "";
    icon = "";
    fields = [];
    manualIdFields = new Set();
    manualIdSubFields = new Map();
    isSubmitting = false;
    submitError = "";
  }

  function handleClose() {
    reset();
    onClose();
  }
</script>

<ModalShell
  {isOpen}
  title={isEditMode ? "Edit Credential Type" : "Create Credential Type"}
  onClose={handleClose}
>
  <svelte:fragment slot="icon">
    <svg
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      stroke-width="2"
      width="18"
      height="18"
    >
      <rect x="3" y="11" width="18" height="11" rx="2" ry="2" />
      <path d="M7 11V7a5 5 0 0 1 10 0v4" />
    </svg>
  </svelte:fragment>

  <form
    method="POST"
    action={isEditMode ? "?/updateCredentialType" : "?/createCredentialType"}
    use:enhance={({ formData }) => {
      formData.set("fields", JSON.stringify(fields));
      isSubmitting = true;
      submitError = "";
      return async ({ result, update }) => {
        isSubmitting = false;
        if (result.type === "success") {
          reset();
          await update({ reset: false });
          onSuccess();
          return;
        } else if (result.type === "failure") {
          submitError = String(
            (result.data as Record<string, unknown>)?.message ??
              (isEditMode
                ? "Failed to update credential type."
                : "Failed to create credential type."),
          );
        } else if (result.type === "error") {
          submitError =
            result.error?.message ?? "An unexpected error occurred.";
        }
        await update({ reset: false });
      };
    }}
  >
    {#if isEditMode && typeToEdit}
      <input type="hidden" name="id" value={typeToEdit.id} />
    {/if}

    <div class="modal-body">
      {#if submitError}
        <div class="error-banner">
          <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>
          {submitError}
        </div>
      {/if}

      <div class="form-row">
        <div class="form-group">
          <label for="ct-name">Name <span class="req">*</span></label>
          <input
            id="ct-name"
            name="name"
            type="text"
            placeholder="e.g. AWS Credentials"
            bind:value={name}
            required
          />
        </div>
        <div class="form-group">
          <label for="ct-scope">
            Permission Scope <span class="req">*</span>
          </label>
          <input
            id="ct-scope"
            name="permissionScope"
            type="text"
            placeholder="e.g. aws"
            bind:value={permissionScope}
            required
          />
        </div>
      </div>

      <div class="form-group">
        <label for="ct-icon"
          >Icon <span class="label-hint">Optional</span></label
        >
        <input
          id="ct-icon"
          name="icon"
          type="text"
          placeholder="e.g. cloud, key, database"
          bind:value={icon}
        />
      </div>

      <!-- Fields section -->
      <div class="fields-section">
        <div class="fields-section-header">
          <span class="fields-label">Fields</span>
          {#if fields.length > 0}
            <span class="selected-badge"
              >{fields.length} field{fields.length === 1 ? "" : "s"}</span
            >
          {/if}
        </div>

        {#if fields.length === 0}
          <p class="fields-empty">
            No fields defined yet. Fields define the data a credential of this
            type will store.
          </p>
        {:else}
          <div class="fields-list">
            {#each fields as field, index}
              <div class="field-card">
                <div class="field-card-header">
                  <span class="field-number">#{index + 1}</span>
                  <div class="field-card-actions">
                    {#if index > 0}
                      <button
                        type="button"
                        class="field-move-btn"
                        aria-label="Move up"
                        on:click={() => moveField(index, "up")}
                      >
                        <svg
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                          width="12"
                          height="12"
                        >
                          <path d="M18 15l-6-6-6 6" />
                        </svg>
                      </button>
                    {/if}
                    {#if index < fields.length - 1}
                      <button
                        type="button"
                        class="field-move-btn"
                        aria-label="Move down"
                        on:click={() => moveField(index, "down")}
                      >
                        <svg
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                          width="12"
                          height="12"
                        >
                          <path d="M6 9l6 6 6-6" />
                        </svg>
                      </button>
                    {/if}
                    <button
                      type="button"
                      class="field-remove-btn"
                      aria-label="Remove field"
                      on:click={() => removeField(index)}
                    >
                      <svg
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        stroke-width="2"
                        width="13"
                        height="13"
                      >
                        <line x1="18" y1="6" x2="6" y2="18" />
                        <line x1="6" y1="6" x2="18" y2="18" />
                      </svg>
                    </button>
                  </div>
                </div>
                <div class="field-card-body">
                  <div class="field-row">
                    <div class="form-group field-name-group">
                      <label for="field-name-{index}">Name</label>
                      <input
                        id="field-name-{index}"
                        type="text"
                        placeholder="e.g. Access Key ID"
                        bind:value={field.name}
                        on:input={() => handleFieldNameInput(index)}
                      />
                    </div>
                    <div class="form-group field-type-group">
                      <label for="field-type-{index}">Type</label>
                      <select
                        id="field-type-{index}"
                        bind:value={field.valueType}
                        on:change={() => handleValueTypeChange(index)}
                      >
                        {#each valueTypeOptions as opt}
                          <option value={opt.value}>{opt.label}</option>
                        {/each}
                      </select>
                    </div>
                  </div>
                  <div class="field-id-row">
                    <div class="form-group field-id-group">
                      <label for="field-id-{index}"
                        >ID <span class="req">*</span></label
                      >
                      <input
                        id="field-id-{index}"
                        type="text"
                        placeholder="auto-generated from name"
                        bind:value={field.id}
                        on:input={() => handleFieldIdInput(index)}
                        class="field-id-input"
                      />
                    </div>
                  </div>
                  <div class="field-toggles">
                    <label class="toggle-label">
                      <input type="checkbox" bind:checked={field.required} />
                      <span class="toggle-text">Required</span>
                    </label>
                    <label
                      class="toggle-label"
                      class:toggle-disabled={field.valueType ===
                        "multi_credential"}
                    >
                      <input
                        type="checkbox"
                        bind:checked={field.secure}
                        disabled={field.valueType === "multi_credential"}
                      />
                      <span class="toggle-text">Secure</span>
                    </label>
                  </div>

                  {#if field.valueType === "multi_credential"}
                    <div class="sub-fields-section">
                      <div class="sub-fields-header">
                        <span class="sub-fields-label">
                          <svg
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            stroke-width="2"
                            width="12"
                            height="12"
                          >
                            <path
                              d="M16 21v-2a4 4 0 00-4-4H5a4 4 0 00-4-4v-2"
                            />
                            <path d="M9 7l-4 4 4 4" />
                          </svg>
                          Sub-Fields
                        </span>
                        {#if field.subFields && field.subFields.length > 0}
                          <span class="sub-fields-count"
                            >{field.subFields.length}</span
                          >
                        {/if}
                      </div>

                      {#if !field.subFields || field.subFields.length === 0}
                        <p class="sub-fields-empty">
                          No sub-fields defined. Sub-fields define the structure
                          of each entry in this multi-credential.
                        </p>
                      {:else}
                        <div class="sub-fields-list">
                          {#each field.subFields as subField, subIndex}
                            <div class="sub-field-card">
                              <div class="sub-field-card-header">
                                <span class="field-number">#{subIndex + 1}</span
                                >
                                <div class="field-card-actions">
                                  {#if subIndex > 0}
                                    <button
                                      type="button"
                                      class="field-move-btn"
                                      aria-label="Move up"
                                      on:click={() =>
                                        moveSubField(index, subIndex, "up")}
                                    >
                                      <svg
                                        viewBox="0 0 24 24"
                                        fill="none"
                                        stroke="currentColor"
                                        stroke-width="2"
                                        width="12"
                                        height="12"
                                        ><path d="M18 15l-6-6-6 6" /></svg
                                      >
                                    </button>
                                  {/if}
                                  {#if subIndex < (field.subFields?.length ?? 0) - 1}
                                    <button
                                      type="button"
                                      class="field-move-btn"
                                      aria-label="Move down"
                                      on:click={() =>
                                        moveSubField(index, subIndex, "down")}
                                    >
                                      <svg
                                        viewBox="0 0 24 24"
                                        fill="none"
                                        stroke="currentColor"
                                        stroke-width="2"
                                        width="12"
                                        height="12"
                                        ><path d="M6 9l6 6 6-6" /></svg
                                      >
                                    </button>
                                  {/if}
                                  <button
                                    type="button"
                                    class="field-remove-btn"
                                    aria-label="Remove sub-field"
                                    on:click={() =>
                                      removeSubField(index, subIndex)}
                                  >
                                    <svg
                                      viewBox="0 0 24 24"
                                      fill="none"
                                      stroke="currentColor"
                                      stroke-width="2"
                                      width="13"
                                      height="13"
                                    >
                                      <line
                                        x1="18"
                                        y1="6"
                                        x2="6"
                                        y2="18"
                                      /><line x1="6" y1="6" x2="18" y2="18" />
                                    </svg>
                                  </button>
                                </div>
                              </div>
                              <div class="sub-field-card-body">
                                <div class="field-row">
                                  <div class="form-group field-name-group">
                                    <label
                                      for="sub-field-name-{index}-{subIndex}"
                                      >Name</label
                                    >
                                    <input
                                      id="sub-field-name-{index}-{subIndex}"
                                      type="text"
                                      placeholder="e.g. Server"
                                      bind:value={subField.name}
                                      on:input={() =>
                                        handleSubFieldNameInput(
                                          index,
                                          subIndex,
                                        )}
                                    />
                                  </div>
                                  <div class="form-group field-type-group">
                                    <label
                                      for="sub-field-type-{index}-{subIndex}"
                                      >Type</label
                                    >
                                    <select
                                      id="sub-field-type-{index}-{subIndex}"
                                      bind:value={subField.valueType}
                                    >
                                      {#each subFieldValueTypeOptions as opt}
                                        <option value={opt.value}
                                          >{opt.label}</option
                                        >
                                      {/each}
                                    </select>
                                  </div>
                                </div>
                                <div class="field-id-row">
                                  <div class="form-group field-id-group">
                                    <label for="sub-field-id-{index}-{subIndex}"
                                      >ID <span class="req">*</span></label
                                    >
                                    <input
                                      id="sub-field-id-{index}-{subIndex}"
                                      type="text"
                                      placeholder="auto-generated from name"
                                      bind:value={subField.id}
                                      on:input={() =>
                                        handleSubFieldIdInput(index, subIndex)}
                                      class="field-id-input"
                                    />
                                  </div>
                                </div>
                                <div class="field-toggles">
                                  <label class="toggle-label">
                                    <input
                                      type="checkbox"
                                      bind:checked={subField.required}
                                    />
                                    <span class="toggle-text">Required</span>
                                  </label>
                                  <label class="toggle-label">
                                    <input
                                      type="checkbox"
                                      bind:checked={subField.secure}
                                    />
                                    <span class="toggle-text">Secure</span>
                                  </label>
                                </div>
                              </div>
                            </div>
                          {/each}
                        </div>
                      {/if}

                      <button
                        type="button"
                        class="add-sub-field-btn"
                        on:click={() => addSubField(index)}
                      >
                        <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 Sub-Field
                      </button>
                    </div>
                  {/if}
                </div>
              </div>
            {/each}
          </div>
        {/if}

        <button type="button" class="add-field-btn" on:click={addField}>
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            width="13"
            height="13"
          >
            <line x1="12" y1="5" x2="12" y2="19" />
            <line x1="5" y1="12" x2="19" y2="12" />
          </svg>
          Add Field
        </button>
      </div>
    </div>

    <div class="modal-footer">
      <button
        type="button"
        class="btn-cancel"
        on:click={handleClose}
        disabled={isSubmitting}
      >
        Cancel
      </button>
      <button
        type="submit"
        class="btn-submit"
        disabled={!isValid || isSubmitting}
      >
        {#if isSubmitting}
          {isEditMode ? "Saving…" : "Creating…"}
        {:else}
          {isEditMode ? "Save Changes" : "Create Credential Type"}
        {/if}
      </button>
    </div>
  </form>
</ModalShell>

<style>
  form {
    display: flex;
    flex-direction: column;
    flex: 1;
    overflow: hidden;
    min-height: 0;
  }

  .modal-body {
    padding: 18px 22px;
    overflow-y: auto;
    flex: 1;
    min-height: 0;
  }

  .error-banner {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 10px 14px;
    margin-bottom: 16px;
    background: rgba(220, 38, 38, 0.08);
    border: 1px solid rgba(220, 38, 38, 0.2);
    border-radius: 8px;
    font-size: 13px;
    color: #dc2626;
  }

  .form-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 14px;
    margin-bottom: 14px;
  }

  .form-group {
    display: flex;
    flex-direction: column;
    gap: 5px;
    margin-bottom: 14px;
  }

  .form-row .form-group {
    margin-bottom: 0;
  }

  label {
    font-size: 12.5px;
    font-weight: 600;
    color: var(--text-secondary);
  }

  .req {
    color: #dc2626;
  }

  .label-hint {
    font-weight: 400;
    color: var(--text-muted);
    font-size: 11px;
  }

  input[type="text"],
  select {
    padding: 7px 10px;
    border: 1px solid var(--border-subtle);
    border-radius: 7px;
    background: var(--bg-inset);
    font-size: 13px;
    color: var(--text-primary);
    transition:
      border-color 0.15s,
      box-shadow 0.15s;
  }

  input[type="text"]:focus,
  select:focus {
    outline: none;
    border-color: var(--input-focus-border);
    box-shadow: 0 0 0 3px rgba(0, 102, 204, 0.1);
  }

  input[type="text"]::placeholder {
    color: var(--text-muted);
  }

  /* Fields section */
  .fields-section {
    margin-top: 4px;
  }

  .fields-section-header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 10px;
  }

  .fields-label {
    font-size: 13px;
    font-weight: 600;
    color: var(--text-primary);
  }

  .selected-badge {
    font-size: 11px;
    font-weight: 500;
    padding: 2px 8px;
    border-radius: 8px;
    background: var(--status-neutral-bg);
    color: var(--text-secondary);
    border: 1px solid var(--border-subtle);
  }

  .fields-empty {
    margin: 0 0 12px;
    font-size: 13px;
    color: var(--text-muted);
    line-height: 1.5;
  }

  .fields-list {
    display: flex;
    flex-direction: column;
    gap: 10px;
    margin-bottom: 12px;
  }

  .field-card {
    border: 1px solid var(--border-subtle);
    border-radius: 9px;
    background: var(--bg-inset);
    overflow: hidden;
  }

  .field-card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 6px 10px;
    background: var(--bg-surface);
    border-bottom: 1px solid var(--border-subtle);
  }

  .field-number {
    font-size: 11px;
    font-weight: 600;
    color: var(--text-muted);
  }

  .field-card-actions {
    display: flex;
    align-items: center;
    gap: 4px;
  }

  .field-move-btn,
  .field-remove-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 22px;
    height: 22px;
    padding: 0;
    background: none;
    border: 1px solid transparent;
    border-radius: 5px;
    cursor: pointer;
    color: var(--text-muted);
    transition:
      background 0.1s,
      color 0.1s;
  }

  .field-move-btn:hover {
    background: var(--card-hover-bg);
    color: var(--text-primary);
  }

  .field-remove-btn:hover {
    background: rgba(220, 38, 38, 0.08);
    color: #dc2626;
  }

  .field-card-body {
    padding: 10px;
  }

  .field-row {
    display: grid;
    grid-template-columns: 1fr 140px;
    gap: 10px;
    margin-bottom: 8px;
  }

  .field-name-group,
  .field-type-group,
  .field-id-group {
    margin-bottom: 0;
  }

  .field-id-row {
    margin-bottom: 8px;
  }

  .field-id-input {
    font-family: ui-monospace, "SF Mono", "Cascadia Code", Menlo, monospace;
    font-size: 12px;
  }

  .field-toggles {
    display: flex;
    gap: 16px;
  }

  .toggle-label {
    display: flex;
    align-items: center;
    gap: 6px;
    cursor: pointer;
    font-weight: 400;
  }

  .toggle-label input[type="checkbox"] {
    accent-color: var(--accent-color, #0066cc);
    width: 14px;
    height: 14px;
    cursor: pointer;
  }

  .toggle-text {
    font-size: 12px;
    color: var(--text-secondary);
  }

  .add-field-btn {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 6px 14px;
    background: var(--bg-inset);
    border: 1px dashed var(--border-subtle);
    border-radius: 7px;
    font-size: 12.5px;
    font-weight: 500;
    color: var(--text-secondary);
    cursor: pointer;
    transition:
      background 0.12s,
      border-color 0.12s,
      color 0.12s;
  }

  .add-field-btn:hover {
    background: var(--card-hover-bg);
    border-color: var(--accent-color, #0066cc);
    color: var(--text-primary);
  }

  /* Sub-fields section */
  .sub-fields-section {
    margin-top: 10px;
    padding-top: 10px;
    border-top: 1px dashed var(--border-subtle);
  }

  .sub-fields-header {
    display: flex;
    align-items: center;
    gap: 6px;
    margin-bottom: 8px;
  }

  .sub-fields-label {
    display: flex;
    align-items: center;
    gap: 5px;
    font-size: 12px;
    font-weight: 600;
    color: var(--text-secondary);
  }

  .sub-fields-count {
    font-size: 10px;
    font-weight: 500;
    padding: 1px 6px;
    border-radius: 8px;
    background: var(--status-neutral-bg);
    color: var(--text-secondary);
    border: 1px solid var(--border-subtle);
  }

  .sub-fields-empty {
    margin: 0 0 8px;
    font-size: 12px;
    color: var(--text-muted);
    line-height: 1.5;
  }

  .sub-fields-list {
    display: flex;
    flex-direction: column;
    gap: 8px;
    margin-bottom: 8px;
  }

  .sub-field-card {
    border: 1px solid var(--border-subtle);
    border-radius: 7px;
    background: var(--bg-surface);
    overflow: hidden;
  }

  .sub-field-card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 4px 8px;
    background: var(--bg-inset);
    border-bottom: 1px solid var(--border-subtle);
  }

  .sub-field-card-body {
    padding: 8px;
  }

  .add-sub-field-btn {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 4px 12px;
    background: none;
    border: 1px dashed var(--border-subtle);
    border-radius: 6px;
    font-size: 11.5px;
    font-weight: 500;
    color: var(--text-muted);
    cursor: pointer;
    transition:
      background 0.12s,
      border-color 0.12s,
      color 0.12s;
  }

  .add-sub-field-btn:hover {
    background: var(--card-hover-bg);
    border-color: var(--accent-color, #0066cc);
    color: var(--text-primary);
  }

  .toggle-disabled {
    opacity: 0.4;
    cursor: not-allowed;
  }

  /* Footer */
  .modal-footer {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: 8px;
    padding: 14px 22px;
    border-top: 1px solid var(--border-subtle);
  }

  .btn-cancel {
    padding: 7px 16px;
    border-radius: 7px;
    font-size: 13px;
    font-weight: 500;
    cursor: pointer;
    background: var(--bg-inset);
    border: 1px solid var(--border-subtle);
    color: var(--text-secondary);
    transition:
      background 0.15s,
      border-color 0.15s;
  }

  .btn-cancel:hover:not(:disabled) {
    background: var(--card-hover-bg);
    border-color: var(--border-default);
    color: var(--text-primary);
  }

  .btn-cancel:disabled {
    opacity: 0.45;
    cursor: not-allowed;
  }

  .btn-submit {
    padding: 7px 18px;
    border-radius: 7px;
    font-size: 13px;
    font-weight: 500;
    cursor: pointer;
    background: var(--accent-color, #0066cc);
    border: 1px solid transparent;
    color: #fff;
    transition: filter 0.15s;
  }

  .btn-submit:hover:not(:disabled) {
    filter: brightness(1.1);
  }

  .btn-submit:disabled {
    opacity: 0.45;
    cursor: not-allowed;
  }
</style>
