// references.jsx — 모델 근거 레퍼런스 (국내외 논문·저널·공시자료)
// 각 요인이 어떤 학술/공시 근거에 기반하는지 명시. 프론트는 요약, 본 페이지는 전체.

const REF_SOURCES = {
  // 공시·통계 (1차 데이터)
  rtms:   { label: '국토교통부 실거래가 공개시스템 (RTMS)', org: '국토교통부', kind: '공시', url: 'https://rt.molit.go.kr', note: '아파트 매매·전월세 실거래 신고 원자료. 전국 시군구·읍면동·단지·전용면적·층·거래일 단위.' },
  reb:    { label: '전국주택가격동향조사 (R-ONE)', org: '한국부동산원', kind: '공시', url: 'https://www.reb.or.kr/r-one', note: '주간·월간 매매/전세 가격지수, 변동률, 거래량, 전세가율 공식 통계.' },
  kb:     { label: 'KB주택가격동향 · 월간 시계열', org: 'KB국민은행', kind: '공시', url: 'https://kbland.kr/webview.html#/main/statistics', note: '매매·전세 지수, PIR(소득대비주택가격), 매수우위지수 등 장기 시계열.' },
  ecos:   { label: '경제통계시스템 (ECOS)', org: '한국은행', kind: '공시', url: 'https://ecos.bok.or.kr', note: '기준금리, 주택담보대출 금리, 통화량(M2), 가계신용 등 거시 지표.' },
  kosis:  { label: '국가통계포털 (KOSIS)', org: '통계청', kind: '공시', url: 'https://kosis.kr', note: 'CPI, GDP, 인구이동, 가구소득, 미분양 등.' },
  applyhome: { label: '청약홈 경쟁률·공급 통계', org: '한국부동산원', kind: '공시', url: 'https://www.applyhome.co.kr', note: '단지별 청약 경쟁률·공급물량.' },
  krihs:  { label: '부동산시장 진단·전망', org: '국토연구원(KRIHS)', kind: '리포트', url: 'https://www.krihs.re.kr', note: '반기 주택시장 전망, 정책 영향 분석.' },
  kdi:    { label: 'KDI 부동산시장 동향·정책연구', org: '한국개발연구원(KDI)', kind: '리포트', url: 'https://www.kdi.re.kr', note: 'GTX 등 교통 인프라의 지가 효과, 금리-주택가격 연구.' },

  // 국내 학술
  jhs:    { label: '주택연구 (Housing Studies Review)', org: '한국주택학회', kind: '논문', url: 'https://www.khousing.or.kr', note: '헤도닉 가격모형 기반 학군·교통 프리미엄 실증 다수.' },
  kreaa:  { label: '부동산학연구', org: '한국부동산분석학회', kind: '논문', url: 'http://www.kreaa.or.kr', note: '실거래가 시계열·공급·금리 요인의 가격결정 분석.' },
  kticonf:{ label: '국토연구 (The Korea Spatial Planning Review)', org: '국토연구원', kind: '논문', url: 'https://www.krihs.re.kr', note: '광역교통망(GTX)·신도시 개발의 인접 단지 가격 효과.' },

  // 해외 학술 (방법론·이론 근거)
  rosen:  { label: 'Hedonic Prices and Implicit Markets (Rosen, 1974)', org: 'Journal of Political Economy', kind: '논문(해외)', url: 'https://www.journals.uchicago.edu/doi/10.1086/260169', note: '주택 특성별 가격 분해(헤도닉) 이론의 출발점.' },
  caseshiller: { label: 'The Efficiency of the Market for Single-Family Homes (Case & Shiller, 1989)', org: 'American Economic Review', kind: '논문(해외)', url: 'https://www.nber.org/papers/w2506', note: '주택가격의 모멘텀·자기상관 → 단기 추세 예측 근거.' },
  glaeser:{ label: 'Housing Supply and Housing Bubbles (Glaeser et al., 2008)', org: 'Journal of Urban Economics', kind: '논문(해외)', url: 'https://www.sciencedirect.com/science/article/abs/pii/S0094119008000557', note: '공급 탄력성과 가격 변동성의 관계 → 공급물량 가중치 근거.' },
  himmelberg: { label: 'Assessing High House Prices: Bubbles, Fundamentals (Himmelberg et al., 2005)', org: 'Journal of Economic Perspectives', kind: '논문(해외)', url: 'https://www.aeaweb.org/articles?id=10.1257/089533005775196769', note: 'PIR·이자율 기반 적정가치 평가 프레임.' },
  shap:   { label: 'A Unified Approach to Interpreting Model Predictions (Lundberg & Lee, 2017)', org: 'NeurIPS', kind: '논문(해외)', url: 'https://arxiv.org/abs/1705.07874', note: '요인별 기여도(SHAP) 산출 방법론.' },
  lgbm:   { label: 'LightGBM: A Highly Efficient Gradient Boosting (Ke et al., 2017)', org: 'NeurIPS', kind: '논문(해외)', url: 'https://papers.nips.cc/paper/6907-lightgbm', note: '예측 모델의 핵심 알고리즘.' },
};

// 12개 요인 → 근거 소스 매핑
const FACTOR_REFS = [
  { id: 'transactions', label: '실거래가 추이', weight: 18.4, refs: ['rtms', 'caseshiller', 'kreaa'] },
  { id: 'supply',       label: '공급 물량 (입주예정)', weight: 14.2, refs: ['reb', 'glaeser', 'krihs'] },
  { id: 'rates',        label: '기준금리 / 대출 규제', weight: 11.8, refs: ['ecos', 'kdi', 'himmelberg'] },
  { id: 'transit',      label: '교통 호재 (GTX·역세권)', weight: 9.6, refs: ['kdi', 'kticonf'] },
  { id: 'school',       label: '학군 / 학원가', weight: 8.1, refs: ['jhs', 'rosen'] },
  { id: 'redev',        label: '재건축 / 재개발 단계', weight: 7.4, refs: ['reb', 'krihs'] },
  { id: 'pir',          label: 'PIR (소득 대비 가격)', weight: 7.0, refs: ['kb', 'himmelberg'] },
  { id: 'macro',        label: '거시 경제 (GDP·CPI)', weight: 6.2, refs: ['kosis', 'ecos'] },
  { id: 'volume',       label: '거래량 / 매물 수', weight: 5.7, refs: ['rtms', 'reb'] },
  { id: 'jeonse',       label: '전세가율', weight: 4.8, refs: ['kb', 'reb'] },
  { id: 'income',       label: '지역별 소득 수준', weight: 3.5, refs: ['kosis'] },
  { id: 'pop',          label: '인구 이동 / 청약 경쟁률', weight: 3.3, refs: ['kosis', 'applyhome'] },
];

const KIND_COLOR = { '공시': '#1FB57A', '리포트': '#2D7FF9', '논문': '#8B5CF6', '논문(해외)': '#FFB020' };

// 요인별 상세 설명 (클릭 시 표시) — 무엇을·왜·어떻게·현재값
const FACTOR_DETAIL = {
  transactions: { what: '단지·평형별 국토부 실거래 신고가의 최근 추세(6개월 이동평균)', why: '실제 체결가는 호가보다 시장을 정확히 반영하며, 단기 모멘텀이 다음 분기 가격을 예측하는 가장 강한 신호입니다.', how: '6·12개월 변화율과 거래 빈도를 결합해 추세 강도를 점수화', now: '전국 평균 +0.42% MoM · 서울 +0.8%' },
  supply: { what: '향후 2년 입주 예정 물량과 분양 일정', why: '공급이 늘면 가격 상승이 둔화됩니다(공급탄력성 이론). 입주 폭탄 지역은 단기 조정 위험.', how: '권역별 입주물량 대비 수요(가구 증가)를 비율화', now: '서울 입주물량 전년比 −32% (공급 부족 → 상방)' },
  rates: { what: '한국은행 기준금리와 DSR 등 대출 규제', why: '금리는 대출 이자·구매력을 직접 좌우합니다. 규제 완화는 수요를 늘립니다.', how: '기준금리 수준·방향 + 규제 강도를 결합', now: '기준금리 2.75% 동결 · DSR 완화 검토' },
  transit: { what: 'GTX·지하철 신설/연장 등 교통 인프라 진척도', why: '역세권 접근성 개선은 인접 단지에 뚜렷한 프리미엄을 형성합니다(KDI 연구).', how: '노선 진척률·개통 임박도로 가중', now: 'GTX-A·C 진척률 87%' },
  school: { what: '학군·학원가 밀집도와 명문 배정 여부', why: '교육 수요는 비탄력적이라 학군 우수지는 하방 경직성이 강합니다(헤도닉 분석).', how: '학원 밀집도·학업성취·배정학교 등급', now: '대치·분당·목동 강세' },
  redev: { what: '재건축·재개발 사업 단계(안전진단~사업시행~관리처분)', why: '단계가 진척될수록 불확실성이 줄며 가치가 단계적으로 반영됩니다.', how: '정비사업 단계별 가중 + 분담금 리스크 차감', now: '주요 단지 사업시행계획 단계' },
  pir: { what: '가구소득 대비 주택가격 배율(Price to Income Ratio)', why: 'PIR이 역사적 고점이면 추가 상승 여력이 제한됩니다(적정가치 평가).', how: '지역 중위소득 대비 중위가격 배율', now: '서울 28.4 (역사적 고점권 → 하방 요인)' },
  macro: { what: 'GDP 성장률·소비자물가(CPI) 등 거시 환경', why: '경기·물가는 자산 전반의 방향을 좌우하는 배경 변수입니다.', how: 'GDP·CPI·고용 추세를 종합 스코어링', now: 'GDP +2.1% · CPI 2.4%' },
  volume: { what: '거래량과 시장 매물(재고) 수', why: '거래량 증가는 가격 상승의 선행지표, 매물 적체는 하락 신호입니다.', how: '거래량 MoM + 매물 회전율', now: '거래량 +24% MoM' },
  jeonse: { what: '매매가 대비 전세가 비율(전세가율)', why: '전세가율이 높으면 갭이 작아 하방을 지지하고 투자 진입이 쉽습니다.', how: '전세/매매 비율의 수준·추세', now: '전국 평균 54.2%' },
  income: { what: '지역별 가구 소득 수준과 증가율', why: '소득이 높고 늘어나는 지역은 구매력 기반 수요가 탄탄합니다.', how: '국세청 통합소득 + 증가율', now: '강남3구 +6.4% YoY' },
  pop: { what: '인구 순유입과 청약 경쟁률', why: '인구가 몰리고 청약 경쟁이 치열하면 실수요가 강하다는 의미입니다.', how: '순이동 + 청약 경쟁률', now: '청약 경쟁률 평균 18:1' },
};

function ReferencesPage() {
  const isMobile = useIsMobile();
  const focusId = (() => { try { return new URLSearchParams((location.hash.split('?')[1] || '')).get('f'); } catch (e) { return null; } })();
  useEffect(() => {
    document.title = '모델 근거·레퍼런스 — 우리집사기';
    window.UJTrack.track('view_references', { focus: focusId });
    if (focusId) { const el = document.getElementById('factor-' + focusId); if (el) setTimeout(() => el.scrollIntoView({ behavior: 'smooth', block: 'center' }), 200); }
  }, [focusId]);

  const allRefs = Object.entries(REF_SOURCES);
  const byKind = {};
  allRefs.forEach(([id, r]) => { (byKind[r.kind] = byKind[r.kind] || []).push({ id, ...r }); });
  const focusFactor = focusId ? FACTOR_REFS.find(f => f.id === focusId) : null;

  return (
    <div style={{ padding: isMobile ? 12 : 20, maxWidth: 1000, margin: '0 auto' }}>
      <PageHead title="모델 근거 · 레퍼런스" sub="우리집사기 AI가 무엇을 근거로 점수·시그널을 산출하는지" />

      {/* 선택한 요인 상세 (요인 클릭 시) */}
      {focusFactor && FACTOR_DETAIL[focusFactor.id] && (
        <Panel title={'요인 상세 · ' + focusFactor.label} subtitle={'가중치 ' + focusFactor.weight + '%'} style={{ marginBottom: 16, borderColor: T.hot }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {[['무엇을 보나', FACTOR_DETAIL[focusFactor.id].what], ['왜 중요한가', FACTOR_DETAIL[focusFactor.id].why], ['모델에서 어떻게 쓰나', FACTOR_DETAIL[focusFactor.id].how], ['현재 수치', FACTOR_DETAIL[focusFactor.id].now]].map(([k, v]) => (
              <div key={k}>
                <div style={{ fontSize: 11, fontFamily: T.mono, color: T.hot, letterSpacing: 1, marginBottom: 4 }}>{k}</div>
                <div style={{ fontSize: 13, color: T.fg, lineHeight: 1.6 }}>{v}</div>
              </div>
            ))}
            <div style={{ paddingTop: 10, borderTop: '1px solid ' + T.line }}>
              <div style={{ fontSize: 11, fontFamily: T.mono, color: T.fgMuted, marginBottom: 6 }}>근거 자료</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                {focusFactor.refs.map(rid => { const r = REF_SOURCES[rid]; return (
                  <a key={rid} href={r.url} target="_blank" rel="noopener noreferrer" style={{ display: 'inline-flex', alignItems: 'center', gap: 5, padding: '4px 10px', borderRadius: 4, background: (KIND_COLOR[r.kind] || T.line) + '18', border: '1px solid ' + (KIND_COLOR[r.kind] || T.line) + '50', color: KIND_COLOR[r.kind] || T.fgDim, fontSize: 11, textDecoration: 'none' }}>{r.org} ↗</a>
                ); })}
              </div>
            </div>
          </div>
        </Panel>
      )}

      {/* 방법론 요약 */}
      <Panel title="방법론 한눈에" style={{ marginBottom: 16 }}>
        <div style={{ fontSize: 13, color: T.fgDim, lineHeight: 1.8 }}>
          <strong style={{ color: T.fg }}>1차 데이터</strong> — 국토부 RTMS 실거래가를 기준으로, 한국부동산원·KB·한국은행·통계청 공시 통계를 결합합니다.<br/>
          <strong style={{ color: T.fg }}>모델</strong> — LightGBM(Gradient Boosting)으로 12개 요인을 학습하고, <strong style={{ color: T.ai }}>SHAP</strong>으로 각 요인의 기여도를 분해합니다.<br/>
          <strong style={{ color: T.fg }}>이론 근거</strong> — 헤도닉 가격모형(Rosen, 1974), 주택가격 모멘텀(Case &amp; Shiller, 1989), 공급탄력성(Glaeser, 2008), PIR 적정가치(Himmelberg, 2005) 등 검증된 연구에 기반합니다.
        </div>
      </Panel>

      {/* 요인별 근거 */}
      <Panel title="12개 요인별 근거" subtitle="가중치 · 출처" style={{ marginBottom: 16 }} noPad>
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          {FACTOR_REFS.map((f, i) => (
            <div key={f.id} id={'factor-' + f.id} style={{ padding: isMobile ? '12px 14px' : '14px 18px', borderBottom: i < FACTOR_REFS.length - 1 ? '1px solid ' + T.line : 'none', background: focusId === f.id ? 'rgba(255,176,32,0.06)' : 'transparent' }}>
              <a href={'#/app/references?f=' + f.id} data-track="factor_detail_open" data-track-factor={f.id} style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8, textDecoration: 'none', color: T.fg, cursor: 'pointer' }}>
                <span style={{ fontFamily: T.mono, fontSize: 11, color: T.fgMuted, width: 22 }}>{String(i + 1).padStart(2, '0')}</span>
                <span style={{ fontSize: 14, fontWeight: 600, color: T.fg, flex: 1 }}>{f.label}</span>
                <span style={{ fontFamily: T.mono, fontSize: 12, color: T.hot, fontWeight: 700 }}>{f.weight}%</span>
                <span style={{ fontSize: 11, color: T.info }}>{focusId === f.id ? '▲' : '상세 ▾'}</span>
              </a>
              {FACTOR_DETAIL[f.id] && (
                <div style={{ paddingLeft: 32, marginBottom: 8, fontSize: 12, color: T.fgDim, lineHeight: 1.6 }}>{FACTOR_DETAIL[f.id].what} · <span style={{ color: T.fgMuted }}>현재: {FACTOR_DETAIL[f.id].now}</span></div>
              )}
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, paddingLeft: 32 }}>
                {f.refs.map(rid => {
                  const r = REF_SOURCES[rid];
                  return (
                    <a key={rid} href={r.url} target="_blank" rel="noopener noreferrer"
                      style={{ display: 'inline-flex', alignItems: 'center', gap: 5, padding: '3px 9px', borderRadius: 4,
                        background: (KIND_COLOR[r.kind] || T.line) + '18', border: '1px solid ' + (KIND_COLOR[r.kind] || T.line) + '50',
                        color: KIND_COLOR[r.kind] || T.fgDim, fontSize: 11, textDecoration: 'none', fontFamily: T.font }}>
                      <span style={{ fontFamily: T.mono, fontSize: 9, opacity: 0.8 }}>{r.kind}</span>
                      {r.org} ↗
                    </a>
                  );
                })}
              </div>
            </div>
          ))}
        </div>
      </Panel>

      {/* 전체 레퍼런스 목록 */}
      {['공시', '리포트', '논문', '논문(해외)'].map(kind => (
        <Panel key={kind} title={kind === '논문(해외)' ? '해외 학술 (방법론·이론)' : kind === '논문' ? '국내 학술' : kind === '공시' ? '공시·통계 (1차 데이터)' : '기관 리포트'}
          subtitle={`${(byKind[kind] || []).length}건`} style={{ marginBottom: 16 }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {(byKind[kind] || []).map(r => (
              <a key={r.id} href={r.url} target="_blank" rel="noopener noreferrer"
                style={{ display: 'flex', gap: 12, textDecoration: 'none', padding: 12, background: T.card, border: '1px solid ' + T.line, borderRadius: 6 }}>
                <span style={{ width: 4, alignSelf: 'stretch', borderRadius: 2, background: KIND_COLOR[kind] || T.line, flexShrink: 0 }} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: T.fg, lineHeight: 1.4 }}>{r.label}</div>
                  <div style={{ fontSize: 11, color: T.fgMuted, fontFamily: T.mono, marginTop: 3 }}>{r.org}</div>
                  <div style={{ fontSize: 12, color: T.fgDim, marginTop: 6, lineHeight: 1.5 }}>{r.note}</div>
                </div>
                <span style={{ color: T.fgMuted, fontSize: 13, flexShrink: 0 }}>↗</span>
              </a>
            ))}
          </div>
        </Panel>
      ))}

      <div style={{ fontSize: 10, color: T.fgFaint, fontFamily: T.mono, lineHeight: 1.7, padding: '8px 4px 24px' }}>
        ※ 외부 데이터·논문의 저작권은 각 기관·저자에 귀속됩니다. 본 서비스는 공개된 공시자료와 검증된 연구 방법론을 근거로 한 정보 제공 도구이며, 투자 자문이 아닙니다. 실제 거래 전 등기부등본·공인중개사·세무사 확인을 권장합니다.
      </div>
    </div>
  );
}

Object.assign(window, { REF_SOURCES, FACTOR_REFS, ReferencesPage });
