<div class="off">
  <!-- ============================ LANDING ============================ -->
  <ng-container *ngIf="mode === 'landing'">
    <!-- Start card -->
    <section class="card rise" style="--d: 0ms">
      <div class="card__head">
        <h2 class="card__title">Start</h2>
        <span class="card__zh">開始</span>
      </div>

      <div class="start">
        <label class="flex flex-col gap-1">
          <span class="start__label">Session date · 奉獻日期</span>
          <kendo-datepicker [(ngModel)]="sessionDate" (valueChange)="checkDate()"></kendo-datepicker>
        </label>

        <div class="start__action">
          <button *ngIf="!dateConflict" kendoButton themeColor="primary" size="large" (click)="startEntry()">
            Start entry / 開始錄入
          </button>

          <div *ngIf="dateConflict" class="start__exists">
            <span class="start__note">A session already exists for this date · 此日期已有 session</span>
            <button kendoButton themeColor="primary" size="large" (click)="openViewByDate()">
              View session / 檢視
            </button>
          </div>
        </div>
      </div>
    </section>

    <!-- Recent sessions -->
    <section class="card rise" style="--d: 80ms">
      <div class="card__head">
        <h2 class="card__title">Recent Sessions</h2>
        <span class="card__zh">最近的奉獻紀錄</span>
      </div>

      <kendo-grid class="lined clickable-rows" [data]="sessions" (cellClick)="onSessionCellClick($event)">
        <kendo-grid-column field="sessionDate" title="Date" [width]="120"></kendo-grid-column>
        <kendo-grid-column title="Status" [width]="130">
          <ng-template kendoGridCellTemplate let-s>
            <span class="pill" [ngClass]="'pill--' + s.status.toLowerCase()">{{ s.status }}</span>
          </ng-template>
        </kendo-grid-column>
        <kendo-grid-column field="lineCount" title="Lines" [width]="80"></kendo-grid-column>
        <kendo-grid-column title="Attendance · 主日人數" [width]="140">
          <ng-template kendoGridCellTemplate let-s>{{ s.sundayAttendanceCount ?? '—' }}</ng-template>
        </kendo-grid-column>
        <kendo-grid-column title="Proof" [width]="70">
          <ng-template kendoGridCellTemplate let-s>
            <span *ngIf="s.hasProof" title="Paper proof attached · 已附證明">📎</span>
          </ng-template>
        </kendo-grid-column>
        <kendo-grid-column field="systemTotal" title="System" [width]="120" format="c2"></kendo-grid-column>
        <kendo-grid-column field="difference" title="Diff" [width]="110" format="c2"></kendo-grid-column>
        <ng-template kendoGridNoRecordsTemplate>
          <div class="empty">No sessions yet — pick a date above to start.<br><span>尚無紀錄 — 選擇上方日期開始</span></div>
        </ng-template>
      </kendo-grid>
      <kendo-contextmenu #sessionMenu [items]="sessionMenuItems" (select)="onSessionMenuSelect($event)"></kendo-contextmenu>
      <div class="hint-text-sm">點一列檢視 · 右鍵修改主日人數 / Click a row to view · right-click to edit attendance</div>
    </section>
  </ng-container>

  <!-- ============================ WORKSPACE (new entry & edit) ============================ -->
  <ng-container *ngIf="mode === 'workspace'">
    <!-- Session bar -->
    <div class="bar rise" style="--d: 0ms">
      <button kendoButton fillMode="flat" (click)="backToLanding()">← Back / 返回</button>
      <span class="bar__date">{{ sessionDate | date:'EEE, MMM d, y' }}</span>
      <span *ngIf="editingSessionId != null" class="pill pill--draft">Editing / 編輯中</span>
      <span class="bar__spacer"></span>
      <button *ngIf="editingSessionId != null" kendoButton fillMode="flat" (click)="backToLanding()">Cancel / 取消</button>
    </div>

    <!-- Two-column working area -->
    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
      <!-- Add giving -->
      <section class="card rise" style="--d: 80ms">
        <div class="card__head">
          <h2 class="card__title">Add Giving</h2>
          <span class="card__zh">錄入奉獻</span>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-x-4 gap-y-3">
          <label class="flex flex-col gap-1 md:col-span-2">Giver
            <kendo-dropdownlist *ngIf="!entry.isAnonymous" [data]="memberResults" textField="displayName" valueField="id"
              [valuePrimitive]="true" [filterable]="true" (filterChange)="onMemberFilter($event)"
              [(ngModel)]="selectedMemberId" (valueChange)="onMemberSelected($event)"
              placeholder="Search by name"></kendo-dropdownlist>
            <span *ngIf="entry.isAnonymous" class="flex items-center gap-2">
              <span class="anon-chip">Anonymous · 匿名</span>
              <button kendoButton fillMode="flat" size="small" (click)="clearAnonymous()">Clear</button>
            </span>
          </label>

          <label class="flex flex-col gap-1">Type
            <kendo-dropdownlist [data]="categories" textField="label" valueField="id" [valuePrimitive]="true"
              [(ngModel)]="entry.givingCategoryId"></kendo-dropdownlist>
          </label>
          <label class="flex flex-col gap-1">Method
            <kendo-dropdownlist [data]="paymentMethods" textField="label" valueField="value" [valuePrimitive]="true"
              [(ngModel)]="entry.paymentMethod"></kendo-dropdownlist>
          </label>

          <label *ngIf="entry.paymentMethod === 'Check'" class="flex flex-col gap-1">Check #
            <kendo-textbox [(ngModel)]="entry.checkNumber"></kendo-textbox>
          </label>
          <label class="flex flex-col gap-1">Amount
            <kendo-numerictextbox [(ngModel)]="entry.amount" [min]="0" [format]="'c2'"
              (keydown.enter)="addLine()"></kendo-numerictextbox>
          </label>

          <label class="flex flex-col gap-1 md:col-span-2">Notes
            <kendo-textbox [(ngModel)]="entry.notes" (keydown.enter)="addLine()"></kendo-textbox>
          </label>

          <div class="flex flex-wrap gap-2 md:col-span-2">
            <button kendoButton (click)="markAnonymous()">Anonymous</button>
            <button kendoButton (click)="showQuickAdd = true">+ Quick add member</button>
            <button kendoButton themeColor="primary" (click)="addLine()">{{ editingIndex !== null ? 'Update line' : '+ Add (Enter)' }}</button>
          </div>
        </div>
      </section>

      <!-- Lines -->
      <section class="card rise" style="--d: 160ms">
        <div class="card__head">
          <h2 class="card__title">Lines</h2>
          <span class="card__zh">已加入明細</span>
        </div>

        <div *ngIf="buffer.length === 0" class="empty">No lines yet — add givings on the left.<br><span>尚無明細 — 由左側錄入</span></div>
        <kendo-grid class="lined" *ngIf="buffer.length > 0" [data]="buffer">
          <kendo-grid-column title="Giver">
            <ng-template kendoGridCellTemplate let-l>{{ l.isAnonymous ? '(Anonymous)' : l.memberName }}</ng-template>
          </kendo-grid-column>
          <kendo-grid-column field="categoryName" title="Type"></kendo-grid-column>
          <kendo-grid-column field="paymentMethod" title="Method" [width]="90"></kendo-grid-column>
          <kendo-grid-column field="checkNumber" title="Check #" [width]="90"></kendo-grid-column>
          <kendo-grid-column field="amount" title="Amount" [width]="110" format="c2"></kendo-grid-column>
          <kendo-grid-column title="" [width]="110">
            <ng-template kendoGridCellTemplate let-l let-i="rowIndex">
              <button kendoButton fillMode="flat" (click)="editLine(i)">Edit</button>
              <button kendoButton fillMode="flat" (click)="removeLine(i)">×</button>
            </ng-template>
          </kendo-grid-column>
        </kendo-grid>
        <div *ngIf="buffer.length > 0" class="lines-footer">Lines: {{ buffer.length }} · System total: {{ systemTotal | currency }}</div>
      </section>
    </div>

    <!-- Paper proof -->
    <section class="card rise" style="--d: 200ms">
      <div class="card__head">
        <h2 class="card__title">Paper Proof</h2>
        <span class="card__zh">紙本證明</span>
      </div>

      <p class="proof-hint">
        Attach photos or PDFs of the count sheets / envelopes. Images are compressed and all files
        are merged into a single PDF when you submit.
        <br><span>附上點算單／信封的照片或 PDF。圖片會自動壓縮，送出時合併為單一 PDF。</span>
      </p>

      <input type="file" multiple accept="image/*,application/pdf"
        class="proof-input" (change)="onProofFilesSelected($event)" />

      <ul *ngIf="pendingProofFiles.length" class="proof-list">
        <li *ngFor="let f of pendingProofFiles; let i = index">
          <span class="proof-name">{{ f.name }}</span>
          <button kendoButton fillMode="flat" size="small" (click)="removeProofFile(i)">×</button>
        </li>
      </ul>

      <p *ngIf="editingSessionId != null && pendingProofFiles.length" class="proof-warn">
        Selecting files here replaces any existing proof for this session.
        <br><span>於此選擇檔案會取代此 session 既有的證明。</span>
      </p>
    </section>

    <!-- Reconcile & submit -->
    <section class="card rise" style="--d: 240ms">
      <div class="card__head">
        <h2 class="card__title">Reconcile &amp; Submit</h2>
        <span class="card__zh">對帳</span>
      </div>

      <div class="grid grid-cols-1 md:grid-cols-2 gap-x-4 gap-y-3">
        <label class="flex flex-col gap-1">Cash counted
          <kendo-numerictextbox [(ngModel)]="cashTotal" [min]="0" [format]="'c2'"></kendo-numerictextbox>
        </label>
        <label class="flex flex-col gap-1">Check counted
          <kendo-numerictextbox [(ngModel)]="checkTotal" [min]="0" [format]="'c2'"></kendo-numerictextbox>
        </label>
        <label class="flex flex-col gap-1 md:col-span-2">Session notes
          <kendo-textarea [(ngModel)]="notes" [rows]="2"></kendo-textarea>
        </label>
      </div>

      <div class="reconcile-bar">
        <span>System total: <strong>{{ systemTotal | currency }}</strong></span>
        <span [class.ok]="difference === 0" [class.bad]="difference !== 0">Difference: {{ difference | currency }}</span>
        <span class="bar__spacer"></span>
        <button kendoButton themeColor="primary" size="large"
          [disabled]="buffer.length === 0 || (editingSessionId == null && dateConflict) || submitting"
          (click)="submit()">{{ editingSessionId != null ? 'Update Session' : 'Submit' }}</button>
      </div>
    </section>
  </ng-container>

  <!-- ============================ VIEW (read-only) ============================ -->
  <ng-container *ngIf="mode === 'view' && viewSession as v">
    <!-- Session bar -->
    <div class="bar rise" style="--d: 0ms">
      <button kendoButton fillMode="flat" (click)="backToLanding()">← Back / 返回</button>
      <span class="bar__date">{{ v.sessionDate }}</span>
      <span class="pill" [ngClass]="'pill--' + v.status.toLowerCase()">{{ v.status }}</span>
      <span class="bar__spacer"></span>
      <button *ngIf="v.status !== 'Reconciled'" kendoButton themeColor="primary" (click)="editFromView()">Edit / 修改</button>
    </div>

    <!-- Summary tiles -->
    <section class="stats rise" style="--d: 80ms">
      <div class="stat">
        <span class="stat__label">System Total · 系統合計</span>
        <span class="stat__value">{{ v.systemTotal | currency }}</span>
      </div>
      <div class="stat">
        <span class="stat__label">Cash · 現金</span>
        <span class="stat__value">{{ v.cashTotal | currency }}</span>
      </div>
      <div class="stat">
        <span class="stat__label">Check · 支票</span>
        <span class="stat__value">{{ v.checkTotal | currency }}</span>
      </div>
      <div class="stat">
        <span class="stat__label">Difference · 差額</span>
        <span class="stat__value" [class.ok]="v.difference === 0" [class.bad]="v.difference !== 0">{{ v.difference | currency }}</span>
      </div>
    </section>

    <!-- Lines (read-only) -->
    <section class="card rise" style="--d: 160ms">
      <div class="card__head">
        <h2 class="card__title">Lines</h2>
        <span class="card__zh">奉獻明細</span>
      </div>
      <kendo-grid class="lined" [data]="v.givings">
        <kendo-grid-column title="Giver">
          <ng-template kendoGridCellTemplate let-l>{{ l.isAnonymous ? '(Anonymous)' : l.memberName }}</ng-template>
        </kendo-grid-column>
        <kendo-grid-column field="categoryName" title="Type"></kendo-grid-column>
        <kendo-grid-column field="paymentMethod" title="Method" [width]="90"></kendo-grid-column>
        <kendo-grid-column field="checkNumber" title="Check #" [width]="90"></kendo-grid-column>
        <kendo-grid-column field="amount" title="Amount" [width]="110" format="c2"></kendo-grid-column>
      </kendo-grid>
    </section>

    <!-- Paper proof (view) -->
    <section class="card rise" style="--d: 200ms">
      <div class="card__head">
        <h2 class="card__title">Paper Proof</h2>
        <span class="card__zh">紙本證明</span>
      </div>

      <input #proofInput type="file" multiple accept="image/*,application/pdf" hidden
        (change)="replaceProof($event)" />

      <div class="flex flex-wrap gap-2 items-center">
        <ng-container *ngIf="v.hasProof; else noProof">
          <button kendoButton themeColor="primary" (click)="openProof(v.id)" [disabled]="proofBusy">View proof PDF / 檢視證明</button>
          <button kendoButton (click)="proofInput.click()" [disabled]="proofBusy">Replace / 更換</button>
          <button kendoButton fillMode="flat" (click)="removeProof()" [disabled]="proofBusy">Remove / 移除</button>
        </ng-container>
        <ng-template #noProof>
          <span class="proof-none">No proof attached · 尚未附上證明</span>
          <button kendoButton themeColor="primary" (click)="proofInput.click()" [disabled]="proofBusy">Add proof / 新增證明</button>
        </ng-template>
        <span *ngIf="proofBusy" class="proof-busy">Working… · 處理中…</span>
      </div>
    </section>

    <!-- Session notes -->
    <section *ngIf="v.notes" class="card rise" style="--d: 280ms">
      <div class="card__head">
        <h2 class="card__title">Notes</h2>
        <span class="card__zh">備註</span>
      </div>
      <p class="notes-text">{{ v.notes }}</p>
    </section>
  </ng-container>

  <!-- Reopen confirm dialog -->
  <kendo-dialog *ngIf="confirmReopenOpen" title="Reopen session? / 重新開啟" (close)="confirmReopenOpen = false" [width]="440" [maxWidth]="'95vw'">
    <p class="dialog-text">
      Editing a submitted session will reopen it and set its status back to <strong>Draft</strong> until you submit again.
      <br><span>編輯已送出的 session 會重新開啟並將狀態改回草稿，直到再次送出。</span>
    </p>
    <kendo-dialog-actions>
      <button kendoButton (click)="confirmReopenOpen = false">Cancel / 取消</button>
      <button kendoButton themeColor="primary" (click)="confirmReopen()">Reopen &amp; Edit / 確認</button>
    </kendo-dialog-actions>
  </kendo-dialog>

  <app-member-quick-add-dialog *ngIf="showQuickAdd" (created)="onMemberQuickCreated($event)"
    (cancelled)="showQuickAdd = false"></app-member-quick-add-dialog>

  <!-- ============================ EDIT SUNDAY ATTENDANCE ============================ -->
  <kendo-dialog *ngIf="attDialogOpen" title="修改主日參加人數 · Edit Sunday Attendance"
    (close)="attDialogOpen = false" [width]="440" [maxWidth]="'95vw'">
    <div class="grid grid-cols-1 md:grid-cols-3 gap-x-4 gap-y-3">
      <label class="flex flex-col gap-1">成人 Adult
        <kendo-numerictextbox [(ngModel)]="attForm.adult" [format]="'n0'" [decimals]="0" [min]="0"></kendo-numerictextbox>
      </label>
      <label class="flex flex-col gap-1">青年 Youth
        <kendo-numerictextbox [(ngModel)]="attForm.youth" [format]="'n0'" [decimals]="0" [min]="0"></kendo-numerictextbox>
      </label>
      <label class="flex flex-col gap-1">兒童 Kid
        <kendo-numerictextbox [(ngModel)]="attForm.kid" [format]="'n0'" [decimals]="0" [min]="0"></kendo-numerictextbox>
      </label>
    </div>
    <div class="att-total">總數 Total: {{ attTotal }}</div>
    <kendo-dialog-actions>
      <button kendoButton (click)="attDialogOpen = false">Cancel</button>
      <button kendoButton themeColor="primary" [disabled]="attSaving" (click)="saveAttendance()">Save</button>
    </kendo-dialog-actions>
  </kendo-dialog>
</div>
