// map-view.jsx — 지도 탐색 (시도 → 시군구 → 읍면동 드릴다운 + 단지 핀)
// 데모: APTS(국토부 RTMS 기반 샘플)에서 지역 매칭. 백엔드 연결 시 실거래로 자동 확장.

function MapViewPage() {
  const isMobile = useIsMobile();
  const [sido, setSido] = useState('서울특별시');
  const [selectedDong, setSelectedDong] = useState(null);
  const [selected, setSelected] = useState(null); // 클릭한 단지 → 상세 모달
  useEffect(() => { document.title = '지도 탐색 — 우리집사기'; window.UJTrack.track('view_map', {}); }, []);

  const norm = (s) => (s || '').replace(/특별시|광역시|특별자치시|특별자치도|도$/g, '').replace(/\s/g, '');
  const sidoKey = norm(sido);

  // 선택 시도에 속한 단지
  const apts = useMemo(() => window.APTS.filter(a => {
    const r = norm(a.region);
    return r.includes(sidoKey) || sidoKey.includes(r.slice(0, 2));
  }), [sido]);

  // 읍면동(동) 그룹
  const dongGroups = useMemo(() => {
    const m = {};
    apts.forEach(a => { (m[a.dong] = m[a.dong] || []).push(a); });
    return Object.entries(m).map(([dong, list]) => ({
      dong, list,
      avgScore: Math.round(list.reduce((s, x) => s + x.score, 0) / list.length),
      avgPrice: Math.round(list.reduce((s, x) => s + x.currentPrice, 0) / list.length),
    })).sort((a, b) => b.avgScore - a.avgScore);
  }, [apts]);

  const shownApts = selectedDong ? apts.filter(a => a.dong === selectedDong) : apts;

  const openApt = (a) => {
    window.UJTrack.track('map_pin_click', { apt: a.name, region: a.region });
    setSelected({ apt: { name: a.name, dong: a.dong, trades: a.trades, area: a.area, buildYear: a.built }, region: a.region });
  };

  return (
    <div style={{ padding: isMobile ? 12 : 20 }}>
      <PageHead title="지도 탐색" sub={`${sido} · ${apts.length}개 단지 · ${dongGroups.length}개 읍면동`} />

      {/* 시도 선택 칩 */}
      <div className="uj-xscroll" style={{ display: 'flex', gap: 6, marginBottom: 12, paddingBottom: 4 }}>
        {Object.keys(LAWD_TREE).map(s => (
          <button key={s} onClick={() => { setSido(s); setSelectedDong(null); }}
            style={{ padding: '6px 12px', borderRadius: 999, whiteSpace: 'nowrap', flexShrink: 0,
              background: sido === s ? T.hot : T.card, color: sido === s ? T.bg : T.fgDim,
              border: '1px solid ' + (sido === s ? T.hot : T.line), fontSize: 12, fontWeight: 600, cursor: 'pointer' }}>
            {SIDO_SHORT ? (SIDO_SHORT[s] || s) : s}
          </button>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '300px 1fr', gap: 16 }}>
        {/* 읍면동 리스트 */}
        <Panel title="읍면동" subtitle={selectedDong || '전체'} style={{ alignSelf: 'start' }}>
          <div className="uj-scroll" style={{ maxHeight: isMobile ? 200 : 460, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 2 }}>
            <button onClick={() => setSelectedDong(null)}
              style={{ textAlign: 'left', padding: '8px 10px', borderRadius: 4, border: 'none', cursor: 'pointer',
                background: !selectedDong ? T.cardHi : 'transparent', color: T.fg, fontFamily: T.font, fontSize: 13 }}>
              전체 보기 ({apts.length})
            </button>
            {dongGroups.map(g => (
              <button key={g.dong} onClick={() => setSelectedDong(g.dong)}
                style={{ textAlign: 'left', padding: '8px 10px', borderRadius: 4, border: 'none', cursor: 'pointer',
                  background: selectedDong === g.dong ? T.cardHi : 'transparent',
                  display: 'flex', alignItems: 'center', gap: 8, fontFamily: T.font }}>
                <span style={{ width: 22, height: 22, borderRadius: 4, background: g.avgScore >= 85 ? T.hot : g.avgScore >= 72 ? T.up : T.info, color: T.bg, fontSize: 10, fontWeight: 700, fontFamily: T.mono, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{g.avgScore}</span>
                <span style={{ flex: 1, minWidth: 0, color: T.fg, fontSize: 13, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{g.dong}</span>
                <span style={{ fontSize: 11, color: T.fgMuted, fontFamily: T.mono }}>{g.list.length}</span>
              </button>
            ))}
            {dongGroups.length === 0 && <div style={{ padding: 16, fontSize: 12, color: T.fgMuted, textAlign: 'center' }}>이 지역 데모 단지가 아직 없어요.<br/>백엔드 연결 시 전체 표시됩니다.</div>}
          </div>
        </Panel>

        {/* 추상 지도 + 핀 */}
        <Panel title="단지 분포" subtitle="점수 높을수록 노란색 · 클릭 시 실거래 상세" noPad>
          <div style={{ position: 'relative', height: isMobile ? 320 : 480, overflow: 'hidden', borderRadius: 4 }}>
            {/* 격자 배경 */}
            <div style={{ position: 'absolute', inset: 0,
              backgroundImage: `linear-gradient(${T.line} 1px, transparent 1px), linear-gradient(90deg, ${T.line} 1px, transparent 1px)`,
              backgroundSize: '40px 40px', opacity: 0.4 }} />
            <div style={{ position: 'absolute', inset: 0,
              background: `radial-gradient(circle at 50% 45%, ${T.info}18, transparent 60%)` }} />
            {/* 핀 배치: 점수/가격으로 좌표 결정 (결정적) */}
            {shownApts.slice(0, 40).map((a, i) => {
              let hx = 0; for (let j = 0; j < a.id.length; j++) hx = (hx * 17 + a.id.charCodeAt(j)) % 1000;
              const x = 8 + (hx % 84);
              const y = 10 + ((hx >> 3) % 78);
              const c = a.score >= 85 ? T.hot : a.score >= 72 ? T.up : T.info;
              return (
                <button key={a.id} onClick={() => openApt(a)} title={a.name}
                  style={{ position: 'absolute', left: x + '%', top: y + '%', transform: 'translate(-50%,-50%)',
                    display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2,
                    background: 'transparent', border: 'none', cursor: 'pointer', zIndex: 2 }}>
                  <span style={{ width: 14, height: 14, borderRadius: 7, background: c, border: '2px solid ' + T.bg, boxShadow: '0 0 8px ' + c }} />
                  {!isMobile && <span style={{ fontSize: 9, color: T.fgDim, fontFamily: T.mono, background: 'rgba(11,18,32,0.7)', padding: '0 3px', borderRadius: 2, whiteSpace: 'nowrap' }}>{won(a.currentPrice)}</span>}
                </button>
              );
            })}
            {/* 범례 */}
            <div style={{ position: 'absolute', left: 10, bottom: 10, display: 'flex', gap: 10, fontFamily: T.mono, fontSize: 10, color: T.fgDim, background: 'rgba(11,18,32,0.8)', padding: '6px 10px', borderRadius: 4 }}>
              <span><span style={{ display: 'inline-block', width: 8, height: 8, borderRadius: 4, background: T.hot, marginRight: 4 }} />S 85+</span>
              <span><span style={{ display: 'inline-block', width: 8, height: 8, borderRadius: 4, background: T.up, marginRight: 4 }} />A 72+</span>
              <span><span style={{ display: 'inline-block', width: 8, height: 8, borderRadius: 4, background: T.info, marginRight: 4 }} />B·C</span>
            </div>
          </div>
          {/* 핀 단지 리스트 (모바일·접근성) */}
          <div style={{ borderTop: '1px solid ' + T.line, padding: 10, display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 8, maxHeight: 220, overflowY: 'auto' }} className="uj-scroll">
            {shownApts.slice(0, 20).map(a => (
              <button key={a.id} onClick={() => openApt(a)}
                style={{ textAlign: 'left', display: 'flex', alignItems: 'center', gap: 8, padding: 8, background: T.card, border: '1px solid ' + T.line, borderRadius: 6, cursor: 'pointer', fontFamily: T.font }}>
                <GradePill grade={a.grade} size="sm" />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12, fontWeight: 600, color: T.fg, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{a.name}</div>
                  <div style={{ fontSize: 10, color: T.fgMuted, fontFamily: T.mono }}>{a.dong}</div>
                </div>
                <span className="uj-num" style={{ fontSize: 12, fontWeight: 700, color: T.fg }}>{won(a.currentPrice)}</span>
              </button>
            ))}
          </div>
        </Panel>
      </div>

      {selected && <TradeDetailModal data={selected} isMobile={isMobile} onClose={() => setSelected(null)} />}
    </div>
  );
}

Object.assign(window, { MapViewPage });
