<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="90px">
            <el-form-item label="分配单编号" prop="allocCode">
              <el-input
                v-model="queryParams.allocCode"
                placeholder="请输入分配单编号"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="月份" prop="monthCode">
              <el-date-picker
                v-model="queryParams.monthCode"
                type="month"
                value-format="YYYYMM"
                format="YYYY-MM"
                clearable
                placeholder="请选择月份"
              />
            </el-form-item>
            <el-form-item label="预投项目" prop="projectId">
              <el-select v-model="queryParams.projectId" filterable clearable placeholder="请选择预投项目" class="project-select">
                <el-option
                  v-for="project in sourceProjectOptions"
                  :key="project.projectId"
                  :label="projectLabel(project)"
                  :value="project.projectId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="分配状态" prop="allocStatus">
              <el-select v-model="queryParams.allocStatus" placeholder="请选择分配状态" clearable>
                <el-option v-for="dict in alloc_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['oa/erp:timesheetPreAlloc:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['oa/erp:timesheetPreAlloc:edit']">
              修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple || hasAppliedSelected"
              @click="handleDelete()"
              v-hasPermi="['oa/erp:timesheetPreAlloc:remove']"
            >
              删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oa/erp:timesheetPreAlloc:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" :search="true" @queryTable="getList" />
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="timesheetPreAllocList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="分配单编号" align="center" prop="allocCode" width="180" v-if="columns[8].visible" />
        <el-table-column label="月份" align="center" prop="monthCode" width="100" v-if="columns[0].visible" />
        <el-table-column label="来源预投项目" align="center" min-width="260" v-if="columns[1].visible">
          <template #default="scope">
            <div class="project-cell">
              <span>{{ scope.row.projectCode }}</span>
              <span>{{ scope.row.projectName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="来源工时" align="center" prop="sourceTotalHours" width="110" v-if="columns[2].visible">
          <template #default="scope">{{ formatHours(scope.row.sourceTotalHours) }}</template>
        </el-table-column>
        <el-table-column label="已分配工时" align="center" prop="allocatedTotalHours" width="120" v-if="columns[3].visible">
          <template #default="scope">{{ formatHours(scope.row.allocatedTotalHours) }}</template>
        </el-table-column>
        <el-table-column label="涉及人数" align="center" prop="staffCount" width="100" v-if="columns[4].visible" />
        <el-table-column label="分配状态" align="center" prop="allocStatus" width="110" v-if="columns[5].visible">
          <template #default="scope">
            <dict-tag :options="alloc_status" :value="scope.row.allocStatus" />
          </template>
        </el-table-column>
        <el-table-column label="回写时间" align="center" prop="applyTime" width="170" v-if="columns[6].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" min-width="160" show-overflow-tooltip v-if="columns[7].visible" />
        <el-table-column label="操作" align="center" fixed="right" width="110" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['oa/erp:timesheetPreAlloc:edit']" />
            </el-tooltip>
            <el-tooltip content="已回写单据不允许删除" placement="top" :disabled="scope.row.appliedFlag !== '1'">
              <span>
                <el-button
                  link
                  type="primary"
                  icon="Delete"
                  :disabled="scope.row.appliedFlag === '1'"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['oa/erp:timesheetPreAlloc:remove']"
                />
              </span>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <el-dialog :title="dialog.title" v-model="dialog.visible" width="1180px" append-to-body>
      <el-form ref="timesheetPreAllocFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="月份" prop="monthCode">
              <el-date-picker
                v-model="form.monthCode"
                type="month"
                value-format="YYYYMM"
                format="YYYY-MM"
                clearable
                :disabled="Boolean(form.allocId)"
                placeholder="请选择月份"
                @change="loadStaffAllocDetails"
              />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="预投项目" prop="projectId">
              <el-select
                v-model="form.projectId"
                filterable
                clearable
                :disabled="Boolean(form.allocId)"
                placeholder="请选择来源预投项目"
                class="full-width"
                @change="loadStaffAllocDetails"
              >
                <el-option
                  v-for="project in sourceProjectOptions"
                  :key="project.projectId"
                  :label="projectLabel(project)"
                  :value="project.projectId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态">
              <dict-tag :options="alloc_status" :value="currentAllocStatus" />
            </el-form-item>
          </el-col>
        </el-row>

        <div class="summary-strip">
          <div class="summary-item">
            <span>来源预投工时</span>
            <strong>{{ formatHours(sourceTotalHours) }}</strong>
          </div>
          <div class="summary-item">
            <span>已分配工时</span>
            <strong>{{ formatHours(allocatedTotalHours) }}</strong>
          </div>
          <div class="summary-item">
            <span>未分配工时</span>
            <strong :class="{ 'hour-warn': remainingTotalHours < 0 }">{{ formatHours(remainingTotalHours) }}</strong>
          </div>
          <div class="summary-item">
            <span>涉及人数</span>
            <strong>{{ staffCount }}</strong>
          </div>
        </div>

        <el-table v-loading="detailLoading" border :data="form.staffAllocList || []" class="alloc-table" empty-text="请选择月份和预投项目">
          <el-table-column label="员工" prop="staffName" width="140" />
          <el-table-column label="原预投工时" align="right" width="120">
            <template #default="scope">{{ formatHours(scope.row.sourceHours) }}</template>
          </el-table-column>
          <el-table-column label="已分配" align="right" width="110">
            <template #default="scope">{{ formatHours(calcStaffAllocated(scope.row)) }}</template>
          </el-table-column>
          <el-table-column label="未分配" align="right" width="110">
            <template #default="scope">
              <span :class="{ 'hour-warn': calcStaffRemaining(scope.row) < 0 }">{{ formatHours(calcStaffRemaining(scope.row)) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="分配去向" min-width="560">
            <template #default="scope">
              <div class="target-list">
                <div v-for="(allocItem, index) in scope.row.allocItems" :key="index" class="target-row">
                  <el-select v-model="allocItem.targetProjectId" filterable placeholder="目标物流/备件项目" class="target-project-select">
                    <el-option
                      v-for="project in targetProjectOptions"
                      :key="project.projectId"
                      :label="projectLabel(project)"
                      :value="project.projectId"
                    />
                  </el-select>
                  <el-input-number v-model="allocItem.allocHours" :precision="2" :step="0.5" :min="0" controls-position="right" />
                  <el-button link type="danger" icon="Delete" @click="removeTarget(scope.row, index)" />
                </div>
                <el-button link type="primary" icon="Plus" @click="addTarget(scope.row)">添加去向</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <el-form-item label="备注" prop="remark" class="mt-4">
          <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="TimesheetPreAlloc" lang="ts">
import {
  listTimesheetPreAlloc,
  getTimesheetPreAlloc,
  delTimesheetPreAlloc,
  addTimesheetPreAlloc,
  updateTimesheetPreAlloc,
  getStaffAllocDetails
} from '@/api/oa/erp/timesheetPreAlloc';
import {
  TimesheetPreAllocVO,
  TimesheetPreAllocQuery,
  TimesheetPreAllocForm,
  PreAllocStaffAlloc,
  PreAllocTarget,
  PreAllocDetailVO
} from '@/api/oa/erp/timesheetPreAlloc/types';
import { getErpProjectInfoList } from '@/api/oa/erp/projectInfo';

interface ProjectOption {
  projectId: string;
  projectCode?: string;
  projectName?: string;
  projectCategory?: string;
}

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { alloc_status } = toRefs<any>(proxy?.useDict('alloc_status'));

const timesheetPreAllocList = ref<TimesheetPreAllocVO[]>([]);
const selectedRows = ref<TimesheetPreAllocVO[]>([]);
const sourceProjectOptions = ref<ProjectOption[]>([]);
const targetProjectOptions = ref<ProjectOption[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const detailLoading = ref(false);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const timesheetPreAllocFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const columns = ref<FieldOption[]>([
  { key: 0, label: `月份`, visible: true },
  { key: 1, label: `来源预投项目`, visible: true },
  { key: 2, label: `来源工时`, visible: true },
  { key: 3, label: `已分配工时`, visible: true },
  { key: 4, label: `涉及人数`, visible: true },
  { key: 5, label: `分配状态`, visible: true },
  { key: 6, label: `回写时间`, visible: true },
  { key: 7, label: `备注`, visible: true },
  { key: 8, label: `分配单编号`, visible: true }
]);

const getCurrentMonthCode = () => {
  const now = new Date();
  return `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}`;
};

const initFormData = (): TimesheetPreAllocForm => ({
  allocId: undefined,
  monthCode: getCurrentMonthCode(),
  projectId: undefined,
  sourceTotalHours: 0,
  allocatedTotalHours: 0,
  staffCount: 0,
  allocStatus: '0',
  appliedFlag: '0',
  remark: undefined,
  staffAllocList: []
});

const data = reactive<PageData<TimesheetPreAllocForm, TimesheetPreAllocQuery>>({
  form: initFormData(),
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    allocCode: undefined,
    monthCode: undefined,
    projectId: undefined,
    allocStatus: undefined,
    params: {}
  },
  rules: {
    monthCode: [{ required: true, message: '月份不能为空', trigger: 'change' }],
    projectId: [{ required: true, message: '来源预投项目不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

const normalizeProject = (project: any): ProjectOption => ({
  projectId: String(project.projectId),
  projectCode: project.projectCode,
  projectName: project.projectName,
  projectCategory: project.projectCategory
});

const projectLabel = (project: ProjectOption) => {
  const code = project.projectCode || '';
  const name = project.projectName || '';
  return code ? `${code} ${name}` : name;
};

const toNumber = (value?: number | string | null) => {
  const num = Number(value ?? 0);
  return Number.isFinite(num) ? num : 0;
};

const formatHours = (value?: number | string | null) => toNumber(value).toFixed(2);

const calcStaffAllocated = (staff: PreAllocStaffAlloc) => (staff.allocItems || []).reduce((sum, item) => sum + toNumber(item.allocHours), 0);

const calcStaffRemaining = (staff: PreAllocStaffAlloc) => toNumber(staff.sourceHours) - calcStaffAllocated(staff);

const sourceTotalHours = computed(() => (form.value.staffAllocList || []).reduce((sum, staff) => sum + toNumber(staff.sourceHours), 0));
const allocatedTotalHours = computed(() => (form.value.staffAllocList || []).reduce((sum, staff) => sum + calcStaffAllocated(staff), 0));
const remainingTotalHours = computed(() => sourceTotalHours.value - allocatedTotalHours.value);
const staffCount = computed(() => (form.value.staffAllocList || []).filter((staff) => toNumber(staff.sourceHours) > 0).length);
const currentAllocStatus = computed(() => {
  if (allocatedTotalHours.value <= 0) {
    return '0';
  }
  return allocatedTotalHours.value < sourceTotalHours.value ? '1' : '2';
});
const hasAppliedSelected = computed(() => selectedRows.value.some((row) => row.appliedFlag === '1'));

const loadProjectOptions = async () => {
  if (sourceProjectOptions.value.length === 0) {
    const sourceRes: any = await getErpProjectInfoList({ projectCategory: '4' });
    sourceProjectOptions.value = (sourceRes.data || []).map(normalizeProject);
  }
  if (targetProjectOptions.value.length === 0) {
    const [logisticsRes, spareRes]: any[] = await Promise.all([
      getErpProjectInfoList({ projectCategory: '1' }),
      getErpProjectInfoList({ projectCategory: '2' })
    ]);
    const merged = [...(logisticsRes.data || []), ...(spareRes.data || [])].map(normalizeProject);
    const uniqueMap = new Map<string, ProjectOption>();
    merged.forEach((project) => uniqueMap.set(project.projectId, project));
    targetProjectOptions.value = Array.from(uniqueMap.values());
  }
};

const normalizeStaffAlloc = (staff: PreAllocStaffAlloc): PreAllocStaffAlloc => ({
  staffUserId: staff.staffUserId,
  staffName: staff.staffName,
  sourceHours: toNumber(staff.sourceHours),
  allocatedHours: toNumber(staff.allocatedHours),
  remainingHours: toNumber(staff.remainingHours),
  allocItems: (staff.allocItems || []).map((item) => ({
    targetProjectId: item.targetProjectId ? String(item.targetProjectId) : undefined,
    targetProjectCode: item.targetProjectCode,
    targetProjectName: item.targetProjectName,
    allocHours: toNumber(item.allocHours)
  }))
});

const applyDetailToForm = (detail: PreAllocDetailVO) => {
  const sourceProjectId = detail.projectId ? String(detail.projectId) : undefined;
  if (sourceProjectId && !sourceProjectOptions.value.some((project) => project.projectId === sourceProjectId)) {
    sourceProjectOptions.value.push({
      projectId: sourceProjectId,
      projectCode: detail.projectCode,
      projectName: detail.projectName,
      projectCategory: '4'
    });
  }
  form.value.allocId = detail.allocId;
  form.value.allocCode = detail.allocCode;
  form.value.monthCode = detail.monthCode;
  form.value.standardMonthId = detail.standardMonthId;
  form.value.projectId = sourceProjectId;
  form.value.projectCode = detail.projectCode;
  form.value.projectName = detail.projectName;
  form.value.sourceTotalHours = toNumber(detail.sourceTotalHours);
  form.value.allocatedTotalHours = toNumber(detail.allocatedTotalHours);
  form.value.staffCount = detail.staffCount;
  form.value.allocStatus = detail.allocStatus;
  form.value.appliedFlag = detail.appliedFlag;
  form.value.summaryId = detail.summaryId;
  form.value.applyTime = detail.applyTime;
  form.value.remark = detail.remark;
  form.value.staffAllocList = (detail.staffAllocList || []).map(normalizeStaffAlloc);
  form.value.staffAllocList.forEach((staff) => {
    (staff.allocItems || []).forEach((item) => {
      const targetProjectId = item.targetProjectId ? String(item.targetProjectId) : undefined;
      if (targetProjectId && !targetProjectOptions.value.some((project) => project.projectId === targetProjectId)) {
        targetProjectOptions.value.push({
          projectId: targetProjectId,
          projectCode: item.targetProjectCode,
          projectName: item.targetProjectName
        });
      }
    });
  });
};

const loadStaffAllocDetails = async () => {
  if (!form.value.monthCode || !form.value.projectId) {
    form.value.staffAllocList = [];
    return;
  }
  detailLoading.value = true;
  try {
    const res: any = await getStaffAllocDetails({
      monthCode: form.value.monthCode,
      projectId: form.value.projectId
    });
    applyDetailToForm(res.data);
  } finally {
    detailLoading.value = false;
  }
};

const getList = async () => {
  loading.value = true;
  const params = {
    ...queryParams.value,
    projectId: queryParams.value.projectId || undefined
  };
  const res: any = await listTimesheetPreAlloc(params);
  timesheetPreAllocList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

const cancel = () => {
  reset();
  dialog.visible = false;
};

const reset = () => {
  form.value = initFormData();
  timesheetPreAllocFormRef.value?.resetFields();
};

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

const handleSelectionChange = (selection: TimesheetPreAllocVO[]) => {
  selectedRows.value = selection;
  ids.value = selection.map((item) => item.allocId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

const handleAdd = async () => {
  reset();
  await loadProjectOptions();
  dialog.visible = true;
  dialog.title = '预投工时分配';
};

const handleUpdate = async (row?: TimesheetPreAllocVO) => {
  reset();
  await loadProjectOptions();
  const allocId = row?.allocId || ids.value[0];
  const res: any = await getTimesheetPreAlloc(allocId);
  applyDetailToForm(res.data);
  dialog.visible = true;
  dialog.title = '预投工时分配';
};

const addTarget = (staff: PreAllocStaffAlloc) => {
  if (!staff.allocItems) {
    staff.allocItems = [];
  }
  staff.allocItems.push({ targetProjectId: undefined, allocHours: 0 });
};

const removeTarget = (staff: PreAllocStaffAlloc, index: number) => {
  staff.allocItems?.splice(index, 1);
};

const validateAllocation = () => {
  if (sourceTotalHours.value <= 0) {
    proxy?.$modal.msgError('本月该预投项目没有可分配工时');
    return false;
  }
  for (const staff of form.value.staffAllocList || []) {
    const usedTargets = new Set<string>();
    for (const item of staff.allocItems || []) {
      if (!item.targetProjectId) {
        proxy?.$modal.msgError(`员工[${staff.staffName}]存在未选择目标项目的分配行`);
        return false;
      }
      const targetProjectId = String(item.targetProjectId);
      if (usedTargets.has(targetProjectId)) {
        proxy?.$modal.msgError(`员工[${staff.staffName}]不能重复选择同一目标项目`);
        return false;
      }
      usedTargets.add(targetProjectId);
      if (toNumber(item.allocHours) <= 0) {
        proxy?.$modal.msgError(`员工[${staff.staffName}]分配工时必须大于0`);
        return false;
      }
    }
    if (calcStaffRemaining(staff) < -0.000001) {
      proxy?.$modal.msgError(`员工[${staff.staffName}]分配工时不能超过原预投工时`);
      return false;
    }
  }
  return true;
};

const buildSubmitPayload = (): TimesheetPreAllocForm => ({
  allocId: form.value.allocId,
  monthCode: form.value.monthCode,
  projectId: form.value.projectId,
  sourceTotalHours: sourceTotalHours.value,
  allocatedTotalHours: allocatedTotalHours.value,
  staffCount: staffCount.value,
  allocStatus: currentAllocStatus.value,
  remark: form.value.remark,
  staffAllocList: (form.value.staffAllocList || []).map((staff) => ({
    staffUserId: staff.staffUserId,
    staffName: staff.staffName,
    sourceHours: toNumber(staff.sourceHours),
    allocItems: (staff.allocItems || []).map((item: PreAllocTarget) => ({
      targetProjectId: item.targetProjectId,
      allocHours: toNumber(item.allocHours)
    }))
  }))
});

const submitForm = () => {
  timesheetPreAllocFormRef.value?.validate(async (valid: boolean) => {
    if (!valid || !validateAllocation()) {
      return;
    }
    buttonLoading.value = true;
    const payload = buildSubmitPayload();
    try {
      if (payload.allocId) {
        await updateTimesheetPreAlloc(payload);
      } else {
        await addTimesheetPreAlloc(payload);
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    } finally {
      buttonLoading.value = false;
    }
  });
};

const handleDelete = async (row?: TimesheetPreAllocVO) => {
  const deleteRows = row ? [row] : selectedRows.value;
  if (deleteRows.some((item) => item.appliedFlag === '1')) {
    proxy?.$modal.msgError('已回写月汇总的预投工时分配单不允许删除');
    return;
  }
  const allocIds = row?.allocId || ids.value;
  await proxy?.$modal.confirm(`是否确认删除预投工时分配编号为"${allocIds}"的数据项？`).finally(() => (loading.value = false));
  await delTimesheetPreAlloc(allocIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

const handleExport = () => {
  proxy?.download(
    'oa/erp/timesheetPreAlloc/export',
    {
      ...queryParams.value
    },
    `timesheetPreAlloc_${new Date().getTime()}.xlsx`
  );
};

onMounted(async () => {
  await loadProjectOptions();
  await getList();
});
</script>

<style scoped>
.project-select {
  width: 260px;
}

.full-width {
  width: 100%;
}

.project-cell {
  display: flex;
  flex-direction: column;
  gap: 2px;
  line-height: 1.35;
}

.summary-strip {
  display: grid;
  grid-template-columns: repeat(4, minmax(120px, 1fr));
  gap: 10px;
  margin: 4px 0 12px;
}

.summary-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  min-height: 36px;
  padding: 6px 10px;
  border: 1px solid var(--el-border-color-light);
  border-radius: 6px;
  background: var(--el-fill-color-lighter);
}

.summary-item span {
  color: var(--el-text-color-secondary);
}

.summary-item strong {
  font-size: 16px;
}

.alloc-table {
  width: 100%;
}

.target-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 4px 0;
}

.target-row {
  display: grid;
  grid-template-columns: minmax(260px, 1fr) 150px 32px;
  gap: 8px;
  align-items: center;
}

.target-project-select {
  width: 100%;
}

.hour-warn {
  color: var(--el-color-danger);
  font-weight: 600;
}

@media (max-width: 900px) {
  .summary-strip {
    grid-template-columns: repeat(2, minmax(120px, 1fr));
  }

  .target-row {
    grid-template-columns: 1fr;
  }
}
</style>
