// Listings.jsx — sale + rental, filtered by NYC neighborhood
// Buildings sourced from public developer sites + StreetEasy building pages.
// Unit details (beds/baths/sqft/price) are representative placeholders.

// === Neighborhood taxonomy ===
// Grouped into regions for the filter row. Order matters — drives chip order.
const REGIONS = [
  {
    id: 'manhattan',
    en: 'Manhattan', ko: '맨해튼',
    nhoods: [
      { id: 'uws',       en: 'Upper West Side', ko: 'UWS · 어퍼웨스트' },
      { id: 'ues',       en: 'Upper East Side', ko: 'UES · 어퍼이스트' },
      { id: 'chelsea',   en: 'Chelsea',         ko: '첼시' },
      { id: 'tribeca',   en: 'Tribeca',         ko: '트라이베카' },
      { id: 'west-vil',  en: 'West Village',    ko: '웨스트 빌리지' },
      { id: 'flatiron',  en: 'Flatiron',        ko: '플랫아이언' },
      { id: 'mid-south', en: 'Midtown South',   ko: '미드타운 사우스' },
      { id: 'fidi',      en: 'FiDi',            ko: 'FiDi · 금융가' },
    ],
  },
  {
    id: 'queens',
    en: 'Queens', ko: '퀸즈',
    nhoods: [
      { id: 'lic',       en: 'Long Island City', ko: 'LIC · 롱아일랜드시티' },
    ],
  },
  {
    id: 'brooklyn',
    en: 'Brooklyn', ko: '브루클린',
    nhoods: [
      { id: 'dt-bk',     en: 'Downtown Brooklyn', ko: '다운타운 브루클린' },
      { id: 'williamsburg', en: 'Williamsburg', ko: '윌리엄스버그' },
      { id: 'bk-heights', en: 'Brooklyn Heights', ko: '브루클린 하이츠' },
    ],
  },
];
const NHOOD_LOOKUP = REGIONS.flatMap(r => r.nhoods.map(n => ({ ...n, region: r.id })))
  .reduce((acc, n) => { acc[n.id] = n; return acc; }, {});

const LISTINGS = [
  // ============ SALES — building overviews, not single units ============
  {
    id: 'sale-strathmore',
    cat: 'sale',
    tone: 3,
    nhood: 'ues',
    building: 'The Strathmore',
    address: '400 East 84th Street',
    place: 'Upper East Side · Yorkville',
    title: 'A masterfully reimagined Upper East Side residence',
    ko: '어퍼이스트의 우아함을 새롭게 다듬은 레지던스',
    bedrooms: '1 — 3 bed', bedroomsKo: '원베드 — 3베드',
    startingPrice: 960000,
    type: 'Condop',
    yearBuilt: 1994,
    units: 179,
    stories: 44,
    amenities: ['Private dining & catering kitchen', 'Co-working lounge', 'Fitness center', '50-ft indoor lap pool & sauna', 'Squash / sports court', "Children's playroom"],
    description: "An exquisite home on the Upper East Side.\n\nThe Strathmore rises above one of Manhattan's most enduring neighborhoods — leafy, quiet, sophisticated. A collection of one- to three-bedroom residences by Related Companies and designer Tony Ingrao.\n\nSweeping city and river views. Generous layouts. Understated, timeless detailing.\n\nA grand canopy arrival. A double-height lobby with a fireplace. A private garden retreat.\n\nThe Upper East Side, elevated and effortlessly considered.",
    descriptionKo: '어퍼이스트사이드의 격조 높은 집.\n\n맨해튼에서 가장 오래도록 사랑받아 온 동네 — 푸르고 조용하며, 정제된 분위기가 흐르는 어퍼이스트사이드 위로 솟은 더 스트라스모어. Related Companies와 디자이너 Tony Ingrao가 함께 설계한 원베드룸–쓰리베드룸 레지던스입니다.\n\n도시와 강이 시원하게 펼쳐지는 뷰. 넉넉한 평면. 시간이 지나도 변치 않을 정교한 디테일.\n\n그랜드 캐노피 진입로. 벽난로가 있는 더블 하이트 로비. 그리고 프라이빗 가든까지.\n\n어퍼이스트사이드의 격을 한 단계 올려놓는, 자연스럽고 사려 깊은 집.',
    status: 'new',
    images: ['/assets/listings/strathmore/hero.jpg'],
    courtesy: [
      { label: 'thestrathmore.com', url: 'https://www.thestrathmore.com/' },
    ],
  },
  {
    id: 'sale-one-manhattan-sq',
    cat: 'sale',
    tone: 4,
    nhood: 'fidi',
    building: 'One Manhattan Square',
    address: '252 South Street',
    place: 'Lower East Side · Two Bridges',
    title: 'A river-front tower with a 421-a tax abatement',
    ko: '21년 세제 혜택의 워터프론트 타워',
    bedrooms: 'Studio — 3 bed', bedroomsKo: '스튜디오 — 3베드',
    startingPrice: 1180000,
    type: 'Condominium',
    yearBuilt: 2019,
    units: 815,
    amenities: ['Doorman', '100,000 ft² amenities', 'Pool', 'Spa', 'Sky deck'],
    status: 'new',
    images: ['/assets/listings/one-manhattan-square/hero.jpg'],
    courtesy: [
      { label: 'onemanhattansquare.com', url: 'https://onemanhattansquare.com/' },
    ],
  },
  {
    id: 'sale-one-williamsburg-wharf',
    cat: 'sale',
    tone: 5,
    nhood: 'williamsburg',
    building: 'One Williamsburg Wharf',
    address: '440 Kent Avenue',
    place: 'Brooklyn · Williamsburg Waterfront',
    title: 'A waterfront condominium with Manhattan skyline views',
    ko: '맨해튼 스카이라인이 펼쳐지는 워터프론트 콘도미니엄',
    bedrooms: 'Studio — 3 bed', bedroomsKo: '스튜디오 — 3베드',
    startingPrice: 730000,
    type: 'Condominium',
    yearBuilt: 2025,
    units: 282,
    stories: 22,
    architects: 'FXCollaborative',
    amenities: ['24-hour doorman & concierge', 'Waterfront promenade access', 'Resident lounge & co-working', 'Rooftop pool & sundeck', 'Fitness center & yoga studio', 'Game room & screening room', 'Children\u2019s playroom', 'Pet spa', 'Private dining room'],
    description: "A waterfront address with Manhattan in full view.\n\nOne Williamsburg Wharf rises on the East River at the heart of a new five-tower neighborhood — designed by FXCollaborative, with the city skyline as its front yard.\n\nStudios through three-bedroom condominium residences. Floor-to-ceiling glass. Open chef\u2019s kitchens. Wide-plank oak floors. Select homes with private outdoor space.\n\nResidents step out to a landscaped waterfront promenade, with a rooftop pool and sundeck overhead. Below, a full-service lifestyle suite — fitness, yoga, co-working, screening, private dining, children\u2019s playroom, and a pet spa.\n\nWilliamsburg\u2019s restaurants, galleries, and the Ferry are all within a short walk. The L, J, M, and G trains are nearby — Manhattan in minutes.\n\nFor end-users seeking the view and the lifestyle, and investors drawn to one of New York\u2019s strongest emerging waterfronts.",
    descriptionKo: '맨해튼이 정면으로 펼쳐지는 워터프론트 주소.\n\n원 윌리엄스버그 워프는 이스트강을 따라 새롭게 조성되는 다섯 동 단지의 중심에 자리합니다. FXCollaborative의 설계로, 도시의 스카이라인이 바로 마당이 되는 자리.\n\n스튜디오부터 쓰리베드룸까지의 콘도미니엄 레지던스. 통창, 오픈 셰프스 키친, 와이드 플랭크 오크 마루. 일부 세대는 프라이빗 야외 공간까지 갖췄습니다.\n\n문을 나서면 정원이 어우러진 워터프론트 프롬나드, 그리고 위로는 루프탑 수영장과 선덱. 단지 안에는 피트니스, 요가, 코워킹, 시어터 룸, 프라이빗 다이닝, 어린이 놀이방, 그리고 펫 스파까지 갖춘 풀 서비스 라이프스타일 공간이 마련됩니다.\n\n윌리엄스버그의 레스토랑, 갤러리, 그리고 NYC 페리까지 모두 도보권. L, J, M, G 라인도 가까워 맨해튼까지 단 몇 분.\n\n뷰와 라이프스타일을 찾는 실거주자에게도, 뉴욕에서 가장 빠르게 성장하는 워터프론트에 자산을 두려는 투자자에게도 적합한 주소입니다.',
    status: 'new',
    images: [
      '/assets/listings/one-williamsburg-wharf/01-tower.jpg',
      '/assets/listings/one-williamsburg-wharf/02-skyline.jpg',
      '/assets/listings/one-williamsburg-wharf/03-living.jpg',
      '/assets/listings/one-williamsburg-wharf/04-dining.jpg',
      '/assets/listings/one-williamsburg-wharf/05-terrace.jpg',
    ],
    courtesy: [
      { label: 'onewilliamsburgwharf.com', url: 'https://onewilliamsburgwharf.com/' },
    ],
  },
  {
    id: 'sale-flatiron',
    cat: 'sale',
    tone: 6,
    nhood: 'flatiron',
    building: 'The Flatiron Building',
    address: '175 Fifth Avenue, New York, NY 10010',
    place: 'Flatiron District · Manhattan',
    title: 'A landmark Beaux-Arts conversion at 175 Fifth Avenue',
    ko: '5번가 175번지의 보자르 랜드마크 컨버전',
    bedrooms: '3 — 4+ bed', bedroomsKo: '쓰리베드 — 4베드 이상',
    startingPrice: 10950000,
    type: 'Condominium',
    yearBuilt: 1902,
    converted: 2026,
    units: 38,
    stories: 24,
    style: 'Beaux-Arts',
    architects: 'SLCE Architects & Studio Sofield',
    developers: 'The Brodsky Organization & Sorgente Group',
    amenities: ['Concierge', 'Beaux-Arts lobby', 'Library lounge', 'Fitness', 'Catering kitchen', 'Elevator'],
    description: "An icon, made home.\n\nBehind the world's most recognizable Beaux-Arts façade, only 38 private residences — designed inside and out by Studio Sofield.\n\nCustom millwork. Hand-clipped mosaic. Blackened steel detailing. Poliform cabinetry.\n\nThree- to four-bedroom homes built for both living and entertaining, in a building that needs no introduction.\n\nA rare, irreplaceable hold — strong for end-users and long-view investors alike.\n\nOccupancy this Fall.",
    descriptionKo: '전 세계가 아는 그 빌딩이, 이제 집이 됩니다.\n\n세계적으로 사랑받는 보자르 파사드 안으로, Studio Sofield가 외관과 인테리어 전체를 설계한 단 38채의 프라이빗 레지던스.\n\n맞춤 우드워크. 핸드클립 모자이크. 블랙 스틸 디테일. Poliform 캐비닛.\n\n쓰리베드룸부터 4베드 이상까지 — 가족과 손님 모두를 위한 넉넉한 평면. 따로 설명이 필요 없는 빌딩의 안쪽 풍경입니다.\n\n실거주자에게도, 긴 안목의 투자자에게도 명확한 가치를 지닌 희소 자산.\n\n올 가을 입주.',
    status: 'new',
    images: ['/assets/listings/flatiron/hero.jpg'],
    courtesy: [
      { label: 'theflatironbuilding.com', url: 'https://www.theflatironbuilding.com/' },
    ],
  },

  // ============ RENTALS ============
  // Addresses hidden — neighborhood + attractive title only.
  {
    id: 'rent-waterline-square',
    cat: 'rent',
    tone: 5,
    nhood: 'uws',
    building: 'Waterline Square',
    address: '645 West 59th Street',
    place: 'Upper West Side · Riverside Park',
    title: 'River-facing rentals at Waterline Square',
    ko: '허드슨 강을 마주한 리버사이드 파크의 렌탈',
    bedrooms: 'Studio — 4 bed', bedroomsKo: '스튜디오 — 4베드',
    startingPrice: null,
    pricingOnRequest: true,
    price: null,
    type: 'Rental & Condominium',
    yearBuilt: 2018,
    units: 1132,
    stories: 38,
    architects: 'Richard Meier · Kohn Pedersen Fox · Rafael Viñoly',
    tags: ['Doorman', 'Pet-friendly', 'River views'],
    amenities: ['24-hour doorman & concierge', 'Live-in super · Valet parking', '100,000 ft² indoor amenities', '25m indoor lap pool · Hot tub', 'Indoor tennis · Basketball · Squash', 'Rock climbing wall · Half-pipe skate park', 'Soccer field · Pilates reformer room', "Children's playroom & adventure club", 'Art, recording & gardening studios', 'Empellón Taqueria by Alex Stupak', '2.6-acre landscaped park with water features', 'Garden · Patio · Roof Deck · Private outdoor space'],
    description: "An address that lives between two worlds — the cultural pulse of Lincoln Square, and the easy elegance of the Upper West Side.\n\nSteps from Lincoln Center, Juilliard, and Fordham. A short ride to Columbia. The Calhoun School, Trinity, and Collegiate are all nearby — a setting long favored by the city\u2019s most established families.\n\nThree towers rise above a 2.6-acre landscaped park. Studios through four-bedroom residences, designed by Richard Meier, Kohn Pedersen Fox, and Rafael Viñoly.\n\nInside: floor-to-ceiling glass, walk-in closets, chef\u2019s kitchens with islands. Outside: select homes with private outdoor space and Hudson River views.\n\nThe Waterline Club brings 100,000 ft² of amenities — a 25-meter indoor lap pool, tennis, basketball, squash, rock climbing, and a half-pipe skate park. A Pilates reformer room. A children\u2019s adventure club. Art, music, and gardening studios.\n\nAnd downstairs, Empellón Taqueria by James Beard-nominated chef Alex Stupak.\n\nA condominium portion is available for purchase in the same complex, with a 421-a tax abatement on select residences.",
    descriptionKo: '두 세계가 만나는 주소 — 링컨 스퀘어의 문화적 활기, 그리고 어퍼웨스트사이드의 여유로운 품격이 함께 흐르는 곳입니다.\n\n링컨 센터, 줄리아드, 포드햄까지 도보권. 컬럼비아 대학교까지 한 정거장. 칼훈, 트리니티, 컬리지에이트 스쿨도 가깝습니다 — 오랫동안 뉴욕의 품격 있는 가족들이 머물러 온 동네입니다.\n\n2.6에이커의 정원 위로 솟은 세 개의 타워. 리처드 마이어, KPF, 라파엘 비뇰리가 설계한 스튜디오부터 4베드룸까지의 레지던스.\n\n안으로는 통창, 워크인 클로젯, 아일랜드를 갖춘 셰프스 키친. 일부 세대는 프라이빗 야외 공간과 허드슨강 뷰까지 갖췄습니다.\n\n약 100,000 ft²의 워터라인 클럽 — 25m 실내 수영장, 실내 테니스·농구·스쿼시, 락클라이밍 월, 하프파이프 스케이트 파크. 필라테스 리포머 룸. 어린이 어드벤처 클럽. 아트·레코딩·가드닝 스튜디오까지.\n\n그리고 단지 1층에는 제임스 비어드 어워드 노미니 셰프 알렉스 스투파크의 Empellón Taqueria.\n\n같은 단지 내 콘도미니엄 매매도 가능하며, 일부 세대는 421-a 세제 혜택이 적용됩니다.',
    saleAvailable: true,
    taxAbatement: '421-a',
    status: 'new',
    images: [
      '/assets/listings/waterline-square/03-lobby.jpg',
      '/assets/listings/waterline-square/01-pool.jpg',
      '/assets/listings/waterline-square/02-lounge.jpg',
      '/assets/listings/waterline-square/04-atrium.jpg',
      '/assets/listings/waterline-square/06-terrace.jpg',
      '/assets/listings/waterline-square/05-park.jpg',
    ],
    courtesy: [
      { label: 'windsorcommunities.com', url: 'https://www.windsorcommunities.com/properties/waterline-square/floorplans/' },
    ],
  },
  {
    id: 'rent-williamsburg-wharf',
    cat: 'rent',
    tone: 1,
    nhood: 'williamsburg',
    building: 'Williamsburg Wharf Rentals',
    address: 'Williamsburg Waterfront',
    place: 'Brooklyn · Williamsburg Waterfront',
    title: 'Waterfront rentals across three Williamsburg towers',
    ko: '윌리엄스버그 워터프론트의 세 개 타워 렌탈',
    bedrooms: 'Studio — 3 bed', bedroomsKo: '스튜디오 — 3베드',
    startingPrice: null,
    pricingOnRequest: true,
    price: null,
    type: 'Rental building',
    yearBuilt: 2025,
    stories: 21,
    architects: 'FXCollaborative',
    tags: ['Doorman', 'Pet-friendly', 'Waterfront'],
    amenities: ['24-hour doorman & concierge', 'Waterfront promenade access', 'Rooftop pool & sundeck', 'Fitness center & yoga studio', 'Co-working lounge', 'Game room & screening room', 'Children\u2019s playroom', 'Pet spa', 'In-unit washer/dryer'],
    description: "Williamsburg, on the water.\n\nThree rental towers along the East River, part of a new five-tower waterfront neighborhood — designed by FXCollaborative, opening onto a landscaped promenade with Manhattan in full view.\n\nStudios through three-bedroom residences. Floor-to-ceiling glass. Open chef\u2019s kitchens. In-unit washer/dryer. Select homes with private outdoor space.\n\nAmenities shared across the complex: rooftop pool and sundeck, fitness center, yoga studio, co-working lounge, screening room, children\u2019s playroom, pet spa, and 24-hour doorman.\n\nWilliamsburg\u2019s restaurants, galleries, and the NYC Ferry are at the door. The L, J, M, and G trains are nearby — Manhattan in minutes.\n\nA condominium portion is also available for purchase in the same complex.",
    descriptionKo: '물 위의 윌리엄스버그.\n\n이스트강을 따라 새롭게 조성되는 다섯 동 워터프론트 단지의 일부, 세 개의 렌탈 타워. FXCollaborative의 설계로, 정원이 어우러진 프롬나드 위로 맨해튼이 정면으로 펼쳐지는 자리입니다.\n\n스튜디오부터 쓰리베드룸까지의 레지던스. 통창, 오픈 셰프스 키친, 인유닛 세탁기·건조기. 일부 세대는 프라이빗 야외 공간까지 갖췄습니다.\n\n단지 전체가 공유하는 편의시설 — 루프탑 수영장과 선덱, 피트니스 센터, 요가 스튜디오, 코워킹 라운지, 시어터 룸, 어린이 놀이방, 펫 스파, 그리고 24시간 도어맨.\n\n윌리엄스버그의 레스토랑, 갤러리, 그리고 NYC 페리까지 모두 도보권. L, J, M, G 라인도 가까워 맨해튼까지 단 몇 분.\n\n같은 단지 내 콘도미니엄 매매도 가능합니다.',
    saleAvailable: true,
    status: 'new',
    images: [
      '/assets/listings/williamsburg-wharf-rentals/01-rooftop.jpg',
      '/assets/listings/williamsburg-wharf-rentals/02-living-terrace.jpg',
      '/assets/listings/williamsburg-wharf-rentals/03-living.jpg',
      '/assets/listings/williamsburg-wharf-rentals/04-bedroom.jpg',
      '/assets/listings/williamsburg-wharf-rentals/05-pool-lounge.jpg',
      '/assets/listings/williamsburg-wharf-rentals/06-gym.jpg',
      '/assets/listings/williamsburg-wharf-rentals/07-lounge.jpg',
    ],
    courtesy: [
      { label: 'williamsburgwharfrentals.com', url: 'https://williamsburgwharfrentals.com/' },
    ],
  },
  {
    id: 'rent-solari',
    cat: 'rent',
    tone: 3,
    nhood: 'mid-south',
    building: 'Solari',
    address: '42 West 33rd Street',
    place: 'Midtown South · Herald Square',
    title: 'A transit-first rental at Solari',
    ko: '교통 요지에 자리한 미드타운 사우스의 렌탈',
    bedrooms: 'Studio — 3 bed', bedroomsKo: '스튜디오 — 3베드',
    startingPrice: null,
    pricingOnRequest: true,
    price: null,
    type: 'Rental building',
    yearBuilt: 2018,
    units: 223,
    stories: 39,
    tags: ['Doorman', 'Pet-friendly', 'Transit hub'],
    amenities: ['24-hour doorman & concierge', 'Resident lounge & co-working', 'Fitness center & yoga studio', 'Rooftop deck with skyline views', 'Game room & screening room', 'Bike storage', 'Package room', 'Laundry in unit'],
    description: "A new building at the crossroads of New York.\n\nSolari rises on West 33rd Street — between Fifth and Sixth Avenue — in the middle of everything: Herald Square, Koreatown, Times Square, the Empire State Building, all within a short walk.\n\nFor commuters, this is the city\u2019s best-connected address. Herald Square (B · D · F · M · N · Q · R · W) is at the door. Penn Station (1 · 2 · 3 · A · C · E · LIRR · NJ Transit · Amtrak) and PATH (33rd Street) are a block away. Port Authority is five minutes north. Grand Central — and Metro-North — is a quick shuttle east.\n\nStudios through three-bedroom residences with floor-to-ceiling glass, in-unit washer/dryer, and modern open kitchens.\n\nAmenities include a 24-hour doorman, a fitness center and yoga studio, a resident lounge and co-working space, a game room and screening room, and a rooftop deck with skyline views.\n\nBuilt for students, young professionals, and anyone whose week moves across multiple boroughs.",
    descriptionKo: '뉴욕의 한복판, 모든 교통이 만나는 자리.\n\n솔라리는 5번가와 6번가 사이, 웨스트 33가에 자리합니다 — 헤럴드 스퀘어, 코리아타운, 타임스 스퀘어, 엠파이어 스테이트 빌딩이 모두 도보권에 있는 위치입니다.\n\n출퇴근하는 분들에게는 뉴욕에서 가장 편리한 주소입니다. 헤럴드 스퀘어역(B·D·F·M·N·Q·R·W)이 바로 앞. 펜 스테이션(1·2·3·A·C·E·LIRR·NJ Transit·Amtrak)과 PATH(33가)는 한 블록 거리. 포트 오소리티 버스 터미널까지 도보 5분. 그랜드 센트럴과 메트로-노스도 셔틀 한 번이면 닿습니다.\n\n스튜디오부터 쓰리베드룸까지 — 통창, 인유닛 세탁기·건조기, 그리고 모던한 오픈 키친.\n\n편의시설은 24시간 도어맨, 피트니스 센터와 요가 스튜디오, 레지던트 라운지와 코워킹 공간, 게임 룸과 시어터 룸, 그리고 스카이라인이 보이는 루프 데크까지.\n\n맨해튼 곳곳을 오가는 학생, 영 프로페셔널, 그리고 일주일을 여러 자치구에 걸쳐 보내는 분들을 위한 집.',
    status: 'new',
    images: [
      '/assets/listings/solari/01-living.jpg',
      '/assets/listings/solari/02-sunset.jpg',
      '/assets/listings/solari/03-kitchen.jpg',
      '/assets/listings/solari/04-rooftop.jpg',
      '/assets/listings/solari/05-lounge.jpg',
    ],
    courtesy: [
      { label: 'solarinyc.com', url: 'https://solarinyc.com/' },
    ],
  },
  {
    id: 'rent-one-park-row',
    cat: 'rent',
    tone: 4,
    nhood: 'fidi',
    building: 'One Park Row',
    address: '1 Park Row',
    place: 'Lower Manhattan · Financial District',
    title: 'A boutique waterfront tower at City Hall Park',
    ko: '시티홀 파크 옆, 부티크 워터프론트 타워',
    bedrooms: 'Studio — 3 bed', bedroomsKo: '스튜디오 — 3베드',
    startingPrice: null,
    pricingOnRequest: true,
    price: null,
    type: 'Rental building',
    yearBuilt: 2024,
    units: 60,
    stories: 24,
    architects: 'Rockwell Group',
    tags: ['Doorman', 'Pet-friendly', 'Boutique'],
    amenities: ['24-hour doorman & concierge', 'Library & lounge by Rockwell Group', 'Fitness center & yoga studio', 'Landscaped rooftop terrace', 'Bicycle storage', 'Package room', 'In-unit washer/dryer'],
    description: "Originally conceived as a luxury condominium, now reimagined as a rental — One Park Row offers the finishes, the scale, and the lifestyle of an ownership building, available without the commitment.\n\nA boutique 24-story tower of just 60 residences, designed by Rockwell Group at the edge of City Hall Park. Quiet, intimate, and meant to be known.\n\nStudios through three-bedroom homes with floor-to-ceiling windows, open chef\u2019s kitchens with marble and natural oak millwork, in-unit washer/dryer, and curved-glass views toward the Brooklyn Bridge, the Woolworth Building, and One World Trade.\n\nA library lounge by Rockwell, a landscaped rooftop terrace with firepits and dining at dusk, fitness, yoga, and 24-hour concierge.\n\nThe Financial District\u2019s most connected corner — 4, 5, 6, J, Z, R, W, and the 2, 3, A, C all within a few blocks. PATH at Fulton Street. NYC Ferry at Wall Street. The Brooklyn Bridge at your door.\n\nMade for those who want the elevated finish and the boutique scale — without the long-term commitment.",
    descriptionKo: '본래 럭셔리 콘도미니엄으로 설계된 빌딩이, 이제 렌탈로 새롭게 선보입니다 — 원 파크 로우는 분양 빌딩의 마감과 스케일, 그리고 라이프스타일을 매수의 부담 없이 누릴 수 있는 자리입니다.\n\nRockwell Group이 시티홀 파크 옆에 설계한 24층, 단 60세대의 부티크 타워. 조용하고, 친밀하며, 아는 얼굴이 있는 규모.\n\n스튜디오부터 쓰리베드룸까지 — 통창, 마블과 내추럴 오크로 마감된 오픈 셰프스 키친, 인유닛 세탁기·건조기, 그리고 곡선 유리 너머로 펼쳐지는 브루클린 브리지, 울워스 빌딩, 원 월드 트레이드의 뷰.\n\nRockwell이 설계한 라이브러리 라운지, 파이어핏과 다이닝이 어우러진 루프탑 테라스, 피트니스와 요가, 그리고 24시간 컨시어지.\n\n파이낸셜 디스트릭트에서 가장 잘 연결된 코너 — 4·5·6, J·Z, R·W, 그리고 2·3·A·C까지 모두 몇 블록 거리. 풀턴 스트리트 PATH, 월스트리트 NYC 페리, 그리고 바로 앞의 브루클린 브리지.\n\n분양 빌딩 수준의 마감과 부티크 스케일을, 장기 약정 없이 누리고 싶은 분들을 위한 집.',
    status: 'new',
    images: [
      '/assets/listings/one-park-row/01-living.jpg',
      '/assets/listings/one-park-row/02-bedroom.jpg',
      '/assets/listings/one-park-row/03-kitchen.jpg',
      '/assets/listings/one-park-row/04-terrace-day.jpg',
      '/assets/listings/one-park-row/05-terrace-night.jpg',
      '/assets/listings/one-park-row/06-exterior.jpg',
    ],
    courtesy: [
      { label: 'oneparkrownyc.com', url: 'https://oneparkrownyc.com/' },
    ],
  },
  {
    id: 'rent-the-orchard',
    cat: 'rent',
    tone: 1,
    nhood: 'lic',
    building: 'The Orchard',
    address: '42-06 Orchard Street',
    place: 'Queens · Long Island City',
    title: 'Queens\u2019 tallest tower with a 60,000 ft² backyard',
    ko: '60,000 ft²의 백야드를 품은 퀸즈에서 가장 높은 타워',
    bedrooms: 'Studio — 3 bed', bedroomsKo: '스튜디오 — 3베드',
    startingPrice: null,
    pricingOnRequest: true,
    price: null,
    type: 'Rental building',
    yearBuilt: 2026,
    units: 824,
    stories: 70,
    tags: ['Doorman', 'Pet-friendly', 'Resort amenities'],
    amenities: ['24/7 concierge & on-site parking', '60,000 ft² landscaped backyard', 'Pool, cabanas & firepits', 'Pickleball, basketball & running track', 'NBA-designed Arena · Aquatic Center', 'Fieldhouse: gym, boxing, Pilates', 'The Commons: coworking & podcast studio', 'Bloom & Brew Café · Royal Gala dining', 'Arcade · Screening lounges · Event space', '70th-floor Sky Lounge with viewing deck', 'Dog park · Yoga deck · Great Lawn', "The Sapling Zone children's playground"],
    description: "Welcome to The Orchard — New York\u2019s biggest backyard, at the city\u2019s most connected address.\n\nA seventy-story tower in Long Island City, with Midtown one stop away. The E, F, M, R, and N/W reach Manhattan in minutes. The 7 runs straight to Grand Central, the G links Queens and Brooklyn, and LIRR, ferry, Citi Bike, LGA and JFK are all within easy reach.\n\nStudios through three-bedroom homes with floor-to-ceiling windows, open layouts, and skyline and river views. Select residences feature private outdoor space.\n\nOver 100,000 ft² of resort-style amenities and a 60,000 ft² landscaped backyard — pool, pickleball, the Arena designed by NBA trainer Chris Brickley, the Aquatic Center, gym and yoga, coworking and a podcast studio, café and dining.\n\nHigh above the city, the 70th-floor Sky Lounge opens to panoramic views in every direction.\n\nMade for those who want everything close — work, play, and home.",
    descriptionKo: '뉴욕에서 가장 넓은 백야드, 그리고 도시에서 가장 잘 연결된 주소 — 디 오차드에 오신 것을 환영합니다.\n\n롱아일랜드시티에 자리한 70층 타워. 미드타운까지 단 한 정거장입니다. E·F·M·R·N/W로 맨해튼까지 몇 분, 7번선은 그랜드 센트럴까지 직행, G라인은 퀸즈와 브루클린을 잇습니다. LIRR, 페리, Citi Bike, 그리고 LGA·JFK 공항까지 모두 가까이.\n\n스튜디오부터 쓰리베드룸까지 — 통창, 오픈 평면, 스카이라인과 강이 펼쳐지는 뷰. 일부 세대는 프라이빗 야외 공간까지 갖췄습니다.\n\n100,000 ft²가 넘는 리조트급 편의시설과 60,000 ft²의 정원 — 수영장, 피클볼, NBA 트레이너 Chris Brickley가 설계한 The Arena, Aquatic Center, 피트니스와 요가, 코워킹과 팟캐스트 스튜디오, 카페와 다이닝까지.\n\n70층 Sky Lounge에선 사방으로 펼쳐지는 파노라믹 뷰가 기다립니다.\n\n일과 여유, 그리고 집 — 모두를 가까이 두고 싶은 분들을 위한 주소.',
    status: 'new',
    images: [
      '/assets/listings/the-orchard/01-skyline.jpg',
      '/assets/listings/the-orchard/02-entrance.jpg',
      '/assets/listings/the-orchard/03-kitchen.jpg',
      '/assets/listings/the-orchard/04-bedroom.jpg',
      '/assets/listings/the-orchard/05-great-lawn.jpg',
      '/assets/listings/the-orchard/06-backyard.jpg',
    ],
    courtesy: [
      { label: 'theorchardlic.com', url: 'https://theorchardlic.com/' },
    ],
  },
];

const formatPrice = (l, isKR) => {
  if (l.pricingOnRequest) {
    return isKR ? '가격 문의' : 'Pricing on request';
  }
  if (l.startingPrice) {
    if (l.cat === 'rent') {
      return `${isKR ? '시작 월세 ' : 'From '}$${l.startingPrice.toLocaleString()}${isKR ? ' / 월' : ' / mo'}`;
    }
    return `${isKR ? '시작가 ' : 'From '}$${l.startingPrice.toLocaleString()}`;
  }
  if (l.cat === 'rent') {
    return `$${l.price.toLocaleString()}${isKR ? ' / 월' : ' / mo'}`;
  }
  return `$${l.price.toLocaleString()}`;
};

const ListingCard = ({ l, onOpen, lang = 'EN' }) => {
  const isKR = lang === 'KR';
  return (
    <article className="ms-listing" data-tone={l.tone} onClick={() => onOpen(l)}>
      <div className="img">
        {l.images && l.images[0] && (
          <img
            className="ms-listing-photo"
            src={l.images[0]}
            alt={l.building ? `${l.building} — ${isKR ? l.ko : l.title}` : (isKR ? l.ko : l.title)}
            loading="lazy"
            onError={(e) => { e.currentTarget.style.display = 'none'; }}
          />
        )}
        {/* Architectural overlay — building name in ultra-bold sans, photo-style */}
        <div className="ms-listing-overlay" aria-hidden="true">
          <span className="ms-listing-overlay-status">
            {l.status === 'new' && (
              l.cat === 'sale'
                ? (isKR ? '신축' : 'New Development')
                : (isKR ? '신규' : 'New')
            )}
            {l.status === 'pend' && (isKR ? '계약 진행' : 'Pending')}
            {l.status === 'sold' && (isKR ? '계약 완료' : 'Sold')}
            {!l.status && (isKR ? '매물' : 'Available')}
          </span>
          <span className="ms-listing-overlay-name">
            {l.building || l.place.split(' · ').slice(-1)[0]}
          </span>
        </div>
      </div>
      <div className="meta">
        <p className="place">{l.place}</p>
        <h3 className="title">{isKR ? l.ko : l.title}</h3>
        {l.bedrooms ? (
          <div className="stats">
            <span>{isKR ? l.bedroomsKo : l.bedrooms}</span>
            {l.units && <span>{l.units} {isKR ? '세대' : 'units'}</span>}
            {l.yearBuilt && <span>{isKR ? `${l.yearBuilt}년` : `Built ${l.yearBuilt}`}</span>}
          </div>
        ) : (
          <div className="stats">
            <span>{l.bed === 0 ? (isKR ? '스튜디오' : 'Studio') : `${l.bed} ${isKR ? '베드' : 'bed'}`}</span>
            <span>{l.bath} {isKR ? '바스' : 'bath'}</span>
            <span>{l.sqft.toLocaleString()} sqft</span>
          </div>
        )}
        {l.tags && l.tags.length > 0 && (
          <div className="ms-listing-tags">
            {l.tags.map(t => <span key={t}>{t}</span>)}
          </div>
        )}
        {l.amenities && l.amenities.length > 0 && (
          <div className="ms-listing-tags">
            {l.amenities.slice(0, 4).map(t => <span key={t}>{t}</span>)}
          </div>
        )}
        <p className="price">{formatPrice(l, isKR)}</p>
        {l.courtesy && l.courtesy.length > 0 && (
          <p className="ms-listing-courtesy">
            {isKR ? '제공: ' : 'Listing courtesy of '}
            {l.courtesy.map((c, i) => (
              <React.Fragment key={c.url}>
                {i > 0 && <span aria-hidden="true"> · </span>}
                <a href={c.url} target="_blank" rel="noopener noreferrer" onClick={(e) => e.stopPropagation()}>
                  {c.label}
                </a>
              </React.Fragment>
            ))}
          </p>
        )}
      </div>
    </article>
  );
};

const ListingGrid = ({ onOpen, lang = 'EN', category = 'sale' }) => {
  const isKR = lang === 'KR';
  const isSale = category === 'sale';
  const [active, setActive] = React.useState('all');

  const heading = isSale
    ? (isKR ? '뉴욕 매매 매물' : 'New York · For Sale')
    : (isKR ? '뉴욕 임대 매물' : 'New York · For Rent');

  const inCat = LISTINGS.filter(l => l.cat === (isSale ? 'sale' : 'rent'));
  const filtered = active === 'all'
    ? inCat
    : inCat.filter(l => l.nhood === active);

  return (
    <section className="ms-grid-wrap" data-screen-label={isSale ? 'Sales' : 'Rentals'}>
      <div className="ms-grid-h">
        <div className="ms-grid-titles">
          <p className="ms-grid-eyebrow">{isSale ? (isKR ? '매매' : 'Sale') : (isKR ? '임대' : 'Rent')}</p>
          <h2>{heading}</h2>
        </div>
      </div>

      <div className="ms-nhood-bar" role="tablist" aria-label={isKR ? '동네별 매물' : 'Listings by neighborhood'}>
        <button
          className={"chip-outline" + (active === 'all' ? ' active' : '')}
          onClick={() => setActive('all')}
        >
          {isKR ? '전체' : 'All'}
        </button>
        {REGIONS.map(r => (
          <div key={r.id} className="ms-nhood-region">
            <span className="ms-nhood-region-label">{isKR ? r.ko : r.en}</span>
            <div className="ms-nhood-group">
              {r.nhoods.map(n => (
                <button
                  key={n.id}
                  className={"chip-outline" + (active === n.id ? ' active' : '')}
                  onClick={() => setActive(n.id)}
                >
                  {isKR ? n.ko : n.en}
                </button>
              ))}
            </div>
          </div>
        ))}
      </div>

      <div className="ms-grid">
        {filtered.map(l => <ListingCard key={l.id} l={l} onOpen={onOpen} lang={lang} />)}
      </div>

      {filtered.length === 0 && (
        <p className="ms-grid-empty">
          {isKR
            ? '오늘은 이 블록이 조용하네요. 매주 새로운 매물이 업데이트됩니다 — 찾으시는 조건을 알려주시면 가장 먼저 보여드릴게요.'
            : 'Quiet on this block today. Fresh listings drop weekly — tell me what you\u2019re looking for and I\u2019ll send the right doors first.'}
        </p>
      )}
    </section>
  );
};

const ListingGallery = ({ images = [], building, status, isRent, isKR, place }) => {
  const trackRef = React.useRef(null);
  const [active, setActive] = React.useState(0);
  const hasImages = images.length > 0;
  const slides = hasImages ? images : [null]; // single placeholder slide if no images

  const scrollTo = (i) => {
    const track = trackRef.current;
    if (!track) return;
    const slide = track.children[i];
    if (slide) track.scrollTo({ left: slide.offsetLeft - track.offsetLeft, behavior: 'smooth' });
  };
  const next = () => scrollTo(Math.min(active + 1, slides.length - 1));
  const prev = () => scrollTo(Math.max(active - 1, 0));

  React.useEffect(() => {
    const track = trackRef.current;
    if (!track) return;
    const onScroll = () => {
      const slideWidth = track.children[0]?.offsetWidth || 1;
      const i = Math.round(track.scrollLeft / slideWidth);
      setActive(Math.max(0, Math.min(i, slides.length - 1)));
    };
    track.addEventListener('scroll', onScroll, { passive: true });
    return () => track.removeEventListener('scroll', onScroll);
  }, [slides.length]);

  return (
    <div className="ms-gallery" data-has-images={hasImages}>
      <div className="ms-gallery-track" ref={trackRef}>
        {slides.map((src, i) => (
          <div key={i} className="ms-gallery-slide">
            {src ? (
              <img src={src} alt={`${building || ''} — ${i + 1}`} loading={i === 0 ? 'eager' : 'lazy'} />
            ) : (
              <div className="ms-gallery-placeholder" />
            )}
          </div>
        ))}
      </div>
      <div className="ms-detail-hero-overlay" aria-hidden="true">
        <span className="ms-detail-hero-coming">
          {status === 'new'
            ? (isRent ? (isKR ? '신규' : 'Now showing') : (isKR ? '신축' : 'New Development'))
            : (isKR ? '매물' : 'Available')}
        </span>
        <span className="ms-detail-hero-name">{building || place?.split(' · ').slice(-1)[0]}</span>
      </div>
      {slides.length > 1 && (
        <>
          <button className="ms-gallery-arrow prev" onClick={prev} aria-label={isKR ? '이전' : 'Previous'} disabled={active === 0}>
            <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M15 18l-6-6 6-6"/></svg>
          </button>
          <button className="ms-gallery-arrow next" onClick={next} aria-label={isKR ? '다음' : 'Next'} disabled={active === slides.length - 1}>
            <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M9 18l6-6-6-6"/></svg>
          </button>
          <div className="ms-gallery-dots" role="tablist">
            {slides.map((_, i) => (
              <button
                key={i}
                className={"ms-gallery-dot" + (i === active ? " active" : "")}
                onClick={() => scrollTo(i)}
                aria-label={`${isKR ? '슬라이드' : 'Slide'} ${i + 1}`}
              />
            ))}
          </div>
        </>
      )}
    </div>
  );
};

window.ListingGallery = ListingGallery;

const ListingDetail = ({ l, onBack, onContact, lang = 'EN' }) => {
  const isKR = lang === 'KR';
  const isRent = l.cat === 'rent';
  // Rentals never show street address. Sales show building + neighborhood.
  const headerLine = isRent ? l.place : (l.building || l.place);
  const subLine = isRent ? null : (l.address || null);
  return (
    <section className="ms-detail" data-screen-label="Listing detail">
      <button className="back" onClick={onBack}>
        {isKR ? '← 매물 목록' : '← Back to listings'}
      </button>
      <ListingGallery images={l.images || []} building={l.building} status={l.status} isRent={isRent} isKR={isKR} place={l.place} />
      <div className="ms-detail-grid">
        <div>
          <h1>{isKR ? l.ko : l.title}</h1>
          <p className="ko">
            {headerLine}
            {subLine && <span style={{opacity: 0.6}}> · {subLine}</span>}
          </p>
          <p className="lede">
            {isKR
              ? `${l.place}. 채광 좋은 노출과 차분한 동선, 그리고 평수보다 넓게 사는 평면.`
              : `${l.place}. Bright exposures, considered circulation, and a layout that lives larger than the square footage suggests.`}
          </p>
          <div className="body">
            {(isKR ? l.descriptionKo : l.description) ? (
              (isKR ? l.descriptionKo : l.description).split('\n\n').map((para, i) => (
                <p key={i}>{para}</p>
              ))
            ) : isRent ? (
              isKR ? (
                <>
                  <p>도어맨이 상주하는 신축 건물의 렌탈 유닛입니다. 큰 창과 와이드 플랭크 마루, 빌트인 가전이 갖춰져 있고, 건물 내 피트니스와 라운지를 사용할 수 있습니다.</p>
                  <p>일정에 맞춰 리스 조건을 협의합니다.</p>
                </>
              ) : (
                <>
                  <p>A rental in a full-service building — doorman, fitness, residents' lounge. Floor-to-ceiling windows, wide-plank floors, full appliance package.</p>
                  <p>Flexible move-in. Lease terms tailored to your timeline. Remote coordination available for international clients.</p>
                </>
              )
            ) : (
              isKR ? (
                <>
                  <p>큰 창과 와이드 플랭크 마루, 그리고 천천히 머무를 수 있는 부엌이 있는 신축 콘도입니다. 도어맨, 피트니스, 라운지를 갖춘 풀 서비스 빌딩.</p>
                  <p>실거주뿐 아니라 투자자, 세컨드 홈 매수자에게도 적합합니다 — 일부 빌딩은 세제 혜택, 안정적인 임대 정책, 그리고 리세일 유동성까지 갖춘 매물입니다.</p>
                  <p>해외에 계신 분은 원격 투어와 계약 검토를 진행해 드립니다.</p>
                </>
              ) : (
                <>
                  <p>A new-development residence with floor-to-ceiling windows, wide-plank oak floors, and a kitchen designed for slow mornings. Full-service building: 24-hour doorman, fitness, residents' lounge.</p>
                  <p>Suited for end-users, investors, and pied-à-terre buyers — select buildings carry tax abatements, strong rental policies, and resale liquidity worth examining.</p>
                  <p>Showings are by appointment. Remote coordination available for clients relocating from abroad.</p>
                </>
              )
            )}
          </div>
          {l.courtesy && l.courtesy.length > 0 && (
            <p className="ms-detail-courtesy">
              {isKR ? '본 매물 정보 제공: ' : 'Listing courtesy of '}
              {l.courtesy.map((c, i) => (
                <React.Fragment key={c.url}>
                  {i > 0 && <span aria-hidden="true"> · </span>}
                  <a href={c.url} target="_blank" rel="noopener noreferrer">{c.label}</a>
                </React.Fragment>
              ))}
            </p>
          )}
          {l.saleAvailable && (
            <p className="ms-detail-sale-note">
              {isKR
                ? '※ 같은 단지 내 콘도미니엄 매매도 가능합니다' + (l.taxAbatement ? ` — 일부 세대는 ${l.taxAbatement} 세제 혜택이 적용됩니다.` : '.')
                : '※ Condominium units in the same complex are also available for purchase' + (l.taxAbatement ? ` — select residences carry a ${l.taxAbatement} tax abatement.` : '.')}
            </p>
          )}
          <div style={{ marginTop: 32, display:'flex', gap: 14 }}>
            <button className="btn btn-primary" onClick={onContact}>
              {isKR ? '상담 예약' : (isRent ? 'Schedule a tour' : 'Book a viewing')}
            </button>
            <button className="btn btn-secondary">
              {isKR ? '저장하기' : 'Save listing'}
            </button>
          </div>
        </div>
        <aside className="ms-detail-side">
          <div className="stats">
            {l.bedrooms ? (
              <>
                <div><p className="k">{isKR ? '구성' : 'Bedrooms'}</p><p className="v">{isKR ? l.bedroomsKo : l.bedrooms}</p></div>
                {l.units && <div><p className="k">{isKR ? '세대 수' : 'Units'}</p><p className="v">{l.units}</p></div>}
                {l.yearBuilt && <div><p className="k">{isKR ? '준공' : 'Year built'}</p><p className="v">{l.yearBuilt}</p></div>}
                <div><p className="k">{isKR ? '유형' : 'Type'}</p><p className="v">{l.type}</p></div>
                <div><p className="k">{l.cat === 'rent' ? (isKR ? '시작 월세' : 'Starting rent') : (isKR ? '시작가' : 'Starting price')}</p><p className="v">{l.pricingOnRequest ? (isKR ? '가격 문의' : 'On request') : (l.cat === 'rent' ? `$${l.startingPrice.toLocaleString()}${isKR ? ' / 월' : ' / mo'}` : `$${l.startingPrice.toLocaleString()}`)}</p></div>
              </>
            ) : (
              <>
                <div><p className="k">{isKR ? '베드' : 'Bedrooms'}</p><p className="v">{l.bed === 0 ? (isKR ? '스튜디오' : 'Studio') : l.bed}</p></div>
                <div><p className="k">{isKR ? '바스' : 'Bathrooms'}</p><p className="v">{l.bath}</p></div>
                <div><p className="k">{isKR ? '면적' : 'Interior'}</p><p className="v">{l.sqft.toLocaleString()} ft²</p></div>
                <div><p className="k">{isKR ? '유형' : 'Type'}</p><p className="v">{l.type}</p></div>
                {l.cat === 'rent' && <div><p className="k">{isKR ? '리스' : 'Lease'}</p><p className="v">{isKR ? '12–24개월' : '12–24 months'}</p></div>}
                <div><p className="k">{l.cat === 'rent' ? (isKR ? '월세' : 'Rent') : (isKR ? '매매가' : 'List price')}</p><p className="v">{formatPrice(l, isKR)}</p></div>
              </>
            )}
          </div>
          {l.amenities && l.amenities.length > 0 && (
            <>
              <p style={{ fontFamily: 'var(--font-sans)', fontSize: 11, letterSpacing: '0.32em', textTransform: 'uppercase', color: 'var(--fg-muted)', margin: '24px 0 12px' }}>
                {isKR ? '편의시설' : 'Amenities'}
              </p>
              <ul style={{ listStyle:'none', padding:0, margin:0, display:'flex', flexDirection:'column', gap: 8 }}>
                {l.amenities.map(a => (
                  <li key={a} style={{ fontFamily: 'var(--font-sans)', fontSize: 14, color: 'var(--fg-default)' }}>· {a}</li>
                ))}
              </ul>
            </>
          )}
        </aside>
      </div>
    </section>
  );
};

window.ListingGrid = ListingGrid;
window.ListingDetail = ListingDetail;
window.ListingCard = ListingCard;
window.LISTINGS = LISTINGS;
window.REGIONS = REGIONS;
