<script setup lang="ts">
import {
  currencies,
  currencyMinorUnits,
  type CurrencyCode,
  type EntryType,
  type LedgerEntry,
} from "@cents/domain";
import {
  ArrowLeft,
  BookOpen,
  CalendarDays,
  Check,
  ChevronRight,
  CircleUserRound,
  CloudOff,
  NotebookText,
  RotateCcw,
  Trash2,
  WalletCards,
  X,
} from "@lucide/vue";
import { computed, onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  categories,
  entryTypes,
  findCategory,
  findCategoryPath,
  type Category,
} from "../data/categories";
import { ledgerTheme } from "../data/ledgers";
import { createEntry } from "../data/entries";
import {
  isReimbursement,
  netOriginalAmount,
  reimbursementsForExpense,
  reimbursedOriginalAmount,
} from "../data/reimbursements";
import { useAuthStore } from "../stores/auth";
import { useEntryStore } from "../stores/entries";
import { useLedgerStore } from "../stores/ledgers";
import CurrencyPicker from "../components/CurrencyPicker.vue";

type CategorySheetMode = "parent" | "child";

const route = useRoute();
const router = useRouter();
const store = useEntryStore();
const authStore = useAuthStore();
const ledgerStore = useLedgerStore();
const entry = ref<LedgerEntry | null>(null);
const loading = ref(true);
const saving = ref(false);
const savedToast = ref(false);
const errorMessage = ref("");
const categorySheetMode = ref<CategorySheetMode | null>(null);
const ledgerPickerOpen = ref(false);
const dateInput = ref<HTMLInputElement | null>(null);
const currencyPickerOpen = ref(false);
const reimbursementOpen = ref(false);
const reimbursementAmount = ref("");
const reimbursementOccurredAt = ref("");
const reimbursementNote = ref("");
const reimbursementSaving = ref(false);

const amount = ref("");
const currency = ref<CurrencyCode>("CNY");
const ledgerIds = ref<string[]>([]);
const parentCategoryId = ref("");
const childCategoryId = ref("");
const note = ref("");
const occurredAt = ref("");

const entryType = computed<EntryType>(() => entry.value?.type ?? "expense");
const reimbursementEntry = computed(() => entry.value ? isReimbursement(entry.value) : false);
const categoryEntryType = computed<EntryType>(() => reimbursementEntry.value ? "expense" : entryType.value);
const typeOption = computed(() => entryTypes.find((type) => type.id === entryType.value)!);
const parentCategories = computed(() => categories[categoryEntryType.value]);
const selectedParent = computed(() =>
  parentCategories.value.find((category) => category.id === parentCategoryId.value),
);
const childCategories = computed(() => selectedParent.value?.children ?? []);
const selectedChild = computed(() =>
  childCategories.value.find((category) => category.id === childCategoryId.value),
);
const selectedCategory = computed(() => selectedChild.value ?? selectedParent.value);
const dateLabel = computed(() => {
  if (!occurredAt.value) return "请选择时间";
  const date = new Date(occurredAt.value);
  return new Intl.DateTimeFormat("zh-CN", {
    year: "numeric",
    month: "long",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
    hour12: false,
  }).format(date);
});
const timeInvalid = computed(() => {
  if (!occurredAt.value) return true;
  return Number.isNaN(new Date(occurredAt.value).getTime());
});
const linkedLedgerNames = computed(() =>
  ledgerStore.ledgers
    .filter((ledger) => ledgerIds.value.includes(ledger.id))
    .map((ledger) => ledger.name),
);
const ledgerLabel = computed(() => linkedLedgerNames.value.join("、") || "未知账本");
const createdAtLabel = computed(() => {
  if (!entry.value) return "";
  return new Intl.DateTimeFormat("zh-CN", {
    year: "numeric",
    month: "long",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
    hour12: false,
  }).format(new Date(entry.value.createdAt));
});
const currencySymbol = computed(() => currencies[currency.value].symbol);
const conversionLabel = computed(() => {
  if (!entry.value || entry.value.currency === "CNY") return "";
  if (entry.value.baseAmount === null) return "人民币金额等待后台换算";
  const rateDate = entry.value.exchangeRateEffectiveDate ?? entry.value.exchangeRateDate;
  return `约 ¥${(entry.value.baseAmount / 100).toLocaleString("zh-CN", { minimumFractionDigits: 2, maximumFractionDigits: 2 })} · ${rateDate}${entry.value.conversionStatus === "fallback" ? " 最近汇率" : ""}`;
});
const sourceExpense = computed(() =>
  entry.value?.reimbursementOfEntryId
    ? store.entries.find((item) => item.id === entry.value?.reimbursementOfEntryId) ?? null
    : null,
);
const expenseReimbursements = computed(() =>
  entry.value?.type === "expense" ? reimbursementsForExpense(store.entries, entry.value.id) : [],
);
const reimbursementLocked = computed(() => reimbursementEntry.value || expenseReimbursements.value.length > 0);
const reimbursedAmount = computed(() =>
  entry.value?.type === "expense" ? reimbursedOriginalAmount(entry.value, store.entries) : 0,
);
const remainingReimbursement = computed(() =>
  entry.value?.type === "expense" ? Math.max(0, entry.value.amount - reimbursedAmount.value) : 0,
);
const netExpenseAmount = computed(() =>
  entry.value?.type === "expense" ? netOriginalAmount(entry.value, store.entries) : 0,
);
const canRecordReimbursement = computed(() =>
  entry.value?.type === "expense"
  && entry.value.ownerId === authStore.user?.id
  && remainingReimbursement.value > 0,
);

onMounted(async () => {
  await Promise.all([store.loadEntries(), ledgerStore.loadLedgers()]);
  hydrateCurrentEntry();
  loading.value = false;
});

watch(() => route.params.id, () => {
  hydrateCurrentEntry();
});

function hydrateCurrentEntry() {
  const found = store.entries.find((item) => item.id === String(route.params.id));
  if (!found) return;
  categorySheetMode.value = null;
  ledgerPickerOpen.value = false;
  currencyPickerOpen.value = false;
  reimbursementOpen.value = false;
  errorMessage.value = "";
  hydrate(found);
}

function hydrate(value: LedgerEntry) {
  entry.value = value;
  currency.value = value.currency;
  const minorUnits = currencyMinorUnits(value.currency);
  amount.value = (value.amount / 10 ** minorUnits).toFixed(minorUnits);
  ledgerIds.value = [...new Set([...value.ledgerIds, ledgerStore.personalLedger?.id].filter((id): id is string => Boolean(id)))];
  note.value = value.note;
  occurredAt.value = toLocalDateTime(new Date(value.occurredAt));
  const path = findCategoryPath(value.reimbursementOfEntryId ? "expense" : value.type, value.categoryId);
  parentCategoryId.value = path[0]?.id ?? "";
  childCategoryId.value = path[1]?.id ?? "";
}

function toLocalDateTime(date: Date) {
  const pad = (value: number) => String(value).padStart(2, "0");
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
}

function openDatePicker() {
  const input = dateInput.value;
  if (!input) return;
  if (typeof input.showPicker === "function") input.showPicker();
  else input.click();
}

function chooseParent(category: Category) {
  const parentChanged = parentCategoryId.value !== category.id;
  parentCategoryId.value = category.id;
  if (parentChanged) childCategoryId.value = "";
  categorySheetMode.value = null;
}

function clearCategory() {
  parentCategoryId.value = "";
  childCategoryId.value = "";
  categorySheetMode.value = null;
}

function chooseChild(category: Category) {
  childCategoryId.value = category.id;
  categorySheetMode.value = null;
}

function toggleLedger(ledgerId: string) {
  if (reimbursementEntry.value) return;
  if (ledgerId === ledgerStore.personalLedger?.id) return;
  if (ledgerIds.value.includes(ledgerId)) {
    if (ledgerIds.value.length > 1) ledgerIds.value = ledgerIds.value.filter((id) => id !== ledgerId);
    return;
  }
  ledgerIds.value = [...ledgerIds.value, ledgerId];
}

function formatEntryAmount(value: number, code = currency.value) {
  return new Intl.NumberFormat("zh-CN", {
    style: "currency",
    currency: code,
    currencyDisplay: "narrowSymbol",
    minimumFractionDigits: currencyMinorUnits(code),
    maximumFractionDigits: currencyMinorUnits(code),
  }).format(value / 10 ** currencyMinorUnits(code));
}

function formatShortDate(value: string) {
  return new Intl.DateTimeFormat("zh-CN", {
    month: "numeric",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
    hour12: false,
  }).format(new Date(value));
}

function openReimbursement() {
  if (!entry.value || !canRecordReimbursement.value) return;
  const minorUnits = currencyMinorUnits(entry.value.currency);
  reimbursementAmount.value = (remainingReimbursement.value / 10 ** minorUnits).toFixed(minorUnits);
  reimbursementOccurredAt.value = toLocalDateTime(new Date());
  reimbursementNote.value = "";
  errorMessage.value = "";
  reimbursementOpen.value = true;
}

async function saveReimbursement() {
  if (!entry.value || reimbursementSaving.value) return;
  const numericAmount = Number(reimbursementAmount.value.replaceAll(",", ""));
  const minorAmount = Math.round(numericAmount * 10 ** currencyMinorUnits(entry.value.currency));
  const occurredDate = new Date(reimbursementOccurredAt.value);
  if (
    !Number.isFinite(numericAmount)
    || minorAmount <= 0
    || minorAmount > remainingReimbursement.value
  ) {
    errorMessage.value = "报销金额应大于 0 且不超过剩余可报销金额";
    return;
  }
  if (Number.isNaN(occurredDate.getTime())) {
    errorMessage.value = "请选择报销到账时间";
    return;
  }

  reimbursementSaving.value = true;
  errorMessage.value = "";
  try {
    await store.addEntry(createEntry({
      ledgerIds: [...entry.value.ledgerIds],
      type: "income",
      amount: minorAmount,
      currency: entry.value.currency,
      categoryId: entry.value.categoryId,
      note: reimbursementNote.value.trim() || `${entry.value.note || selectedCategory.value?.label || "支出"}报销`,
      occurredAt: occurredDate.toISOString(),
      createdBy: authStore.user?.id,
      reimbursementOfEntryId: entry.value.id,
    }));
    reimbursementOpen.value = false;
    savedToast.value = true;
    window.setTimeout(() => (savedToast.value = false), 1600);
  } catch (error) {
    errorMessage.value = error instanceof Error ? error.message : "记录报销失败";
  } finally {
    reimbursementSaving.value = false;
  }
}

async function saveEntry() {
  if (!entry.value || saving.value) return;
  const numericAmount = Number(amount.value.replaceAll(",", ""));
  if (!Number.isFinite(numericAmount) || numericAmount <= 0) {
    errorMessage.value = "请输入有效金额";
    return;
  }
  const occurredDate = new Date(occurredAt.value);
  if (timeInvalid.value) {
    errorMessage.value = "请选择时间";
    return;
  }

  saving.value = true;
  errorMessage.value = "";
  try {
    const minorAmount = Math.round(numericAmount * 10 ** currencyMinorUnits(currency.value));
    const updated = await store.updateEntry({
      ...entry.value,
      amount: minorAmount,
      currency: currency.value,
      ledgerIds: [...ledgerIds.value],
      categoryId: reimbursementEntry.value
        ? entry.value.categoryId
        : childCategoryId.value || parentCategoryId.value || entryType.value,
      note: note.value.trim(),
      occurredAt: occurredDate.toISOString(),
    });
    hydrate(updated);
    savedToast.value = true;
    window.setTimeout(() => (savedToast.value = false), 1600);
  } catch (error) {
    console.error("Failed to save entry locally", error);
    errorMessage.value = "保存失败，请重试";
  } finally {
    saving.value = false;
  }
}

async function deleteEntry() {
  if (!entry.value) return;
  if (entry.value.type === "expense" && expenseReimbursements.value.length) {
    errorMessage.value = "存在报销记录，请先删除关联的报销到账";
    return;
  }
  const count = ledgerIds.value.length;
  const message = `确定从这笔账目关联的全部账本中删除吗？\n\n共 ${count} 个账本，删除后无法恢复。`;
  if (!window.confirm(message)) return;
  try {
    await store.deleteEntry(entry.value.id);
    await router.back();
  } catch (error) {
    errorMessage.value = error instanceof Error ? error.message : "删除失败";
  }
}
</script>

<template>
  <main class="app-shell entry-detail-shell">
    <header class="entry-detail-appbar">
      <button class="entry-detail-icon-button" type="button" aria-label="返回" title="返回" @click="router.back()">
        <ArrowLeft :size="22" />
      </button>
      <strong>条目明细</strong>
      <span aria-hidden="true"></span>
    </header>

    <div v-if="loading" class="entry-detail-state">正在载入...</div>
    <div v-else-if="!entry" class="entry-detail-state">
      <strong>条目不存在</strong>
      <button type="button" @click="router.back()">返回</button>
    </div>

    <form v-else class="entry-detail-form" @submit.prevent="saveEntry">
      <div class="entry-detail-scroll">
        <section class="entry-detail-amount" :class="entryType">
          <div
            class="entry-detail-category-mark"
            :style="{
              color: reimbursementEntry ? '#287c70' : selectedCategory?.color ?? typeOption.color,
              background: reimbursementEntry ? '#e8f6f2' : selectedCategory?.tint ?? typeOption.tint,
            }"
          >
            <RotateCcw v-if="reimbursementEntry" :size="27" />
            <component v-else :is="selectedCategory?.icon ?? typeOption.icon" :size="27" />
          </div>
          <span class="entry-type-label">{{ reimbursementEntry ? "报销到账" : typeOption.label }}</span>
          <label class="entry-amount-input">
            <button type="button" :disabled="reimbursementLocked" :aria-label="`切换币种，当前${currencies[currency].name}`" @click="currencyPickerOpen = true">
              {{ currencySymbol }}
            </button>
            <input v-model="amount" inputmode="decimal" aria-label="金额" />
          </label>
          <span v-if="conversionLabel" class="entry-conversion-label">{{ conversionLabel }}</span>
        </section>

        <section class="entry-edit-fields" aria-label="编辑条目">
          <button class="entry-edit-row" type="button" :disabled="reimbursementLocked" @click="categorySheetMode = 'parent'">
            <span class="entry-field-icon category"><WalletCards :size="19" /></span>
            <span class="entry-field-copy"><small>大类</small><strong>{{ selectedParent?.label ?? "请选择" }}</strong></span>
            <ChevronRight :size="19" />
          </button>

          <button
            class="entry-edit-row"
            type="button"
            :disabled="reimbursementLocked || !childCategories.length"
            @click="categorySheetMode = 'child'"
          >
            <span class="entry-field-icon subcategory">
              <component :is="selectedParent?.icon ?? WalletCards" :size="19" />
            </span>
            <span class="entry-field-copy">
              <small>小类</small>
              <strong>{{ childCategories.length ? selectedChild?.label ?? "未选择" : "无小类" }}</strong>
            </span>
            <ChevronRight v-if="childCategories.length" :size="19" />
          </button>

          <button class="entry-edit-row" :class="{ invalid: timeInvalid }" type="button" @click="openDatePicker">
            <span class="entry-field-icon date"><CalendarDays :size="19" /></span>
            <span class="entry-field-copy"><small>时间</small><strong>{{ dateLabel }}</strong></span>
            <ChevronRight :size="19" />
          </button>
          <input
            ref="dateInput"
            v-model="occurredAt"
            class="entry-native-date-input"
            type="datetime-local"
            aria-label="时间"
            :aria-invalid="timeInvalid"
            tabindex="-1"
          />

          <button class="entry-edit-row ledger-associations" type="button" :disabled="reimbursementLocked" @click="ledgerPickerOpen = true">
            <span class="entry-field-icon ledger"><BookOpen :size="19" /></span>
            <span class="entry-field-copy"><small>关联账本 · {{ ledgerIds.length }} 个</small><strong>{{ ledgerLabel }}</strong></span>
            <ChevronRight :size="18" />
          </button>

          <div class="entry-edit-row readonly-row">
            <span class="entry-field-icon member"><CircleUserRound :size="19" /></span>
            <span class="entry-field-copy"><small>记录人</small><strong>{{ ledgerStore.memberName(entry.createdBy) }}</strong></span>
          </div>

          <label class="entry-note-row">
            <span class="entry-field-icon note"><NotebookText :size="19" /></span>
            <span class="entry-field-copy">
              <small>备注</small>
              <textarea v-model="note" maxlength="120" rows="3" placeholder="补充说明"></textarea>
            </span>
          </label>
        </section>

        <section v-if="entry.type === 'expense'" class="entry-reimbursement-card">
          <header>
            <span class="entry-field-icon reimbursement"><RotateCcw :size="19" /></span>
            <div><strong>报销</strong><small>{{ expenseReimbursements.length ? `${expenseReimbursements.length} 笔到账` : "尚未报销" }}</small></div>
          </header>
          <div v-if="expenseReimbursements.length" class="entry-reimbursement-math">
            <span><small>原支出</small><strong>{{ formatEntryAmount(entry.amount, entry.currency) }}</strong></span>
            <span><small>已报销</small><strong>− {{ formatEntryAmount(reimbursedAmount, entry.currency) }}</strong></span>
            <span><small>净支出</small><strong>{{ formatEntryAmount(netExpenseAmount, entry.currency) }}</strong></span>
          </div>
          <div v-if="expenseReimbursements.length" class="entry-reimbursement-list">
            <RouterLink v-for="item in expenseReimbursements" :key="item.id" :to="`/entries/${item.id}`">
              <span><RotateCcw :size="15" />{{ formatShortDate(item.occurredAt) }}</span>
              <strong>+ {{ formatEntryAmount(item.amount, item.currency) }}</strong>
              <ChevronRight :size="16" />
            </RouterLink>
          </div>
          <button v-if="canRecordReimbursement" class="entry-reimbursement-action" type="button" @click="openReimbursement">
            <RotateCcw :size="17" />记录报销
          </button>
          <p v-else-if="remainingReimbursement === 0">已全额报销</p>
        </section>

        <RouterLink v-else-if="reimbursementEntry && sourceExpense" class="entry-reimbursement-card source" :to="`/entries/${sourceExpense.id}`">
          <span class="entry-field-icon reimbursement"><RotateCcw :size="19" /></span>
          <div>
            <small>关联原支出</small>
            <strong>{{ sourceExpense.note || findCategory(sourceExpense.categoryId)?.label || "支出" }}</strong>
          </div>
          <span>{{ formatEntryAmount(sourceExpense.amount, sourceExpense.currency) }}</span>
          <ChevronRight :size="17" />
        </RouterLink>

        <p class="entry-created-at">
          <span v-if="store.isEntryPending(entry.id)" class="entry-sync-pending" role="img" aria-label="未同步云端" title="未同步云端"><CloudOff :size="13" /></span>
          由{{ ledgerStore.memberName(entry.createdBy) }}创建 · {{ createdAtLabel }}
        </p>
        <p v-if="errorMessage" class="entry-save-error" role="alert">{{ errorMessage }}</p>
      </div>

      <div class="entry-detail-actions">
        <button class="entry-delete-button" type="button" aria-label="从所有关联账本删除" title="从所有关联账本删除" @click="deleteEntry">
          <Trash2 :size="20" />
        </button>
        <button class="entry-save-button" type="submit" :disabled="saving">
          <Check :size="19" />{{ saving ? "保存中" : "保存修改" }}
        </button>
      </div>
    </form>

    <Transition name="sheet">
      <div v-if="categorySheetMode" class="entry-category-layer">
        <button class="entry-category-scrim" type="button" aria-label="关闭类别选择" @click="categorySheetMode = null"></button>
        <section class="entry-category-sheet" :aria-label="categorySheetMode === 'parent' ? '选择大类' : '选择小类'">
          <div class="entry-sheet-handle"></div>
          <header>
            <strong>{{ categorySheetMode === "parent" ? "选择大类" : "选择小类" }}</strong>
            <button type="button" aria-label="关闭" title="关闭" @click="categorySheetMode = null"><X :size="20" /></button>
          </header>

          <div v-if="categorySheetMode === 'parent'" class="entry-category-grid">
            <button
              type="button"
              :class="{ active: !parentCategoryId }"
              :style="{ '--category-color': '#6f7f83', '--category-tint': '#edf2f1' }"
              @click="clearCategory"
            >
              <span><X :size="23" /></span>
              <small>不选择</small>
              <Check v-if="!parentCategoryId" :size="15" />
            </button>
            <button
              v-for="category in parentCategories"
              :key="category.id"
              type="button"
              :class="{ active: parentCategoryId === category.id }"
              :style="{ '--category-color': category.color, '--category-tint': category.tint }"
              @click="chooseParent(category)"
            >
              <span><component :is="category.icon" :size="23" /></span>
              <small>{{ category.label }}</small>
              <Check v-if="parentCategoryId === category.id" :size="15" />
            </button>
          </div>

          <div v-else class="entry-subcategory-grid">
            <button
              v-for="category in childCategories"
              :key="category.id"
              type="button"
              :class="{ active: childCategoryId === category.id }"
              :style="{ '--category-color': category.color, '--category-tint': category.tint }"
              @click="chooseChild(category)"
            >
              <span><component :is="category.icon" :size="22" /></span>
              <strong>{{ category.label }}</strong>
              <Check v-if="childCategoryId === category.id" :size="16" />
            </button>
          </div>
        </section>
      </div>
    </Transition>

    <CurrencyPicker v-model="currency" :open="currencyPickerOpen" @close="currencyPickerOpen = false" />

    <div v-if="ledgerPickerOpen" class="quick-ledger-picker-layer">
      <button class="quick-ledger-picker-scrim" type="button" aria-label="关闭账本选择" @click="ledgerPickerOpen = false"></button>
      <section class="quick-ledger-picker" aria-label="选择关联账本">
        <div class="quick-ledger-picker-handle"></div>
        <header><div><strong>选择账本</strong><span>至少选择一个账本</span></div><button type="button" aria-label="关闭" @click="ledgerPickerOpen = false"><X :size="19" /></button></header>
        <div class="quick-ledger-options">
          <button v-for="ledger in ledgerStore.ledgers" :key="ledger.id" type="button" :class="{ selected: ledgerIds.includes(ledger.id), automatic: ledger.isPersonal }" :disabled="ledger.isPersonal" @click="toggleLedger(ledger.id)">
            <span :style="{ background: ledgerTheme(ledger.theme).gradient }"><BookOpen :size="17" /></span>
            <strong>{{ ledger.name }}<small v-if="ledger.isPersonal">自动记入</small></strong>
            <Check v-if="ledgerIds.includes(ledger.id)" :size="19" />
          </button>
        </div>
        <button class="quick-ledger-picker-done" type="button" @click="ledgerPickerOpen = false"><Check :size="18" />完成</button>
      </section>
    </div>

    <Transition name="sheet">
      <div v-if="reimbursementOpen" class="entry-category-layer reimbursement-layer">
        <button class="entry-category-scrim" type="button" aria-label="关闭记录报销" @click="reimbursementOpen = false"></button>
        <form class="reimbursement-sheet" @submit.prevent="saveReimbursement">
          <div class="entry-sheet-handle"></div>
          <header>
            <div><strong>记录报销</strong><small>剩余 {{ entry ? formatEntryAmount(remainingReimbursement, entry.currency) : "" }}</small></div>
            <button type="button" aria-label="关闭" title="关闭" @click="reimbursementOpen = false"><X :size="20" /></button>
          </header>
          <label class="reimbursement-amount">
            <span>{{ entry ? currencies[entry.currency].symbol : "¥" }}</span>
            <input v-model="reimbursementAmount" inputmode="decimal" aria-label="本次报销金额" autofocus />
          </label>
          <label><span>到账时间</span><input v-model="reimbursementOccurredAt" type="datetime-local" /></label>
          <label><span>备注</span><input v-model="reimbursementNote" maxlength="120" placeholder="补充说明" /></label>
          <p v-if="errorMessage" role="alert">{{ errorMessage }}</p>
          <button class="reimbursement-submit" type="submit" :disabled="reimbursementSaving">
            <Check :size="18" />{{ reimbursementSaving ? "保存中" : "确认报销" }}
          </button>
        </form>
      </div>
    </Transition>

    <Transition name="toast">
      <div v-if="savedToast" class="entry-detail-toast" role="status"><Check :size="17" />修改已保存</div>
    </Transition>
  </main>
</template>

<style scoped>
.entry-detail-shell {
  color: #1d2926;
  background: #f5f8f7;
}

.entry-detail-appbar {
  position: relative;
  z-index: 3;
  height: calc(58px + env(safe-area-inset-top));
  display: grid;
  grid-template-columns: 44px 1fr 44px;
  align-items: end;
  gap: 8px;
  border-bottom: 1px solid #dce8e4;
  padding: env(safe-area-inset-top) 12px 7px;
  background: rgba(255, 255, 255, 0.97);
  backdrop-filter: blur(14px);
}

.entry-detail-appbar > strong {
  align-self: center;
  text-align: center;
  font-size: 17px;
}

.entry-detail-icon-button {
  width: 42px;
  height: 42px;
  display: grid;
  place-items: center;
  border: 0;
  border-radius: 8px;
  background: transparent;
  color: #31504a;
}

.entry-detail-form {
  height: calc(100% - 58px - env(safe-area-inset-top));
}

.entry-detail-scroll {
  height: 100%;
  overflow-y: auto;
  padding-bottom: calc(92px + env(safe-area-inset-bottom));
}

.entry-detail-amount {
  min-height: 184px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-bottom: 1px solid #dce7e4;
  padding: 22px 18px;
  background: #ffffff;
}

.entry-detail-category-mark {
  width: 52px;
  height: 52px;
  display: grid;
  place-items: center;
  border-radius: 12px;
}

.entry-type-label {
  margin-top: 7px;
  color: #73817d;
  font-size: 13px;
  font-weight: 650;
}

.entry-amount-input {
  width: min(100%, 270px);
  height: 52px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 7px;
  color: #d84c36;
}

.income .entry-amount-input {
  color: #0d8b67;
}

.entry-amount-input > button {
  min-width: 34px;
  border: 0;
  border-bottom: 1px dashed currentColor;
  padding: 0 2px 1px;
  background: transparent;
  color: inherit;
  font-size: 23px;
  font-weight: 700;
}

.entry-amount-input input {
  width: 200px;
  border: 0;
  padding: 0;
  outline: 0;
  background: transparent;
  color: inherit;
  font-size: 36px;
  font-weight: 760;
  font-variant-numeric: tabular-nums;
  text-align: center;
}

.entry-conversion-label {
  min-height: 16px;
  color: #7b8884;
  font-size: 11px;
}

.entry-edit-fields {
  margin-top: 12px;
  border-top: 1px solid #dce7e4;
  border-bottom: 1px solid #dce7e4;
  padding: 0 16px;
  background: #ffffff;
}

.entry-edit-row,
.entry-note-row {
  width: 100%;
  min-height: 64px;
  display: grid;
  grid-template-columns: 34px minmax(0, 1fr) auto;
  align-items: center;
  gap: 10px;
  border: 0;
  border-bottom: 1px solid #e3ece9;
  padding: 8px 0;
  background: transparent;
  color: #27342f;
  text-align: left;
}

.entry-edit-row:disabled {
  cursor: default;
  opacity: 0.62;
}

.entry-edit-row.invalid {
  border-bottom-color: transparent;
  border-radius: 8px;
  padding-right: 8px;
  padding-left: 8px;
  background: #fff3f0;
  color: #c83f2d;
  box-shadow: inset 0 0 0 1px #ef9a8c;
}

.entry-edit-row.invalid .entry-field-icon.date {
  background: #ffe2dc;
  color: #d44531;
}

.entry-edit-row.invalid .entry-field-copy small,
.entry-edit-row.invalid .entry-field-copy strong {
  color: #c83f2d;
}

.entry-field-icon {
  width: 32px;
  height: 32px;
  display: grid;
  place-items: center;
  border-radius: 8px;
}

.entry-field-icon.category { background: #fff0e8; color: #e85e2b; }
.entry-field-icon.subcategory { background: #fff7dd; color: #a56e05; }
.entry-field-icon.date { background: #fff7dd; color: #9b6d0f; }
.entry-field-icon.ledger { background: #e9f7f3; color: #087f72; }
.entry-field-icon.member { background: #edf4ff; color: #3478e5; }
.entry-field-icon.note { background: #f3efff; color: #7559d9; }

.entry-field-copy {
  min-width: 0;
  display: grid;
  gap: 2px;
}

.entry-field-copy small {
  color: #7b8884;
  font-size: 11px;
}

.entry-field-copy strong {
  min-width: 0;
  overflow: hidden;
  font-size: 14px;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.ledger-associations .entry-field-copy strong {
  overflow: visible;
  line-height: 1.4;
  text-overflow: clip;
  white-space: normal;
}

.entry-select-row {
  position: relative;
  grid-template-columns: 34px minmax(0, 1fr) 18px;
}

.entry-select-row select {
  position: absolute;
  inset: 0;
  width: 100%;
  opacity: 0;
  cursor: pointer;
}

.readonly-row {
  grid-template-columns: 34px minmax(0, 1fr);
}

.entry-note-row {
  align-items: start;
  border-bottom: 0;
  padding-top: 12px;
}

.entry-note-row .entry-field-icon {
  margin-top: 3px;
}

.entry-note-row textarea {
  width: 100%;
  min-height: 64px;
  border: 0;
  padding: 0;
  outline: 0;
  resize: none;
  background: transparent;
  color: #27342f;
  font-size: 14px;
  line-height: 1.45;
}

.entry-native-date-input {
  position: absolute;
  width: 1px;
  height: 1px;
  opacity: 0;
  pointer-events: none;
}

.entry-created-at {
  margin: 18px 16px 8px;
  color: #8b9693;
  text-align: center;
  font-size: 12px;
}

.entry-sync-pending {
  display: inline-flex;
  align-items: center;
  margin-right: 4px;
  color: #b35a24;
  vertical-align: -2px;
}

.entry-save-error {
  margin: 8px 16px;
  color: #c94635;
  text-align: center;
  font-size: 13px;
}

.entry-detail-actions {
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 4;
  display: grid;
  grid-template-columns: 48px 1fr;
  gap: 10px;
  border-top: 1px solid #d8e5e1;
  padding: 10px 16px calc(10px + env(safe-area-inset-bottom));
  background: rgba(255, 255, 255, 0.97);
  backdrop-filter: blur(14px);
}

.entry-detail-actions button {
  height: 46px;
  border-radius: 8px;
}

.entry-delete-button {
  display: grid;
  place-items: center;
  border: 1px solid #f1c8c2;
  background: #fff7f5;
  color: #c94635;
}

.entry-save-button {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 7px;
  border: 0;
  background: #087f72;
  color: #ffffff;
  font-weight: 720;
}

.entry-save-button:disabled {
  opacity: 0.65;
}

.entry-category-layer {
  position: absolute;
  inset: 0;
  z-index: 10;
}

.entry-category-scrim {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  border: 0;
  background: rgba(18, 35, 32, 0.42);
  backdrop-filter: blur(3px);
}

.entry-category-sheet {
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
  max-height: 68%;
  overflow-y: auto;
  border-radius: 14px 14px 0 0;
  padding: 0 16px calc(22px + env(safe-area-inset-bottom));
  background: #ffffff;
  box-shadow: 0 -16px 36px rgba(22, 45, 40, 0.22);
}

.entry-sheet-handle {
  width: 38px;
  height: 4px;
  margin: 8px auto 3px;
  border-radius: 2px;
  background: #b9cac5;
}

.entry-category-sheet header {
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.entry-category-sheet header > strong {
  font-size: 16px;
}

.entry-category-sheet header button {
  width: 38px;
  height: 38px;
  display: grid;
  place-items: center;
  border: 0;
  border-radius: 8px;
  background: #f0f5f3;
  color: #536762;
}

.entry-category-grid {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 16px 8px;
}

.entry-category-grid button {
  position: relative;
  min-width: 0;
  display: grid;
  place-items: center;
  gap: 5px;
  border: 0;
  padding: 0;
  background: transparent;
  color: #53615e;
}

.entry-category-grid button > span {
  width: 50px;
  height: 50px;
  display: grid;
  place-items: center;
  border: 2px solid transparent;
  border-radius: 50%;
  background: var(--category-tint);
  color: var(--category-color);
}

.entry-category-grid button.active > span {
  border-color: var(--category-color);
  box-shadow: 0 0 0 3px color-mix(in srgb, var(--category-color) 13%, white);
}

.entry-category-grid button > svg {
  position: absolute;
  top: 0;
  right: max(0px, calc(50% - 30px));
  border-radius: 50%;
  padding: 2px;
  background: var(--category-color);
  color: #ffffff;
}

.entry-category-grid small {
  overflow: hidden;
  font-size: 12px;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.entry-subcategory-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 10px;
}

.entry-subcategory-grid button {
  min-width: 0;
  height: 58px;
  display: grid;
  grid-template-columns: 32px minmax(0, 1fr) 18px;
  align-items: center;
  gap: 8px;
  border: 1px solid color-mix(in srgb, var(--category-color) 24%, #d8e4e1);
  border-radius: 8px;
  padding: 0 10px;
  background: var(--category-tint);
  color: var(--category-color);
  text-align: left;
}

.entry-subcategory-grid button.active {
  border-color: var(--category-color);
}

.entry-subcategory-grid button > span {
  width: 32px;
  height: 32px;
  display: grid;
  place-items: center;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.72);
}

.entry-subcategory-grid strong {
  overflow: hidden;
  font-size: 13px;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.entry-field-icon.reimbursement {
  background: #e8f6f2;
  color: #287c70;
}

.entry-reimbursement-card {
  margin-top: 12px;
  border-top: 1px solid #dce7e4;
  border-bottom: 1px solid #dce7e4;
  padding: 14px 16px;
  background: #ffffff;
}

.entry-reimbursement-card > header {
  display: grid;
  grid-template-columns: 34px minmax(0, 1fr);
  align-items: center;
  gap: 10px;
}

.entry-reimbursement-card > header div {
  display: grid;
  gap: 2px;
}

.entry-reimbursement-card > header small,
.entry-reimbursement-card.source small {
  color: #7b8884;
  font-size: 11px;
}

.entry-reimbursement-math {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  margin-top: 13px;
  border: 1px solid #e1ebe8;
  border-radius: 8px;
  background: #f8fbfa;
}

.entry-reimbursement-math span {
  min-width: 0;
  display: grid;
  gap: 4px;
  padding: 10px 8px;
  text-align: center;
}

.entry-reimbursement-math span + span {
  border-left: 1px solid #e1ebe8;
}

.entry-reimbursement-math small {
  color: #7b8884;
  font-size: 10px;
}

.entry-reimbursement-math strong {
  overflow: hidden;
  color: #31504a;
  font-size: 12px;
  text-overflow: ellipsis;
}

.entry-reimbursement-math span:nth-child(2) strong {
  color: #287c70;
}

.entry-reimbursement-list {
  margin-top: 8px;
}

.entry-reimbursement-list a {
  min-height: 42px;
  display: grid;
  grid-template-columns: minmax(0, 1fr) auto 18px;
  align-items: center;
  gap: 7px;
  border-bottom: 1px solid #edf2f0;
  color: #536762;
  text-decoration: none;
}

.entry-reimbursement-list a span {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
}

.entry-reimbursement-list a strong {
  color: #287c70;
  font-size: 12px;
}

.entry-reimbursement-action {
  width: 100%;
  min-height: 42px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 7px;
  margin-top: 12px;
  border: 1px solid #9bcfc3;
  border-radius: 8px;
  background: #edf8f5;
  color: #176d61;
  font-weight: 720;
}

.entry-reimbursement-card > p {
  margin: 12px 0 0;
  color: #287c70;
  text-align: center;
  font-size: 12px;
}

.entry-reimbursement-card.source {
  display: grid;
  grid-template-columns: 34px minmax(0, 1fr) auto 18px;
  align-items: center;
  gap: 10px;
  color: #27342f;
  text-decoration: none;
}

.entry-reimbursement-card.source > div {
  min-width: 0;
  display: grid;
  gap: 2px;
}

.entry-reimbursement-card.source > span:not(.entry-field-icon) {
  color: #687873;
  font-size: 12px;
}

.reimbursement-sheet {
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 2;
  display: grid;
  gap: 13px;
  border-radius: 8px 8px 0 0;
  padding: 8px 16px calc(16px + env(safe-area-inset-bottom));
  background: #ffffff;
  box-shadow: 0 -14px 34px rgba(22, 50, 44, 0.16);
}

.reimbursement-sheet > header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.reimbursement-sheet > header div {
  display: grid;
  gap: 2px;
}

.reimbursement-sheet > header small {
  color: #7b8884;
  font-size: 11px;
}

.reimbursement-sheet > header button {
  width: 38px;
  height: 38px;
  display: grid;
  place-items: center;
  border: 0;
  border-radius: 8px;
  background: #f0f5f3;
  color: #536762;
}

.reimbursement-sheet > label {
  display: grid;
  gap: 6px;
  color: #687873;
  font-size: 11px;
}

.reimbursement-sheet > label input {
  width: 100%;
  height: 44px;
  border: 1px solid #d8e5e1;
  border-radius: 8px;
  padding: 0 11px;
  outline: none;
  background: #fbfdfc;
  color: #27342f;
  font-size: 14px;
}

.reimbursement-sheet > label input:focus {
  border-color: #4b9e8e;
  box-shadow: 0 0 0 3px rgba(75, 158, 142, 0.12);
}

.reimbursement-sheet .reimbursement-amount {
  position: relative;
  display: flex;
  align-items: center;
  color: #287c70;
}

.reimbursement-amount > span {
  position: absolute;
  left: 12px;
  z-index: 1;
  font-size: 25px;
  font-weight: 720;
}

.reimbursement-sheet .reimbursement-amount input {
  height: 62px;
  padding-left: 44px;
  color: #287c70;
  font-size: 30px;
  font-weight: 760;
}

.reimbursement-sheet > p {
  margin: -4px 0;
  color: #c94635;
  font-size: 12px;
}

.reimbursement-submit {
  min-height: 46px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 7px;
  border: 0;
  border-radius: 8px;
  background: #287c70;
  color: #ffffff;
  font-weight: 760;
}

.reimbursement-submit:disabled {
  opacity: 0.55;
}

.entry-detail-toast {
  position: absolute;
  right: 50%;
  bottom: 82px;
  z-index: 20;
  min-height: 40px;
  display: flex;
  align-items: center;
  gap: 7px;
  transform: translateX(50%);
  border-radius: 8px;
  padding: 0 14px;
  background: #173c35;
  color: #ffffff;
  box-shadow: 0 10px 24px rgba(21, 50, 44, 0.2);
  font-size: 13px;
  white-space: nowrap;
}

.entry-detail-state {
  height: calc(100% - 58px);
  display: grid;
  place-items: center;
  align-content: center;
  gap: 10px;
  color: #71807c;
}

.entry-detail-state button {
  height: 40px;
  border: 0;
  border-radius: 8px;
  padding: 0 14px;
  background: #087f72;
  color: #ffffff;
}

.sheet-enter-active,
.sheet-leave-active {
  transition: opacity 180ms ease;
}

.sheet-enter-active .entry-category-sheet,
.sheet-leave-active .entry-category-sheet,
.sheet-enter-active .reimbursement-sheet,
.sheet-leave-active .reimbursement-sheet {
  transition: transform 220ms ease;
}

.sheet-enter-from,
.sheet-leave-to {
  opacity: 0;
}

.sheet-enter-from .entry-category-sheet,
.sheet-leave-to .entry-category-sheet,
.sheet-enter-from .reimbursement-sheet,
.sheet-leave-to .reimbursement-sheet {
  transform: translateY(100%);
}

@media (max-width: 360px) {
  .entry-edit-fields {
    padding-right: 12px;
    padding-left: 12px;
  }

  .entry-category-grid {
    column-gap: 4px;
  }

  .entry-subcategory-grid {
    grid-template-columns: 1fr;
  }
}
</style>
