<script setup lang="ts">
import { computed, onActivated, onMounted, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { Circle, CircleDot } from 'lucide-vue-next'
import {
  getQuickCalcGroups,
  getMajorDictItemById,
  getServiceDictItemById,
  getIndustryDisplayName,
  industryTypeList
} from '@/sql'
import { roundTo } from '@/lib/decimal'
import { parseNumberOrNull } from '@/lib/number'
import { useKvStore } from '@/pinia/kv'
import { loadConsultCategoryFactorMap, loadMajorFactorMap } from '@/lib/xmFactorDefaults'
import { getIndustryMajorEntry } from '@/lib/pricingScaleCalc'
import { getBenchmarkBudgetSplitByScale, getScaleBudgetFeeSplit } from '@/lib/pricingScaleFee'
import { QUICK_PROJECT_INFO_KEY } from '@/lib/workspace'
import { initializeProjectFactorStates } from '@/lib/projectWorkspace'

const props = defineProps<{
  contractId: string
  contractName?: string
  projectConsultCategoryFactorKey?: string
  projectMajorFactorKey?: string
}>()

interface QuickProjectInfoState {
  projectIndustry?: string
}

type DictFactorItem = {
  id: string
  name: string
  code: string
  defCoe: number | null
  hasCost?: boolean | null
  hasArea?: boolean | null
  scale?: boolean | null
  onlyCostScale?: boolean | null
}

type QuickCalcScaleMode = 'cost' | 'area'

const kvStore = useKvStore()
const { t, locale } = useI18n()
const consultFactorMap = ref<Map<string, number | null>>(new Map())
const majorFactorMap = ref<Map<string, number | null>>(new Map())
const quickCalcGroups = getQuickCalcGroups()

const projectIndustry = ref('')
const selectedConsultKey = ref('')
const selectedMajor = ref<{ groupKey: string; optionKey: string } | null>(null)
const investScale = ref('')
const landScale = ref('')
const workEnvFactor = ref('1')
const industrySaving = ref(false)
let latestIndustryRequest = 0

const hasSelectedIndustry = computed(() => projectIndustry.value.trim() !== '')
const hasSelectedConsult = computed(() => selectedConsultKey.value.trim() !== '')

const mapDictItemToFactorItem = (id: string, item: Record<string, unknown> | undefined): DictFactorItem | null => {
  if (!item) return null
  return {
    id,
    name: String(item.name || ''),
    code: String(item.code || ''),
    defCoe: typeof item.defCoe === 'number' ? item.defCoe : null,
    hasCost: item.hasCost === true,
    hasArea: item.hasArea === true,
    scale: item.scale === true,
    onlyCostScale: item.onlyCostScale === true
  }
}

const isDefined = <T,>(value: T | null | undefined): value is T => value != null

const resolveOptionId = (option: { id: string | Record<string, string> } | null) => {
  if (!option) return ''
  if (typeof option.id === 'string') return option.id
  const industry = projectIndustry.value.trim()
  return option.id[industry] || Object.values(option.id)[0] || ''
}

const shouldShowMajorOption = (
  group: { key: string },
  option: { id: string | Record<string, string> }
) => {
  if (!hasSelectedConsult.value) return false
  if (!consultSupportsScale.value) return false
  if (consultOnlySupportsCostScale.value) return false
  const majorDictItem = getMajorDictItemById(resolveOptionId(option))
  const code = String(majorDictItem?.code || '').trim()
  if (!code) return false
  const isLeafMajor = code.includes('-')
  return isLeafMajor
}

const visibleGroups = computed(() => {
  const industry = projectIndustry.value.trim()
  return quickCalcGroups
    .filter(group => {
      if (group.key === 'consult') return true
      if (!industry || !hasSelectedConsult.value) return false
      if (!group.industryId) return true
      return group.industryId === industry
    })
    .map(group => {
      const filteredItems = group.key === 'consult'
        ? group.items
        : group.items.filter(item => shouldShowMajorOption(group, item))
      const itemMap = new Map(filteredItems.map(item => [item.key, item]))
      return {
        ...group,
        items: filteredItems,
        rows: group.rows
          .map(row => row.map(optionKey => itemMap.get(optionKey)).filter(isDefined))
          .filter(row => row.length > 0)
      }
    })
    .filter(group => group.key === 'consult' || group.items.length > 0)
})

const industryLabel = computed(() => {
  const target = projectIndustry.value.trim()
  if (!target) return t('quickCalc.notSelected')
  return getIndustryDisplayName(target, locale.value) || t('quickCalc.notSelected')
})

const isIndustrySelected = (industryId: string | number) => {
  return projectIndustry.value.trim() === String(industryId).trim()
}

const handleIndustrySelect = (industryId: string | number) => {
  const nextIndustry = String(industryId).trim()
  projectIndustry.value = isIndustrySelected(nextIndustry) ? '' : nextIndustry
}

const selectedConsultOption = computed(() =>
  quickCalcGroups
    .find(item => item.key === 'consult')
    ?.items.find(item => item.key === selectedConsultKey.value) || null
)
const selectedMajorGroup = computed(() =>
  selectedMajor.value
    ? quickCalcGroups.find(item => item.key === selectedMajor.value?.groupKey) || null
    : null
)
const selectedMajorOption = computed(() => {
  if (!selectedMajor.value) return null
  const group = visibleGroups.value.find(item => item.key === selectedMajor.value?.groupKey)
  return group?.items.find(item => item.key === selectedMajor.value?.optionKey) || null
})
const selectedConsultId = computed(() => resolveOptionId(selectedConsultOption.value))
const selectedMajorId = computed(() => resolveOptionId(selectedMajorOption.value))
const selectedConsultCode = computed(() => String(selectedConsultDictItem.value?.code || ''))
const selectedConsultLabel = computed(() => selectedConsultOption.value?.label || '')
const selectedConsultDictItem = computed(() =>
  mapDictItemToFactorItem(selectedConsultId.value, getServiceDictItemById(selectedConsultId.value) as Record<string, unknown> | undefined)
)
const selectedMajorDictItem = computed(() => {
  if (!selectedMajor.value) return null
  return mapDictItemToFactorItem(selectedMajorId.value, getMajorDictItemById(selectedMajorId.value) as Record<string, unknown> | undefined)
})
const effectiveMajorDictItem = computed(() => {
  if (selectedMajorDictItem.value) return selectedMajorDictItem.value
  if (!consultOnlySupportsCostScale.value) return null
  const industryMajorEntry = getIndustryMajorEntry(projectIndustry.value.trim())
  if (!industryMajorEntry) return null
  return {
    id: String(industryMajorEntry.id),
    name: String(industryMajorEntry.item?.name || ''),
    code: String(industryMajorEntry.item?.code || ''),
    defCoe: typeof industryMajorEntry.item?.defCoe === 'number' ? industryMajorEntry.item.defCoe : null,
    hasCost: industryMajorEntry.item?.hasCost === true,
    hasArea: industryMajorEntry.item?.hasArea === true
  }
})
const consultCategoryFactor = computed(() => {
  const serviceId = selectedConsultDictItem.value?.id
  if (!serviceId) return null
  return consultFactorMap.value.get(serviceId) ?? null
})
const defaultEngineeringMajorFactor = computed(() => {
  const majorId = effectiveMajorDictItem.value?.id
  if (!majorId) return null
  return majorFactorMap.value.get(majorId) ?? null
})
const engineeringMajorFactor = computed(() => defaultEngineeringMajorFactor.value)
const hasResolvedMajor = computed(() => effectiveMajorDictItem.value != null)
const majorSupportsCostScale = computed(() => effectiveMajorDictItem.value?.hasCost === true)
const majorSupportsLandScale = computed(() => effectiveMajorDictItem.value?.hasArea === true)
const preferLandScaleForDualMajor = computed(() => majorSupportsCostScale.value && majorSupportsLandScale.value)
const workEnvCoefficient = computed(() =>
  parseNumberOrNull(workEnvFactor.value, { sanitize: true, precision: 3 })
)
const consultSupportsScale = computed(() => selectedConsultDictItem.value?.scale === true)
const consultOnlySupportsCostScale = computed(() => selectedConsultDictItem.value?.onlyCostScale === true)
const canUseInvestScale = computed(() =>
  consultSupportsScale.value &&
  hasResolvedMajor.value &&
  (
    consultOnlySupportsCostScale.value ||
    (majorSupportsCostScale.value && !preferLandScaleForDualMajor.value)
  )
)
const canUseLandScale = computed(() =>
  consultSupportsScale.value &&
  hasResolvedMajor.value &&
  !consultOnlySupportsCostScale.value &&
  majorSupportsLandScale.value
)
const investScalePlaceholder = computed(() => {
  if (!selectedConsultLabel.value) return t('quickCalc.placeholder.selectConsultFirst')
  if (!consultSupportsScale.value) return t('quickCalc.placeholder.scaleUnavailable')
  if (!hasResolvedMajor.value) return t('quickCalc.placeholder.selectMajorFirst')
  if (preferLandScaleForDualMajor.value) return t('quickCalc.placeholder.preferLandScale')
  if (!consultOnlySupportsCostScale.value && !majorSupportsCostScale.value) return t('quickCalc.placeholder.investUnavailable')
  return t('quickCalc.placeholder.input')
})
const landScalePlaceholder = computed(() => {
  if (!selectedConsultLabel.value) return t('quickCalc.placeholder.selectConsultFirst')
  if (!consultSupportsScale.value) return t('quickCalc.placeholder.scaleUnavailable')
  if (!hasResolvedMajor.value) return t('quickCalc.placeholder.selectMajorFirst')
  if (consultOnlySupportsCostScale.value) return t('quickCalc.placeholder.consultCostOnly')
  if (!majorSupportsLandScale.value) return t('quickCalc.placeholder.landUnavailable')
  return t('quickCalc.placeholder.input')
})
const activeScaleMode = computed<QuickCalcScaleMode | null>(() => {
  const hasInvestValue = investScale.value.trim() !== ''
  const hasLandValue = landScale.value.trim() !== ''

  if (canUseInvestScale.value && hasInvestValue) return 'cost'
  if (canUseLandScale.value && hasLandValue) return 'area'
  if (canUseInvestScale.value) return 'cost'
  if (canUseLandScale.value) return 'area'
  return null
})
const scaleBudgetPreview = computed(() => {
  const mode = activeScaleMode.value
  if (!mode) return null
  const scaleValue = parseNumberOrNull(
    mode === 'cost' ? investScale.value : landScale.value,
    { sanitize: true, precision: 3 }
  )
  if (scaleValue == null) return null

  const rawSplit = getBenchmarkBudgetSplitByScale(scaleValue, mode)
  if (!rawSplit) return null

  const checkedSplit = {
    ...rawSplit,
    basic: rawSplit.basic,
    optional: rawSplit.optional,
    total: rawSplit.total
  }
  const budgetFeeSplit = getScaleBudgetFeeSplit({
    benchmarkBudgetBasic: checkedSplit.basic,
    benchmarkBudgetOptional: checkedSplit.optional,
    majorFactor: engineeringMajorFactor.value,
    consultCategoryFactor: consultCategoryFactor.value,
    workStageFactor: workEnvCoefficient.value
  })

  return {
    mode,
    scaleValue,
    benchmarkBudgetBasic: checkedSplit.basic,
    benchmarkBudgetOptional: checkedSplit.optional,
    benchmarkBudget: checkedSplit.total,
    basicFormula: rawSplit.basicFormula,
    optionalFormula: rawSplit.optionalFormula,
    budgetFeeBasic: budgetFeeSplit?.basic ?? null,
    budgetFeeOptional: budgetFeeSplit?.optional ?? null,
    budgetFeeTotal: budgetFeeSplit?.total ?? null
  }
})
const formulaText = computed(() => {
  const preview = scaleBudgetPreview.value
  if (!preview) return t('quickCalc.placeholder.selectScaleFirst')
  const parts = [preview.basicFormula, preview.optionalFormula].filter(Boolean)
  return parts.join(' + ') || '--'
})
const benchmarkAmountText = computed(() => {
  const total = scaleBudgetPreview.value?.benchmarkBudget
  if (total == null) return '--'
  return total.toLocaleString(locale.value, { minimumFractionDigits: 2, maximumFractionDigits: 2 })
})
const computedBudgetAmount = computed(() => {
  const total = scaleBudgetPreview.value?.budgetFeeTotal
  if (total == null) return '--'
  return total.toLocaleString(locale.value, { minimumFractionDigits: 2, maximumFractionDigits: 2 })
})

const applyScaleInput = (field: 'invest' | 'land') => {
  const currentValue = field === 'invest' ? investScale.value : landScale.value
  const next = parseNumberOrNull(currentValue, { sanitize: true, precision: 3 })
  const normalized = next == null ? '' : String(next)
  if (field === 'invest') {
    investScale.value = normalized
    return
  }
  landScale.value = normalized
}

const formatFactorValue = (value: number | null | undefined) =>
  value == null ? '--' : String(roundTo(value, 3))

const applyWorkEnvFactorInput = () => {
  const next = parseNumberOrNull(workEnvFactor.value, { sanitize: true, precision: 3 })
  workEnvFactor.value = next == null ? '' : String(next)
}

const totalSelectedCount = computed(() => {
  let count = 0
  if (selectedConsultKey.value) count += 1
  if (selectedMajor.value) count += 1
  return count
})

const isOptionSelected = (groupKey: string, optionKey: string) => {
  if (groupKey === 'consult') return selectedConsultKey.value === optionKey
  return selectedMajor.value?.groupKey === groupKey && selectedMajor.value?.optionKey === optionKey
}

const toggleItem = (groupKey: string, optionKey: string) => {
  if (groupKey === 'consult') {
    selectedConsultKey.value = selectedConsultKey.value === optionKey ? '' : optionKey
    return
  }
  if (isOptionSelected(groupKey, optionKey)) {
    selectedMajor.value = null
    return
  }
  selectedMajor.value = { groupKey, optionKey }
}

const getGroupTitle = (group: { key: string; label: string }) => {
  if (group.key !== 'consult') return group.label
  return group.label.replace(/([（(](?:常用|Common)[)）])$/i, '\n$1')
}

const loadFactorDefaults = async () => {
  const [consultMap, majorMap] = await Promise.all([
    loadConsultCategoryFactorMap(props.projectConsultCategoryFactorKey),
    loadMajorFactorMap(props.projectMajorFactorKey)
  ])
  consultFactorMap.value = consultMap
  majorFactorMap.value = majorMap
}

const loadQuickIndustry = async () => {
  try {
    const data = await kvStore.getItem<QuickProjectInfoState>(QUICK_PROJECT_INFO_KEY)
    projectIndustry.value =
      typeof data?.projectIndustry === 'string' ? data.projectIndustry.trim() : ''
  } catch (error) {
    console.error('loadQuickIndustry failed:', error)
    projectIndustry.value = ''
  }
}

const persistQuickIndustry = async (industry: string) => {
  const currentInfo = await kvStore.getItem<QuickProjectInfoState>(QUICK_PROJECT_INFO_KEY)
  await kvStore.setItem(QUICK_PROJECT_INFO_KEY, {
    ...currentInfo,
    projectIndustry: industry,
    projectName: t('quickCalc.projectName')
  })
}

onMounted(async () => {
  await Promise.all([loadQuickIndustry(), loadFactorDefaults()])
})

onActivated(() => {
  void Promise.all([loadQuickIndustry(), loadFactorDefaults()])
})

watch(
  () => projectIndustry.value.trim(),
  async (industry, previousIndustry) => {
    if (industry === previousIndustry) return

    if (selectedMajorGroup.value?.industryId && selectedMajorGroup.value.industryId !== industry) {
      selectedMajor.value = null
    }
    if (!industry && selectedMajor.value) {
      selectedMajor.value = null
    }

    const requestId = ++latestIndustryRequest
    industrySaving.value = true
    try {
      await persistQuickIndustry(industry)
      if (industry) {
        await initializeProjectFactorStates(
          kvStore,
          industry,
          props.projectConsultCategoryFactorKey || '',
          props.projectMajorFactorKey || ''
        )
        await loadFactorDefaults()
      }
    } finally {
      if (requestId === latestIndustryRequest) {
        industrySaving.value = false
      }
    }
  }
)

watch(
  [hasSelectedConsult, consultSupportsScale, consultOnlySupportsCostScale],
  () => {
    if (!selectedMajor.value) return
    const group = visibleGroups.value.find(item => item.key === selectedMajor.value?.groupKey)
    const stillVisible = group?.items.some(item => item.key === selectedMajor.value?.optionKey) === true
    if (!stillVisible) {
      selectedMajor.value = null
    }
  }
)

watch(canUseInvestScale, enabled => {
  if (!enabled) {
    investScale.value = ''
  }
})

watch(canUseLandScale, enabled => {
  if (!enabled) {
    landScale.value = ''
  }
})
</script>

<template>
  <div class="quick-calc-shell h-full min-h-0">
    <div class="quick-calc-layout">
      <section class="quick-calc-panel quick-calc-panel--catalog">
    

        <div class="quick-calc-toolbar">
          <section class="quick-calc-form-section quick-calc-toolbar__section">
            <div class="quick-calc-field quick-calc-field--wide">
              <span class="quick-calc-field__label">{{ t('quickCalc.fields.industry') }}</span>
              <div class="quick-calc-industry-grid" role="radiogroup" :aria-label="t('quickCalc.fields.industry')">
                <label
                  v-for="item in industryTypeList"
                  :key="`quick-workbench-${item.id}`"
                  class="quick-calc-industry-card"
                  :class="{ 'is-selected': isIndustrySelected(item.id) }"
                  :aria-checked="isIndustrySelected(item.id)"
                  role="radio"
                  tabindex="0"
                  @click.prevent="handleIndustrySelect(item.id)"
                  @keydown.enter.prevent="handleIndustrySelect(item.id)"
                  @keydown.space.prevent="handleIndustrySelect(item.id)"
                >
                  <input
                    :checked="isIndustrySelected(item.id)"
                    type="radio"
                    name="quick-calc-industry-choice"
                    class="quick-calc-option__input"
                    tabindex="-1"
                  >
                  <span
                    class="quick-calc-industry-card__icon"
                    :class="{ 'is-selected': isIndustrySelected(item.id) }"
                  >
                    <CircleDot v-if="isIndustrySelected(item.id)" class="h-3.5 w-3.5" />
                    <Circle v-else class="h-3.5 w-3.5" />
                  </span>
                  <span class="quick-calc-industry-card__text">
                    {{ getIndustryDisplayName(item.id, locale) }}
                  </span>
                </label>
              </div>
            </div>

           
          </section>
        </div>

        <div v-if="!hasSelectedIndustry" class="quick-calc-empty-state">
          {{ t('quickCalc.empty.selectIndustry') }}
        </div>

        <div v-else-if="!hasSelectedConsult" class="quick-calc-empty-state">
          {{ t('quickCalc.empty.selectConsult') }}
        </div>

        <div v-else-if="!consultSupportsScale" class="quick-calc-empty-state">
          {{ t('quickCalc.empty.scaleUnavailable') }}
        </div>

        <div v-else-if="consultOnlySupportsCostScale" class="quick-calc-empty-state">
          {{ t('quickCalc.empty.consultCostOnly') }}
        </div>

        <div class="quick-calc-catalog">
          <article
            v-for="group in visibleGroups"
            :key="group.key"
            class="quick-calc-group quick-calc-group--table"
            :class="{
              'quick-calc-group--major': group.key !== 'consult',
              'quick-calc-group--general': group.key === 'general'
            }"
          >
            <div class="quick-calc-group__side">
              <div class="quick-calc-group__eyebrow">{{ group.key === 'consult' ? t('quickCalc.consultCategory') : t('quickCalc.majorCategory') }}</div>
              <h3 class="quick-calc-group__title quick-calc-group__title--multiline">{{ getGroupTitle(group) }}</h3>
             
            </div>

            <div class="quick-calc-group__rows">
              <div
                v-for="(row, rowIndex) in group.rows"
                :key="`${group.key}-${rowIndex}`"
                class="quick-calc-selection-row"
              >
                <label
                  v-for="option in row"
                  :key="`${group.key}-${option.key}`"
                  class="quick-calc-inline-option"
                  :class="{ 'is-selected': isOptionSelected(group.key, option.key) }"
                >
                  <input
                    :checked="isOptionSelected(group.key, option.key)"
                    type="radio"
                    :name="group.key === 'consult' ? 'quick-calc-consult-choice' : 'quick-calc-major-choice'"
                    class="quick-calc-option__input"
                    @change="toggleItem(group.key, option.key)"
                  >
                  <span class="quick-calc-inline-option__icon" :class="{ 'is-selected': isOptionSelected(group.key, option.key) }">
                    <CircleDot v-if="isOptionSelected(group.key, option.key)" class="h-3.5 w-3.5" />
                    <Circle v-else class="h-3.5 w-3.5" />
                  </span>
                  <span
                    class="quick-calc-inline-option__text"
                    :class="{ 'is-selected': isOptionSelected(group.key, option.key) }"
                  >{{ option.label }}</span>
                </label>

                <div v-if="row.length === 0" class="quick-calc-selection-row__blank" />
              </div>
            </div>
          </article>
        </div>
      </section>

      <aside class="quick-calc-panel quick-calc-panel--form">
      

        <div class="quick-calc-form">
          <div class="quick-calc-form-stack">
            <section class="quick-calc-form-section quick-calc-form-section--summary">
          

              <div class="quick-calc-form-grid quick-calc-form-grid--summary">
                <label class="quick-calc-field">
                  <span class="quick-calc-field__label">{{ t('quickCalc.consultCategory') }}</span>
                  <div class="quick-calc-field__readonly">{{ selectedConsultLabel || t('quickCalc.notSelected') }}</div>
                </label>

                <label class="quick-calc-field">
                  <span class="quick-calc-field__label">{{ t('quickCalc.fields.code') }}</span>
                  <div class="quick-calc-field__readonly">{{ selectedConsultCode || '--' }}</div>
                </label>
              </div>
            </section>

            <section class="quick-calc-form-section">
             

              <div class="quick-calc-form-grid">
                <label class="quick-calc-field">
                  <span class="quick-calc-field__label">{{ t('quickCalc.fields.investScale') }}</span>
                  <input
                    v-model="investScale"
                    type="text"
                    inputmode="decimal"
                    class="quick-calc-field__input"
                    :class="{ 'is-disabled': !canUseInvestScale }"
                    :disabled="!canUseInvestScale"
                    :placeholder="investScalePlaceholder"
                    @blur="applyScaleInput('invest')"
                    @keydown.enter.prevent="applyScaleInput('invest')"
                  >
                </label>

                <label class="quick-calc-field">
                  <span class="quick-calc-field__label">{{ t('quickCalc.fields.landScale') }}</span>
                  <input
                    v-model="landScale"
                    type="text"
                    inputmode="decimal"
                    class="quick-calc-field__input"
                    :class="{ 'is-disabled': !canUseLandScale }"
                    :disabled="!canUseLandScale"
                    :placeholder="landScalePlaceholder"
                    @blur="applyScaleInput('land')"
                    @keydown.enter.prevent="applyScaleInput('land')"
                  >
                </label>
              </div>
            </section>

            <section class="quick-calc-form-section">
              <header class="quick-calc-form-section__header">
                <h3 class="quick-calc-form-section__title">{{ t('quickCalc.sections.benchmarkBudget') }}</h3>
              </header>

              <div class="quick-calc-form-grid">
                <label class="quick-calc-field quick-calc-field--wide">
                  <span class="quick-calc-field__label">{{ t('quickCalc.fields.formula') }}</span>
                  <div class="quick-calc-field__readonly quick-calc-field__readonly--multiline">{{ formulaText }}</div>
                </label>

                <label class="quick-calc-field">
                  <span class="quick-calc-field__label">{{ t('quickCalc.fields.amount') }}</span>
                  <div class="quick-calc-field__readonly">{{ benchmarkAmountText }}</div>
                </label>
              </div>
            </section>

            <section class="quick-calc-form-section">
              <header class="quick-calc-form-section__header">
                <h3 class="quick-calc-form-section__title">{{ t('quickCalc.sections.serviceBudget') }}</h3>
              </header>

              <div class="quick-calc-form-grid">
                <label class="quick-calc-field">
                  <span class="quick-calc-field__label">{{ t('quickCalc.fields.consultFactor') }}</span>
                  <div class="quick-calc-field__readonly">
                    {{ formatFactorValue(consultCategoryFactor) }}
                  </div>
                </label>

                <label class="quick-calc-field">
                  <span class="quick-calc-field__label">{{ t('quickCalc.fields.majorFactor') }}</span>
                  <div class="quick-calc-field__readonly">
                    {{ formatFactorValue(engineeringMajorFactor) }}
                  </div>
                </label>

                <div class="quick-calc-field">
                  <span class="quick-calc-field__label">{{ t('quickCalc.fields.workEnvCoefficient') }}</span>
                  <input
                    v-model="workEnvFactor"
                    class="quick-calc-field__input"
                    :placeholder="t('quickCalc.fields.workEnvCoefficientPlaceholder')"
                    @blur="applyWorkEnvFactorInput"
                    @keydown.enter.prevent="applyWorkEnvFactorInput"
                  >
                </div>

                <label class="quick-calc-field">
                  <span class="quick-calc-field__label">{{ t('quickCalc.fields.budgetAmount') }}</span>
                  <div class="quick-calc-field__readonly quick-calc-field__readonly--emphasis">
                    {{ computedBudgetAmount || '--' }}
                  </div>
                </label>
              </div>
            </section>
          </div>
        </div>
      </aside>
    </div>
  </div>
</template>

<style scoped>
.quick-calc-shell {
  --qc-surface: color-mix(in srgb, var(--card) 96%, var(--background));
  --qc-surface-muted: color-mix(in srgb, var(--muted) 82%, var(--card));
  --qc-surface-strong: color-mix(in srgb, var(--foreground) 8%, var(--card));
  --qc-border: color-mix(in srgb, var(--foreground) 14%, transparent);
  --qc-border-strong: color-mix(in srgb, var(--foreground) 28%, transparent);
  --qc-text: var(--foreground);
  --qc-muted: var(--muted-foreground);
  --qc-accent: hsl(var(--destructive));
  --qc-accent-soft: color-mix(in srgb, hsl(var(--destructive)) 10%, transparent);
  --qc-shadow: 0 18px 40px color-mix(in srgb, var(--foreground) 8%, transparent);
  padding: 8px;
  background:
    radial-gradient(circle at top left, color-mix(in srgb, hsl(var(--destructive)) 8%, transparent) 0%, transparent 34%),
    linear-gradient(180deg, color-mix(in srgb, var(--background) 96%, var(--muted)) 0%, var(--background) 100%);
}

.quick-calc-layout {
  display: grid;
  grid-template-columns: minmax(0, 1.45fr) minmax(340px, 0.95fr);
  gap: 10px;
  height: 100%;
  min-height: 0;
}

.quick-calc-panel {
  display: flex;
  flex-direction: column;
  min-height: 0;
  border: 1px solid var(--qc-border);
  border-radius: 18px;
  background: var(--qc-surface);
  box-shadow: var(--qc-shadow);
  overflow: hidden;
}

.quick-calc-panel__header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 10px;
  padding: 10px 12px 8px;
  border-bottom: 1px solid var(--qc-border);
  background:
    linear-gradient(90deg, color-mix(in srgb, hsl(var(--destructive)) 10%, transparent) 0%, transparent 24%),
    linear-gradient(180deg, color-mix(in srgb, white 20%, transparent) 0%, transparent 100%);
}

.quick-calc-toolbar {
  display: flex;
  align-items: stretch;
  gap: 12px;
  padding: 12px;
  border-bottom: 1px solid var(--qc-border);
  background: color-mix(in srgb, var(--qc-surface-muted) 72%, transparent);
}

.quick-calc-toolbar__section {
  min-width: min(280px, 100%);
  flex: 1;
}

.quick-calc-industry-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(136px, 1fr));
  gap: 8px;
}

.quick-calc-industry-card {
  position: relative;
  display: flex;
  align-items: center;
  gap: 10px;
  min-width: 0;
  min-height: 42px;
  padding: 0 12px;
  border: 1px solid var(--qc-border);
  border-radius: 12px;
  background: color-mix(in srgb, var(--background) 92%, var(--card));
  color: var(--qc-text);
  cursor: pointer;
  transition: transform 160ms ease, border-color 160ms ease, background 160ms ease, box-shadow 160ms ease;
}

.quick-calc-industry-card:hover {
  transform: translateY(-1px);
  border-color: var(--qc-border-strong);
}

.quick-calc-industry-card:focus-visible {
  outline: none;
  border-color: color-mix(in srgb, hsl(var(--destructive)) 42%, var(--qc-border));
  box-shadow: 0 0 0 3px color-mix(in srgb, hsl(var(--destructive)) 10%, transparent);
}

.quick-calc-industry-card.is-selected {
  border-color: color-mix(in srgb, hsl(var(--destructive)) 42%, var(--qc-border));
  background: color-mix(in srgb, hsl(var(--destructive)) 7%, white);
  box-shadow: 0 0 0 3px color-mix(in srgb, hsl(var(--destructive)) 10%, transparent);
}

.quick-calc-industry-card__icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 14px;
  height: 14px;
  flex: 0 0 14px;
  color: color-mix(in srgb, var(--foreground) 44%, transparent);
  transition: color 140ms ease, transform 140ms ease;
}

.quick-calc-industry-card__icon.is-selected {
  color: hsl(var(--destructive));
  transform: scale(1.02);
}

.quick-calc-industry-card__text {
  min-width: 0;
  font-size: 14px;
  line-height: 1.3;
}

.quick-calc-toolbar__meta {
  justify-content: flex-end;
  color: var(--qc-muted);
}

.quick-calc-empty-state {
  margin: 12px 12px 0;
  padding: 14px 16px;
  border: 1px dashed var(--qc-border-strong);
  border-radius: 14px;
  color: var(--qc-muted);
  background: color-mix(in srgb, var(--qc-surface-muted) 60%, transparent);
}

.quick-calc-panel__title-wrap {
  display: grid;
  gap: 4px;
}

.quick-calc-panel__eyebrow,
.quick-calc-group__eyebrow,
.quick-calc-field__label {
  font-size: 10px;
  letter-spacing: 0.16em;
  text-transform: uppercase;
  font-weight: 700;
}

.quick-calc-panel__eyebrow,
.quick-calc-group__eyebrow {
  color: var(--qc-accent);
}

.quick-calc-panel__title,
.quick-calc-group__title {
  margin: 0;
  font-size: clamp(1.06rem, 1.36vw, 1.3rem);
  line-height: 1.08;
  font-weight: 700;
  color: var(--qc-text);
}

.quick-calc-group__title--multiline {
  white-space: pre-line;
  line-height: 1.2;
}

.quick-calc-status {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-end;
  gap: 6px;
}

.quick-calc-status--stack {
  max-width: 180px;
}

.quick-calc-status__item {
  display: inline-flex;
  align-items: center;
  min-height: 24px;
  padding: 0 8px;
  border-radius: 999px;
  background: var(--qc-surface-muted);
  color: var(--qc-muted);
  font-size: 10px;
  white-space: nowrap;
}

.quick-calc-catalog,
.quick-calc-form {
  min-height: 0;
  overflow: auto;
  padding: 10px;
}

.quick-calc-hint-banner {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  margin: 8px 10px 0;
  padding: 8px 10px;
  border: 1px solid var(--qc-border);
  border-radius: 10px;
  background: color-mix(in srgb, var(--background) 92%, var(--card));
}

.quick-calc-hint-banner__content {
  display: grid;
  gap: 2px;
  min-width: 0;
}

.quick-calc-hint-banner__title {
  color: var(--qc-text);
  font-size: 12px;
  font-weight: 700;
}

.quick-calc-hint-banner__text {
  color: var(--qc-muted);
  font-size: 10px;
  line-height: 1.3;
}

.quick-calc-hint-banner__action {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  width: 26px;
  height: 26px;
  flex: 0 0 26px;
  border: 1px solid color-mix(in srgb, var(--qc-accent) 32%, var(--qc-border));
  border-radius: 999px;
  background: color-mix(in srgb, hsl(var(--destructive)) 8%, white);
  color: hsl(var(--destructive));
  box-shadow: inset 0 1px 0 color-mix(in srgb, white 58%, transparent);
  cursor: pointer;
  transition: transform 180ms ease, background 180ms ease, border-color 180ms ease, color 180ms ease;
}

.quick-calc-hint-banner__action:hover {
  transform: translateY(-1px) scale(1.03);
  border-color: hsl(var(--destructive));
  background: color-mix(in srgb, hsl(var(--destructive)) 14%, white);
}

.quick-calc-hint-enter-active,
.quick-calc-hint-leave-active {
  transition: opacity 220ms ease, transform 220ms ease, max-height 220ms ease, margin 220ms ease, padding 220ms ease;
  overflow: hidden;
}

.quick-calc-hint-enter-from,
.quick-calc-hint-leave-to {
  opacity: 0;
  transform: translateY(-8px);
  max-height: 0;
  margin-top: 0;
  padding-top: 0;
  padding-bottom: 0;
}

.quick-calc-catalog {
  display: grid;
  gap: 12px;
  align-content: start;
}

.quick-calc-group {
  border: 1px solid var(--qc-border);
  border-radius: 14px;
  background:
    linear-gradient(180deg, color-mix(in srgb, white 22%, transparent) 0%, transparent 100%),
    color-mix(in srgb, var(--card) 94%, var(--muted));
}

.quick-calc-group--major .quick-calc-group__eyebrow {
  color: color-mix(in srgb, var(--qc-text) 58%, var(--qc-accent));
}

.quick-calc-group--table {
  display: grid;
  grid-template-columns: 172px minmax(0, 1fr);
  overflow: hidden;
}

.quick-calc-group__side {
  display: grid;
  align-content: center;
  gap: 6px;
  padding: 14px 14px 14px 16px;
  border-right: 1px solid var(--qc-border);
  background:
    linear-gradient(180deg, color-mix(in srgb, var(--qc-surface-strong) 92%, white) 0%, color-mix(in srgb, var(--qc-surface-muted) 86%, transparent) 100%);
  position: relative;
}

.quick-calc-group__side::after {
  content: '';
  position: absolute;
  left: 16px;
  right: 16px;
  top: 10px;
  height: 2px;
  background: linear-gradient(90deg, var(--qc-accent) 0%, color-mix(in srgb, var(--qc-accent) 34%, transparent) 55%, transparent 100%);
  opacity: 0.72;
}

.quick-calc-group__eyebrow {
  margin-top: 4px;
  margin-bottom: 0;
  font-size: 11px;
  letter-spacing: 0.18em;
}

.quick-calc-group__count {
  min-width: 36px;
  height: 24px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  justify-self: start;
  border-radius: 999px;
  border: 1px solid var(--qc-border);
  background: color-mix(in srgb, white 40%, var(--qc-surface-muted));
  font-size: 11px;
  font-weight: 700;
  color: var(--qc-text);
}

.quick-calc-group__rows {
  display: grid;
  grid-auto-rows: minmax(46px, auto);
  background:
    linear-gradient(180deg, color-mix(in srgb, white 18%, transparent) 0%, transparent 100%);
}

.quick-calc-group__rows:has(.quick-calc-selection-row:only-child) {
  grid-auto-rows: minmax(46px, auto);
}

.quick-calc-group--general .quick-calc-group__rows,
.quick-calc-group--general .quick-calc-group__rows:has(.quick-calc-selection-row:only-child) {
  grid-auto-rows: minmax(38px, auto);
}

.quick-calc-selection-row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px 16px;
  min-height: 48px;
  padding: 10px 16px;
  border-bottom: 1px solid var(--qc-border);
  position: relative;
}

.quick-calc-selection-row:last-child {
  border-bottom: none;
}

.quick-calc-group--general .quick-calc-selection-row {
  min-height: 38px;
  padding-top: 7px;
  padding-bottom: 7px;
}

.quick-calc-selection-row::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 3px;
  background: linear-gradient(180deg, color-mix(in srgb, var(--qc-accent) 72%, transparent) 0%, transparent 100%);
  opacity: 0.18;
}

.quick-calc-option__input,
.quick-calc-segment__item input {
  position: absolute;
  opacity: 0;
  pointer-events: none;
}

.quick-calc-inline-option {
  position: relative;
  display: inline-flex;
  align-items: center;
  gap: 7px;
  min-width: 0;
  padding: 2px 4px 2px 0;
  cursor: pointer;
  color: var(--qc-text);
  transition: color 140ms ease, transform 140ms ease, opacity 140ms ease;
}

.quick-calc-inline-option:hover {
  transform: translateX(1px);
}

.quick-calc-inline-option__icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 14px;
  height: 14px;
  flex: 0 0 14px;
  color: color-mix(in srgb, var(--foreground) 44%, transparent);
  transition: color 140ms ease, transform 140ms ease;
}

.quick-calc-inline-option__icon.is-selected {
  color: hsl(var(--destructive));
  transform: scale(1.02);
}

.quick-calc-inline-option__text {
  font-size: 14px;
  line-height: 1.3;
  white-space: nowrap;
  transition: color 140ms ease, opacity 140ms ease;
}

.quick-calc-inline-option.is-selected {
  padding-left: 4px;
  padding-right: 6px;
  border-radius: 6px;
  background: color-mix(in srgb, hsl(var(--destructive)) 7%, transparent);
}

.quick-calc-inline-option__text.is-selected {
  color: hsl(var(--destructive));
  font-weight: 700;
}

.quick-calc-selection-row__blank {
  width: 100%;
  min-height: 20px;
}

.quick-calc-form-stack {
  display: grid;
  gap: 8px;
  align-content: start;
}

.quick-calc-panel--form .quick-calc-panel__header {
  padding: 8px 10px 6px;
}

.quick-calc-panel--form .quick-calc-panel__title-wrap {
  gap: 2px;
}

.quick-calc-panel--form .quick-calc-panel__title {
  font-size: 14px;
}

.quick-calc-panel--form .quick-calc-panel__eyebrow {
  font-size: 14px;
}

.quick-calc-panel--form .quick-calc-status__item {
  min-height: 20px;
  padding: 0 6px;
  font-size: 14px;
}

.quick-calc-panel--form .quick-calc-form {
  overflow: auto;
  padding: 8px;
  font-size: 14px;
}

.quick-calc-panel--form .quick-calc-form-stack {
  gap: 6px;
}

.quick-calc-form-section {
  display: grid;
  gap: 8px;
  padding: 10px 12px;
  border: 1px solid var(--qc-border);
  border-radius: 14px;
  background:
    linear-gradient(180deg, color-mix(in srgb, white 24%, transparent) 0%, transparent 100%),
    color-mix(in srgb, var(--card) 96%, var(--muted));
}

.quick-calc-form-section--summary {
  background:
    linear-gradient(180deg, color-mix(in srgb, hsl(var(--destructive)) 5%, transparent) 0%, transparent 100%),
    color-mix(in srgb, var(--card) 96%, var(--muted));
}

.quick-calc-panel--form .quick-calc-form-section {
  gap: 6px;
  padding: 8px 10px;
  border-radius: 12px;
}

.quick-calc-form-section__header {
  display: grid;
  gap: 2px;
}

.quick-calc-form-section__eyebrow {
  color: var(--qc-accent);
  font-size: 10px;
  letter-spacing: 0.16em;
  text-transform: uppercase;
  font-weight: 700;
}

.quick-calc-form-section__title {
  margin: 0;
  color: var(--qc-text);
  font-size: 14px;
  font-weight: 700;
}

.quick-calc-panel--form .quick-calc-form-section__eyebrow {
  font-size: 14px;
  letter-spacing: 0;
  text-transform: none;
}

.quick-calc-panel--form .quick-calc-form-section__title {
  font-size: 14px;
}

.quick-calc-form-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 8px 10px;
}

.quick-calc-panel--form .quick-calc-form-grid {
  gap: 6px 8px;
}

.quick-calc-form-grid--summary {
  grid-template-columns: minmax(0, 7fr) minmax(0, 3fr);
}

.quick-calc-field {
  display: grid;
  gap: 5px;
  min-width: 0;
}

.quick-calc-panel--form .quick-calc-field {
  gap: 4px;
}

.quick-calc-field--wide {
  grid-column: span 2;
}

.quick-calc-field__label {
  color: var(--qc-muted);
}

.quick-calc-field__input,
.quick-calc-field__readonly {
  min-height: 38px;
  display: flex;
  align-items: center;
  width: 100%;
  min-width: 0;
  padding: 0 10px;
  border: 1px solid var(--qc-border);
  border-radius: 10px;
  background: color-mix(in srgb, var(--background) 92%, var(--card));
  color: var(--qc-text);
  font-size: 13px;
  line-height: 1.4;
}

.quick-calc-panel--form .quick-calc-field__label {
  font-size: 14px;
  letter-spacing: 0;
  text-transform: none;
  font-weight: 600;
}

.quick-calc-panel--form .quick-calc-field__input,
.quick-calc-panel--form .quick-calc-field__readonly {
  min-height: 32px;
  padding: 0 8px;
  font-size: 14px;
  border-radius: 9px;
}

.quick-calc-field__input {
  outline: none;
  transition: border-color 160ms ease, box-shadow 160ms ease, background 160ms ease;
}

.quick-calc-field__input.is-disabled,
.quick-calc-field__input:disabled {
  cursor: not-allowed;
  color: var(--qc-muted);
  background: color-mix(in srgb, var(--muted) 72%, var(--card));
}

.quick-calc-field__input:focus {
  border-color: color-mix(in srgb, var(--qc-accent) 42%, var(--qc-border));
  background: color-mix(in srgb, hsl(var(--destructive)) 4%, white);
  box-shadow: 0 0 0 3px color-mix(in srgb, hsl(var(--destructive)) 10%, transparent);
}

.quick-calc-field__readonly {
  color: color-mix(in srgb, var(--qc-text) 58%, var(--qc-muted));
  border-color: color-mix(in srgb, var(--foreground) 10%, transparent);
  background: color-mix(in srgb, var(--muted) 72%, var(--card));
}

.quick-calc-field__readonly--multiline {
  min-height: 52px;
  align-items: flex-start;
  padding-top: 8px;
  padding-bottom: 8px;
}

.quick-calc-panel--form .quick-calc-field__readonly--multiline {
  min-height: 40px;
  padding-top: 6px;
  padding-bottom: 6px;
  line-height: 1.25;
}

.quick-calc-field__readonly--emphasis {
  font-size: 16px;
  font-weight: 700;
  letter-spacing: 0.01em;
}

.quick-calc-panel--form .quick-calc-field__readonly--emphasis {
  font-size: 14px;
}

.quick-calc-form-hint {
  color: var(--qc-muted);
  font-size: 10px;
  line-height: 1.35;
}

.quick-calc-panel--form .quick-calc-form-hint {
  font-size: 14px;
  line-height: 1.35;
}

.quick-calc-segment {
  display: inline-grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 6px;
}

.quick-calc-segment__item {
  position: relative;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-height: 32px;
  border: 1px solid var(--qc-border);
  border-radius: 10px;
  background: color-mix(in srgb, var(--background) 88%, var(--card));
  color: var(--qc-text);
  font-size: 12px;
  font-weight: 600;
  cursor: pointer;
  transition: border-color 160ms ease, background 160ms ease, box-shadow 160ms ease;
}

.quick-calc-segment__item.is-active {
  border-color: color-mix(in srgb, var(--foreground) 24%, transparent);
  background: color-mix(in srgb, var(--muted) 82%, var(--card));
  box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--foreground) 12%, transparent);
}

@media (max-width: 980px) {
  .quick-calc-shell {
    padding: 8px;
  }

  .quick-calc-toolbar {
    align-items: stretch;
    flex-direction: column;
  }

  .quick-calc-toolbar__meta {
    justify-content: flex-start;
  }

  .quick-calc-layout {
    grid-template-columns: 1fr;
  }

  .quick-calc-catalog,
  .quick-calc-form {
    max-height: none;
  }

  .quick-calc-status {
    justify-content: flex-start;
  }

  .quick-calc-group--table {
    grid-template-columns: 1fr;
  }

  .quick-calc-group__side {
    border-right: none;
    border-bottom: 1px solid var(--qc-border);
  }

  .quick-calc-group__rows {
    grid-template-rows: none;
  }

  .quick-calc-form-grid,
  .quick-calc-form-grid--summary {
    grid-template-columns: 1fr;
  }

  .quick-calc-hint-banner {
    align-items: flex-start;
    flex-direction: column;
  }
}

@media (max-width: 720px) {
  .quick-calc-selection-row {
    gap: 8px 12px;
  }

  .quick-calc-inline-option__text {
    font-size: 13px;
    white-space: normal;
  }

  .quick-calc-form-section {
    padding: 10px;
  }

  .quick-calc-field--wide {
    grid-column: auto;
  }
}
</style>
