// pages/discover.jsx — 探索貓人力: 依「大分類 / 服務區域 / 服務項目」找到適合的貓人力。
// 三種篩選都遵循專案慣例：選擇一律在獨立的 bottom sheet 完成，不在當頁原地展開。
const { useState } = React;

// 大分類（expert_category）— 呼應貓人力端 profile 設定的專長。每類帶可篩選的服務項目。
const CATEGORIES = [
  { key: 'sitter',   label: '貓保母',   icon: 'paw',      color: 'brand',  desc: '到府餵食、清貓砂、住宿托管，出門安心交給專人', services: ['到府餵食', '清貓砂', '住宿托管', '餵藥', '陪玩', '每日回報'] },
  { key: 'behavior', label: '行為諮詢', icon: 'heart',    color: 'rose',   desc: '貓亂叫、亂尿、打架、分離焦慮？交給專業諮詢師',   services: ['亂叫', '亂尿', '攻擊行為', '分離焦慮', '多貓關係', '緊張怕生'] },
  { key: 'groom',    label: '美容',     icon: 'scissors', color: 'butter', soon: true, desc: '洗澡、剪指甲、剃毛，溫柔對待每一隻貓',           services: ['洗澡', '剪指甲', '剃毛', '清耳朵', '美容造型'] },
  { key: 'vet',      label: '到府獸醫', icon: 'drop',     color: 'sage',   soon: true, desc: '到府健檢、打疫苗、慢性病追蹤，免出門',           services: ['健康檢查', '打疫苗', '慢性病追蹤', '採血', '餵藥指導'] },
];

// 服務區域（單選縣市 + 單選行政區）— 對應貓人力 profile.jsx 設定的服務地區
const REGIONS = {
  '台北市': ['全區', '中正', '大同', '中山', '松山', '大安', '萬華', '信義', '士林', '北投', '內湖', '南港', '文山'],
  '新北市': ['全區', '板橋', '三重', '中和', '永和', '新莊', '新店', '土城', '蘆洲', '汐止', '樹林', '三峽'],
  '桃園市': ['全區', '桃園', '中壢', '平鎮', '八德', '龜山', '蘆竹', '大溪', '楊梅', '龍潭'],
  '台中市': ['全區', '中區', '東區', '南區', '西區', '北區', '北屯', '西屯', '南屯', '太平', '大里'],
};

const SORTS = [['recommend', '寵答推薦'], ['rating', '評分最高'], ['price', '價格由低到高']];
const PAGE_SIZE = 5; // 每頁載入筆數（貓人力資料量大時分批載入，避免一次塞滿）

const distLabel = x => x === '全區' ? '全區' : x + '區';
const regionSummary = r => `${r.city}·${distLabel(r.district)}`;
const locOf = p => p.online ? '線上諮詢' : (p.districts.includes('全區') ? p.city + ' 全區' : p.districts.slice(0, 2).join('、'));

// ---- shared sheet primitives ----
const sheetGhostBtn   = { flex: 1, padding: '13px', borderRadius: 'var(--rmd)', border: '1.5px solid var(--line)', background: 'var(--surface)', color: 'var(--ink2)', fontFamily: 'inherit', fontSize: 14.5, fontWeight: 800, cursor: 'pointer' };
const sheetPrimaryBtn = { flex: 2, padding: '13px', borderRadius: 'var(--rmd)', border: 'none', background: 'var(--accent)', color: '#fff', fontFamily: 'inherit', fontSize: 14.5, fontWeight: 800, cursor: 'pointer' };

const SheetLabel = ({ children, style }) => A('div', { style: { fontSize: 11.5, fontWeight: 800, color: 'var(--ink3)', marginBottom: 9, ...style } }, children);
const ChipWrap = ({ children }) => A('div', { style: { display: 'flex', flexWrap: 'wrap', gap: 8 } }, children);
const selChip = (label, sel, onClick, withCheck) => A('button', { key: label, className: 'ccaTap', onClick, style: {
  display: 'flex', alignItems: 'center', gap: 5, padding: '9px 14px', borderRadius: 'var(--rpill)', border: 'none',
  fontFamily: 'inherit', fontSize: 13.5, fontWeight: 700, cursor: 'pointer',
  background: sel ? 'var(--accent)' : 'var(--bgSoft)', color: sel ? '#fff' : 'var(--ink2)',
  boxShadow: sel ? 'none' : 'inset 0 0 0 1px var(--line2)' } },
  withCheck && sel && A(Icon, { name: 'check', size: 13, color: '#fff', sw: 2.6 }), label);

// loading placeholder shown while the next page streams in
const SkeletonCard = () => A('div', { style: { display: 'flex', gap: 12, padding: 13, borderRadius: 'var(--rlg)', border: '1px solid var(--line2)', background: 'var(--surface)' } },
  A('div', { className: 'ccaPulse', style: { width: 56, height: 56, borderRadius: 16, background: 'var(--bgSoft)', flexShrink: 0 } }),
  A('div', { style: { flex: 1, display: 'flex', flexDirection: 'column', gap: 9, paddingTop: 5 } },
    A('div', { className: 'ccaPulse', style: { width: '42%', height: 13, borderRadius: 6, background: 'var(--bgSoft)' } }),
    A('div', { className: 'ccaPulse', style: { width: '68%', height: 11, borderRadius: 6, background: 'var(--bgSoft)' } }),
    A('div', { className: 'ccaPulse', style: { width: '54%', height: 11, borderRadius: 6, background: 'var(--bgSoft)' } })));

// bottom-sheet shell: backdrop + slide-up panel (sticky title + scroll body + footer)
function FilterSheet({ title, onClose, children, footer }) {
  return A('div', { style: { position: 'absolute', inset: 0, zIndex: 50, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end' } },
    A('div', { onClick: onClose, style: { position: 'absolute', inset: 0, background: 'rgba(46,31,20,.5)', backdropFilter: 'blur(2px)' } }),
    A('div', { className: 'ccaPop', style: { position: 'relative', background: 'var(--surface)', borderRadius: '26px 26px 0 0', boxShadow: '0 -12px 44px rgba(0,0,0,.22)', maxHeight: '82%', display: 'flex', flexDirection: 'column' } },
      A('div', { style: { padding: '10px 22px 4px', flexShrink: 0 } },
        A('div', { style: { width: 38, height: 4, borderRadius: 2, background: 'var(--line)', margin: '0 auto 14px' } }),
        A('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 } },
          A('h2', { style: { fontSize: 18, fontWeight: 800, margin: 0, letterSpacing: -0.3 } }, title),
          A('button', { className: 'ccaTap', onClick: onClose, style: { width: 32, height: 32, borderRadius: '50%', border: 'none', background: 'var(--bgSoft)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--ink2)' } }, A(Icon, { name: 'x', size: 16, sw: 2.2 })))),
      A('div', { style: { overflowY: 'auto', padding: '6px 22px 6px' } }, children),
      footer && A('div', { style: { flexShrink: 0, padding: '12px 22px 22px', borderTop: '1px solid var(--line2)', display: 'flex', gap: 10 } }, footer)));
}

// 區域 sheet：縣市單選 + 行政區單選
function RegionSheet({ region, onApply, onClose }) {
  const [d, setD] = useState(region);
  return A(FilterSheet, { title: '選擇服務區域', onClose, footer: [
    A('button', { key: 'a', className: 'ccaTap', onClick: () => onApply({ city: d.city, district: '全區' }), style: sheetGhostBtn }, '全區'),
    A('button', { key: 'b', className: 'ccaTap', onClick: () => onApply(d), style: sheetPrimaryBtn }, '套用') ] },
    A(SheetLabel, null, '縣市 · 單選'),
    A(ChipWrap, null, Object.keys(REGIONS).map(c => selChip(c, c === d.city, () => setD({ city: c, district: '全區' })))),
    A(SheetLabel, { style: { marginTop: 18 } }, '行政區 · 單選'),
    A(ChipWrap, null, (REGIONS[d.city] || []).map(x => selChip(distLabel(x), x === d.district, () => setD({ city: d.city, district: x }), x !== '全區'))));
}

// 服務項目 sheet：依目前分類顯示可選項目（多選）。全部分類時分區段列出。
function ServiceSheet({ cat, selected, onApply, onClose }) {
  const [sel, setSel] = useState(selected);
  const groups = cat === 'all' ? CATEGORIES : CATEGORIES.filter(c => c.key === cat);
  const toggle = s => setSel(p => p.includes(s) ? p.filter(x => x !== s) : [...p, s]);
  return A(FilterSheet, { title: '服務項目', onClose, footer: [
    A('button', { key: 'a', className: 'ccaTap', onClick: () => setSel([]), style: sheetGhostBtn }, '清除'),
    A('button', { key: 'b', className: 'ccaTap', onClick: () => onApply(sel), style: sheetPrimaryBtn }, sel.length ? `套用（${sel.length}）` : '套用') ] },
    groups.map((c, i) => A('div', { key: c.key, style: { marginBottom: i === groups.length - 1 ? 6 : 18 } },
      A(SheetLabel, null, c.label),
      A(ChipWrap, null, c.services.map(s => selChip(s, sel.includes(s), () => toggle(s), true))))));
}

// 排序 sheet：單選，點選即套用
function SortSheet({ sort, onApply, onClose }) {
  return A(FilterSheet, { title: '排序方式', onClose },
    A('div', { style: { display: 'flex', flexDirection: 'column', paddingBottom: 10 } },
      SORTS.map(([k, l], i) => A('button', { key: k, className: 'ccaTap', onClick: () => onApply(k), style: {
        display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%', padding: '15px 4px',
        border: 'none', borderBottom: i < SORTS.length - 1 ? '1px solid var(--line2)' : 'none', background: 'transparent',
        fontFamily: 'inherit', fontSize: 15, fontWeight: 700, color: sort === k ? 'var(--accentDeep)' : 'var(--ink)', cursor: 'pointer' } },
        l, sort === k && A(Icon, { name: 'check', size: 19, color: 'var(--accent)', sw: 2.4 })))));
}

// 即將開放的分類（soon）：僅顯示預告，不列出服務者
function ComingSoon({ catDef }) {
  const ic = catDef.color === 'butter' ? '#9A6B12' : `var(--${catDef.color})`;
  return A('div', { style: { textAlign: 'center', padding: '48px 28px 24px' } },
    A('div', { style: { width: 88, height: 88, borderRadius: 26, background: `var(--${catDef.color}Soft)`, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 18px', color: ic } }, A(Icon, { name: catDef.icon, size: 40, sw: 1.7 })),
    A('div', { style: { display: 'flex', justifyContent: 'center', marginBottom: 12 } }, A(Tag, { color: 'butter', icon: 'clock' }, '即將開放')),
    A('h2', { style: { fontSize: 19, fontWeight: 800, margin: '0 0 8px', letterSpacing: -0.3 } }, `${catDef.label}服務即將開放`),
    A('p', { style: { fontSize: 13.5, color: 'var(--ink2)', lineHeight: 1.7, margin: '0 auto', maxWidth: 264 } }, `${catDef.desc}`));
}

function Explore({ onNav = () => {}, go = () => {}, variant = 'notch' }) {
  const [cat, setCat] = useState('all');
  const [region, setRegion] = useState({ city: '台北市', district: '全區' });
  const [services, setServices] = useState([]);
  const [sort, setSort] = useState('recommend');
  const [sheet, setSheet] = useState(null);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(false);

  const catDef = CATEGORIES.find(c => c.key === cat);
  const soon = !!(catDef && catDef.soon); // 選到尚未開放的分類
  const pickCat = k => { setCat(k); setServices([]); };

  const openCat = c => !(CATEGORIES.find(x => x.key === c) || {}).soon;
  let list = PROVIDERS.filter(p => {
    if (!openCat(p.category)) return false; // 尚未開放的分類不列入清單（含「全部」）
    if (cat !== 'all' && p.category !== cat) return false;
    if (!p.online) {
      if (p.city !== region.city) return false;
      if (region.district !== '全區' && !p.districts.includes(region.district) && !p.districts.includes('全區')) return false;
    }
    if (services.length && !services.some(s => p.services.includes(s))) return false;
    return true;
  });
  list = [...list].sort((a, b) =>
    sort === 'rating' ? b.rating - a.rating : sort === 'price' ? a.price - b.price : (Number(b.ai) - Number(a.ai)) || (b.rating - a.rating));

  // 分頁載入：捲到接近底部就載入下一頁；篩選條件變動時回到第一頁
  const filterKey = `${cat}|${region.city}|${region.district}|${services.join(',')}|${sort}`;
  React.useEffect(() => { setPage(1); setLoading(false); }, [filterKey]);
  const visible = list.slice(0, page * PAGE_SIZE);
  const hasMore = visible.length < list.length;
  const onScroll = e => {
    if (loading || !hasMore) return;
    const el = e.target;
    if (el.scrollHeight - el.scrollTop - el.clientHeight < 140) {
      setLoading(true);
      setTimeout(() => { setPage(p => p + 1); setLoading(false); }, 450);
    }
  };

  const hasFilter = cat !== 'all' || region.district !== '全區' || services.length > 0;
  const clearAll = () => { setCat('all'); setRegion(r => ({ city: r.city, district: '全區' })); setServices([]); };

  // filter trigger pill → opens a bottom sheet
  const trigger = (icon, label, active, onClick, badge) => A('button', { className: 'ccaTap', onClick, style: {
    display: 'inline-flex', alignItems: 'center', gap: 6, padding: '8px 13px', borderRadius: 'var(--rpill)', border: 'none', flexShrink: 0,
    fontFamily: 'inherit', fontSize: 13, fontWeight: 700, cursor: 'pointer',
    background: active ? 'var(--accentSoft)' : 'var(--surface)', color: active ? 'var(--accentDeep)' : 'var(--ink2)',
    boxShadow: active ? 'inset 0 0 0 1.5px var(--accent)' : 'inset 0 0 0 1px var(--line)' } },
    A(Icon, { name: icon, size: 15, sw: 2 }), label,
    badge ? A('span', { style: { background: 'var(--accent)', color: '#fff', fontSize: 10.5, fontWeight: 800, minWidth: 16, height: 16, borderRadius: 8, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', padding: '0 4px' } }, badge) : null,
    A(Icon, { name: 'chevD', size: 14, sw: 2 }));

  return A('div', { style: { flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0 } },
    // ---- header + functional search ----
    A('div', { style: { padding: '4px 20px 12px', flexShrink: 0 } },
      A('h1', { style: { fontSize: 24, fontWeight: 800, letterSpacing: -0.5, margin: '4px 0 2px' } }, '探索貓人力'),
      A('p', { style: { fontSize: 12.5, color: 'var(--ink3)', margin: 0 } }, '找到最適合你家貓咪的照顧者')),
    // ---- 大分類 pills (primary axis) ----
    A('div', { style: { display: 'flex', gap: 8, overflowX: 'auto', padding: '0 20px 10px', flexShrink: 0 } },
      A(Chip, { active: cat === 'all', onClick: () => pickCat('all') }, '全部'),
      CATEGORIES.map(c => A(Chip, { key: c.key, icon: c.icon, active: cat === c.key, onClick: () => pickCat(c.key) },
        c.label,
        c.soon && A('span', { key: 'soon', style: { fontSize: 9.5, fontWeight: 800, padding: '1px 5px', borderRadius: 999, background: 'var(--butterSoft)', color: '#9A6B12', marginLeft: 2 } }, '即將')))),
    // contextual category blurb (open categories only)
    catDef && !soon && A('div', { style: { padding: '0 20px 10px', flexShrink: 0 } },
      A('div', { style: { fontSize: 12.5, color: 'var(--ink2)', background: `var(--${catDef.color}Soft)`, borderRadius: 'var(--rmd)', padding: '9px 13px', lineHeight: 1.5 } }, catDef.desc)),
    // ---- 區域 / 服務項目 / 排序 triggers (hidden for not-yet-open categories) ----
    !soon && A('div', { style: { display: 'flex', gap: 8, overflowX: 'auto', padding: '0 20px 12px', flexShrink: 0 } },
      trigger('pin', regionSummary(region), region.district !== '全區', () => setSheet('region')),
      trigger('sliders', '服務項目', services.length > 0, () => setSheet('service'), services.length || null),
      trigger('swap', SORTS.find(s => s[0] === sort)[1], false, () => setSheet('sort'))),
    // ---- results ----
    A(Scroll, { onScroll: soon ? undefined : onScroll, style: { padding: '2px 20px 16px' } },
      soon ? A(ComingSoon, { catDef }) : A(React.Fragment, null,
      A('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', margin: '2px 2px 12px' } },
        A('div', { style: { fontSize: 13, color: 'var(--ink2)', fontWeight: 700 } }, '找到 ', A('span', { className: 'num' }, list.length), ' 位貓人力'),
        hasFilter && A('button', { className: 'ccaTap', onClick: clearAll, style: { border: 'none', background: 'transparent', fontFamily: 'inherit', fontSize: 12.5, fontWeight: 700, color: 'var(--accentDeep)', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 3 } },
          A(Icon, { name: 'x', size: 13, sw: 2.4 }), '清除篩選')),
      // removable active service chips
      services.length > 0 && A('div', { style: { display: 'flex', flexWrap: 'wrap', gap: 7, marginBottom: 14 } },
        services.map(s => A('button', { key: s, className: 'ccaTap', onClick: () => setServices(p => p.filter(x => x !== s)), style: { display: 'inline-flex', alignItems: 'center', gap: 5, padding: '6px 12px', borderRadius: 'var(--rpill)', border: 'none', background: 'var(--accentSoft)', color: 'var(--accentDeep)', fontFamily: 'inherit', fontSize: 12.5, fontWeight: 700, cursor: 'pointer' } }, s, A(Icon, { name: 'x', size: 13, sw: 2.4 })))),
      // list or empty state
      list.length
        ? A(React.Fragment, null,
            A('div', { style: { display: 'flex', flexDirection: 'column', gap: 12 } },
              visible.map(p => A(ProviderCard, { key: p.id, p, loc: locOf(p), onClick: () => go('providerDetail') })),
              loading && [0, 1].map(i => A(SkeletonCard, { key: 'sk' + i }))),
            !hasMore && A('div', { style: { textAlign: 'center', fontSize: 12, color: 'var(--ink3)', padding: '20px 0 4px' } }, `已顯示全部 ${list.length} 位貓人力 🐾`))
        : A('div', { style: { textAlign: 'center', padding: '44px 20px', color: 'var(--ink3)' } },
            A('div', { style: { width: 64, height: 64, borderRadius: 20, background: 'var(--bgSoft)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 16px', color: 'var(--neutral)' } }, A(Icon, { name: 'search', size: 28 })),
            A('div', { style: { fontSize: 15, fontWeight: 700, color: 'var(--ink2)', marginBottom: 6 } }, '找不到符合的貓人力'),
            A('div', { style: { fontSize: 13, lineHeight: 1.6, marginBottom: 16 } }, '試試擴大區域、減少服務項目，或換個分類'),
            A(Btn, { variant: 'soft', size: 'md', onClick: clearAll }, '清除所有篩選')))),
    // ---- sheets ----
    sheet === 'region' && A(RegionSheet, { region, onApply: r => { setRegion(r); setSheet(null); }, onClose: () => setSheet(null) }),
    sheet === 'service' && A(ServiceSheet, { cat, selected: services, onApply: s => { setServices(s); setSheet(null); }, onClose: () => setSheet(null) }),
    sheet === 'sort' && A(SortSheet, { sort, onApply: s => { setSort(s); setSheet(null); }, onClose: () => setSheet(null) }),
    A(BottomNavOwner, { active: 'explore', onNav, variant }));
}

Object.assign(window, { Explore });
