// Artboard 1: Isometric City Map
// Pixel-ish temple city — 6 server "cities", ministry temple buildings clustered,
// tiny monk figures walking paths between them, glowing mesh connections.

const { MINISTRIES: MM1, AGENTS: AA1, SERVERS: SS1 } = window.DHAM;

// Convert iso grid (x,y) to screen (px,py). Unit = half-tile.
// Standard 2:1 iso: sx = (x - y) * tw/2, sy = (x + y) * th/2
const TW = 56;  // tile width
const TH = 28;  // tile height

function iso(x, y) {
  return { sx: (x - y) * (TW / 2), sy: (x + y) * (TH / 2) };
}

// Isometric tile — diamond.
function IsoTile({ x, y, fill = '#1E2A4E', stroke = 'rgba(212,168,67,0.12)', z = 0 }) {
  const { sx, sy } = iso(x, y);
  return (
    <polygon
      points={`${sx},${sy - TH / 2} ${sx + TW / 2},${sy} ${sx},${sy + TH / 2} ${sx - TW / 2},${sy}`}
      fill={fill}
      stroke={stroke}
      strokeWidth="0.6"
      style={{ transition: 'fill .3s' }}
    />
  );
}

// Temple building — base + mid + tiered roof. Drawn as iso 3D.
// gx/gy = grid position (center of footprint). footprint in tiles (1 or 2).
// roofColor, wallColor, h = total height in px
function Temple({ gx, gy, footprint = 1, h = 44, wall = '#2A3557', roof = '#D4A843', accent = '#F5A623', glow = null, spire = true, label }) {
  const half = footprint / 2;
  const { sx, sy } = iso(gx, gy);
  // 4 corners in iso
  const c = {
    n: iso(gx - half, gy - half), // north
    e: iso(gx + half, gy - half), // east
    s: iso(gx + half, gy + half), // south
    w: iso(gx - half, gy + half), // west
  };
  // top corners (lifted by h)
  const t = {
    n: { sx: c.n.sx, sy: c.n.sy - h },
    e: { sx: c.e.sx, sy: c.e.sy - h },
    s: { sx: c.s.sx, sy: c.s.sy - h },
    w: { sx: c.w.sx, sy: c.w.sy - h },
  };
  // mid band (sash) at 2/3 height
  const mh = h * 0.35;
  const mid = {
    n: { sx: c.n.sx, sy: c.n.sy - mh },
    e: { sx: c.e.sx, sy: c.e.sy - mh },
    s: { sx: c.s.sx, sy: c.s.sy - mh },
    w: { sx: c.w.sx, sy: c.w.sy - mh },
  };
  // Roof overhang
  const ov = TW * 0.14;
  const roofH = h * 0.38;
  const ridge = { sx: sx, sy: sy - h - roofH };

  return (
    <g style={{ filter: glow ? `drop-shadow(0 0 10px ${glow})` : undefined }}>
      {/* shadow */}
      <ellipse cx={sx} cy={c.s.sy + 3} rx={TW * footprint * 0.55} ry={TH * footprint * 0.55} fill="rgba(0,0,0,0.35)" />

      {/* east wall (lit) */}
      <polygon points={`${c.e.sx},${c.e.sy} ${t.e.sx},${t.e.sy} ${t.s.sx},${t.s.sy} ${c.s.sx},${c.s.sy}`} fill={wall} />
      {/* west wall (shaded) */}
      <polygon points={`${c.w.sx},${c.w.sy} ${t.w.sx},${t.w.sy} ${t.s.sx},${t.s.sy} ${c.s.sx},${c.s.sy}`} fill={wall} opacity="0.75" />
      {/* sash band */}
      <polygon points={`${c.e.sx},${mid.e.sy} ${c.s.sx},${mid.s.sy} ${c.s.sx},${mid.s.sy + 3} ${c.e.sx},${mid.e.sy + 3}`} fill={accent} opacity="0.9" />
      <polygon points={`${c.w.sx},${mid.w.sy} ${c.s.sx},${mid.s.sy} ${c.s.sx},${mid.s.sy + 3} ${c.w.sx},${mid.w.sy + 3}`} fill={accent} opacity="0.7" />

      {/* lit window dots */}
      {glow && <>
        <circle cx={(c.e.sx + t.s.sx) / 2 - 6} cy={(c.e.sy + t.s.sy) / 2 + 5} r="1.6" fill="#FFE9A3" />
        <circle cx={(c.e.sx + t.s.sx) / 2 + 3} cy={(c.e.sy + t.s.sy) / 2 + 2} r="1.6" fill="#FFE9A3" />
        <circle cx={(c.w.sx + t.s.sx) / 2 - 3} cy={(c.w.sy + t.s.sy) / 2 + 3} r="1.6" fill="#FFE9A3" opacity="0.8" />
      </>}

      {/* Roof — 4 triangular slopes meeting at ridge */}
      <polygon points={`${t.e.sx + ov},${t.e.sy} ${t.s.sx},${t.s.sy + ov / 2} ${ridge.sx},${ridge.sy}`} fill={roof} />
      <polygon points={`${t.w.sx - ov},${t.w.sy} ${t.s.sx},${t.s.sy + ov / 2} ${ridge.sx},${ridge.sy}`} fill={roof} opacity="0.8" />
      <polygon points={`${t.e.sx + ov},${t.e.sy} ${t.n.sx},${t.n.sy - ov / 2} ${ridge.sx},${ridge.sy}`} fill={roof} opacity="0.92" />
      <polygon points={`${t.w.sx - ov},${t.w.sy} ${t.n.sx},${t.n.sy - ov / 2} ${ridge.sx},${ridge.sy}`} fill={roof} opacity="0.72" />

      {/* Curved roof tips (temple style) */}
      <circle cx={t.e.sx + ov} cy={t.e.sy - 2} r="2" fill={accent} />
      <circle cx={t.w.sx - ov} cy={t.w.sy - 2} r="2" fill={accent} />
      <circle cx={t.n.sx} cy={t.n.sy - ov / 2 - 2} r="2" fill={accent} />
      <circle cx={t.s.sx} cy={t.s.sy + ov / 2 - 2} r="2" fill={accent} />

      {/* Spire */}
      {spire && <>
        <line x1={ridge.sx} y1={ridge.sy} x2={ridge.sx} y2={ridge.sy - 14} stroke={accent} strokeWidth="1.6" />
        <circle cx={ridge.sx} cy={ridge.sy - 16} r="2.4" fill={accent} />
        <circle cx={ridge.sx} cy={ridge.sy - 16} r="5" fill={accent} opacity="0.25" />
      </>}

      {/* Label */}
      {label && (
        <text x={sx} y={c.s.sy + 18} textAnchor="middle" fontSize="8" fontFamily="var(--mono)" fill="var(--text-dim)" style={{ letterSpacing: 1.2, textTransform: 'uppercase' }}>{label}</text>
      )}
    </g>
  );
}

// Mesh line connecting two iso points with a glowing dashed gradient.
function MeshLine({ from, to, color = '#D4A843', idx = 0 }) {
  const a = iso(from[0], from[1]);
  const b = iso(to[0], to[1]);
  return (
    <g>
      <line x1={a.sx} y1={a.sy - 20} x2={b.sx} y2={b.sy - 20} stroke={color} strokeWidth="1" opacity="0.25" strokeDasharray="2 4" />
      <line x1={a.sx} y1={a.sy - 20} x2={b.sx} y2={b.sy - 20} stroke={color} strokeWidth="2" opacity="0.6" strokeDasharray="4 16" strokeDashoffset={-idx * 3}>
        <animate attributeName="stroke-dashoffset" from="0" to="-40" dur="2s" repeatCount="indefinite" />
      </line>
    </g>
  );
}

// Tiny iso monk — just a vertical oval + circle head.
function IsoMonk({ x, y, color = '#D4A843', status = 'online' }) {
  const { sx, sy } = iso(x, y);
  const glow = status === 'working' ? '#FBBF24' : status === 'online' ? '#4ADE80' : null;
  return (
    <g style={{ filter: glow ? `drop-shadow(0 0 3px ${glow})` : undefined }}>
      <ellipse cx={sx} cy={sy + 2} rx="3" ry="1.2" fill="rgba(0,0,0,0.4)" />
      <path d={`M${sx - 2.5} ${sy} L${sx + 2.5} ${sy} L${sx + 1.5} ${sy - 8} L${sx - 1.5} ${sy - 8} Z`} fill={color} />
      <circle cx={sx} cy={sy - 10} r="1.8" fill="#C4A77A" />
      {status === 'working' && <circle cx={sx} cy={sy - 13} r="1.2" fill="#FBBF24">
        <animate attributeName="opacity" values="0.3;1;0.3" dur="1.2s" repeatCount="indefinite" />
      </circle>}
    </g>
  );
}

// Layout — each cluster sits in an iso sub-plot
const CLUSTERS = [
  // [clusterId, gx, gy, footprint, temples[]]
  { id: 'pm',       gx:  0, gy:  0, label: 'GOVERNMENT',     color: '#D4A843',
    temples: [ { m: 'pm',  gx:  0, gy:  0, size: 2, h: 66 }, { m: 'ind', gx: -2.5, gy:  0, size: 1, h: 42 } ] },
  { id: 'tech',     gx:  4, gy: -3, label: 'TECHNOLOGY',     color: '#60A5FA',
    temples: [ { m: 'tech', gx:  3, gy: -3, size: 2, h: 58 }, { m: 'tech', gx:  5.5, gy: -2, size: 1, h: 36 }, { m: 'tech', gx:  5, gy: -4, size: 1, h: 40 } ] },
  { id: 'interior', gx:  4, gy:  3, label: 'INTERIOR',       color: '#7F8CFF',
    temples: [ { m: 'interior', gx:  4, gy:  3, size: 1.5, h: 48 }, { m: 'interior', gx:  6, gy:  3.5, size: 1, h: 36 } ] },
  { id: 'finance',  gx: -4, gy: -3, label: 'FINANCE',         color: '#4ADE80',
    temples: [ { m: 'finance', gx: -4, gy: -3, size: 1.5, h: 46 }, { m: 'commerce', gx: -5.5, gy: -4.5, size: 1, h: 34 } ] },
  { id: 'culture',  gx: -4, gy:  3, label: 'CIVIC · CULTURE', color: '#F472B6',
    temples: [ { m: 'culture', gx: -4, gy:  3, size: 1, h: 40 }, { m: 'comms', gx: -5.5, gy:  3, size: 1, h: 36 }, { m: 'justice', gx: -4, gy:  4.5, size: 1, h: 34 } ] },
  { id: 'intel',    gx:  0, gy: -5, label: 'FOREIGN · INTEL', color: '#8B5CF6',
    temples: [ { m: 'foreign', gx:  0, gy: -5, size: 1, h: 36 }, { m: 'intel', gx:  1.5, gy: -6, size: 1, h: 40 }, { m: 'defense', gx: -1.5, gy: -6, size: 1, h: 44 } ] },
  { id: 'data',     gx:  0, gy:  5, label: 'DATA · HEALTH',  color: '#22D3EE',
    temples: [ { m: 'data', gx:  0, gy:  5, size: 1.5, h: 46 }, { m: 'health', gx:  1.5, gy:  6, size: 1, h: 36 }, { m: 'agri', gx: -1.5, gy:  6, size: 1, h: 32 } ] },
];

// Network connections between cluster centers
const MESH = [
  [[0,0], [4,-3]], [[0,0], [4,3]], [[0,0], [-4,-3]], [[0,0], [-4,3]],
  [[0,0], [0,-5]], [[0,0], [0,5]],
  [[4,-3], [4,3]], [[-4,-3], [-4,3]],
  [[4,-3], [0,-5]], [[-4,-3], [0,-5]],
];

function Artboard_CityMap() {
  const [time, setTime] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setTime((t) => t + 1), 80);
    return () => clearInterval(id);
  }, []);

  // Precompute monk positions — each cluster has a few monks, some moving along paths
  const monks = React.useMemo(() => {
    const list = [];
    CLUSTERS.forEach((cl) => {
      const clusterAgents = AA1.filter((a) => {
        // rough mapping
        if (cl.id === 'pm') return a.ministry === 'pm' || a.ministry === 'ind';
        if (cl.id === 'tech') return a.ministry === 'tech';
        if (cl.id === 'interior') return a.ministry === 'interior';
        if (cl.id === 'finance') return a.ministry === 'finance' || a.ministry === 'commerce';
        if (cl.id === 'culture') return a.ministry === 'culture' || a.ministry === 'comms' || a.ministry === 'justice' || a.ministry === 'cr';
        if (cl.id === 'intel') return a.ministry === 'foreign' || a.ministry === 'intel' || a.ministry === 'defense';
        if (cl.id === 'data') return a.ministry === 'data' || a.ministry === 'health' || a.ministry === 'agri' || a.ministry === 'company';
        return false;
      }).slice(0, 5);
      clusterAgents.forEach((a, i) => {
        const angle = (i / clusterAgents.length) * Math.PI * 2;
        const r = 1.2 + (i % 2) * 0.4;
        list.push({
          a, baseX: cl.gx + Math.cos(angle) * r, baseY: cl.gy + Math.sin(angle) * r,
          phase: i * 0.7, color: MM1[a.ministry]?.color || '#D4A843',
        });
      });
    });
    return list;
  }, []);

  const BOX_W = 1050;
  const BOX_H = 600;
  const CENTER_X = BOX_W / 2;
  const CENTER_Y = BOX_H / 2 + 40;

  return (
    <AppChrome activePage="map" padded={false}
      rightSlot={
        <div style={{ display: 'flex', alignItems: 'center', gap: 16, fontSize: 11, color: 'var(--text-dim)', fontFamily: 'var(--mono)' }}>
          <span>33/35 <span style={{ color: 'var(--online)' }}>●</span></span>
          <span>$47.12 today</span>
          <span>14.2M tok</span>
        </div>
      }>
      <div style={{ position: 'relative', flex: 1, overflow: 'hidden', background: 'radial-gradient(ellipse at 50% 40%, var(--purple-lo) 0%, var(--base) 70%)' }}>
        {/* Stars */}
        <svg width="100%" height="100%" style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}>
          {Array.from({ length: 60 }).map((_, i) => {
            const x = (i * 97) % 100;
            const y = (i * 53) % 40;
            const size = (i % 3) + 1;
            return <circle key={i} cx={`${x}%`} cy={`${y}%`} r={size * 0.5} fill="#FFE9A3" opacity={0.15 + (i % 4) * 0.08} />;
          })}
        </svg>

        {/* Iso city svg */}
        <svg width={BOX_W} height={BOX_H} style={{ position: 'absolute', left: '50%', top: 0, transform: 'translateX(-50%)' }}>
          <g transform={`translate(${CENTER_X}, ${CENTER_Y})`}>
            {/* Ground tiles — big diamond */}
            {Array.from({ length: 17 }).flatMap((_, i) =>
              Array.from({ length: 17 }).map((_, j) => {
                const x = i - 8, y = j - 8;
                if (Math.abs(x) + Math.abs(y) > 10) return null;
                const { sx, sy } = iso(x, y);
                const fill = (x + y) % 2 === 0 ? 'rgba(45,27,78,0.55)' : 'rgba(30,20,56,0.55)';
                return (
                  <polygon key={`${x}-${y}`}
                    points={`${sx},${sy - TH / 2} ${sx + TW / 2},${sy} ${sx},${sy + TH / 2} ${sx - TW / 2},${sy}`}
                    fill={fill}
                    stroke="rgba(212,168,67,0.07)"
                    strokeWidth="0.5" />
                );
              })
            )}

            {/* Paths — radial from center */}
            {CLUSTERS.map((cl) => {
              const a = iso(0, 0);
              const b = iso(cl.gx * 0.6, cl.gy * 0.6);
              return (
                <line key={`p-${cl.id}`} x1={a.sx} y1={a.sy} x2={b.sx} y2={b.sy} stroke="rgba(212,168,67,0.2)" strokeWidth="3" strokeLinecap="round" />
              );
            })}

            {/* Mesh network lines — above ground, below buildings */}
            {MESH.map((m, i) => (
              <MeshLine key={i} from={m[0]} to={m[1]} color="#D4A843" idx={i} />
            ))}

            {/* Buildings — sorted by y (back to front) */}
            {CLUSTERS
              .flatMap((cl) => cl.temples.map((t) => ({ ...t, cluster: cl })))
              .sort((a, b) => (a.gx + a.gy) - (b.gx + b.gy))
              .map((t, i) => {
                const m = MM1[t.m];
                return (
                  <Temple key={i} gx={t.gx} gy={t.gy} footprint={t.size}
                    h={t.h} wall="#2A3557" roof={m.color}
                    accent="#F5A623" glow={m.color} />
                );
              })}

            {/* Cluster labels */}
            {CLUSTERS.map((cl) => {
              const { sx, sy } = iso(cl.gx, cl.gy);
              return (
                <g key={`lbl-${cl.id}`}>
                  <text x={sx} y={sy + 58} textAnchor="middle" fontSize="8.5" fontFamily="var(--mono)" fill={cl.color} style={{ letterSpacing: 2 }}>
                    {cl.label}
                  </text>
                </g>
              );
            })}

            {/* Monks — walking in small orbits */}
            {monks.map((mk, i) => {
              const t = time * 0.02 + mk.phase;
              const x = mk.baseX + Math.cos(t) * 0.2;
              const y = mk.baseY + Math.sin(t) * 0.2;
              return <IsoMonk key={i} x={x} y={y} color={mk.color} status={mk.a.status} />;
            })}
          </g>
        </svg>

        {/* Server nodes — overlay — 6 hex chips around the city */}
        <div style={{ position: 'absolute', top: 16, left: 20, display: 'flex', flexDirection: 'column', gap: 8, fontSize: 11, fontFamily: 'var(--mono)' }}>
          <div style={{ color: 'var(--text-dim)', fontSize: 9, letterSpacing: 2 }}>6 SERVERS · MESH</div>
          {SS1.map((s) => (
            <div key={s.id} style={{ display: 'flex', alignItems: 'center', gap: 8, background: 'rgba(22,33,62,0.75)', border: '1px solid var(--line)', padding: '6px 10px', borderRadius: 3, minWidth: 180 }}>
              <div style={{ width: 6, height: 6, borderRadius: '50%', background: s.status === 'working' ? 'var(--working)' : 'var(--online)', boxShadow: s.status === 'working' ? '0 0 6px var(--working)' : '0 0 4px var(--online)' }} />
              <div style={{ flex: 1 }}>
                <div style={{ color: 'var(--gold)', fontSize: 10, fontFamily: 'var(--thai)' }}>{s.thai}</div>
                <div style={{ color: 'var(--text-dim)', fontSize: 9 }}>{s.role}</div>
              </div>
              <div style={{ color: 'var(--text)', fontSize: 10 }}>{s.cpu}%</div>
            </div>
          ))}
        </div>

        {/* Legend */}
        <div style={{ position: 'absolute', top: 16, right: 20, background: 'rgba(22,33,62,0.75)', border: '1px solid var(--line)', borderRadius: 3, padding: 12, fontSize: 10, fontFamily: 'var(--mono)', minWidth: 180 }}>
          <div style={{ color: 'var(--text-dim)', fontSize: 9, letterSpacing: 2, marginBottom: 8 }}>LEGEND</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {[['Online', 'var(--online)'], ['Working', 'var(--working)'], ['Offline', 'var(--offline)']].map(([l, c]) => (
              <div key={l} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <div style={{ width: 8, height: 8, borderRadius: '50%', background: c }} />
                <span style={{ color: 'var(--text)' }}>{l}</span>
              </div>
            ))}
            <div style={{ height: 1, background: 'var(--line)', margin: '4px 0' }} />
            <div style={{ color: 'var(--text-dim)' }}>◇ Temple = Ministry</div>
            <div style={{ color: 'var(--text-dim)' }}>— Mesh network</div>
          </div>
        </div>

        {/* Selected-ministry detail card */}
        <div style={{ position: 'absolute', bottom: 20, left: 20, background: 'rgba(22,33,62,0.9)', border: '1px solid var(--line-strong)', borderRadius: 3, padding: '14px 16px', minWidth: 300, backdropFilter: 'blur(6px)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
            <div style={{ width: 8, height: 8, background: '#60A5FA', borderRadius: 2 }} />
            <div style={{ fontSize: 11, fontFamily: 'var(--mono)', color: 'var(--text-dim)', letterSpacing: 1.5 }}>MINISTRY DETAIL</div>
          </div>
          <div style={{ fontSize: 16, fontWeight: 600, letterSpacing: -0.3 }}>Ministry of Technology</div>
          <div style={{ fontSize: 11, color: 'var(--text-dim)', fontFamily: 'var(--thai)', marginBottom: 10 }}>กระทรวงเทคโนโลยี · 8 bhikkhus · 4 working</div>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {AA1.filter((a) => a.ministry === 'tech').slice(0, 8).map((a) => (
              <Avatar key={a.id} agent={a} size={26} />
            ))}
          </div>
        </div>

        {/* Day/night + clock */}
        <div style={{ position: 'absolute', bottom: 20, right: 20, textAlign: 'right', fontFamily: 'var(--mono)' }}>
          <div style={{ fontSize: 9, color: 'var(--text-dim)', letterSpacing: 2 }}>CITY TIME · UTC+7</div>
          <div style={{ fontSize: 24, color: 'var(--gold)', fontWeight: 600, letterSpacing: 2 }}>23:48</div>
          <div style={{ fontSize: 10, color: 'var(--text-dim)' }}>waxing half moon · ♆</div>
        </div>
      </div>
    </AppChrome>
  );
}

window.Artboard_CityMap = Artboard_CityMap;
