<kendo-dialog [title]="title" (close)="cancel.emit()" [width]="showReceiptPanel ? 1200 : 760" [maxWidth]="'95vw'"
  [maxHeight]="'90vh'">
  <!-- Two columns on desktop: form on the left, receipt preview on the right. Stacks on mobile. -->
  <div class="flex flex-col gap-4 md:flex-row">

    <div class="flex-1 min-w-0 grid grid-cols-1 md:grid-cols-2 gap-x-4 gap-y-3">

      <!-- Snapshot tools (vendor mode): quick-load a saved template, or save the current form -->
      <div *ngIf="showSnapshotTools" class="md:col-span-2 flex flex-wrap items-end gap-2 rounded border border-gray-200 bg-gray-50 p-2">
        <label class="flex flex-1 min-w-[14rem] flex-col gap-1">範本 / Load from snapshot
          <kendo-dropdownlist [data]="snapshots" textField="name" valueField="id" [valuePrimitive]="true"
            [(ngModel)]="selectedSnapshotId" (valueChange)="applySnapshot($event)"
            [defaultItem]="{ id: null, name: '-- 選擇範本 / Select a saved snapshot --' }">
          </kendo-dropdownlist>
        </label>
        <button kendoButton fillMode="outline" themeColor="primary" type="button"
          [disabled]="!isValid" (click)="openSnapshotPrompt()"
          title="Save the current form as a reusable snapshot / 儲存為範本">💾 存為範本 / Save as snapshot</button>
      </div>

      <!-- Continuous entry: keep member/ministry/category/date after each save (on-behalf reimbursement only) -->
      <label *ngIf="showContinueEntry" class="flex items-center gap-2 md:col-span-2">
        <kendo-switch [(ngModel)]="continueEntry"></kendo-switch>
        <span>連續登打 / Continuous Entry</span>
      </label>

      <!-- Description (with AI assist: translate to English + suggest a category) -->
      <div class="flex flex-col gap-1 md:col-span-2">
        <div class="flex items-end justify-between gap-2">
          <label class="flex flex-1 flex-col gap-1">Description
            <kendo-textbox [(ngModel)]="form.description"
              placeholder="Brief description of expense / 費用說明（可輸入中文）"></kendo-textbox>
          </label>
          <button kendoButton fillMode="outline" themeColor="primary" type="button"
            [disabled]="!form.description.trim() || aiLoading" (click)="requestAiAssist()"
            title="Translate to English and suggest a category / 翻譯並建議分類">
            {{ aiLoading ? '思考中… / Thinking…' : '✨ AI 建議' }}
          </button>
        </div>

        <!-- Suggestion card: the "suggest & confirm" step — user applies or dismisses -->
        <div *ngIf="hasAiSuggestion" class="rounded border border-blue-200 bg-blue-50 p-3 flex flex-col gap-2 text-sm">
          <div class="font-semibold text-blue-800">AI 建議 / Suggestion</div>
          <div *ngIf="aiSuggestedDescription" class="flex gap-2">
            <span class="text-gray-500 shrink-0">說明 / Description:</span>
            <span class="font-medium">{{ aiSuggestedDescription }}</span>
          </div>
          <div *ngIf="aiSuggestion?.groupLabel" class="flex gap-2">
            <span class="text-gray-500 shrink-0">分類 / Category:</span>
            <span class="font-medium">{{ aiSuggestion?.groupLabel }}<span *ngIf="aiSuggestion?.subLabel"> → {{
                aiSuggestion?.subLabel }}</span></span>
          </div>
          <div class="text-xs text-gray-500">信心 / Confidence: {{ (aiSuggestion?.confidence ?? 0) * 100 | number:'1.0-0'
            }}%</div>
          <div class="flex gap-2">
            <button kendoButton themeColor="primary" size="small" type="button" (click)="applyAiSuggestion()">套用 /
              Apply</button>
            <button kendoButton fillMode="flat" size="small" type="button" (click)="dismissAiSuggestion()">忽略 /
              Dismiss</button>
          </div>
        </div>
      </div>
      <!-- Member picker (finance creating on behalf of a member) -->
      <label *ngIf="allowMemberPick" class="flex flex-col gap-1 md:col-span-2">Member
        <kendo-dropdownlist [data]="memberResults" textField="displayName" valueField="id" [valuePrimitive]="true"
          [filterable]="true" (filterChange)="onMemberFilter($event)" [(ngModel)]="form.memberId"
          placeholder="Search member by name">
        </kendo-dropdownlist>
      </label>

      <!-- Ministry -->
      <label class="flex flex-col gap-1">Ministry
        <kendo-dropdownlist [data]="ministries" textField="label" valueField="id" [valuePrimitive]="true"
          [(ngModel)]="form.ministryId" [defaultItem]="{ id: null, label: '-- Select ministry --/請選擇事工' }">
        </kendo-dropdownlist>
      </label>

      <!-- Expense Date -->
      <label class="flex flex-col gap-1">Expense Date
        <kendo-datepicker [(ngModel)]="form.expenseDate"></kendo-datepicker>
      </label>

      <!-- Category lines: one invoice can span several categories -->
      <div class="md:col-span-2 flex flex-col gap-2">
        <div class="flex items-center justify-between">
          <span class="font-semibold">明細 / Line Items</span>
          <span class="text-sm text-gray-600">合計 / Total: {{ totalAmount | currency }}</span>
        </div>

        <div *ngFor="let line of lines; let i = index" class="flex flex-col gap-3 rounded border border-gray-200 p-3">
          <!-- Line header: number + remove -->
          <div class="flex items-center justify-between">
            <span class="text-sm font-medium text-gray-600">明細 {{ i + 1 }} / Item {{ i + 1 }}</span>
            <button kendoButton fillMode="outline" themeColor="primary" size="small" type="button"
              [disabled]="!line.description.trim() || line.aiLoading" (click)="requestLineAiAssist(line)"
              title="Translate this line and suggest a category / 翻譯並建議此列分類">
              {{ line.aiLoading ? '思考中… / Thinking…' : '✨ AI 建議此列' }}
            </button>
            <button kendoButton fillMode="flat" themeColor="error" size="small" [disabled]="lines.length === 1"
              (click)="removeLine(i)" title="Remove line / 刪除此列">✕ 刪除</button>
          </div>

          <!-- Row 1: Category Group + Sub-Category -->
          <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
            <label class="flex flex-col gap-1">Category Group
              <kendo-dropdownlist [data]="groups" textField="label" valueField="id" [valuePrimitive]="true"
                [(ngModel)]="line.categoryGroupId" (valueChange)="onLineGroupChange(line, $event)"
                [defaultItem]="{ id: null, label: '-- Select group --/請選擇大類' }">
              </kendo-dropdownlist>
            </label>

            <label class="flex flex-col gap-1">Sub-Category
              <kendo-dropdownlist [data]="line.subs" textField="label" valueField="id" [valuePrimitive]="true"
                [(ngModel)]="line.subCategoryId" [defaultItem]="{ id: null, label: '-- Select sub-category --/請選擇子項' }"
                [disabled]="!line.categoryGroupId">
              </kendo-dropdownlist>
            </label>
          </div>

          <!-- Row 2: Description (optional) + Amount -->
          <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
            <label class="flex flex-col gap-1"><span>Description / 說明 <span class="text-gray-400">(Optional)</span></span>
              <kendo-textbox [(ngModel)]="line.description" placeholder="e.g. 點心、文具…"></kendo-textbox>
            </label>

            <label class="flex flex-col gap-1">Amount
              <kendo-numerictextbox [(ngModel)]="line.amount" [min]="0" [format]="'c2'"></kendo-numerictextbox>
            </label>
          </div>

          <!-- Per-line suggestion card: the "suggest & confirm" step for this line -->
          <div *ngIf="hasLineSuggestion(line)"
            class="rounded border border-blue-200 bg-blue-50 p-3 flex flex-col gap-2 text-sm">
            <div class="font-semibold text-blue-800">AI 建議 / Suggestion</div>
            <div *ngIf="lineSuggestedDescription(line)" class="flex gap-2">
              <span class="text-gray-500 shrink-0">說明 / Description:</span>
              <span class="font-medium">{{ lineSuggestedDescription(line) }}</span>
            </div>
            <div *ngIf="line.aiSuggestion?.groupLabel" class="flex gap-2">
              <span class="text-gray-500 shrink-0">分類 / Category:</span>
              <span class="font-medium">{{ line.aiSuggestion?.groupLabel }}<span *ngIf="line.aiSuggestion?.subLabel"> →
                  {{ line.aiSuggestion?.subLabel }}</span></span>
            </div>
            <div class="text-xs text-gray-500">信心 / Confidence: {{ (line.aiSuggestion?.confidence ?? 0) * 100 |
              number:'1.0-0' }}%</div>
            <div class="flex gap-2">
              <button kendoButton themeColor="primary" size="small" type="button"
                (click)="applyLineAiSuggestion(line)">套用 / Apply</button>
              <button kendoButton fillMode="flat" size="small" type="button" (click)="dismissLineAiSuggestion(line)">忽略
                / Dismiss</button>
            </div>
          </div>
        </div>

        <div>
          <button kendoButton fillMode="outline" (click)="addLine()">+ 新增一列 / Add Line</button>
        </div>
      </div>


      <!-- Vendor mode: vendor name + check number + optional 1099 recipient -->
      <ng-container *ngIf="mode === 'vendor'">
        <label class="flex flex-col gap-1">Vendor Name
          <kendo-textbox [(ngModel)]="form.vendorName" placeholder="Payee / vendor name"></kendo-textbox>
        </label>
        <label class="flex flex-col gap-1">Check #
          <kendo-textbox [(ngModel)]="form.checkNumber" placeholder="Check number (optional)"></kendo-textbox>
        </label>
        <label class="flex flex-col gap-1 md:col-span-2">1099 Recipient / 1099 收款人 <span class="text-gray-400 font-normal">(optional)</span>
          <kendo-dropdownlist [data]="payees" textField="legalName" valueField="id" [valuePrimitive]="true"
            [defaultItem]="{ id: null, legalName: '— none —' }"
            [(ngModel)]="form.payeeId">
          </kendo-dropdownlist>
        </label>
      </ng-container>

      <!-- Reimbursement mode: receipt file input -->
      <ng-container *ngIf="mode === 'reimbursement'">
        <label class="flex flex-col gap-1 md:col-span-2">Receipt (optional)
          <!--
          Stop the native 'cancel' DOM event (fired when the OS file picker is dismissed)
          from bubbling up to the host, where it would collide with this component's
          @Output() cancel and wrongly close the dialog. See Angular issues #50556 / #13997.
        -->
          <input #receiptInput type="file" accept="image/*,application/pdf" (change)="onFileSelected($event)"
            (cancel)="$event.stopPropagation()"
            class="block w-full text-sm text-gray-700 file:mr-3 file:py-1 file:px-3 file:rounded file:border-0 file:text-sm file:bg-gray-100 hover:file:bg-gray-200" />
        </label>
      </ng-container>

    </div>
    <!-- /left form column -->

    <!-- Right: receipt preview (shown once a file is selected or an existing receipt is loaded) -->
    <div *ngIf="showReceiptPanel" class="md:w-[34rem] md:shrink-0 md:border-l md:pl-4 flex flex-col gap-2">
      <div class="flex items-center justify-between">
        <span class="font-semibold">收據預覽 / Receipt</span>
        <!-- Zoom controls (image only; PDF uses the browser viewer's own zoom) -->
        <div *ngIf="receiptImageUrl" class="flex items-center gap-1">
          <button kendoButton size="small" fillMode="flat" (click)="zoomOut()" [disabled]="receiptZoom <= minZoom"
            title="縮小 / Zoom out">−</button>
          <span class="w-12 text-center text-sm tabular-nums">{{ receiptZoom * 100 | number:'1.0-0' }}%</span>
          <button kendoButton size="small" fillMode="flat" (click)="zoomIn()" [disabled]="receiptZoom >= maxZoom"
            title="放大 / Zoom in">＋</button>
          <button kendoButton size="small" fillMode="flat" (click)="resetZoom()" title="重設 / Reset">⟲</button>
        </div>
      </div>

      <!-- Scrollable so a zoomed-in image can be panned for comparison -->
      <div *ngIf="receiptImageUrl" class="overflow-auto rounded border border-gray-200 bg-gray-50"
        style="max-height: 72vh;">
        <img [src]="receiptImageUrl" alt="Receipt preview" [style.width.%]="receiptZoom * 100"
          class="block max-w-none" />
      </div>

      <iframe *ngIf="receiptPdfUrl" [src]="receiptPdfUrl" title="Receipt PDF"
        class="w-full rounded border border-gray-200" style="height: 72vh;"></iframe>
    </div>

  </div>
  <!-- /two-column body -->

  <kendo-dialog-actions>
    <button kendoButton (click)="cancel.emit()">Cancel</button>
    <button kendoButton themeColor="primary" [disabled]="!isValid" (click)="emitSave()">Save</button>
  </kendo-dialog-actions>
</kendo-dialog>

<!-- Save-as-snapshot name prompt -->
<kendo-dialog *ngIf="showSnapshotNamePrompt" title="存為範本 / Save as Snapshot" [width]="420" [maxWidth]="'95vw'"
  (close)="cancelSnapshotPrompt()">
  <div class="flex flex-col gap-2 p-2">
    <label class="flex flex-col gap-1">名稱 / Name
      <kendo-textbox [(ngModel)]="snapshotName" placeholder="e.g. Monthly Rent — Landlord X"></kendo-textbox>
    </label>
    <p class="text-xs text-gray-500">費用日期不會存入範本 / The Expense Date is not saved in a snapshot.</p>
  </div>
  <kendo-dialog-actions>
    <button kendoButton (click)="cancelSnapshotPrompt()">Cancel</button>
    <button kendoButton themeColor="primary" [disabled]="!snapshotName.trim() || snapshotSaving"
      (click)="saveSnapshot()">{{ snapshotSaving ? '儲存中… / Saving…' : 'Save' }}</button>
  </kendo-dialog-actions>
</kendo-dialog>