// pages/owner-home.jsx — the app's home: a live conversation with 寵答 (no navigating into a room).
// Lands directly in chat — welcome message + starter prompts + a proactive reminder, with a
// persistent input. Scripted replies (CTA / insight cards) appear inline via the shared chat-cards.

// starter prompts shown in the empty/welcome state — tapping one seeds that intent
const SUGGEST = [
  ['paw', '找保姆', '出差、旅遊安心託付', 'sitter'],
  ['drop', '預約到府獸醫', '喝水變多、想健檢', 'vet'],
  ['edit', '記錄日常照護', '體重、飲食、用藥', 'record'],
  ['heart', '行為問題諮詢', '亂叫、抓門、怕生', 'behavior'],
];

// fallback turn for free-typed text that doesn't match a known intent
const GENERIC = {
  name: '新對話',
  turn: [
    { from: 'ai', text: '收到～讓我幫你看看 🐾 可以多說一點細節，或從這幾個方向挑一個，我馬上接手處理：' },
    { type: 'cta', icon: 'paw', title: '幫你找合適的服務', desc: '保姆 / 獸醫 / 行為諮詢', action: '看可預約的對象', target: 'providers' },
  ],
  quick: ['找保姆', '預約到府獸醫', '記錄今天體重'],
};

// scripted first AI turn per intent
const INTENT = {
  sitter: {
    user: '我下週三到週五要出差，想找個到府保姆',
    name: '出差找保姆',
    turn: [
      { from: 'ai', text: '沒問題！出差期間想用「到府餵食」還是「住宿托管」呢？我幫你找評價好、那幾天又有空的保姆 🐾' },
      { type: 'cta', icon: 'calendar', title: '幫你找保姆', desc: '已預填 6/4（三）–6/6（五）·到府', action: '看可預約的保姆', target: 'providers' },
    ],
    quick: ['到府餵食就好', '想要住宿托管', '附近有推薦的嗎？'],
  },
  vet: {
    user: '最近喝水變超多，想找到府獸醫看看',
    name: '喝水變多',
    turn: [
      { from: 'ai', text: '多喝水有時和腎臟或內分泌有關，建議做個基礎健檢。我幫你約「到府獸醫」，也可以先上傳之前的血檢報告讓我先看一眼。' },
      { type: 'cta', icon: 'drop', title: '預約到府獸醫', desc: '類別已選＝健康檢查', action: '挑選時間', target: 'providers' },
    ],
    quick: ['先上傳血檢報告', '這週末可以嗎？'],
  },
  behavior: {
    user: '最近一直抓門、半夜亂叫',
    name: '抓門亂叫',
    turn: [
      { from: 'ai', text: '聽起來像是分離焦慮或精力沒消耗完。可以先做環境調整，也可以預約行為諮詢師線上聊聊。' },
      { type: 'cta', icon: 'heart', title: '預約行為諮詢', desc: '類別已選＝行為諮詢', action: '看諮詢師', target: 'providers' },
    ],
    quick: ['先給我幾個居家小撇步', '預約諮詢'],
  },
  record: {
    user: '幫我記一下今天 5.0 公斤',
    name: '體重記錄',
    turn: [
      { from: 'ai', text: '記好囉！比上次（4.7kg）多了 0.3，落在健康範圍內 👍 我已經更新到活檔案。' },
      { type: 'insight', cat: '小橘', item: '體重 5.0kg', thumb: true, note: '4.7 → 5.0kg · 6/1 更新' },
    ],
    quick: ['看體重曲線', '再記一筆飲食'],
  },
};

// suggestion card (empty-state starter prompt)
function SuggestCard({ ic, title, sub, onClick }) {
  return A('button', { className: 'ccaTap ccaPop', onClick, style: {
    display: 'flex', flexDirection: 'column', alignItems: 'flex-start', textAlign: 'left',
    background: 'var(--surface)', border: '1px solid var(--line2)', borderRadius: 'var(--rmd)',
    padding: '12px 13px', fontFamily: 'inherit', cursor: 'pointer' } },
    A('div', { style: { width: 34, height: 34, borderRadius: 11, background: 'var(--brandSoft)', color: 'var(--brandDeep)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 9 } }, A(Icon, { name: ic, size: 19, sw: 1.9 })),
    A('div', { style: { fontSize: 13.5, fontWeight: 700 } }, title),
    A('div', { style: { fontSize: 11, color: 'var(--ink3)', marginTop: 2, lineHeight: 1.35 } }, sub));
}

const HOME_WELCOME = [
  { from: 'ai', first: true, text: '嗨，我是寵答 🐱' },
  { from: 'ai', first: false, text: '找保姆、約獸醫、記錄日常⋯⋯不用切換頁面，直接在這裡跟我說就好。' },
];

function OwnerHome({ variant = 'notch', onNav = () => {}, go = () => {}, initialSheet = null, initialUsed = 0 }) {
  const [msgs, setMsgs] = React.useState(HOME_WELCOME);
  const [typing, setTyping] = React.useState(false);
  const [quick, setQuick] = React.useState([]);
  const [text, setText] = React.useState('');
  const FREE_QUOTA = 3;
  const [subbed, setSubbed] = React.useState(false);
  const [used, setUsed] = React.useState(initialUsed); // AI messages used against the free quota
  const [sheet, setSheet] = React.useState(initialSheet); // null | {type:'login',reason,forAI} | {type:'subscribe'}
  const pendingRef = React.useRef(null);
  const scrollRef = React.useRef(null);
  const started = msgs.some(m => m.from === 'me');
  React.useEffect(() => { const el = scrollRef.current; if (el) el.scrollTop = el.scrollHeight + 999; }, [msgs, typing, quick]);

  // run a turn: push the user's message, then the AI's scripted reply
  const run = (userText, intentKey) => {
    const it = intentKey && INTENT[intentKey] ? INTENT[intentKey] : GENERIC;
    setMsgs(m => [...m, { from: 'me', text: userText }]);
    setText('');
    setQuick([]);
    setTyping(true);
    setTimeout(() => { setTyping(false); setMsgs(m => [...m, ...it.turn]); setQuick(it.quick || []); }, 950);
  };
  // login happens up-front; inside the app you get a free quota, then must subscribe
  const askAI = (userText, intentKey) => {
    if (!subbed && used >= FREE_QUOTA) { pendingRef.current = { userText, intentKey }; setSheet({ type: 'subscribe' }); return; }
    run(userText, intentKey);
    if (!subbed) setUsed(u => u + 1);
  };
  const send = () => { const t = text.trim(); if (t) askAI(t, null); };
  const newChat = () => { setMsgs(HOME_WELCOME); setQuick([]); setText(''); };
  const closeSheet = () => { pendingRef.current = null; setSheet(null); };
  const handleSubscribe = () => { setSubbed(true); setSheet(null); const p = pendingRef.current; pendingRef.current = null; if (p) run(p.userText, p.intentKey); };

  const iconBtn = { width: 38, height: 38, borderRadius: '50%', border: 'none', background: 'transparent', color: 'var(--ink2)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, cursor: 'pointer' };

  return A('div', { style: { flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0, background: 'var(--bg)' } },
    // ---- chat header: you're already talking to 寵答 ----
    A('div', { style: { display: 'flex', alignItems: 'center', gap: 6, padding: '2px 12px 8px', flexShrink: 0 } },
      A('button', { className: 'ccaTap', onClick: () => onNav('inbox'), style: { ...iconBtn, position: 'relative' } },
        A(Icon, { name: 'list', size: 21 }),
        A('div', { style: { position: 'absolute', top: 8, right: 8, width: 7, height: 7, borderRadius: 4, background: 'var(--brand)', boxShadow: '0 0 0 2px var(--bg)' } })),
      A('div', { style: { flex: 1, display: 'flex', alignItems: 'center', gap: 9, justifyContent: 'center' } },
        A('div', { style: { position: 'relative' } },
          A(Avatar, { size: 34, kind: 'ai' }),
          A('div', { style: { position: 'absolute', bottom: -1, right: -1, width: 11, height: 11, borderRadius: 6, background: 'var(--ok)', border: '2.5px solid var(--bg)' } })),
        A('div', { style: { lineHeight: 1.18 } },
          A('div', { style: { fontSize: 15.5, fontWeight: 800, letterSpacing: -0.2, display: 'flex', alignItems: 'center', gap: 5 } }, '寵答',
            A('span', { style: { fontSize: 9, fontWeight: 800, color: 'var(--brandDeep)', background: 'var(--brandSoft)', padding: '2px 6px', borderRadius: 6 } }, 'AI')),
          A('div', { style: { fontSize: 10.5, color: 'var(--ink3)' } }, subbed ? '線上 · Premium · 無限對話' : `線上 · 今日免費額度 ${Math.max(0, FREE_QUOTA - used)}/${FREE_QUOTA}`))),
      A('button', { className: 'ccaTap', onClick: newChat, style: iconBtn }, A(Icon, { name: 'edit', size: 20 }))),

    // ---- the conversation IS the home ----
    A('div', { ref: scrollRef, style: { flex: 1, overflowY: 'auto', padding: '6px 16px 8px', display: 'flex', flexDirection: 'column', gap: 12 } },
      msgs.map((m, i) => renderMsg(m, i, go)),
      typing && A(Typing, { key: 'typing' }),

      // welcome state: starter prompts + a proactive reminder, all in-thread
      !started && !typing && A('div', { key: 'welcome', style: { display: 'flex', flexDirection: 'column', gap: 12, marginTop: 2 } },
        A('div', null,
          A('div', { style: { fontSize: 11.5, fontWeight: 700, color: 'var(--ink3)', margin: '2px 2px 9px' } }, '你可以這樣開始 👇'),
          A('div', { style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 9 } },
            SUGGEST.map(([ic, t, sub, key]) => A(SuggestCard, { key, ic, title: t, sub, onClick: () => askAI(INTENT[key].user, key) })))),
        A(AIWrap, { first: true }, A(Bubble, { from: 'ai' }, '對了，你這週有一筆預約，需要我幫你看看嗎？')),
        A(AIWrap, { first: false }, A(CTACard, { icon: 'calendar', title: '即將到來 · 6/4（三）到府餵食', desc: '林依婷 · 連續 3 天', action: '查看預約', onClick: () => go('bookingDetail') })))),

    // ---- contextual quick replies ----
    quick.length > 0 && A('div', { style: { display: 'flex', gap: 8, padding: '4px 16px 2px', overflowX: 'auto', flexShrink: 0 } },
      quick.map((q, i) => A(Chip, { key: i, onClick: () => askAI(q, null) }, q))),

    // ---- free quota used up → nudge to subscribe ----
    !subbed && used >= FREE_QUOTA && A('div', { className: 'ccaTap', onClick: () => setSheet({ type: 'subscribe' }), style: { flexShrink: 0, margin: '0 14px 2px', display: 'flex', alignItems: 'center', gap: 8, padding: '9px 12px', borderRadius: 12, background: 'var(--butterSoft)' } },
      A(Icon, { name: 'shield', size: 16, color: '#9A6B12' }),
      A('span', { style: { flex: 1, fontSize: 12, fontWeight: 700, color: '#7A5310' } }, '今日免費額度已用完'),
      A('span', { style: { fontSize: 12, fontWeight: 800, color: 'var(--brandDeep)' } }, '訂閱解鎖 ›')),

    // ---- persistent input: always ready to talk ----
    A('div', { style: { flexShrink: 0, padding: '8px 14px 8px', background: 'var(--bg)' } },
      A('div', { style: { display: 'flex', alignItems: 'center', gap: 8, background: 'var(--surface)', borderRadius: 'var(--rpill)', border: '1px solid var(--line)', padding: '6px 6px 6px 14px' } },
        A('button', { style: { border: 'none', background: 'transparent', color: 'var(--ink3)', display: 'flex', padding: 2, cursor: 'pointer' } }, A(Icon, { name: 'plus', size: 22 })),
        A('input', { value: text, onChange: e => setText(e.target.value), placeholder: '傳訊息給寵答…',
          onKeyDown: e => { if (e.key === 'Enter') send(); },
          style: { flex: 1, border: 'none', outline: 'none', background: 'transparent', fontSize: 14, fontFamily: 'inherit', color: 'var(--ink)', minWidth: 0 } }),
        A('button', { style: { border: 'none', background: 'transparent', color: 'var(--ink3)', display: 'flex', padding: 2, cursor: 'pointer' } }, A(Icon, { name: 'camera', size: 21 })),
        text.trim()
          ? A('button', { className: 'ccaTap', onClick: send, style: { width: 38, height: 38, borderRadius: '50%', border: 'none', background: 'var(--brand)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, cursor: 'pointer' } }, A(Icon, { name: 'send', size: 19, fill: false, color: '#fff', sw: 1.8 }))
          : A('button', { style: { width: 38, height: 38, borderRadius: '50%', border: 'none', background: 'var(--brandSoft)', color: 'var(--brandDeep)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, cursor: 'pointer' } }, A(Icon, { name: 'mic', size: 20 })))),

    A(BottomNavOwner, { active: 'home', variant, onNav }),
    sheet && sheet.type === 'subscribe' && A(SubscribeSheet, { onClose: closeSheet, onSubscribe: handleSubscribe }));
}

Object.assign(window, { OwnerHome, INTENT, SUGGEST, GENERIC, SuggestCard });
