// trade-detail.jsx — 실거래 클릭 시 상세 모달
// 거래 이력 + 학술/실무 핵심 요인 SHAP + 한국부동산원 호재 리포트 + AI 예측/매수적기 + AI인프라 투자관점

// 지역별 호재 리포트 (한국부동산원·국토부·언론 중심, 호재 위주 큐레이션)
const REGION_BOONS = {
  '강남': [{ src: '한국부동산원', t: '강남권 재건축 정비사업 가속 — 대치·개포 일대 사업시행인가 확대', impact: 'high' }, { src: '국토부', t: '영동대로 복합환승센터 2026 착공 — GTX-A/C 환승 허브', impact: 'high' }],
  '서초': [{ src: '한국부동산원', t: '반포 일대 재건축 일반분양 흥행 — 인근 시세 견인', impact: 'high' }, { src: '언론', t: '서초 방배 재개발 구역 다수 관리처분 통과', impact: 'mid' }],
  '송파': [{ src: '국토부', t: '잠실 마이스(MICE) 복합개발 본격화 — 일자리·유동인구 증가', impact: 'high' }, { src: '한국부동산원', t: '가락·문정 업무지구 확장', impact: 'mid' }],
  '용산': [{ src: '국토부', t: '용산국제업무지구 개발계획 확정 — 초대형 복합단지', impact: 'high' }, { src: '언론', t: '한남뉴타운 재개발 속도', impact: 'high' }],
  '성동': [{ src: '한국부동산원', t: '성수 IT·지식산업센터 클러스터 확장 — 직주근접 수요', impact: 'high' }],
  '마포': [{ src: '한국부동산원', t: '마포·공덕 업무지구 + 경의선숲길 프리미엄', impact: 'mid' }],
  '분당': [{ src: '국토부', t: '1기 신도시 특별법 — 분당 선도지구 재건축 추진', impact: 'high' }, { src: '언론', t: '판교 제3테크노밸리 조성 — AI·바이오 기업 유치', impact: 'high' }],
  '판교': [{ src: '언론', t: '판교 테크노밸리 AI 기업 집적 — 네이버·카카오 R&D 확대', impact: 'high' }],
  '수원': [{ src: '국토부', t: '수원 영통 삼성 DX 캠퍼스 인접 — R&D 수요', impact: 'high' }, { src: '한국부동산원', t: '광교신도시 인프라 성숙', impact: 'mid' }],
  '용인': [{ src: '국토부', t: '용인 반도체 클러스터(SK하이닉스) 착공 — 사상 최대 투자', impact: 'high' }, { src: '언론', t: '경기 남부 반도체 메가클러스터 핵심', impact: 'high' }],
  '평택': [{ src: '언론', t: '삼성 평택 반도체 캠퍼스 P4~P6 증설 — 고용 폭증', impact: 'high' }, { src: '국토부', t: 'GTX-A 평택 연장 논의', impact: 'mid' }],
  '화성': [{ src: '국토부', t: '동탄2 SRT·GTX-A 개통 효과 — 강남 30분권', impact: 'high' }, { src: '언론', t: '삼성 화성 반도체 인접', impact: 'high' }],
  '하남': [{ src: '국토부', t: '3호선·5호선 연장 + 미사·교산신도시', impact: 'high' }],
  '인천': [{ src: '한국부동산원', t: '송도 국제업무지구 바이오 클러스터 + GTX-B', impact: 'high' }],
  '해운대': [{ src: '한국부동산원', t: '해운대 관광·마이스 + 동부산 개발', impact: 'mid' }],
  '세종': [{ src: '국토부', t: '행정수도 기능 강화 + 데이터센터 집적', impact: 'mid' }],
};
function boonsFor(region, name) {
  for (const k of Object.keys(REGION_BOONS)) {
    if (region.includes(k) || name.includes(k)) return REGION_BOONS[k];
  }
  return [{ src: '한국부동산원', t: '지역 생활 인프라 안정 — 실수요 기반 견조', impact: 'mid' }];
}

function TradeDetailModal({ data, onClose, isMobile }) {
  const { apt, region } = data;
  const ai = useMemo(() => window.analyzeUnit({ name: apt.name, region, trades: apt.trades, area: apt.area, buildYear: apt.buildYear }), [apt.name]);
  const boons = boonsFor(region, apt.name);
  const sorted = [...apt.trades].sort((a, b) => {
    const ka = +(a.ymd + ('' + (a.day || 0)).padStart(2, '0')), kb = +(b.ymd + ('' + (b.day || 0)).padStart(2, '0'));
    return kb - ka;
  });

  useEffect(() => {
    window.UJTrack.track('view_apt_detail', { apt_name: apt.name, region, signal: ai.signal, ai_growth: ai.annualGrowth });
    // XAI 모달 활성화 로그
    window.UJLog.log(window.UJLog.EVENT_TYPES.MODAL_OPEN, { modal: 'xai_detail', aptCode: apt.code || (region + '-' + apt.name), aptName: apt.name, region, opinion: ai.signal, score: ai.score, bestBuyMonth: ai.bestBuyMonth });
    const esc = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', esc);
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', esc);
      document.body.style.overflow = '';
      window.UJLog.log(window.UJLog.EVENT_TYPES.MODAL_CLOSE, { modal: 'xai_detail', aptName: apt.name });
    };
  }, []);

  const prices = sorted.map(t => t.price);
  const spark = prices.slice(0, 14).reverse();

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 9990, background: 'rgba(0,0,0,0.7)',
      display: 'flex', alignItems: isMobile ? 'flex-end' : 'center', justifyContent: 'center', padding: isMobile ? 0 : 24,
      backdropFilter: 'blur(4px)',
    }}>
      <div onClick={(e) => e.stopPropagation()} className="uj-scroll" style={{
        background: T.bg, border: '1px solid ' + T.lineHi,
        borderRadius: isMobile ? '16px 16px 0 0' : 12,
        width: '100%', maxWidth: 720, maxHeight: isMobile ? '92vh' : '90vh', overflowY: 'auto',
      }}>
        {/* 헤더 */}
        <div style={{ position: 'sticky', top: 0, background: T.bgAlt, borderBottom: '1px solid ' + T.line, padding: isMobile ? '14px 16px' : '18px 22px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', zIndex: 2 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, minWidth: 0 }}>
            <ScoreRing score={ai.score} size={isMobile ? 46 : 56} stroke={5} />
            <div style={{ minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <h2 style={{ fontSize: isMobile ? 17 : 21, fontWeight: 700, margin: 0, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{apt.name}</h2>
                <SignalBadge kind={ai.signal} />
              </div>
              <div style={{ fontSize: 11, color: T.fgMuted, fontFamily: T.mono, marginTop: 2 }}>
                {region} {apt.dong} · {apt.buildYear ? apt.buildYear + '년식 · ' : ''}{apt.trades.length}건 실거래
              </div>
            </div>
          </div>
          <button onClick={onClose} aria-label="닫기" style={{ background: 'transparent', border: 'none', color: T.fgMuted, cursor: 'pointer', flexShrink: 0, display: 'flex', padding: 4 }}><Ico name="close" size={20} /></button>
        </div>

        <div style={{ padding: isMobile ? 16 : 22, display: 'flex', flexDirection: 'column', gap: 16 }}>
          {/* ① XAI 핵심 이유 요약 */}
          <XAIReason ai={ai} apt={apt} />
          {/* AI 예측 핵심 */}
          <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr 1fr' : 'repeat(4, 1fr)', gap: 10 }}>
            <StatBox label="최근 실거래" value={manWon(ai.stats.latest)} />
            <StatBox label="AI 12개월 예측" value={`${ai.annualGrowth > 0 ? '+' : ''}${ai.annualGrowth}%`} color={ai.annualGrowth >= 0 ? T.up : T.down} sub={manWon(ai.forecast12)} />
            <StatBox label="매수 적기" value={ai.bestBuyMonth} color={T.hot} />
            <StatBox label="적정 매수가" value={manWon(ai.targetPrice)} sub={`신뢰도 ${ai.confidence}%`} />
          </div>

          {/* ② 오늘(TODAY) 기점 매수적기 + 실거래가 추이 미니차트 */}
          <BuyTimingChart ai={ai} trades={apt.trades} isMobile={isMobile} />

          {/* ③ 주요 지표 대시보드 (점수판) */}
          <MetricScoreboard ai={ai} isMobile={isMobile} />

          {/* AI BUY SIGNAL 카드 */}
          <div style={{ padding: 16, background: 'rgba(255,176,32,0.08)', border: '1px solid ' + T.hot + '40', borderRadius: 8 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
              <span style={{ fontSize: 11, fontFamily: T.mono, color: T.hot, fontWeight: 700, letterSpacing: 1 }}>AI 종합 분석</span>
              <span style={{ fontSize: 11, color: T.fgMuted }}>· 모델 v3.2 · {ai.factors.length}개 요인</span>
            </div>
            <div style={{ fontSize: 13, color: T.fgDim, lineHeight: 1.7 }}>
              <strong style={{ color: T.fg }}>{apt.name}</strong>은(는) 최근 거래 모멘텀 <strong style={{ color: ai.stats.momentum >= 0 ? T.up : T.down }}>{ai.stats.momentum > 0 ? '+' : ''}{ai.stats.momentum}%</strong>,
              AI·반도체 인프라 인접도 <strong style={{ color: T.ai }}>{ai.infra.score}점</strong> 기준,
              향후 12개월 <strong style={{ color: ai.annualGrowth >= 0 ? T.up : T.down }}>{ai.annualGrowth > 0 ? '약 ' + ai.annualGrowth + '% 상승' : ai.annualGrowth + '% 조정'}</strong> 전망입니다.
              {ai.stats.momentum > 8 ? ' 단기 과열 구간으로 ' + ai.bestBuyMonth + ' 조정 후 매수가 유리합니다.' : ' 매수 적기는 ' + ai.bestBuyMonth + ' 전후로 분석됩니다.'}
            </div>
          </div>

          {/* AI 인프라 투자 관점 */}
          <div>
            <SectionTitle>AI·반도체 인프라 투자 매력</SectionTitle>
            <div style={{ padding: 14, background: 'rgba(139,92,246,0.08)', border: '1px solid ' + T.ai + '40', borderRadius: 8 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
                <div style={{ fontSize: 24, fontWeight: 800, color: T.ai, fontFamily: T.mono }}>{ai.infra.score}</div>
                <div style={{ flex: 1 }}>
                  <ScoreBar score={ai.infra.score} height={5} showTicks={false} />
                </div>
              </div>
              <div style={{ fontSize: 13, color: T.fg, fontWeight: 600 }}>{ai.infra.label}</div>
              <div style={{ display: 'flex', gap: 5, marginTop: 8, flexWrap: 'wrap' }}>
                {ai.infra.tags.map(t => <span key={t} style={{ fontSize: 10, fontFamily: T.mono, color: T.ai, padding: '2px 8px', border: '1px solid ' + T.ai + '50', borderRadius: 3 }}>{t}</span>)}
              </div>
              <div style={{ fontSize: 11, color: T.fgMuted, marginTop: 10, lineHeight: 1.6 }}>
                반도체 Fab·데이터센터·AI R&D 등 HW/SW/인프라 인접 단지는 양질의 일자리 유입으로 중장기 수요가 견조합니다.
              </div>
            </div>
          </div>

          {/* 핵심 요인 SHAP */}
          <div>
            <SectionTitle>매수 의사결정 핵심 요인 <span style={{ fontSize: 10, color: T.fgMuted, fontWeight: 400 }}>(실무 + 논문 기반)</span></SectionTitle>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {ai.factors.map(f => {
                const s = Math.round(ai.factorScores[f.id]);
                return (
                  <div key={f.id} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <div style={{ width: isMobile ? 110 : 150, flexShrink: 0 }}>
                      <div style={{ fontSize: 12, color: T.fg }}>{f.label}</div>
                      <div style={{ fontSize: 9, color: T.fgMuted, fontFamily: T.mono }}>{f.source} · {f.kind}</div>
                    </div>
                    <div style={{ flex: 1, height: 6, background: T.cardLo, borderRadius: 3, overflow: 'hidden' }}>
                      <div style={{ height: '100%', width: s + '%', background: s >= 70 ? T.up : s >= 50 ? T.hot : T.fgMuted, borderRadius: 3 }} />
                    </div>
                    <div style={{ width: 28, textAlign: 'right', fontSize: 11, fontFamily: T.mono, color: T.fgDim }}>{s}</div>
                    <div style={{ width: 26, textAlign: 'right', fontSize: 10, fontFamily: T.mono, color: T.fgMuted }}>{f.weight}%</div>
                  </div>
                );
              })}
            </div>
          </div>

          {/* 한국부동산원 호재 리포트 */}
          <div>
            <SectionTitle>호재 리포트 <span style={{ fontSize: 10, color: T.fgMuted, fontWeight: 400 }}>(한국부동산원·국토부 중심)</span></SectionTitle>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {boons.map((b, i) => (
                <div key={i} style={{ display: 'flex', gap: 10, padding: '10px 12px', background: T.card, border: '1px solid ' + T.line, borderRadius: 6 }}>
                  <span style={{ color: T.up, fontSize: 14, flexShrink: 0 }}>↑</span>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13, color: T.fg, lineHeight: 1.5 }}>{b.t}</div>
                    <div style={{ fontSize: 10, color: T.fgMuted, fontFamily: T.mono, marginTop: 3 }}>
                      {b.src} · 영향도 {b.impact === 'high' ? '높음' : b.impact === 'mid' ? '보통' : '낮음'}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* 실거래 이력 */}
          <div>
            <SectionTitle>실거래 이력 <span style={{ fontSize: 10, color: T.fgMuted, fontWeight: 400 }}>(국토부 RTMS)</span></SectionTitle>
            <div className="uj-scroll" style={{ maxHeight: 240, overflowY: 'auto', border: '1px solid ' + T.line, borderRadius: 6 }}>
              <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
                <thead style={{ position: 'sticky', top: 0, background: T.bgAlt }}>
                  <tr style={{ color: T.fgMuted, fontFamily: T.mono }}>
                    {['거래월', '전용', '층', '거래가'].map(h => <th key={h} style={{ textAlign: h === '거래가' ? 'right' : 'left', padding: '8px 12px', fontWeight: 500, fontSize: 10, borderBottom: '1px solid ' + T.line }}>{h}</th>)}
                  </tr>
                </thead>
                <tbody>
                  {sorted.slice(0, 40).map((t, i) => (
                    <tr key={i} style={{ borderBottom: '1px solid ' + T.line + '60' }}>
                      <td style={{ padding: '7px 12px', fontFamily: T.mono, color: T.fgDim }}>{t.ymd.slice(2, 4)}.{t.ymd.slice(4)}{t.day ? '.' + ('' + t.day).padStart(2, '0') : ''}</td>
                      <td style={{ padding: '7px 12px', fontFamily: T.mono, color: T.fgDim }}>{t.area ? t.area + '㎡' : '-'}</td>
                      <td style={{ padding: '7px 12px', fontFamily: T.mono, color: T.fgDim }}>{t.floor ? t.floor + 'F' : '-'}</td>
                      <td style={{ padding: '7px 12px', fontFamily: T.mono, fontWeight: 700, textAlign: 'right' }}>{manWon(t.price)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          <div style={{ fontSize: 10, color: T.fgFaint, fontFamily: T.mono, lineHeight: 1.6, paddingTop: 4 }}>
            ※ 본 분석은 국토부 RTMS 실거래가와 통계 모델 기반 정보이며 투자 자문이 아닙니다. 매매 결정은 본인 책임입니다.
          </div>
        </div>
      </div>
    </div>
  );
}

// ① XAI 핵심 이유 요약
function XAIReason({ ai, apt }) {
  const op = window.opinionOf(ai.signal);
  return (
    <div style={{ padding: 16, background: op.bg, border: '1px solid ' + op.color + '55', borderRadius: 10 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8, flexWrap: 'wrap' }}>
        <span style={{ fontSize: 10, fontFamily: T.mono, color: op.color, fontWeight: 700, letterSpacing: 1, padding: '2px 8px', border: '1px solid ' + op.color + '66', borderRadius: 999 }}>XAI · AI가 이렇게 판단한 이유</span>
        <span style={{ fontSize: 11, color: T.fgMuted, fontFamily: T.mono }}>종합 {ai.score}점 · 신뢰도 {ai.confidence}%</span>
      </div>
      <div style={{ fontSize: isMobile2(), fontWeight: 700, color: T.fg, lineHeight: 1.5, marginBottom: 6 }}>
        “{ai.reason.headline}”
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <span style={{ width: 8, height: 8, borderRadius: 4, background: op.color, flexShrink: 0 }} />
        <span style={{ fontSize: 13, color: op.color, fontWeight: 600 }}>{op.label} · {ai.reason.verdict}</span>
      </div>
    </div>
  );
}
function isMobile2() { return window.innerWidth <= 640 ? 16 : 18; }

// ② 오늘(TODAY) 기점 매수적기 + 실거래가 추이 미니차트
function BuyTimingChart({ ai, trades, isMobile }) {
  const W = 640, H = isMobile ? 150 : 170, padL = 8, padR = 8, padT = 16, padB = 26;
  const ymNum = (y, m) => y * 12 + (m - 1);

  const series = useMemo(() => {
    const byM = {};
    (trades || []).forEach(t => {
      if (!t.ymd || !(t.price > 0)) return;
      const y = +t.ymd.slice(0, 4), m = +t.ymd.slice(4, 6);
      const k = ymNum(y, m);
      if (!byM[k]) byM[k] = { n: 0, sum: 0, y, m };
      byM[k].n++; byM[k].sum += t.price;
    });
    return Object.keys(byM).map(Number).sort((a, b) => a - b)
      .map(k => ({ x: k, price: Math.round(byM[k].sum / byM[k].n), y: byM[k].y, m: byM[k].m }));
  }, [trades]);

  const now = new Date();
  const todayX = ymNum(now.getFullYear(), now.getMonth() + 1);
  const bb = ai.bestBuyDate ? ai.bestBuyDate.split('-') : null;
  const bestX = bb ? ymNum(+bb[0], +bb[1]) : todayX + (ai.buyMonthsAhead || 3);

  if (series.length < 1) {
    return (
      <div style={{ padding: 14, background: T.cardLo, border: '1px solid ' + T.line, borderRadius: 8 }}>
        <SectionTitle>매수 타이밍 차트</SectionTitle>
        <div style={{ fontSize: 12, color: T.fgMuted }}>거래 데이터가 부족해 추이 차트를 표시할 수 없습니다.</div>
      </div>
    );
  }

  const lastHist = series[series.length - 1];
  const projPrice = ai.forecast12 || ai.targetPrice || lastHist.price;
  const pts = series.map(p => ({ x: p.x, price: p.price }));
  const proj = { x: bestX, price: projPrice };

  const xMin = Math.min(series[0].x, todayX);
  const xMax = Math.max(bestX, lastHist.x, todayX);
  const allPrices = pts.map(p => p.price).concat([projPrice]);
  const yMin = Math.min(...allPrices), yMax = Math.max(...allPrices);
  const yRange = (yMax - yMin) || 1;
  const xRange = (xMax - xMin) || 1;
  const sx = (x) => padL + ((x - xMin) / xRange) * (W - padL - padR);
  const sy = (p) => padT + (1 - (p - yMin) / yRange) * (H - padT - padB);

  const histPath = 'M ' + pts.map(p => sx(p.x) + ' ' + sy(p.price)).join(' L ');
  const projPath = `M ${sx(lastHist.x)} ${sy(lastHist.price)} L ${sx(proj.x)} ${sy(proj.price)}`;
  const up = ai.annualGrowth >= 0;
  const histColor = (ai.stats.momentum || 0) >= 0 ? T.up : T.down;
  const op = window.opinionOf(ai.signal);

  const fmtMon = (x) => { const y = Math.floor(x / 12), m = (x % 12) + 1; return `${('' + y).slice(2)}.${('' + m).padStart(2, '0')}`; };

  return (
    <div style={{ padding: 14, background: T.cardLo, border: '1px solid ' + T.line, borderRadius: 8 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 4, flexWrap: 'wrap', gap: 6 }}>
        <SectionTitle>매수 타이밍 · 실거래가 추이</SectionTitle>
        <div style={{ display: 'flex', gap: 12, fontSize: 10, fontFamily: T.mono }}>
          <span style={{ color: histColor, display: 'inline-flex', alignItems: 'center', gap: 4 }}><span style={{ width: 14, height: 2, background: histColor, display: 'inline-block' }} />실거래</span>
          <span style={{ color: T.hot, display: 'inline-flex', alignItems: 'center', gap: 4 }}><span style={{ width: 14, height: 2, background: T.hot, display: 'inline-block', borderTop: '2px dashed ' + T.hot }} />AI 예측</span>
        </div>
      </div>
      <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" style={{ display: 'block', width: '100%', height: H }}>
        {/* grid */}
        {[0.25, 0.5, 0.75].map((f, i) => <line key={i} x1={padL} x2={W - padR} y1={padT + (H - padT - padB) * f} y2={padT + (H - padT - padB) * f} stroke={T.line} strokeWidth="1" strokeDasharray="2 3" />)}
        {/* TODAY 세로선 */}
        <line x1={sx(todayX)} x2={sx(todayX)} y1={padT - 4} y2={H - padB} stroke={T.fgMuted} strokeWidth="1" strokeDasharray="3 3" />
        <text x={sx(todayX)} y={padT - 7} fill={T.fgDim} fontSize="9" fontFamily={T.mono} textAnchor="middle">오늘 {fmtMon(todayX)}</text>
        {/* 매수적기 세로선 */}
        <line x1={sx(bestX)} x2={sx(bestX)} y1={padT - 4} y2={H - padB} stroke={T.hot} strokeWidth="1" strokeDasharray="3 3" />
        {/* 실거래 라인 + 점 */}
        <path d={histPath} fill="none" stroke={histColor} strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" />
        {pts.map((p, i) => <circle key={i} cx={sx(p.x)} cy={sy(p.price)} r="2.5" fill={histColor} />)}
        {/* 예측 점선 */}
        <path d={projPath} fill="none" stroke={T.hot} strokeWidth="2" strokeDasharray="5 4" strokeLinecap="round" />
        {/* 매수적기 마커 */}
        <circle cx={sx(proj.x)} cy={sy(proj.price)} r="5" fill={T.hot} stroke={T.bg} strokeWidth="2" />
        {/* x축 라벨 */}
        <text x={padL} y={H - 8} fill={T.fgFaint} fontSize="9" fontFamily={T.mono}>{fmtMon(series[0].x)}</text>
        <text x={sx(bestX)} y={H - 8} fill={T.hot} fontSize="9" fontFamily={T.mono} textAnchor="end">매수적기 {ai.bestBuyMonth}</text>
      </svg>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8, gap: 10, flexWrap: 'wrap' }}>
        <div style={{ fontSize: 11, color: T.fgDim }}>
          최근 실거래 <strong className="uj-num" style={{ color: T.fg }}>{manWon(lastHist.price)}</strong>
          <span style={{ color: T.fgMuted }}> → </span>
          매수적기 예상 <strong className="uj-num" style={{ color: T.hot }}>{manWon(projPrice)}</strong>
          <span style={{ color: up ? T.up : T.down, marginLeft: 6, fontFamily: T.mono }}>({up ? '+' : ''}{ai.annualGrowth}%)</span>
        </div>
        <div style={{ fontSize: 11, fontFamily: T.mono, color: op.color }}>{op.label} · 적기 {ai.bestBuyMonth}</div>
      </div>
    </div>
  );
}

// ③ 주요 지표 대시보드 (점수판)
function MetricScoreboard({ ai, isMobile }) {
  const fs = ai.factorScores || {};
  const cnt = ai.stats.count || 0;
  const mom = ai.stats.momentum || 0;
  const absorb = cnt >= 6 ? { label: '빠름', score: Math.min(95, cnt * 12) } : cnt >= 3 ? { label: '보통', score: 55 } : { label: '느림', score: 32 };
  const metrics = [
    { k: '거래가 모멘텀', v: `${mom > 0 ? '+' : ''}${mom}%`, score: Math.round(fs.transaction || 50), color: mom >= 0 ? T.up : T.down, note: '최근 vs 이전 평균' },
    { k: '거래량(건수)', v: `${cnt}건`, score: Math.min(95, cnt * 12), color: T.info, note: '최근 3개월 신고' },
    { k: '매물 소화 속도', v: absorb.label, score: absorb.score, color: T.hot, note: '거래 회전 추정' },
    { k: '학군 점수', v: `${Math.round(fs.school || 0)}`, score: Math.round(fs.school || 0), color: T.ai, note: '학원가·배정' },
    { k: '교통 호재', v: `${Math.round(fs.transit || 0)}`, score: Math.round(fs.transit || 0), color: T.info, note: 'GTX·역세권' },
    { k: 'AI·반도체 인프라', v: `${ai.infra.score}`, score: ai.infra.score, color: T.ai, note: '일자리 인접' },
  ];
  return (
    <div>
      <SectionTitle>주요 지표 점수판 <span style={{ fontSize: 10, color: T.fgMuted, fontWeight: 400 }}>(AI가 매긴 항목별 점수)</span></SectionTitle>
      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr 1fr' : 'repeat(3, 1fr)', gap: 10 }}>
        {metrics.map(m => (
          <div key={m.k} style={{ padding: 12, background: T.card, border: '1px solid ' + T.line, borderRadius: 8 }}>
            <div style={{ fontSize: 10, color: T.fgMuted, fontFamily: T.mono, marginBottom: 4 }}>{m.k}</div>
            <div className="uj-num" style={{ fontSize: 18, fontWeight: 700, color: m.color, marginBottom: 8 }}>{m.v}</div>
            <div style={{ height: 5, background: T.cardLo, borderRadius: 3, overflow: 'hidden' }}>
              <div style={{ height: '100%', width: Math.max(4, Math.min(100, m.score)) + '%', background: m.color, borderRadius: 3 }} />
            </div>
            <div style={{ fontSize: 9, color: T.fgFaint, fontFamily: T.mono, marginTop: 5 }}>{m.note} · {Math.round(m.score)}점</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function StatBox({ label, value, sub, color }) {
  return (
    <div style={{ padding: 12, background: T.card, border: '1px solid ' + T.line, borderRadius: 6 }}>
      <div style={{ fontSize: 9, color: T.fgMuted, fontFamily: T.mono, letterSpacing: 1, textTransform: 'uppercase' }}>{label}</div>
      <div className="uj-num" style={{ fontSize: 18, fontWeight: 700, color: color || T.fg, marginTop: 3 }}>{value}</div>
      {sub && <div style={{ fontSize: 10, color: T.fgMuted, fontFamily: T.mono, marginTop: 1 }}>{sub}</div>}
    </div>
  );
}
function SectionTitle({ children }) {
  return <div style={{ fontSize: 12, fontFamily: T.mono, color: T.fgDim, letterSpacing: 1, textTransform: 'uppercase', marginBottom: 10, fontWeight: 600 }}>{children}</div>;
}

Object.assign(window, { TradeDetailModal });
