// mock-rtms.jsx — 백엔드(RTMS) 미연결 시 사용하는 현실적 실거래 이력 생성기
// ⚠ 데모용. 백엔드(api.uri-jib.com) + 국토부 MOLIT_API_KEY 연결 시
//   live-feed.jsx / search-live.jsx 가 진짜 RTMS 데이터로 자동 전환됩니다.
//
// 목적: 데모 상태에서도 "단지마다 여러 건의 실거래 이력"이 보이고,
//       전국 피드/검색이 정상 동작 + 클릭 시 상세 모달로 이어지도록.

(function () {
  // 평형 구성 (전용면적 ㎡) — 단지 규모/연식에 따라 달라지도록
  function areaSetFor(apt) {
    const big = apt.units >= 2000;
    if (apt.currentPrice >= 400000) return [84.97, 112.96, 137.41, 168.42]; // 대형 고가
    if (apt.currentPrice >= 250000) return [59.92, 84.96, 109.41, 134.88];
    if (big) return [49.94, 59.92, 74.85, 84.97];
    return [59.92, 74.85, 84.96, 101.82];
  }

  // 면적별 가격 배율 (84㎡ = 1.0 기준), 소형은 단가↑ 대형은 총액↑
  function priceForArea(base84, area) {
    const ratio = area / 84.96;
    // 단가 약간 체감: 면적^0.92
    return Math.round(base84 * Math.pow(ratio, 0.92));
  }

  function pad2(n) { return ('' + n).padStart(2, '0'); }

  // 단지별 실거래 이력 생성 (최근 ~26개월, 월 0~4건)
  function genTrades(apt, seed) {
    const trades = [];
    const areas = areaSetFor(apt);
    const now = new Date(2026, 4, 1); // 2026.05 기준
    // 의사난수 (단지별 고정 → 새로고침해도 동일)
    let s = 0;
    for (let i = 0; i < apt.id.length; i++) s += apt.id.charCodeAt(i) * (i + 7);
    const rnd = () => { s = (s * 9301 + 49297) % 233280; return s / 233280; };

    const yearGrowth = apt.delta1y || 3;
    for (let m = 25; m >= 0; m--) {
      const d = new Date(now); d.setMonth(d.getMonth() - m);
      const ymd = d.getFullYear() + pad2(d.getMonth() + 1);
      // 월별 거래 건수: 대단지일수록 많음
      const baseCount = apt.units >= 4000 ? 3 : apt.units >= 1500 ? 2 : 1;
      const count = Math.max(0, Math.round(baseCount + (rnd() - 0.4) * 2));
      // 과거로 갈수록 가격이 낮아지는 추세 (현재가 → 과거가)
      const trendFactor = Math.pow(1 + yearGrowth / 100, -m / 12);
      for (let k = 0; k < count; k++) {
        const area = areas[Math.floor(rnd() * areas.length)];
        const floorMax = apt.currentPrice >= 270000 ? 35 : 25;
        const floor = 1 + Math.floor(rnd() * floorMax);
        const base = priceForArea(apt.currentPrice, area) * trendFactor;
        // 층/노이즈 보정 (저층 -5%, 고층 +6%)
        const floorAdj = 1 + ((floor / floorMax) - 0.5) * 0.11;
        const noise = 1 + (rnd() - 0.5) * 0.05;
        const price = Math.round((base * floorAdj * noise) / 100) * 100;
        const day = 1 + Math.floor(rnd() * 27);
        trades.push({ name: apt.name, dong: apt.dong, region: apt.region, ymd, day, area: Math.round(area * 100) / 100, floor, price, buildYear: apt.built });
      }
    }
    // 최신순
    trades.sort((a, b) => +(b.ymd + pad2(b.day)) - +(a.ymd + pad2(a.day)));
    return trades;
  }

  // 모든 단지에 trades 부여 + 인덱스
  function buildAll() {
    if (!window.APTS) return;
    window.APTS.forEach(apt => {
      if (!apt.trades || apt.trades.length < 3) {
        apt.trades = genTrades(apt);
      }
    });
  }
  buildAll();

  // 전국 실시간 피드용: 최근 2개월 거래만 모아 셔플
  function mockNationwideFeed(limit) {
    const recent = [];
    const cutYmd = 202603; // 최근 3개월
    window.APTS.forEach(apt => {
      (apt.trades || []).forEach(t => {
        if (+t.ymd >= cutYmd) recent.push(t);
      });
    });
    // 셔플
    for (let i = recent.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [recent[i], recent[j]] = [recent[j], recent[i]];
    }
    return recent.slice(0, limit || 30);
  }

  // 특정 단지의 trades (상세 모달용) — 같은 이름 묶기
  function tradesForName(name, region) {
    const apt = window.APTS.find(a => a.name === name && (!region || a.region === region || region.includes(a.region) || a.region.includes(region)));
    return apt ? apt.trades : [];
  }

  // 지역(시군구)별 trades — 검색 페이지 데모용
  function mockRegionTrades(sidoSigungu) {
    // sidoSigungu 예: "서울특별시 강남구" → APTS.region "서울 강남구" 와 느슨 매칭
    const norm = (s) => s.replace(/특별시|광역시|특별자치시|특별자치도|시$/g, '').replace(/\s/g, '');
    const key = norm(sidoSigungu);
    const out = [];
    window.APTS.forEach(apt => {
      const r = norm(apt.region);
      if (key.includes(r) || r.includes(key) || key.includes(norm(apt.dong))) {
        (apt.trades || []).forEach(t => out.push(t));
      }
    });
    out.sort((a, b) => +(b.ymd + ('' + b.day).padStart(2, '0')) - +(a.ymd + ('' + a.day).padStart(2, '0')));
    return out;
  }

  Object.assign(window, { mockNationwideFeed, tradesForName, mockRegionTrades, genTrades });
})();
