// pages/pro-order-manager.jsx — 預約單管理: tabbed (待接 / 已接 / 完成 / 取消) order management for 貓人力.
// Entry from 工作台. The 待接 card supports accept/reject; other tabs show status + outcome.
const { useState: uSOM } = React;

const OM_ORDERS = [
  // 待接 pending
  { id: 'o1', owner: '王小美', dates: ['6/4（三）', '6/5（四）', '6/6（五）'], time: '09:00–10:00', area: '大安區', status: 'pending',
    cats: [['小橘', '到府餵食 ×3、清貓砂、餵藥服務', '親人愛撒嬌但怕生，第一次見面動作放慢；每日早晚各餵藥一次，藥放冰箱第二層'], ['麻糬', '到府餵食 ×1', '愛喝流動的水，記得幫忙開飲水機']],
    meta: [['calendar', '每日 09:00 · 連續 3 天'], ['pin', '台北市大安區復興南路一段 1 號 5 樓']], access: '門禁密碼 1234#，鑰匙放鞋櫃', income: '$1,260' },
  { id: 'o2', owner: '李先生', dates: ['6/8（日）'], time: '14:00–15:00', area: '信義區', status: 'pending',
    cats: [['黑嚕 · 公', '清貓砂 + 換水、陪玩 30 分', '精力旺盛，多陣逆貓棒他會很開心']],
    meta: [['calendar', '6/8（日）14:00 · 單次'], ['pin', '台北市信義區松高路 11 號 8 樓']], income: '$350' },
  // 已接 accepted
  { id: 'o3', owner: '張小姐', dates: ['6/3（二）'], time: '18:30–19:00', area: '中山區', status: 'accepted',
    cats: [['布丁 · 母', '到府餵食 ×1', '吃飯慢，請耐心等她吃完再收碗']],
    meta: [['calendar', '6/3（二）18:30 · 單次'], ['pin', '台北市中山區南京東路二段 20 號']], access: '大樓門禁卡於管理室代領，按 8 樓', income: '$420' },
  { id: 'o4', owner: '陳先生', dates: ['6/5（四）', '6/6（五）'], time: '10:00–11:00', area: '松山區', status: 'accepted',
    cats: [['橘子 · 公', '到府餵食 ×2', '不愛被抱，擺好飯就可以'], ['奶茶 · 母', '清貓砂 + 換水', '砂盆要勤鏟，她很愛乾淨']],
    meta: [['calendar', '每日 10:00 · 連續 2 天'], ['pin', '台北市松山區八德路四段 100 號']], access: '鑰匙藏門口地墊下，密碼鎖 5678', income: '$980' },
  // 完成 done
  { id: 'o5', owner: '林太太', dates: ['5/28（三）'], time: '11:00–12:00', area: '大安區', status: 'done', rating: 5,
    cats: [['咪咪 · 母', '到府餵食 ×1、陪玩 30 分', '喜歡逗貓棒，玩 10 分鐘就好']],
    meta: [['calendar', '5/28（三）11:00 · 已完成'], ['pin', '台北市大安區敦化南路一段 5 號']], income: '$620' },
  { id: 'o6', owner: '黃先生', dates: ['5/20（二）', '5/21（三）', '5/22（四）'], time: '08:30–09:30', area: '信義區', status: 'done', rating: 4,
    cats: [['可樂 · 公', '到府餵食 ×3、清貓砂', '要吾需要多陶陶，他會回應']],
    meta: [['calendar', '每日 08:30 · 已完成'], ['pin', '台北市信義區忠孝東路五段 8 號']], income: '$1,410' },
  // 取消 cancelled
  { id: 'o7', owner: '吳小姐', dates: ['5/15（四）'], time: '19:00–19:30', area: '中正區', status: 'cancelled', reason: '飼主臨時取消',
    cats: [['湯圓 · 母', '到府餵食 ×1', '不挑食，但要換新鮮的水']],
    meta: [['calendar', '5/15（四）19:00 · 已取消'], ['pin', '台北市中正區羅斯福路三段 30 號']], income: '$420' },
];

const OM_TABS = [['pending', '待接'], ['accepted', '已接'], ['done', '完成'], ['cancelled', '取消']];
const OM_TAGS = {
  pending: ['warn', 'clock', '待回覆'], accepted: ['ok', 'check', '已接受'],
  done: ['sage', 'check', '已完成'], cancelled: ['ink', 'x', '已取消'],
};

// 列表＝分流卡：只回答「要不要接」。整張卡可點 → 詳情（go('job')）看「接了要做什麼」。
function OMOrderCard({ order, go = () => {} }) {
  const [req, setReq] = uSOM(order.status); // pending tab: pending → accepted | rejected
  const status = order.status === 'pending' ? req : order.status;
  const [tc, ti, tl] = OM_TAGS[status] || OM_TAGS.pending;
  const doneLike = status === 'done' || status === 'cancelled';
  const stop = (fn) => (e) => { e.stopPropagation(); fn(); };
  return A(Card, { pad: 0, style: { overflow: 'hidden', opacity: status === 'cancelled' ? 0.78 : 1 } },
    // tappable body → 詳情
    A('div', { className: 'ccaTap', onClick: () => go('job'), style: { padding: 16, cursor: 'pointer' } },
      // 飼主 + 狀態標籤
      A('div', { style: { display: 'flex', gap: 12, alignItems: 'center' } },
        A(Avatar, { size: 44, kind: 'person', style: { borderRadius: 13 } }),
        A('div', { style: { flex: 1, minWidth: 0 } }, A('div', { style: { fontSize: 15, fontWeight: 700 } }, order.owner)),
        A(Tag, { color: tc, icon: ti }, tl)),
      // 時間 / 區域（分行顯示，日期逐日列出不縮減）
      A('div', { style: { display: 'flex', flexDirection: 'column', gap: 8, marginTop: 13 } },
        A('div', { style: { display: 'flex', gap: 7, alignItems: 'flex-start', fontSize: 13, color: 'var(--ink2)' } },
          A(Icon, { name: 'calendar', size: 16, color: 'var(--sage)', style: { flexShrink: 0, marginTop: 2 } }),
          A('div', { style: { display: 'flex', flexDirection: 'column', gap: 3 } },
            order.dates.map((d, i) => A('span', { key: i, style: { lineHeight: 1.4, whiteSpace: 'nowrap' } }, `${d} · ${order.time}`)))),
        A('div', { style: { display: 'flex', gap: 7, alignItems: 'center', fontSize: 13, color: 'var(--ink2)' } },
          A(Icon, { name: 'pin', size: 16, color: 'var(--sage)', style: { flexShrink: 0 } }), A('span', { style: { lineHeight: 1.4 } }, order.area))),
      // 底部：預估收入 + 進詳情提示
      A('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 14, paddingTop: 13, borderTop: '1px solid var(--line2)' } },
        A('div', { style: { display: 'flex', alignItems: 'baseline', gap: 8 } },
          A('span', { style: { fontSize: 12, color: 'var(--ink3)' } }, doneLike ? (status === 'done' ? '實收' : '原金額') : '預估收入'),
          status === 'done' && order.rating && A(Stars, { value: order.rating, size: 12 })),
        A('span', { className: 'num', style: { fontSize: 18, fontWeight: 800, color: status === 'cancelled' ? 'var(--ink3)' : '#6E8C6B', textDecoration: status === 'cancelled' ? 'line-through' : 'none' } }, order.income))),
    // 動作鈕（stopPropagation：不觸發進詳情）
    status === 'pending'
      ? A('div', { style: { display: 'flex', gap: 0, borderTop: '1px solid var(--line2)' } },
        A('button', { className: 'ccaTap', onClick: stop(() => setReq('rejected')), style: { flex: 1, padding: '14px', border: 'none', background: 'rgba(208,109,92,.10)', color: 'var(--err)', fontFamily: 'inherit', fontSize: 14, fontWeight: 800, borderRight: '1px solid var(--line2)' } }, '拒絕'),
        A('button', { className: 'ccaTap', onClick: stop(() => setReq('accepted')), style: { flex: 1, padding: '14px', border: 'none', background: 'var(--sage)', color: '#fff', fontFamily: 'inherit', fontSize: 14, fontWeight: 800 } }, '接受預約'))
      : status === 'accepted'
        ? A('button', { className: 'ccaTap', onClick: stop(() => go('exec')), style: { width: '100%', padding: '14px', border: 'none', borderTop: '1px solid var(--line2)', background: 'transparent', color: '#6E8C6B', fontFamily: 'inherit', fontSize: 14, fontWeight: 800, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 } }, '前往服務執行 ', A(Icon, { name: 'arrowR', size: 16, sw: 2.2 }))
        : status === 'cancelled' && order.reason
          ? A('div', { style: { padding: '12px 16px', borderTop: '1px solid var(--line2)', fontSize: 12, color: 'var(--ink3)', display: 'flex', alignItems: 'center', gap: 7 } }, A(Icon, { name: 'x', size: 14, color: 'var(--ink3)' }), order.reason)
          : null);
}

function ProOrderManager({ onBack = () => {}, go = () => {}, start = 'pending' }) {
  const [tab, setTab] = uSOM(start);
  const count = (s) => OM_ORDERS.filter(o => o.status === s).length;
  const list = OM_ORDERS.filter(o => o.status === tab);
  return A('div', { style: { flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0, background: 'var(--bg)' } },
    A(AppBar, { title: '預約單管理', onLeft: onBack }),
    // tabs
    A('div', { style: { display: 'flex', gap: 6, padding: '0 16px 10px', flexShrink: 0 } },
      OM_TABS.map(([k, l]) => {
        const on = tab === k;
        const n = count(k);
        return A('button', { key: k, className: 'ccaTap', onClick: () => setTab(k), style: { flex: 1, padding: '9px 4px', borderRadius: 'var(--rpill)', border: 'none', fontFamily: 'inherit', fontSize: 13, fontWeight: 800,
          background: on ? 'var(--sage)' : 'var(--surface)', color: on ? '#fff' : 'var(--ink3)', boxShadow: on ? 'none' : 'inset 0 0 0 1px var(--line2)', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 4 } },
          l, n > 0 && A('span', { className: 'num', style: { fontSize: 11, fontWeight: 800, color: on ? '#fff' : 'var(--ink3)', opacity: on ? 0.9 : 1 } }, n));
      })),
    A(Scroll, { style: { padding: '6px 20px 16px' } },
      list.length
        ? A('div', { style: { display: 'flex', flexDirection: 'column', gap: 14 } }, list.map(o => A(OMOrderCard, { key: o.id, order: o, go })))
        : A('div', { style: { textAlign: 'center', color: 'var(--ink3)', padding: '60px 20px' } },
          A('div', { style: { width: 56, height: 56, borderRadius: '50%', background: 'var(--bgSoft)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 12px' } }, A(Icon, { name: 'list', size: 26, color: 'var(--neutral)' })),
          A('div', { style: { fontSize: 13.5, fontWeight: 600 } }, '目前沒有此類預約單'))),
    A(BottomNavPro, { active: 'dash', onNav: () => {} }));
}

Object.assign(window, { OM_ORDERS, OM_TABS, OM_TAGS, OMOrderCard, ProOrderManager });
