// apt-insight.jsx — 대시보드 추천 단지 클릭 시 XAI 상세 모달
// APTS(큐레이션 단지) 항목을 받아 ①핵심 이유 ②TODAY 기점 매수적기 미니차트 ③주요 지표 점수판 표시.
// 전역: window.AptInsightModal

// YY.MM → 절대 월 번호
function ymToNum2(yymm) {
  if (!yymm) return null;
  const p = ('' + yymm).split('.');
  if (p.length < 2) return null;
  return (2000 + (+p[0])) * 12 + (+p[1] - 1);
}

function AptInsightModal({ apt, onClose, isMobile }) {
  if (!apt) return null;
  const op = window.opinionOf(apt.signal);

  useEffect(() => {
    window.UJLog.log(window.UJLog.EVENT_TYPES.MODAL_OPEN, {
      modal: 'apt_insight', aptCode: apt.id, aptName: apt.name, region: apt.region,
      opinion: apt.signal, score: apt.score, bestBuyMonth: apt.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: 'apt_insight', aptName: apt.name });
    };
  }, [apt.id]);

  // ── 핵심 이유 요약 ──
  const reasonParts = [];
  if (apt.delta1y > 5) reasonParts.push('실거래가 상승 모멘텀 강함');
  else if (apt.delta1y > 1) reasonParts.push('실거래가 완만한 상승');
  else if (apt.delta1y >= -1) reasonParts.push('실거래가 바닥 다지기');
  else reasonParts.push('실거래가 조정 국면');
  (apt.boons || []).slice(0, 2).forEach(b => reasonParts.push(b));
  const headline = reasonParts.slice(0, 3).join(' · ');
  const verdict = op.label + ' · 적기 ' + apt.bestBuyMonth + (apt.delta1y > 8 ? ' (단기 과열, 조정 후 진입)' : '');

  // ── 주요 지표 점수판 ──
  const gradeScore = { S: 92, A: 80, B: 65, '-': 45 };
  const targetGap = Math.round((apt.currentPrice - apt.targetPrice) / apt.currentPrice * 1000) / 10; // +면 현재가>적정가(고평가)
  const metrics = [
    { k: '거래가 모멘텀 (1Y)', v: `${apt.delta1y > 0 ? '+' : ''}${apt.delta1y}%`, score: Math.min(95, 50 + apt.delta1y * 5), color: apt.delta1y >= 0 ? T.up : T.down, note: '최근 1년 변동' },
    { k: '적정가 갭', v: `${targetGap > 0 ? '+' : ''}${targetGap}%`, score: Math.max(10, 70 - targetGap * 4), color: targetGap <= 0 ? T.up : T.hot, note: targetGap <= 0 ? '저평가 영역' : '현재가>적정가' },
    { k: '학군 점수', v: apt.school, score: gradeScore[apt.school] || 55, color: T.ai, note: '학원가·배정' },
    { k: '교통 점수', v: apt.transit, score: gradeScore[apt.transit] || 55, color: T.info, note: 'GTX·역세권' },
    { k: '재건축 단계', v: apt.redevelopment === 'A' ? '진행' : '-', score: apt.redevelopment === 'A' ? 78 : 35, color: T.hot, note: '정비사업' },
    { k: '전세가율', v: `${apt.jeonseRatio}%`, score: Math.min(95, apt.jeonseRatio + 10), color: T.info, note: '갭·하방지지' },
  ];

  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={apt.score} size={isMobile ? 46 : 56} stroke={5} />
            <div style={{ minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                <h2 style={{ fontSize: isMobile ? 17 : 21, fontWeight: 700, margin: 0 }}>{apt.name}</h2>
                <SignalBadge kind={apt.signal} />
              </div>
              <div style={{ fontSize: 11, color: T.fgMuted, fontFamily: T.mono, marginTop: 2 }}>{apt.region} {apt.dong} · {apt.built}년식 · {apt.units.toLocaleString()}세대</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 }}>
          {/* ① 핵심 이유 */}
          <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 }}>종합 {apt.score}점 · 신뢰도 {apt.confidence}%</span>
            </div>
            <div style={{ fontSize: isMobile ? 16 : 18, fontWeight: 700, color: T.fg, lineHeight: 1.5, marginBottom: 6 }}>“{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 }}>{verdict}</span>
            </div>
          </div>

          {/* 핵심 수치 */}
          <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr 1fr' : 'repeat(4, 1fr)', gap: 10 }}>
            {[
              ['현재가', won(apt.currentPrice), T.fg, null],
              ['AI 1년 예측', `${apt.delta1y > 0 ? '+' : ''}${apt.delta1y}%`, apt.delta1y >= 0 ? T.up : T.down, won(apt.priceY1 && Math.round(apt.currentPrice * (1 + apt.delta1y / 100)))],
              ['매수 적기', apt.bestBuyMonth, T.hot, null],
              ['적정 매수가', won(apt.targetPrice), T.fg, `신뢰도 ${apt.confidence}%`],
            ].map(([l, v, c, s]) => (
              <div key={l} 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' }}>{l}</div>
                <div className="uj-num" style={{ fontSize: 17, fontWeight: 700, color: c, marginTop: 3 }}>{v}</div>
                {s && <div style={{ fontSize: 10, color: T.fgMuted, fontFamily: T.mono, marginTop: 1 }}>{s}</div>}
              </div>
            ))}
          </div>

          {/* ② TODAY 기점 매수적기 미니차트 */}
          <AptTimingChart apt={apt} isMobile={isMobile} />

          {/* 시장 통계 및 리스크 분석 (국토교통 통계누리 4종) */}
          <StatNuriSection sido={(apt.region || '').split(' ')[0]} sigungu={(apt.region || '').split(' ')[1] || ''} isMobile={isMobile} />

          {/* ③ 주요 지표 점수판 */}
          <div>
            <div style={{ fontSize: 12, fontFamily: T.mono, color: T.fgDim, letterSpacing: 1, textTransform: 'uppercase', marginBottom: 10, fontWeight: 600 }}>주요 지표 점수판 <span style={{ fontSize: 10, color: T.fgMuted, fontWeight: 400 }}>(AI 항목별 점수)</span></div>
            <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>

          {/* 호재 / 리스크 */}
          <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 12 }}>
            <div>
              <div style={{ fontSize: 11, fontFamily: T.mono, color: T.up, letterSpacing: 1, marginBottom: 8 }}>호재</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                {(apt.boons || []).map((b, i) => <div key={i} style={{ display: 'flex', gap: 8, fontSize: 12, color: T.fgDim }}><span style={{ color: T.up }}>▲</span>{b}</div>)}
              </div>
            </div>
            <div>
              <div style={{ fontSize: 11, fontFamily: T.mono, color: T.down, letterSpacing: 1, marginBottom: 8 }}>리스크</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                {(apt.risks || []).map((r, i) => <div key={i} style={{ display: 'flex', gap: 8, fontSize: 12, color: T.fgDim }}><span style={{ color: T.down }}>▼</span>{r}</div>)}
              </div>
            </div>
          </div>

          <a href={'#/app/detail/' + apt.id} onClick={onClose} data-track="insight_to_detail"
            style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, padding: '11px', background: T.hot, color: T.bg, borderRadius: 6, textDecoration: 'none', fontSize: 13, fontWeight: 700 }}>
            전체 분석 페이지 열기 <Ico name="arrow" size={14} color={T.bg} />
          </a>

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

// TODAY 기점 매수적기 미니차트 (APTS.history 사용)
function AptTimingChart({ apt, isMobile }) {
  const W = 640, H = isMobile ? 150 : 170, padL = 8, padR = 8, padT = 16, padB = 26;
  const hist = (apt.history || []).filter(p => p && p.v > 0);
  if (hist.length < 2) return null;

  const histPts = hist.map(p => ({ x: ymToNum2(p.t), v: p.v })).filter(p => p.x != null);
  const now = new Date();
  const todayX = now.getFullYear() * 12 + now.getMonth();
  const bestX = ymToNum2(apt.bestBuyMonth) || (todayX + 3);
  const last = histPts[histPts.length - 1];
  const projV = Math.round(apt.currentPrice * (1 + (apt.delta1y || 0) / 100));

  const xs = histPts.map(p => p.x).concat([todayX, bestX]);
  const vs = histPts.map(p => p.v).concat([projV]);
  const xMin = Math.min(...xs), xMax = Math.max(...xs);
  const yMin = Math.min(...vs), yMax = Math.max(...vs);
  const xR = (xMax - xMin) || 1, yR = (yMax - yMin) || 1;
  const sx = (x) => padL + ((x - xMin) / xR) * (W - padL - padR);
  const sy = (v) => padT + (1 - (v - yMin) / yR) * (H - padT - padB);
  const histPath = 'M ' + histPts.map(p => sx(p.x) + ' ' + sy(p.v)).join(' L ');
  const projPath = `M ${sx(last.x)} ${sy(last.v)} L ${sx(bestX)} ${sy(projV)}`;
  const histColor = (apt.delta1y || 0) >= 0 ? T.up : T.down;
  const fmtMon = (x) => `${('' + Math.floor(x / 12)).slice(2)}.${('' + ((x % 12) + 1)).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 }}>
        <div style={{ fontSize: 12, fontFamily: T.mono, color: T.fgDim, letterSpacing: 1, textTransform: 'uppercase', fontWeight: 600 }}>매수 타이밍 · 실거래가 추이</div>
        <div style={{ display: 'flex', gap: 12, fontSize: 10, fontFamily: T.mono }}>
          <span style={{ color: histColor }}>― 실거래</span>
          <span style={{ color: T.hot }}>┄ AI 예측</span>
        </div>
      </div>
      <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" style={{ display: 'block', width: '100%', height: H }}>
        {[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" />)}
        <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" />
        <path d={projPath} fill="none" stroke={T.hot} strokeWidth="2" strokeDasharray="5 4" strokeLinecap="round" />
        <circle cx={sx(bestX)} cy={sy(projV)} r="5" fill={T.hot} stroke={T.bg} strokeWidth="2" />
        <text x={sx(bestX)} y={H - 8} fill={T.hot} fontSize="9" fontFamily={T.mono} textAnchor="end">매수적기 {apt.bestBuyMonth}</text>
        <text x={padL} y={H - 8} fill={T.fgFaint} fontSize="9" fontFamily={T.mono}>{fmtMon(histPts[0].x)}</text>
      </svg>
      <div style={{ fontSize: 11, color: T.fgDim, marginTop: 8 }}>
        현재 <strong className="uj-num" style={{ color: T.fg }}>{won(apt.currentPrice)}</strong>
        <span style={{ color: T.fgMuted }}> → </span>매수적기 예상 <strong className="uj-num" style={{ color: T.hot }}>{won(projV)}</strong>
        <span style={{ color: (apt.delta1y || 0) >= 0 ? T.up : T.down, marginLeft: 6, fontFamily: T.mono }}>({apt.delta1y > 0 ? '+' : ''}{apt.delta1y}%)</span>
      </div>
    </div>
  );
}

Object.assign(window, { AptInsightModal });
