<template>
  <main class="analysis-screen">
    <div ref="mapContainer" class="analysis-screen__map" />
    <header class="analysis-screen__title">
      <button class="analysis-screen__entry" type="button" @click="router.push('/index')">进入系统</button>
      <h1>青岛总部能耗总览</h1>
      <div class="analysis-screen__datetime">
        <span>
          <el-icon><Clock /></el-icon>
          <strong>{{ currentTime }}</strong>
        </span>
        <span>
          <el-icon><Calendar /></el-icon>
          <strong>{{ currentDate }}</strong>
        </span>
      </div>
    </header>
    <div class="analysis-screen__panels">
      <section class="analysis-screen__card analysis-screen__card--left-1 board-card">
        <h2 class="board-card__title">项目信息</h2>
        <div class="project-info">
          <div class="project-info__image">
            <img src="@/assets/logo/logo.png" alt="能源管理系统" />
          </div>
          <dl class="project-info__list">
            <div>
              <dt>项目名称：</dt>
              <dd>能源管理系统</dd>
            </div>
            <div>
              <dt>责任人：</dt>
              <dd>管理员</dd>
            </div>
            <div>
              <dt>联系方式：</dt>
              <dd>12345678910</dd>
            </div>
            <div>
              <dt>项目地址：</dt>
              <dd>山东省青岛市</dd>
            </div>
          </dl>
        </div>
      </section>
      <section class="analysis-screen__card analysis-screen__card--left-2 board-card">
        <h2 class="board-card__title">设备状态</h2>
        <el-select v-model="selectedDeviceType" class="board-select" size="small" placeholder="请选择设备类型" @change="loadBoardData">
          <el-option v-for="dict in deviceTypeOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
        <div class="device-status">
          <div ref="onlineChartRef" class="device-status__chart" />
          <div ref="alarmChartRef" class="device-status__chart" />
        </div>
      </section>
      <section class="analysis-screen__card analysis-screen__card--right-1" />
      <section class="analysis-screen__card analysis-screen__card--right-2" />
      <div class="analysis-screen__bottom">
        <section class="analysis-screen__card board-card">
          <h2 class="board-card__title">事件概览</h2>
          <el-segmented v-model="alarmPeriod" class="event-tabs" :options="alarmPeriodOptions" size="small" @change="loadAlarmOverview" />
          <div class="event-summary">
            <div>
              <strong>{{ alarmOverview.total }}</strong>
              <span>事件总数(条)</span>
            </div>
            <div>
              <strong>{{ alarmOverview.handled }}</strong>
              <span>已处理(条)</span>
            </div>
            <div>
              <strong>{{ alarmOverview.unhandled }}</strong>
              <span>未处理(条)</span>
            </div>
          </div>
          <div class="event-table">
            <div class="event-table__head">
              <span>报警设备</span>
              <span>报警时间</span>
              <span>报警原因</span>
            </div>
            <div class="event-table__body">
              <div class="event-table__track" :class="{ 'event-table__track--static': displayAlarmEvents.length <= 4 }">
                <div v-for="(item, index) in marqueeAlarmEvents" :key="`${item.id}-${index}`" class="event-table__row">
                  <span :title="item.alarmDeviceName">{{ item.alarmDeviceName || '-' }}</span>
                  <span :title="item.alarmTime">{{ item.alarmTime || '-' }}</span>
                  <span :title="item.alarmDetail">{{ item.alarmDetail || '-' }}</span>
                </div>
              </div>
            </div>
          </div>
        </section>
        <section class="analysis-screen__card board-card">
          <h2 class="board-card__title">能耗对比</h2>
          <div ref="energyCompareChartRef" class="energy-compare-chart" />
        </section>
        <section class="analysis-screen__card board-card">
          <h2 class="board-card__title">分时占比</h2>
          <div class="time-share">
            <div class="time-share__summary">
              <div v-for="item in timeShareData.items" :key="item.name">
                <span>{{ item.name }}用电</span>
                <strong>{{ formatEnergy(item.value) }}{{ timeShareData.unit }}</strong>
                <em>占比{{ formatPercent(item.percent) }}%</em>
              </div>
            </div>
            <div class="time-share__chart-row">
              <div ref="timeShareChartRef" class="time-share__chart" />
              <div class="time-share__legend">
                <button
                  v-for="item in timeShareData.items"
                  :key="item.name"
                  type="button"
                  :class="{ 'time-share__legend-item--inactive': !timeShareLegendSelected[item.name] }"
                  @click="toggleTimeShareLegend(item.name)"
                >
                  <i :style="{ backgroundColor: item.color }" />
                  <span>{{ item.name }}</span>
                  <strong>{{ formatPercent(item.percent) }}%</strong>
                </button>
              </div>
            </div>
          </div>
        </section>
      </div>
    </div>
  </main>
</template>

<script setup lang="ts">
import { Calendar, Clock } from '@element-plus/icons-vue';
import * as echarts from 'echarts';
import {
  BoardAlarmEventVO,
  BoardEnergyCompareVO,
  BoardTimeShareVO,
  getBoardAlarmOverview,
  getBoardDeviceStatus,
  getBoardEnergyCompare,
  getBoardTimeShare
} from '@/api/ems/board';

const AMAP_KEY = '5ea9dfb08c9ecd90ff1ad2adf249b770';
const AMAP_SECURITY_CODE = 'd7d233f9e392adc432927a4bdfb467af';
const MAP_CENTER: [number, number] = [120.390148, 36.146042];
const AMAP_SCRIPT_ID = 'ems-amap-jsapi';

declare global {
  interface Window {
    AMap?: any;
    _AMapSecurityConfig?: {
      securityJsCode: string;
    };
  }
}

const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { device_type } = toRefs<any>(proxy?.useDict('device_type'));
const mapContainer = ref<HTMLElement>();
const onlineChartRef = ref<HTMLElement>();
const alarmChartRef = ref<HTMLElement>();
const energyCompareChartRef = ref<HTMLElement>();
const timeShareChartRef = ref<HTMLElement>();
const loading = ref(true);
const loadError = ref('');
const now = ref(new Date());
const selectedDeviceType = ref('2');
const alarmPeriod = ref<'today' | 'month'>('today');
const alarmOverview = reactive({
  total: 0,
  handled: 0,
  unhandled: 0
});
const energyCompareData = ref<BoardEnergyCompareVO>({
  unit: 'kWh',
  xAxis: [],
  today: [],
  yesterday: []
});
const timeShareData = ref<BoardTimeShareVO>({
  unit: 'kWh',
  total: 0,
  items: [
    { name: '平', value: 0, percent: 0, color: '#2f86eb' },
    { name: '峰', value: 0, percent: 0, color: '#f2a23a' },
    { name: '谷', value: 0, percent: 0, color: '#22b878' }
  ]
});
const timeShareLegendSelected = reactive<Record<string, boolean>>({
  平: true,
  峰: true,
  谷: true
});
const displayAlarmEvents = ref<BoardAlarmEventVO[]>([]);
let mapInstance: any = null;
let onlineChart: echarts.ECharts | undefined;
let alarmChart: echarts.ECharts | undefined;
let energyCompareChart: echarts.ECharts | undefined;
let timeShareChart: echarts.ECharts | undefined;
let clockTimer: number | undefined;

const fallbackDeviceTypes = [
  { label: '电', value: '2' },
  { label: '水', value: '1' },
  { label: '温度', value: '3' }
];
const alarmPeriodOptions = [
  { label: '今日告警', value: 'today' },
  { label: '本月告警', value: 'month' }
];

const padTime = (value: number) => String(value).padStart(2, '0');
const currentTime = computed(() => `${padTime(now.value.getHours())}:${padTime(now.value.getMinutes())}:${padTime(now.value.getSeconds())}`);
const currentDate = computed(() => `${now.value.getFullYear()}-${padTime(now.value.getMonth() + 1)}-${padTime(now.value.getDate())}`);
const deviceTypeOptions = computed(() => (device_type.value?.length ? device_type.value : fallbackDeviceTypes));
const marqueeAlarmEvents = computed(() => {
  if (!displayAlarmEvents.value.length) {
    return [{ id: 'empty', alarmDeviceName: '暂无数据', alarmTime: '-', alarmDetail: '-' }] as BoardAlarmEventVO[];
  }
  return displayAlarmEvents.value.length > 4 ? [...displayAlarmEvents.value, ...displayAlarmEvents.value] : displayAlarmEvents.value;
});
const formatEnergy = (value: number) => Number(value || 0).toFixed(1).replace(/\.0$/, '');
const formatPercent = (value: number) => Number(value || 0).toFixed(1).replace(/\.0$/, '');

const toPercent = (value: number, total: number) => (total > 0 ? Math.round((value / total) * 100) : 0);

function setRingChart(chart: echarts.ECharts | undefined, value: number, total: number, title: string, subText: string, color: string) {
  const titleText = `${title}${title === '在线率' ? `(${total})` : ''}`;
  const graphicText = subText ? `${subText}\n${titleText}` : titleText;
  chart?.setOption({
    animationDuration: 600,
    title: {
      show: false
    },
    graphic: [
      {
        type: 'text',
        left: 'center',
        top: '38%',
        silent: true,
        style: {
          text: `${toPercent(value, total)}%`,
          fill: '#1268b3',
          fontSize: 19,
          fontWeight: 700,
          textAlign: 'center',
          textVerticalAlign: 'middle'
        }
      },
      {
        type: 'text',
        left: 'center',
        top: subText ? '50%' : '53%',
        silent: true,
        style: {
          text: graphicText,
          fill: '#4f6478',
          fontSize: 10,
          lineHeight: 12,
          textAlign: 'center',
          textVerticalAlign: 'middle'
        }
      }
    ],
    series: [
      {
        type: 'pie',
        radius: ['64%', '82%'],
        center: ['50%', '50%'],
        avoidLabelOverlap: true,
        silent: true,
        label: { show: false },
        data: [
          { value, itemStyle: { color } },
          { value: Math.max(total - value, 0), itemStyle: { color: 'rgba(18, 104, 179, 0.12)' } }
        ]
      }
    ]
  });
}

function renderEnergyCompareChart() {
  const data = energyCompareData.value;
  energyCompareChart?.setOption({
    animationDuration: 700,
    grid: {
      top: 38,
      right: 14,
      bottom: 30,
      left: 44
    },
    legend: {
      top: 0,
      right: 4,
      itemWidth: 10,
      itemHeight: 10,
      textStyle: {
        color: '#36566f',
        fontSize: 11
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      valueFormatter: (value: number) => `${value} ${data.unit || 'kWh'}`
    },
    xAxis: {
      type: 'category',
      data: data.xAxis,
      axisTick: { show: false },
      axisLine: { lineStyle: { color: 'rgba(18, 104, 179, 0.22)' } },
      axisLabel: {
        color: '#617385',
        fontSize: 10,
        interval: 2
      }
    },
    yAxis: {
      type: 'value',
      name: data.unit || 'kWh',
      nameTextStyle: {
        color: '#617385',
        fontSize: 10,
        padding: [0, 26, 0, 0]
      },
      splitLine: { lineStyle: { color: 'rgba(18, 104, 179, 0.1)' } },
      axisLabel: {
        color: '#617385',
        fontSize: 10
      }
    },
    series: [
      {
        name: '当日能耗',
        type: 'bar',
        data: data.today,
        barWidth: 8,
        barGap: '35%',
        itemStyle: {
          color: '#2f86eb',
          borderRadius: [3, 3, 0, 0]
        }
      },
      {
        name: '昨日能耗',
        type: 'bar',
        data: data.yesterday,
        barWidth: 8,
        itemStyle: {
          color: '#22b878',
          borderRadius: [3, 3, 0, 0]
        }
      }
    ]
  });
}

async function loadEnergyCompare() {
  const res = await getBoardEnergyCompare();
  energyCompareData.value = res.data;
  renderEnergyCompareChart();
}

function renderTimeShareChart() {
  const items = (timeShareData.value.items || []).filter((item) => timeShareLegendSelected[item.name]);
  timeShareChart?.setOption({
    animationDuration: 700,
    tooltip: {
      trigger: 'item',
      formatter: (params: any) => `${params.name}用电<br/>${params.value} ${timeShareData.value.unit || 'kWh'} (${formatPercent(params.percent)}%)`
    },
    series: [
      {
        type: 'pie',
        radius: ['58%', '78%'],
        center: ['50%', '50%'],
        avoidLabelOverlap: true,
        label: { show: false },
        labelLine: { show: false },
        data: items.map((item) => ({
          name: item.name,
          value: item.value,
          itemStyle: { color: item.color }
        }))
      }
    ]
  }, true);
}

function toggleTimeShareLegend(name: string) {
  const activeCount = Object.values(timeShareLegendSelected).filter(Boolean).length;
  if (timeShareLegendSelected[name] && activeCount <= 1) return;
  timeShareLegendSelected[name] = !timeShareLegendSelected[name];
  renderTimeShareChart();
}

async function loadTimeShare() {
  const res = await getBoardTimeShare();
  timeShareData.value = res.data;
  renderTimeShareChart();
}

function renderDeviceCharts(total: number, online: number, alarm: number) {
  resizeCharts();
  setRingChart(onlineChart, online, total, '在线率', '', '#20b486');
  setRingChart(alarmChart, alarm, total, '报警设备占比', '', '#e65f5c');
}

async function loadDeviceStatus() {
  const res = await getBoardDeviceStatus({ deviceType: selectedDeviceType.value });
  renderDeviceCharts(res.data.total, res.data.online, res.data.alarm);
}

async function loadAlarmOverview() {
  const res = await getBoardAlarmOverview({ period: alarmPeriod.value });
  alarmOverview.total = res.data.total;
  alarmOverview.handled = res.data.handled;
  alarmOverview.unhandled = res.data.unhandled;
  displayAlarmEvents.value = res.data.events || [];
}

async function loadBoardData() {
  await Promise.all([loadDeviceStatus(), loadAlarmOverview(), loadEnergyCompare(), loadTimeShare()]);
}

function initializeCharts() {
  if (onlineChartRef.value && !onlineChart) onlineChart = echarts.init(onlineChartRef.value, 'macarons');
  if (alarmChartRef.value && !alarmChart) alarmChart = echarts.init(alarmChartRef.value, 'macarons');
  if (energyCompareChartRef.value && !energyCompareChart) energyCompareChart = echarts.init(energyCompareChartRef.value, 'macarons');
  if (timeShareChartRef.value && !timeShareChart) timeShareChart = echarts.init(timeShareChartRef.value, 'macarons');
  nextTick(resizeCharts);
}

function resizeCharts() {
  onlineChart?.resize();
  alarmChart?.resize();
  energyCompareChart?.resize();
  timeShareChart?.resize();
}

function loadAMap(): Promise<any> {
  if (window.AMap) return Promise.resolve(window.AMap);

  window._AMapSecurityConfig = {
    securityJsCode: AMAP_SECURITY_CODE
  };

  return new Promise((resolve, reject) => {
    const globalWindow = window as typeof window & Record<string, any>;
    const callbackName = `__emsAmapReady${Date.now()}`;
    const existingScript = document.getElementById(AMAP_SCRIPT_ID) as HTMLScriptElement | null;

    const cleanup = () => {
      delete globalWindow[callbackName];
    };

    globalWindow[callbackName] = () => {
      cleanup();
      resolve(window.AMap);
    };

    if (existingScript) {
      const pollTimer = window.setInterval(() => {
        if (!window.AMap) return;
        window.clearInterval(pollTimer);
        cleanup();
        resolve(window.AMap);
      }, 100);
      window.setTimeout(() => {
        window.clearInterval(pollTimer);
        if (!window.AMap) {
          cleanup();
          reject(new Error('高德地图加载超时'));
        }
      }, 10000);
      return;
    }

    const script = document.createElement('script');
    script.id = AMAP_SCRIPT_ID;
    script.async = true;
    script.src = `https://webapi.amap.com/maps?v=2.0&key=${AMAP_KEY}&plugin=AMap.Scale,AMap.ToolBar,AMap.DistrictLayer&callback=${callbackName}`;
    script.onerror = () => {
      cleanup();
      script.remove();
      reject(new Error('高德地图资源加载失败'));
    };
    document.head.appendChild(script);
  });
}

async function initializeMap() {
  loading.value = true;
  loadError.value = '';
  mapInstance?.destroy();
  mapInstance = null;

  try {
    const AMap = await loadAMap();
    if (!mapContainer.value) return;

    const chinaDistrictLayer = new AMap.DistrictLayer.Country({
      zIndex: 12,
      SOC: 'CHN',
      depth: 1,
      styles: {
        'nation-stroke': '#1554a3',
        'coastline-stroke': '#2779bd',
        'province-stroke': '#111111',
        'city-stroke': 'rgba(90, 127, 165, 0.2)',
        'stroke-width': 1.6,
        fill: 'rgba(255, 255, 255, 0.04)'
      }
    });

    mapInstance = new AMap.Map(mapContainer.value, {
      viewMode: '3D',
      center: MAP_CENTER,
      zoom: 5,
      zooms: [3, 18],
      pitch: 0,
      mapStyle: 'amap://styles/normal',
      showLabel: true,
      resizeEnable: true,
      layers: [new AMap.TileLayer(), chinaDistrictLayer]
    });

    mapInstance.addControl(new AMap.Scale({ position: 'LB' }));
    mapInstance.addControl(new AMap.ToolBar({ position: 'RB', liteStyle: true }));
    mapInstance.add(
      new AMap.Marker({
        position: MAP_CENTER,
        anchor: 'center',
        content: '<span class="ems-map-marker"><i></i></span>',
        title: '数据分析中心'
      })
    );
  } catch (error) {
    loadError.value = error instanceof Error ? error.message : '地图初始化失败';
  } finally {
    loading.value = false;
  }
}

onMounted(() => {
  document.body.classList.add('analysis-screen-active');
  clockTimer = window.setInterval(() => {
    now.value = new Date();
  }, 1000);
  initializeCharts();
  loadBoardData();
  initializeMap();
  window.addEventListener('resize', resizeCharts);
});

onBeforeUnmount(() => {
  document.body.classList.remove('analysis-screen-active');
  if (clockTimer) window.clearInterval(clockTimer);
  window.removeEventListener('resize', resizeCharts);
  onlineChart?.dispose();
  alarmChart?.dispose();
  energyCompareChart?.dispose();
  timeShareChart?.dispose();
  onlineChart = undefined;
  alarmChart = undefined;
  energyCompareChart = undefined;
  timeShareChart = undefined;
  mapInstance?.destroy();
  mapInstance = null;
});
</script>

<style lang="scss">
body.analysis-screen-active {
  overflow: hidden;
}

body.analysis-screen-active .ai-float-ball {
  display: none !important;
}

.analysis-screen {
  position: fixed;
  inset: 0;
  z-index: 1900;
  overflow: hidden;
  background: #fff;
  color: #303133;
  font-family: 'DIN Alternate', 'PingFang SC', sans-serif;
}

.analysis-screen__map {
  position: absolute;
  inset: 0;
}

.analysis-screen__title {
  position: absolute;
  z-index: 3;
  top: 0;
  left: 0;
  display: grid;
  width: 100%;
  height: 3.75vw;
  place-items: center;
  background: url('@/assets/board/title.png') center top / 100% 100% no-repeat;
  pointer-events: none;
}

.analysis-screen__title h1 {
  margin: 0;
  color: #1268b3;
  font-size: 28px;
  font-weight: 700;
  letter-spacing: 0;
  line-height: 1;
  text-shadow: 0 1px 8px rgba(48, 167, 226, 0.22);
}

.analysis-screen__entry {
  position: absolute;
  top: 50%;
  left: 32px;
  border: 0;
  padding: 6px 0;
  background: transparent;
  color: #1268b3;
  cursor: pointer;
  font-size: 15px;
  font-weight: 600;
  letter-spacing: 0;
  pointer-events: auto;
  transform: translateY(-50%);
  transition:
    color 160ms ease,
    text-shadow 160ms ease;
}

.analysis-screen__entry:hover {
  color: #004b91;
  text-shadow: 0 0 10px rgba(18, 104, 179, 0.32);
}

.analysis-screen__datetime {
  position: absolute;
  top: 50%;
  right: 32px;
  display: flex;
  align-items: center;
  gap: 20px;
  color: #1268b3;
  transform: translateY(-50%);
}

.analysis-screen__datetime span {
  display: inline-flex;
  align-items: center;
  gap: 7px;
  white-space: nowrap;
}

.analysis-screen__datetime .el-icon {
  font-size: 17px;
}

.analysis-screen__datetime strong {
  font-size: 14px;
  font-weight: 600;
  font-variant-numeric: tabular-nums;
}

.analysis-screen__panels {
  position: absolute;
  z-index: 2;
  top: calc(3.75vw + 18px);
  right: 22px;
  bottom: 22px;
  left: 22px;
  display: grid;
  grid-template-areas:
    'left-1 empty-1 empty-2 empty-3 right-1'
    'left-2 empty-1 empty-2 empty-3 right-2'
    'bottom bottom bottom bottom bottom';
  grid-template-columns: clamp(290px, 19vw, 360px) minmax(0, 1fr) minmax(0, 1fr) minmax(0, 1fr) clamp(210px, 13vw, 260px);
  grid-template-rows: minmax(124px, 0.65fr) minmax(184px, 1fr) minmax(240px, 1.28fr);
  gap: 16px;
  pointer-events: none;
}

.analysis-screen__card {
  min-width: 0;
  min-height: 0;
  border: 1px solid rgba(137, 143, 153, 0.58);
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.48);
  box-shadow: 0 8px 24px rgba(67, 78, 91, 0.12);
  backdrop-filter: blur(5px);
  pointer-events: auto;
}

.board-card {
  display: flex;
  overflow: hidden;
  flex-direction: column;
  padding: 12px;
}

.board-card__title {
  position: relative;
  flex: 0 0 auto;
  margin: 0 0 10px;
  padding-left: 12px;
  color: #145f9d;
  font-size: 16px;
  font-weight: 700;
  line-height: 1.2;
}

.board-card__title::before {
  position: absolute;
  top: 2px;
  bottom: 2px;
  left: 0;
  width: 4px;
  border-radius: 999px;
  background: #20a8e8;
  content: '';
}

.board-select {
  width: 100%;
  flex: 0 0 auto;
  margin-bottom: 8px;
}

.project-info {
  display: grid;
  min-height: 0;
  flex: 1;
  grid-template-columns: 38% minmax(0, 1fr);
  gap: 12px;
  align-items: stretch;
}

.project-info__image {
  display: grid;
  height: 100%;
  min-height: 0;
  min-width: 0;
  place-items: center;
  border: 1px solid rgba(18, 104, 179, 0.18);
  border-radius: 8px;
  background:
    linear-gradient(135deg, rgba(32, 168, 232, 0.12), rgba(255, 255, 255, 0.84)),
    rgba(255, 255, 255, 0.66);
}

.project-info__image img {
  width: min(78%, 88px);
  height: min(78%, 88px);
  object-fit: contain;
}

.project-info__list {
  display: flex;
  min-width: 0;
  flex-direction: column;
  justify-content: space-between;
  gap: 4px;
  margin: 0;
  color: #2f4152;
  font-size: 12px;
  line-height: 1.35;
}

.project-info__list div {
  display: flex;
  min-width: 0;
}

.project-info__list dt {
  flex: 0 0 auto;
  color: #66798c;
  font-weight: 500;
}

.project-info__list dd {
  min-width: 0;
  margin: 0;
  overflow: hidden;
  color: #1f3245;
  font-weight: 700;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.device-status {
  display: grid;
  min-height: 0;
  flex: 1;
  grid-template-columns: 48% 48%;
  justify-content: space-between;
  gap: 0;
}

.device-status__chart {
  width: 100%;
  height: 100%;
  min-height: 0;
}

.energy-compare-chart {
  width: 100%;
  min-height: 0;
  flex: 1;
}

.time-share {
  display: flex;
  min-height: 0;
  flex: 1;
  flex-direction: column;
  gap: 8px;
}

.time-share__summary {
  display: grid;
  flex: 0 0 auto;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 6px;
}

.time-share__summary div {
  display: flex;
  min-width: 0;
  flex-direction: column;
  justify-content: center;
  border: 1px solid rgba(18, 104, 179, 0.16);
  border-radius: 6px;
  padding: 7px 6px;
  background: rgba(255, 255, 255, 0.54);
}

.time-share__summary span,
.time-share__summary em {
  overflow: hidden;
  color: #617385;
  font-size: 11px;
  font-style: normal;
  line-height: 1.2;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.time-share__summary strong {
  overflow: hidden;
  margin: 4px 0;
  color: #1268b3;
  font-size: 16px;
  font-weight: 800;
  line-height: 1;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-variant-numeric: tabular-nums;
}

.time-share__chart-row {
  display: grid;
  min-height: 0;
  flex: 1;
  grid-template-columns: minmax(0, 1fr) minmax(86px, 28%);
  gap: 8px;
  align-items: center;
}

.time-share__chart {
  width: 100%;
  height: 100%;
  min-height: 0;
}

.time-share__legend {
  display: flex;
  min-width: 0;
  flex-direction: column;
  gap: 8px;
}

.time-share__legend button {
  display: grid;
  min-width: 0;
  border: 0;
  grid-template-columns: 10px minmax(0, 1fr) auto;
  gap: 6px;
  align-items: center;
  padding: 0;
  background: transparent;
  color: #36566f;
  cursor: pointer;
  font-size: 12px;
  text-align: left;
  transition: opacity 160ms ease;
}

.time-share__legend button:hover {
  opacity: 0.78;
}

.time-share__legend-item--inactive {
  opacity: 0.36;
}

.time-share__legend i {
  width: 9px;
  height: 9px;
  border-radius: 50%;
}

.time-share__legend span {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.time-share__legend strong {
  color: #1f3245;
  font-weight: 800;
  font-variant-numeric: tabular-nums;
}

.event-tabs {
  width: 100%;
  flex: 0 0 auto;
  margin-bottom: 8px;
}

.event-tabs :deep(.el-segmented__item) {
  min-height: 26px;
  padding: 0 4px;
  font-size: 12px;
}

.event-summary {
  display: grid;
  flex: 0 0 auto;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 6px;
  margin-bottom: 8px;
}

.event-summary div {
  display: flex;
  min-width: 0;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 1px solid rgba(18, 104, 179, 0.16);
  border-radius: 6px;
  padding: 6px 3px;
  background: rgba(255, 255, 255, 0.54);
}

.event-summary strong {
  color: #1268b3;
  font-size: 20px;
  font-weight: 800;
  line-height: 1;
  font-variant-numeric: tabular-nums;
}

.event-summary span {
  max-width: 100%;
  margin-top: 4px;
  overflow: hidden;
  color: #617385;
  font-size: 11px;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.event-table {
  display: flex;
  min-height: 0;
  flex: 1;
  flex-direction: column;
  overflow: hidden;
  border: 1px solid rgba(18, 104, 179, 0.16);
  border-radius: 6px;
  background: rgba(255, 255, 255, 0.52);
}

.event-table__head,
.event-table__row {
  display: grid;
  grid-template-columns: 28% 34% 38%;
  min-width: 0;
}

.event-table__head {
  flex: 0 0 auto;
  background: rgba(18, 104, 179, 0.09);
  color: #315b78;
  font-size: 11px;
  font-weight: 700;
}

.event-table__head span,
.event-table__row span {
  min-width: 0;
  overflow: hidden;
  padding: 6px 6px;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.event-table__body {
  min-height: 0;
  flex: 1;
  overflow: hidden;
}

.event-table__track {
  animation: event-table-scroll 14s linear infinite;
}

.event-table__track--static {
  animation: none;
}

.event-table__row {
  border-top: 1px solid rgba(18, 104, 179, 0.08);
  color: #34495c;
  font-size: 11px;
  line-height: 1.2;
}

.event-table__row:nth-child(even) {
  background: rgba(18, 104, 179, 0.035);
}

.analysis-screen__card--left-1 {
  grid-area: left-1;
}

.analysis-screen__card--left-2 {
  grid-area: left-2;
}

.analysis-screen__card--right-1 {
  grid-area: right-1;
}

.analysis-screen__card--right-2 {
  grid-area: right-2;
}

.analysis-screen__bottom {
  display: grid;
  min-width: 0;
  min-height: 0;
  grid-area: bottom;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 16px;
  pointer-events: auto;
}

.analysis-screen__state {
  position: absolute;
  z-index: 3;
  top: 50%;
  left: 50%;
  display: flex;
  min-width: 220px;
  min-height: 130px;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 1px solid #dcdfe6;
  background: rgba(255, 255, 255, 0.96);
  box-shadow: 0 12px 32px rgba(31, 45, 61, 0.12);
  transform: translate(-50%, -50%);
}

.analysis-screen__state p {
  margin: 14px 20px;
  color: #606266;
}

.analysis-screen__state--error > .el-icon {
  color: #ff6b6b;
  font-size: 28px;
}

.analysis-screen__loader {
  width: 30px;
  height: 30px;
  border: 2px solid rgba(89, 210, 255, 0.2);
  border-top-color: #59d2ff;
  border-radius: 50%;
  animation: analysis-screen-spin 800ms linear infinite;
}

.analysis-screen__locator {
  position: absolute;
  z-index: 2;
  bottom: 28px;
  left: 30px;
  display: flex;
  align-items: center;
  gap: 10px;
  color: #345168;
  font-size: 11px;
}

.analysis-screen__pulse {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: #1368ce;
  box-shadow:
    0 0 0 7px rgba(19, 104, 206, 0.14),
    0 0 16px rgba(19, 104, 206, 0.68);
}

.ems-map-marker {
  position: relative;
  display: block;
  width: 34px;
  height: 34px;
  border: 2px solid #0f5fb8;
  border-radius: 50%;
  background: rgba(44, 139, 230, 0.24);
  box-shadow:
    0 0 0 5px rgba(44, 139, 230, 0.12),
    0 0 22px rgba(15, 95, 184, 0.78);
}

.ems-map-marker::before,
.ems-map-marker::after {
  position: absolute;
  top: 50%;
  left: 50%;
  border: 2px solid rgba(15, 95, 184, 0.58);
  border-radius: 50%;
  content: '';
  transform: translate(-50%, -50%);
  animation: analysis-screen-marker 2.2s ease-out infinite;
}

.ems-map-marker::after {
  animation-delay: 1.1s;
}

.ems-map-marker i {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: #0c4f9b;
  box-shadow: 0 0 0 3px #fff;
  transform: translate(-50%, -50%);
}

@keyframes analysis-screen-spin {
  to {
    transform: rotate(360deg);
  }
}

@keyframes analysis-screen-marker {
  from {
    width: 28px;
    height: 28px;
    opacity: 1;
  }
  to {
    width: 82px;
    height: 82px;
    opacity: 0;
  }
}

@keyframes event-table-scroll {
  from {
    transform: translateY(0);
  }
  to {
    transform: translateY(-50%);
  }
}

@media (max-width: 720px) {
  .analysis-screen__title h1 {
    font-size: 14px;
  }

  .analysis-screen__datetime {
    display: none;
  }

  .analysis-screen__entry {
    left: 12px;
    font-size: 12px;
  }

  .analysis-screen__panels {
    top: calc(3.75vw + 12px);
    right: 12px;
    bottom: 12px;
    left: 12px;
    grid-template-areas:
      'left-1 right-1'
      'left-2 right-2'
      'bottom bottom';
    grid-template-columns: repeat(2, minmax(0, 1fr));
    grid-template-rows: repeat(3, minmax(0, 1fr));
    gap: 10px;
  }

  .analysis-screen__bottom {
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: 10px;
  }

  .board-card {
    padding: 8px;
  }

  .board-card__title {
    margin-bottom: 6px;
    font-size: 13px;
  }

  .project-info {
    grid-template-columns: 32% minmax(0, 1fr);
    gap: 8px;
  }

  .project-info__list {
    gap: 4px;
    font-size: 10px;
  }

  .device-status__chart {
    min-height: 0;
  }

  .event-summary strong {
    font-size: 15px;
  }

  .event-summary span,
  .event-table__head,
  .event-table__row {
    font-size: 10px;
  }
}
</style>
