window.SPOTURE_REGIONS = [
  { key: 'seoul', city: '서울', country: '대한민국', domestic: true },
  { key: 'busan', city: '부산', country: '대한민국', domestic: true },
  { key: 'tokyo', city: '도쿄', country: '일본' },
  { key: 'osaka', city: '오사카', country: '일본' },
  { key: 'fukuoka', city: '후쿠오카', country: '일본' },
  { key: 'taipei', city: '타이베이', country: '대만' },
  { key: 'bangkok', city: '방콕', country: '태국' },
  { key: 'danang', city: '다낭', country: '베트남' },
  { key: 'paris', city: '파리', country: '프랑스' },
  { key: 'newyork', city: '뉴욕', country: '미국' }
];
window.SPOTURE_REGION = (key) => {
  if (key && key.indexOf('custom:') === 0) { const city = key.slice(7); return { key: key, city: city || '직접 입력한 지역', country: '직접 입력', custom: true }; }
  return window.SPOTURE_REGIONS.find(r => r.key === key) || window.SPOTURE_REGIONS[0];
};
window.SPOTURE_MANY_BRANCHES = (list, q) => {
  if (!q || !list || list.length < 2) return false;
  const counts = {};
  list.forEach(p => { const k = (p.name || '').split(' ')[0]; counts[k] = (counts[k] || 0) + 1; });
  return Object.keys(counts).some(k => counts[k] >= 2) || list.length >= 4;
};
window.SPOTURE_PLACES_BY_REGION = {
  seoul: [
    { name: '할매순대국 강남점', category: '한식', area: '역삼동' },
    { name: '역삼동 국밥집', category: '한식', area: '역삼동' },
    { name: '청년다방 역삼점', category: '분식', area: '역삼동' },
    { name: '우나기야 역삼', category: '일식', area: '역삼동' }
  ],
  busan: [
    { name: '초량밀면', category: '면요리', area: '동구' },
    { name: '해운대 소문난암소갈비집', category: '한식', area: '해운대구' }
  ],
  tokyo: [
    { name: '이치란 시부야점', category: '라멘', area: '시부야' },
    { name: '츠타 소바 긴자', category: '라멘', area: '긴자' },
    { name: '스시잔마이 츠키지', category: '스시', area: '츠키지' },
    { name: '카페 드 람브르', category: '카페', area: '긴자' }
  ],
  osaka: [
    { name: '쿠시카츠 다루마 도톤보리', category: '쿠시카츠', area: '도톤보리' },
    { name: '이치란 도톤보리점', category: '라멘', area: '도톤보리' },
    { name: '하리주 신사이바시', category: '스키야키', area: '신사이바시' }
  ],
  fukuoka: [
    { name: '이치란 라멘 본점', category: '라멘', area: '나카스' },
    { name: '모츠나베 오오야마', category: '나베', area: '하카타역' }
  ],
  taipei: [
    { name: '딘타이펑 신이본점', category: '딤섬', area: '신이구' },
    { name: '아종면선', category: '면요리', area: '시먼딩' }
  ],
  bangkok: [
    { name: '제이 파이', category: '태국식', area: '방람푸' },
    { name: '쏨분 씨푸드', category: '씨푸드', area: '수라웡' }
  ],
  danang: [
    { name: '반쎄오 바즈엉', category: '베트남', area: '하이쩌우' },
    { name: '미꽝 1A', category: '베트남', area: '하이쩌우' }
  ],
  paris: [
    { name: '셉띰', category: '비스트로', area: '11구' },
    { name: '뒤 팽 에 데 지데', category: '베이커리', area: '11구' }
  ],
  newyork: [
    { name: '카츠 델리카트슨', category: '델리', area: '로어이스트' },
    { name: '조스 피자', category: '피자', area: '그리니치빌리지' }
  ]
};

function RegionPickerSheet({ current, onClose, onPick }) {
  const { BottomSheet, Button } = window.SpotureDesignSystem_f7ad96;
  const params = new URLSearchParams(location.search);
  const [q, setQ] = React.useState(params.get('regq') || '');
  const all = window.SPOTURE_REGIONS;
  const norm = (s) => (s || '').replace(/\s/g, '');
  const hit = (r) => norm(r.city + r.country).includes(norm(q));
  const results = q ? all.filter(hit) : [];
  const recentKeys = ['seoul', 'tokyo'];
  const custom = current && current.indexOf('custom:') === 0 ? window.SPOTURE_REGION(current) : null;
  const recent = (custom ? [custom] : []).concat(recentKeys.map(k => all.find(r => r.key === k)));
  const abroad = all.filter(r => !r.domestic && recentKeys.indexOf(r.key) < 0);
  const Row = ({ r }) => {
    const on = r.key === current;
    return (
      <div onClick={() => onPick && onPick(r.key)} style={{ display: 'flex', alignItems: 'center', gap: 12, background: on ? 'var(--bg-accent)' : 'var(--surface-2)', border: '1.5px solid ' + (on ? 'var(--text-accent)' : 'transparent'), borderRadius: 'var(--radius-tile)', padding: '13px 14px', cursor: 'pointer' }}>
        <div style={{ width: 36, height: 36, borderRadius: 12, flexShrink: 0, background: 'var(--surface-1)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><i className={r.domestic ? 'ti ti-map-pin' : 'ti ti-world'} style={{ fontSize: 17, color: on ? 'var(--text-accent)' : 'var(--text-secondary)' }}></i></div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <span style={{ font: 'var(--text-body-strong)', display: 'block', marginBottom: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.city}</span>
          <span style={{ font: 'var(--text-small)', color: 'var(--text-secondary)' }}>{r.country}</span>
        </div>
        {on && <i className="ti ti-check" style={{ fontSize: 17, color: 'var(--text-accent)', flexShrink: 0 }}></i>}
      </div>
    );
  };
  return (
    <BottomSheet title="지역 선택" titleAside={<span style={{ font: 'var(--text-small)', color: 'var(--text-muted)' }}>검색 범위</span>} onClose={onClose}>
      <p style={{ font: 'var(--text-caption)', color: 'var(--text-secondary)', margin: '0 0 14px', lineHeight: 1.6 }}>사진에 위치 정보가 없어 자동으로 알 수 없어요. 사진을 찍은 도시를 골라주면 그 도시에서만 검색해요.</p>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, background: 'var(--surface-1)', border: '1px solid var(--border)', borderRadius: 'var(--radius-chip)', padding: '13px 16px', marginBottom: 16 }}>
        <i className="ti ti-search" style={{ fontSize: 17, color: 'var(--text-muted)', flexShrink: 0 }}></i>
        <input value={q} onChange={ev => setQ(ev.target.value)} placeholder="도시 · 국가 검색" style={{ flex: 1, minWidth: 0, border: 'none', outline: 'none', background: 'transparent', font: 'var(--text-body)', color: 'var(--text-primary)', fontFamily: 'var(--font-family)' }} />
        {q && <i className="ti ti-x" onClick={() => setQ('')} style={{ fontSize: 16, color: 'var(--text-muted)', cursor: 'pointer', flexShrink: 0 }}></i>}
      </div>
      {q ? (
        <div>
          <span style={{ font: 'var(--text-body-strong)', display: 'block', marginBottom: 10 }}>검색 결과 <span style={{ font: 'var(--text-small)', color: 'var(--text-muted)' }}>{results.length}곳</span></span>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {results.map(r => <Row key={r.key} r={r} />)}
            {results.length === 0 && (
              <div style={{ textAlign: 'center', padding: '26px 0 0' }}>
                <i className="ti ti-world-off" style={{ fontSize: 30, color: 'var(--text-muted)' }}></i>
                <p style={{ font: 'var(--text-caption)', color: 'var(--text-secondary)', margin: '10px 0 16px', lineHeight: 1.6 }}>도시 목록에서 「{q}」를 찾지 못했어요<br />적은 이름으로 그대로 검색할 수 있어요</p>
                <Button variant="primary" size="sm" onClick={() => onPick && onPick('custom:' + q.trim())}><i className="ti ti-world-search" style={{ fontSize: 16 }}></i>{'「' + q.trim() + '」로 검색하기'}</Button>
                <p style={{ font: 'var(--text-micro)', color: 'var(--text-muted)', margin: '10px 0 0', lineHeight: 1.6 }}>등록된 가게가 없으면 장소를 직접 등록하면 되어요</p>
              </div>
            )}
          </div>
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <div>
            <span style={{ font: 'var(--text-body-strong)', display: 'block', marginBottom: 10 }}>최근 사용한 지역</span>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>{recent.map(r => <Row key={r.key} r={r} />)}</div>
          </div>
          <div>
            <span style={{ font: 'var(--text-body-strong)', display: 'block', marginBottom: 10 }}>해외에서 많이 찾는 도시</span>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>{abroad.map(r => <Row key={r.key} r={r} />)}</div>
          </div>
        </div>
      )}
    </BottomSheet>
  );
}
window.RegionPickerSheet = RegionPickerSheet;
