// ─── 仪表板 Page ─────────────────────────────────────────────────
// Shaanxi province city positions (approximate SVG coords in a 400×500 viewBox)
const SX_CITIES = [
  { name:'榆林', x:220, y:60,  wh:'榆林市应急物资储备库', stock:1420, level:'市级', active:false },
  { name:'延安', x:210, y:145, wh:'延安市应急物资储备库', stock:2300, level:'市级', active:true  },
  { name:'铜川', x:205, y:222, wh:'铜川市应急物资储备库', stock:980,  level:'市级', active:false },
  { name:'宝鸡', x:100, y:285, wh:'宝鸡市应急物资储备库', stock:3100, level:'市级', active:false },
  { name:'西安', x:195, y:278, wh:'省级综合应急物资储备库',stock:18600,level:'省级', active:true  },
  { name:'渭南', x:270, y:278, wh:'渭南市应急物资储备库', stock:2200, level:'市级', active:false },
  { name:'商洛', x:260, y:340, wh:'商洛市应急物资储备库', stock:860,  level:'市级', active:false },
  { name:'汉中', x:120, y:370, wh:'汉中市应急物资储备库', stock:1780, level:'市级', active:false },
  { name:'安康', x:225, y:400, wh:'安康市应急物资储备库', stock:1250, level:'市级', active:false },
  { name:'咸阳', x:165, y:268, wh:'咸阳市应急物资储备库', stock:2580, level:'市级', active:false },
];

// Active transport routes (from→to index pairs)
const ROUTES = [
  { from:4, to:1, label:'救援帐篷×20顶', status:'运输中', color:'#F5A623' },
  { from:4, to:6, label:'医疗急救包×50套', status:'已到达', color:'#2E8B57' },
  { from:3, to:9, label:'发电机×3台',    status:'运输中', color:'#F5A623' },
];

// Shaanxi simplified outline path (approximate)
const SX_OUTLINE = "M180,20 L280,25 L310,55 L290,80 L295,100 L280,120 L270,160 L290,185 L310,200 L330,240 L330,270 L310,295 L290,310 L295,340 L280,370 L265,395 L245,420 L215,435 L195,450 L170,440 L145,420 L120,415 L95,400 L75,385 L70,355 L80,330 L65,305 L60,280 L75,255 L90,240 L85,215 L90,190 L85,170 L100,150 L110,130 L105,105 L115,85 L130,65 L155,45 Z";

function MapPage() {
  const [selected, setSelected] = React.useState(null);
  const [hoveredRoute, setHoveredRoute] = React.useState(null);
  const [animOffset, setAnimOffset] = React.useState(0);

  // Animate dashes for in-transit routes
  React.useEffect(() => {
    const id = setInterval(() => setAnimOffset(o => (o + 1) % 20), 60);
    return () => clearInterval(id);
  }, []);

  const totalStock = SX_CITIES.reduce((s,c)=>s+c.stock,0);
  const provinceStock = SX_CITIES.find(c=>c.level==='省级')?.stock || 0;

  const kpis = [
    { label:'全省在库物资', value: (totalStock/10000).toFixed(1), unit:'万件/套', color:'#1B4FA8' },
    { label:'省级仓库占比', value: ((provinceStock/totalStock)*100).toFixed(0), unit:'%', color:'#2E6BCC' },
    { label:'在途调拨任务', value: ROUTES.filter(r=>r.status==='运输中').length, unit:'条', color:'#E87722' },
    { label:'覆盖地市数量', value: SX_CITIES.length, unit:'个', color:'#2E8B57' },
  ];

  // Simple bar chart data
  const barData = SX_CITIES.slice().sort((a,b)=>b.stock-a.stock).slice(0,6);
  const maxBar = barData[0]?.stock || 1;

  // Monthly trend (sparkline-style)
  const trend = [12400,13800,15200,14600,16800,18600,totalStock];
  const maxTrend = Math.max(...trend);
  const trendPts = trend.map((v,i) => `${i*(260/6)},${80-(v/maxTrend)*70}`).join(' ');

  return (
    <div>
      <PageHeader title="仪表板" crumb="首页 › 仪表板"/>

      {/* KPI row */}
      <div style={{display:'grid',gridTemplateColumns:'repeat(4,1fr)',gap:12,marginBottom:16}}>
        {kpis.map(k=><StatCard key={k.label} {...k}/>)}
      </div>

      <div style={{display:'grid',gridTemplateColumns:'1fr 340px',gap:12,alignItems:'start'}}>

        {/* Map panel */}
        <Card title="应急物资储备一张图" extra={
          <div style={{display:'flex',gap:12,fontSize:12,color:T.gray600,alignItems:'center'}}>
            <span style={{display:'flex',alignItems:'center',gap:4}}>
              <span style={{width:10,height:10,borderRadius:'50%',background:'#1B4FA8',display:'inline-block'}}/>省级仓库
            </span>
            <span style={{display:'flex',alignItems:'center',gap:4}}>
              <span style={{width:10,height:10,borderRadius:'50%',background:'#4A7FD4',display:'inline-block'}}/>市级仓库
            </span>
            <span style={{display:'flex',alignItems:'center',gap:4}}>
              <span style={{width:24,height:3,background:'#F5A623',display:'inline-block',borderRadius:1}}/>在途运输
            </span>
          </div>
        }>
          <div style={{position:'relative',background:'#EEF4FF',borderRadius:4,overflow:'hidden'}}>
            <svg viewBox="0 0 400 470" style={{width:'100%',display:'block'}}
              xmlns="http://www.w3.org/2000/svg">
              {/* Background */}
              <rect width="400" height="470" fill="#EEF4FF"/>
              {/* Grid */}
              {[0,1,2,3,4].map(i=>(
                <line key={`h${i}`} x1="0" y1={i*100+20} x2="400" y2={i*100+20} stroke="#DAE8FB" strokeWidth=".5"/>
              ))}
              {[0,1,2,3].map(i=>(
                <line key={`v${i}`} x1={i*100+50} y1="0" x2={i*100+50} y2="470" stroke="#DAE8FB" strokeWidth=".5"/>
              ))}

              {/* Province outline */}
              <path d={SX_OUTLINE} fill="rgba(27,79,168,.08)" stroke="#4A7FD4" strokeWidth="1.5" strokeLinejoin="round"/>

              {/* Transport routes */}
              {ROUTES.map((r,i) => {
                const fc = SX_CITIES[r.from], tc = SX_CITIES[r.to];
                const isMoving = r.status === '运输中';
                const mx = (fc.x+tc.x)/2 + (i%2===0?-20:20);
                const my = (fc.y+tc.y)/2 - 20;
                return (
                  <g key={i}
                    onMouseEnter={()=>setHoveredRoute(i)}
                    onMouseLeave={()=>setHoveredRoute(null)}
                    style={{cursor:'pointer'}}>
                    <path
                      d={`M${fc.x},${fc.y} Q${mx},${my} ${tc.x},${tc.y}`}
                      fill="none" stroke={r.color}
                      strokeWidth={hoveredRoute===i?3:2}
                      strokeDasharray={isMoving?'8 4':'none'}
                      strokeDashoffset={isMoving?-animOffset:0}
                      opacity={.85}/>
                    {/* Arrow at end */}
                    <circle cx={tc.x} cy={tc.y} r="4" fill={r.color} opacity=".7"/>
                  </g>
                );
              })}

              {/* Route tooltip */}
              {hoveredRoute!==null && (() => {
                const r = ROUTES[hoveredRoute];
                const fc = SX_CITIES[r.from], tc = SX_CITIES[r.to];
                const tx = (fc.x+tc.x)/2, ty = (fc.y+tc.y)/2 - 30;
                return (
                  <g>
                    <rect x={tx-60} y={ty-22} width={120} height={44} rx="3" fill="rgba(10,30,70,.85)"/>
                    <text x={tx} y={ty-6} textAnchor="middle" fill="white" fontSize="11" fontFamily="sans-serif">{r.label}</text>
                    <text x={tx} y={ty+11} textAnchor="middle" fill={r.color} fontSize="10" fontFamily="sans-serif">{r.status}</text>
                  </g>
                );
              })()}

              {/* City markers */}
              {SX_CITIES.map((c,i) => {
                const isProv = c.level==='省级';
                const isActive = c.active;
                const r = isProv ? 14 : 9;
                const isSelected = selected?.name === c.name;
                return (
                  <g key={c.name} onClick={()=>setSelected(isSelected?null:c)} style={{cursor:'pointer'}}>
                    {isSelected&&<circle cx={c.x} cy={c.y} r={r+8} fill="rgba(27,79,168,.15)" />}
                    {isActive&&<circle cx={c.x} cy={c.y} r={r+5} fill="rgba(232,119,34,.2)">
                      <animate attributeName="r" values={`${r+3};${r+9};${r+3}`} dur="2s" repeatCount="indefinite"/>
                      <animate attributeName="opacity" values="0.4;0;0.4" dur="2s" repeatCount="indefinite"/>
                    </circle>}
                    <circle cx={c.x} cy={c.y} r={r}
                      fill={isProv?'#1B4FA8':'#4A7FD4'}
                      stroke="white" strokeWidth="1.5"
                      opacity={isSelected?1:.85}/>
                    <text x={c.x} y={c.y+4} textAnchor="middle" fill="white"
                      fontSize={isProv?10:8} fontWeight="600" fontFamily="sans-serif">{isProv?'省':'市'}</text>
                    <text x={c.x+(isProv?18:14)} y={c.y-2} fill={T.gray900}
                      fontSize={isProv?12:10} fontWeight="500" fontFamily="sans-serif">{c.name}</text>
                    <text x={c.x+(isProv?18:14)} y={c.y+10} fill={T.gray600}
                      fontSize="9" fontFamily="sans-serif">{c.stock.toLocaleString()}</text>
                  </g>
                );
              })}
            </svg>

            {/* Selected city popup */}
            {selected&&(
              <div style={{position:'absolute',top:12,right:12,background:'white',borderRadius:4,padding:'12px 14px',boxShadow:'0 4px 16px rgba(0,0,0,.12)',minWidth:180,border:`1px solid ${T.gray200}`,borderTop:`3px solid ${T.blue600}`}}>
                <div style={{fontWeight:600,fontSize:14,marginBottom:8}}>{selected.name}</div>
                <div style={{fontSize:12,color:T.gray600,marginBottom:4}}>{selected.wh}</div>
                <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:6,marginTop:10}}>
                  {[['在库物资',`${selected.stock.toLocaleString()} 件`],['仓库级别',selected.level],['状态',selected.active?'调拨中':'正常']].map(([l,v])=>(
                    <div key={l} style={{padding:'5px 8px',background:T.gray50,borderRadius:3}}>
                      <div style={{fontSize:10,color:T.gray400}}>{l}</div>
                      <div style={{fontSize:12,fontWeight:500}}>{v}</div>
                    </div>
                  ))}
                </div>
                <button onClick={()=>setSelected(null)} style={{marginTop:10,width:'100%',background:'none',border:`1px solid ${T.gray200}`,borderRadius:3,padding:'4px 0',fontSize:12,cursor:'pointer',color:T.gray600}}>关闭</button>
              </div>
            )}
          </div>
          <div style={{marginTop:8,fontSize:12,color:T.gray400,textAlign:'center'}}>点击城市查看详情 · 悬停运输线查看任务</div>
        </Card>

        {/* Right column: charts */}
        <div style={{display:'flex',flexDirection:'column',gap:12}}>

          {/* Bar chart: top warehouses */}
          <Card title="仓库储量 TOP 6">
            {barData.map((c,i)=>(
              <div key={c.name} style={{display:'flex',alignItems:'center',gap:8,marginBottom:9}}>
                <div style={{width:28,fontSize:12,color:T.gray600,textAlign:'right',flexShrink:0}}>{c.name}</div>
                <div style={{flex:1,height:18,background:T.gray100,borderRadius:2,overflow:'hidden'}}>
                  <div style={{height:'100%',width:`${(c.stock/maxBar)*100}%`,
                    background:i===0?T.blue600:'#4A7FD4',
                    opacity:1-i*.08,
                    transition:'width .6s',borderRadius:2}}/>
                </div>
                <div style={{width:52,fontSize:11,color:T.gray600,textAlign:'right',flexShrink:0}}>{(c.stock/1000).toFixed(1)}K</div>
              </div>
            ))}
          </Card>

          {/* Trend sparkline */}
          <Card title="全省库存趋势（近7个月）">
            <svg viewBox="0 0 280 90" style={{width:'100%',overflow:'visible'}}>
              <defs>
                <linearGradient id="trendGrad" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor={T.blue600} stopOpacity=".3"/>
                  <stop offset="100%" stopColor={T.blue600} stopOpacity="0"/>
                </linearGradient>
              </defs>
              {/* Grid lines */}
              {[0,1,2,3].map(i=>(
                <line key={i} x1="0" y1={10+i*20} x2="280" y2={10+i*20} stroke={T.gray100} strokeWidth="1"/>
              ))}
              {/* Area */}
              <polygon points={`0,80 ${trendPts} ${260},80`} fill="url(#trendGrad)"/>
              {/* Line */}
              <polyline points={trendPts} fill="none" stroke={T.blue600} strokeWidth="2" strokeLinejoin="round"/>
              {/* Dots */}
              {trend.map((v,i)=>(
                <circle key={i} cx={i*(260/6)} cy={80-(v/maxTrend)*70} r="3.5" fill={T.blue600} stroke="white" strokeWidth="1.5"/>
              ))}
              {/* Labels */}
              {['10月','11月','12月','1月','2月','3月','4月'].map((m,i)=>(
                <text key={m} x={i*(260/6)} y="88" textAnchor="middle" fontSize="9" fill={T.gray400} fontFamily="sans-serif">{m}</text>
              ))}
            </svg>
          </Card>

          {/* Pie-like donut: category breakdown */}
          <Card title="类别占比">
            {[
              {name:'防汛抗旱',pct:32,color:'#1B4FA8'},
              {name:'生活保障',pct:28,color:'#2E6BCC'},
              {name:'应急装备',pct:18,color:'#4A7FD4'},
              {name:'医疗保障',pct:12,color:'#00A8CC'},
              {name:'通讯资源',pct:6,color:'#6B4FA8'},
              {name:'其他',pct:4,color:'#9BA5B5'},
            ].map((c,i)=>(
              <div key={c.name} style={{display:'flex',alignItems:'center',gap:8,marginBottom:7}}>
                <div style={{width:10,height:10,borderRadius:2,background:c.color,flexShrink:0}}/>
                <div style={{flex:1,fontSize:12,color:T.gray700}}>{c.name}</div>
                <div style={{width:100,height:8,background:T.gray100,borderRadius:4,overflow:'hidden'}}>
                  <div style={{height:'100%',width:`${c.pct}%`,background:c.color,borderRadius:4}}/>
                </div>
                <div style={{width:28,fontSize:12,color:T.gray400,textAlign:'right'}}>{c.pct}%</div>
              </div>
            ))}
          </Card>

          {/* Active transports */}
          <Card title="在途运输" extra={<Badge type="warning">{ROUTES.filter(r=>r.status==='运输中').length} 条进行中</Badge>}>
            {ROUTES.map((r,i)=>{
              const fc=SX_CITIES[r.from], tc=SX_CITIES[r.to];
              return (
                <div key={i} style={{padding:'8px 0',borderBottom:i<ROUTES.length-1?`1px dashed ${T.gray100}`:'none',display:'flex',gap:8,alignItems:'flex-start'}}>
                  <div style={{width:6,height:6,borderRadius:'50%',background:r.color,marginTop:4,flexShrink:0}}/>
                  <div style={{flex:1}}>
                    <div style={{fontSize:12,color:T.gray700}}>{r.label}</div>
                    <div style={{fontSize:11,color:T.gray400,marginTop:2}}>{fc.name} → {tc.name}</div>
                  </div>
                  <Badge type={r.status==='运输中'?'warning':'success'}>{r.status}</Badge>
                </div>
              );
            })}
          </Card>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { MapPage });
