// Page 4: AI Match Dialog — the most important page
// Full-screen, warm conversational interface with typing animation and live-updating needs summary.

const AI_SCRIPT = [
  { role:'ai',   text:'你好，我是好鄰。今天想先問你一件事──你現在最想要的是什麼樣的陪伴？不用完整描述，用一句話說說也可以。', collect: null },
  { role:'user', text:'我剛生完小孩三個月，老公上班，白天都我一個人在家帶寶寶，有點快喘不過氣。想找跟我一樣的爸媽。', collect: { situation:'新手媽媽・產後三個月・白天獨自照顧寶寶', want:'想認識同樣是新手爸媽的人' } },
  { role:'ai',   text:'謝謝你告訴我。新生兒的前幾個月是真的很重的一段時間。我想確認一下──你住哪一帶？找附近可以實體見面的會比較好，還是你現在更希望線上就好？', collect: null },
  { role:'user', text:'我住內湖，可以偶爾出門，但帶寶寶出遠門還是有點困難。最好是內湖或附近能推著推車去的地方。', collect: { region:'台北市・內湖', form:'優先實體・不超過推車可達距離' } },
  { role:'ai',   text:'了解，推車友善很重要。再問一個問題：你希望這個聚會是有主題的（例如親子共讀、副食品研究），還是比較像「大家一起坐著就好」的那種？', collect: null },
  { role:'user', text:'一起坐著就好。有時候只是想聽到別人說寶寶也會這樣，我就鬆一口氣了。', collect: { atmosphere:'非主題式・互相陪伴取向', needs:['情緒支持','不被評價的空間'] } },
  { role:'ai',   text:'我聽到了。那預算呢？有些團是免費的，有些有月費。你現在比較希望哪一種？', collect: null },
  { role:'user', text:'免費最好，育嬰留職停薪中。', collect: { budget:'免費優先' } },
  { role:'ai',   text:'好。我已經有一些方向了，讓我整理一下，幫你推薦 3 個我覺得最適合的好鄰居團。稍等我一下。', collect: null, final: true },
];

const AIMatchPage = ({ onNav }) => {
  const c = useTokens();
  const isMobile = useIsMobile();
  const [needsOpen, setNeedsOpen] = useState(false);
  const D = window.HAOLIN_DATA;

  const [messages, setMessages] = useState([{ role:'ai', text: AI_SCRIPT[0].text }]);
  const [stepIdx, setStepIdx] = useState(1); // index of NEXT step in script
  const [collected, setCollected] = useState({});
  const [typing, setTyping] = useState(false);
  const [input, setInput] = useState('');
  const [finalState, setFinalState] = useState(null); // null | 'loading' | 'done'
  const scrollRef = useRef(null);

  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages, typing]);

  const nextStep = AI_SCRIPT[stepIdx];
  const userSuggestion = nextStep && nextStep.role === 'user' ? nextStep.text : null;

  const sendUser = () => {
    if (!userSuggestion) return;
    // append user message (use suggested text)
    const userMsg = AI_SCRIPT[stepIdx];
    setMessages(m => [...m, { role:'user', text: userMsg.text }]);
    if (userMsg.collect) setCollected(prev => ({ ...prev, ...userMsg.collect }));
    setInput('');
    const nextIdx = stepIdx + 1;
    setStepIdx(nextIdx);
    // AI typing
    if (AI_SCRIPT[nextIdx]) {
      setTyping(true);
      setTimeout(() => {
        const aiMsg = AI_SCRIPT[nextIdx];
        setTyping(false);
        setMessages(m => [...m, { role:'ai', text: aiMsg.text }]);
        if (aiMsg.final) {
          setTimeout(() => setFinalState('loading'), 700);
          setTimeout(() => setFinalState('done'), 2600);
        }
        setStepIdx(nextIdx + 1);
      }, 1400 + Math.random()*700);
    }
  };

  const restart = () => {
    setMessages([{ role:'ai', text: AI_SCRIPT[0].text }]);
    setStepIdx(1);
    setCollected({});
    setTyping(false);
    setFinalState(null);
  };

  const recommendations = [D.groups.find(g=>g.id==='g7'), D.groups.find(g=>g.id==='g1'), D.groups.find(g=>g.id==='g6')];
  const reasons = [
    '專為新生兒爸媽設計，每週日下午內湖捷運站旁邊，推車進出友善。不需要報名，去了就是。',
    '戶外親子團，週六早上在新店溪，雖然在新店，但很多內湖爸媽也會開車過去（有免費停車場）。',
    '如果你某天需要三十分鐘完全安靜，這個桃園的靜心圈有線上場。適合不想社交但想有人的時候。',
  ];

  return (
    <div style={{
      background: c.bg, minHeight:'100vh',
      display:'grid',
      gridTemplateColumns: isMobile ? '1fr' : '1fr 380px',
    }}>
      {/* LEFT: conversation */}
      <div style={{display:'flex', flexDirection:'column', height:'100vh', overflow:'hidden'}}>
        {/* Top bar */}
        <div style={{display:'flex', alignItems:'center', gap: isMobile ? 10 : 14, padding: isMobile ? '12px 14px' : '18px 32px', borderBottom:`1px solid ${c.line}`, background:c.bg}}>
          <button onClick={()=>onNav('home')} style={{background:c.paper, border:`1px solid ${c.line}`, borderRadius:'50%', width:32, height:32, cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0}}>
            <IconX size={14} stroke={c.inkSoft}/>
          </button>
          <div style={{display:'flex', alignItems:'center', gap:10, minWidth:0, flex:1}}>
            <div style={{width: isMobile ? 30 : 36, height: isMobile ? 30 : 36, borderRadius:'50%', background:c.accentSoft, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0}}>
              <IconSparkle size={isMobile ? 15 : 18} stroke={c.accent}/>
            </div>
            <div style={{minWidth:0}}>
              <div style={{fontSize: isMobile ? 14 : 15, fontWeight:600, color:c.ink, display:'flex', alignItems:'center', gap:6, fontFamily:'var(--hl-font-heading)'}}>好鄰 <span style={{fontSize:10, padding:'1px 6px', background:c.accentSoft, color:'#4D6D41', borderRadius:'999px', fontWeight:600}}>AI 媒合</span></div>
              {!isMobile && <div style={{fontSize:12, color:c.inkMuted}}>會用對話幫你找到最適合的好鄰居團</div>}
            </div>
          </div>
          <div style={{marginLeft:'auto', display:'flex', gap:6, flexShrink:0}}>
            {isMobile && (
              <button onClick={()=>setNeedsOpen(o=>!o)} aria-label="檢視需求" style={{
                width:36, height:36, padding:0, background:c.paper,
                border:`1px solid ${c.line}`, borderRadius:'50%',
                cursor:'pointer', color:c.primary,
                display:'inline-flex', alignItems:'center', justifyContent:'center',
                position:'relative',
              }}>
                <IconDoc size={16}/>
                {Object.keys(collected).length > 0 && (
                  <span style={{
                    position:'absolute', top:-2, right:-2,
                    minWidth:16, height:16, padding:'0 4px',
                    borderRadius:8, background:c.primary, color:'#fff',
                    fontSize:10, fontWeight:600,
                    display:'inline-flex', alignItems:'center', justifyContent:'center',
                  }}>{Object.keys(collected).length}</span>
                )}
              </button>
            )}
            <Button variant="ghost" size="sm" onClick={restart} style={isMobile ? {padding:'6px 10px', fontSize:12} : {}}><IconRefresh size={14}/> {isMobile ? '重來' : '重新開始'}</Button>
          </div>
        </div>

        {/* Messages */}
        <div ref={scrollRef} style={{flex:1, overflowY:'auto', padding: isMobile ? '20px 16px 16px' : '32px 32px 20px', display:'flex', flexDirection:'column', gap:20}}>
          <div style={{maxWidth:720, margin:'0 auto', width:'100%', display:'flex', flexDirection:'column', gap:20}}>
            {messages.map((m, i) => <Message key={i} msg={m}/>)}
            {typing && <TypingIndicator/>}

            {finalState && (
              <div style={{marginTop:20}}>
                {finalState === 'loading' ? (
                  <div style={{textAlign:'center', padding:'32px 20px'}}>
                    <div style={{display:'inline-flex', gap:6, alignItems:'center', color:c.inkMuted, fontSize:14}}>
                      <DotsLoader/> 我在幫你挑選⋯⋯
                    </div>
                  </div>
                ) : (
                  <div style={{display:'flex', flexDirection:'column', gap:14}}>
                    <div style={{display:'flex', alignItems:'center', gap:10, marginBottom:8}}>
                      <div style={{width:28, height:28, borderRadius:'50%', background:c.accentSoft, display:'flex', alignItems:'center', justifyContent:'center'}}>
                        <IconSparkle size={14} stroke={c.accent}/>
                      </div>
                      <span style={{fontSize:14, color:c.inkSoft}}>我覺得這 3 個團最適合你，每個都有推薦理由：</span>
                    </div>
                    {recommendations.map((g, i) => (
                      <RecommendCard key={g.id} group={g} reason={reasons[i]} rank={i+1} onOpen={()=>onNav('group-detail', g.id)}/>
                    ))}
                    <div style={{display:'flex', gap:10, marginTop:16, paddingTop:16, borderTop:`1px dashed ${c.line}`}}>
                      <Button variant="secondary" onClick={restart}><IconRefresh size={14}/> 再重新找一次</Button>
                      <Button variant="accent"><IconHeart size={14}/> 儲存這次推薦</Button>
                    </div>
                  </div>
                )}
              </div>
            )}
          </div>
        </div>

        {/* Input */}
        <div style={{padding: isMobile ? '12px 14px 18px' : '16px 32px 28px', borderTop:`1px solid ${c.line}`, background: c.bg}}>
          <div style={{maxWidth:720, margin:'0 auto'}}>
            {userSuggestion && !typing && !finalState && (
              <div style={{marginBottom:10, display:'flex', gap:8, flexWrap:'wrap'}}>
                <button onClick={sendUser} style={{
                  padding:'8px 14px', borderRadius:'999px',
                  background:c.bgAlt, border:`1px dashed ${c.line}`,
                  color:c.inkSoft, fontSize:13, cursor:'pointer',
                  fontFamily:'var(--hl-font-body)',
                  maxWidth:'100%', textAlign:'left', lineHeight:1.5,
                }}>
                  <span style={{color:c.primary, fontWeight:600, marginRight:6}}>示範回應</span>
                  {userSuggestion.length > 50 ? userSuggestion.slice(0,50) + '⋯' : userSuggestion}
                </button>
              </div>
            )}
            <div style={{
              display:'flex', alignItems:'flex-end', gap:12,
              padding:'12px 16px', background:c.paper,
              border:`1px solid ${c.line}`, borderRadius:'var(--hl-radius-xl)',
              boxShadow:'0 4px 16px rgba(80,50,25,0.04)',
            }}>
              <textarea
                value={input}
                placeholder={finalState ? '已媒合完成，可點擊「再重新找一次」繼續' : '告訴好鄰你想要什麼樣的陪伴⋯⋯'}
                onChange={e=>setInput(e.target.value)}
                style={{
                  flex:1, border:'none', outline:'none', background:'transparent',
                  fontSize:15, color:c.ink, fontFamily:'var(--hl-font-body)',
                  resize:'none', minHeight:24, maxHeight:120,
                  lineHeight:1.6,
                }}
                rows={1}
              />
              <div style={{display:'flex', gap:8, alignItems:'center'}}>
                <button style={{background:'none', border:'none', cursor:'pointer', color:c.inkMuted, display:'flex'}}><IconPaperclip size={18}/></button>
                <button
                  onClick={sendUser}
                  disabled={!userSuggestion || typing || !!finalState}
                  style={{
                    width:38, height:38, borderRadius:'50%',
                    background: (!userSuggestion || typing || finalState) ? c.bgAlt : c.primary,
                    color:'#fff', border:'none',
                    cursor: (!userSuggestion || typing || finalState) ? 'not-allowed' : 'pointer',
                    display:'flex', alignItems:'center', justifyContent:'center',
                  }}>
                  <IconSend size={16}/>
                </button>
              </div>
            </div>
            <div style={{fontSize:11, color:c.inkMuted, textAlign:'center', marginTop:10}}>好鄰是 AI 媒合助手，對話內容不會公開，只會用來找到適合你的好鄰居。</div>
          </div>
        </div>
      </div>

      {/* RIGHT: needs summary — desktop sidebar / mobile drawer */}
      {(!isMobile || needsOpen) && (
      <aside style={{
        background: c.bgAlt,
        borderLeft: isMobile ? 'none' : `1px solid ${c.line}`,
        padding: isMobile ? '20px 18px' : '24px 28px',
        overflowY:'auto',
        ...(isMobile ? {
          position:'fixed', inset:0, zIndex:80,
          height:'100vh',
        } : {
          height:'100vh',
        })
      }}>
        {isMobile && (
          <button onClick={()=>setNeedsOpen(false)} style={{
            position:'absolute', top:14, right:14,
            width:36, height:36, borderRadius:'50%',
            background:c.paper, border:`1px solid ${c.line}`,
            cursor:'pointer', color:c.ink,
            display:'inline-flex', alignItems:'center', justifyContent:'center',
            fontSize:18,
          }}>✕</button>
        )}
        <div style={{display:'flex', alignItems:'center', gap:8, marginBottom:18}}>
          <IconDoc size={16} stroke={c.primary}/>
          <h3 style={{fontSize:14, fontWeight:600, color:c.ink, margin:0, letterSpacing:'0.05em'}}>我聽到的需求</h3>
          {Object.keys(collected).length > 0 && <span style={{marginLeft:'auto', fontSize:11, color:c.inkMuted}}>{Object.keys(collected).length} 項</span>}
        </div>

        {Object.keys(collected).length === 0 ? (
          <div style={{padding:'40px 20px', textAlign:'center', color:c.inkMuted, fontSize:13}}>
            <EmptyIllustration size={100}/>
            <p style={{margin:'16px 0 0', lineHeight:1.7}}>你說的我會記在這裡。<br/>這些筆記不會留下，只會用來這次媒合。</p>
          </div>
        ) : (
          <div style={{display:'flex', flexDirection:'column', gap:12}}>
            {collected.situation && <NeedCard label="狀況" value={collected.situation}/>}
            {collected.want && <NeedCard label="想要" value={collected.want}/>}
            {collected.region && <NeedCard label="地區" value={collected.region} icon={<IconPin size={14}/>}/>}
            {collected.form && <NeedCard label="形式" value={collected.form} icon={<IconUsers size={14}/>}/>}
            {collected.atmosphere && <NeedCard label="氣氛" value={collected.atmosphere}/>}
            {collected.needs && <NeedCard label="重視的事" value={collected.needs.join('、')}/>}
            {collected.budget && <NeedCard label="預算" value={collected.budget} icon={<IconHeartHands size={14}/>}/>}
          </div>
        )}

        {finalState === 'done' && (
          <div style={{marginTop:24, padding:16, background:c.accentSoft, borderRadius:'var(--hl-radius-lg)', border:`1px solid ${c.accent}40`}}>
            <div style={{display:'flex', alignItems:'center', gap:8, marginBottom:8}}>
              <IconCheck size={16} stroke="#4D6D41"/>
              <span style={{fontSize:13, fontWeight:600, color:'#4D6D41'}}>媒合完成</span>
            </div>
            <p style={{fontSize:13, color:'#4D6D41', margin:0, lineHeight:1.6}}>我已經幫你從 142 個活躍好鄰居團中挑出 3 個最合適的。你可以直接聯絡主揪。</p>
          </div>
        )}
      </aside>
      )}
    </div>
  );
};

const Message = ({ msg }) => {
  const c = useTokens();
  if (msg.role === 'ai') {
    return (
      <div style={{display:'flex', gap:12, alignItems:'flex-start', maxWidth:'90%'}}>
        <div style={{width:32, height:32, borderRadius:'50%', background:c.accentSoft, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0, marginTop:2}}>
          <IconSparkle size={15} stroke={c.accent}/>
        </div>
        <div style={{
          background: c.paper, padding:'14px 18px', borderRadius:'4px 18px 18px 18px',
          border:`1px solid ${c.line}`,
          fontSize:15, lineHeight:1.75, color:c.ink,
          fontFamily:'var(--hl-font-body)',
        }}>{msg.text}</div>
      </div>
    );
  }
  return (
    <div style={{display:'flex', justifyContent:'flex-end'}}>
      <div style={{
        background: c.primary, color:'#fff',
        padding:'12px 18px', borderRadius:'18px 4px 18px 18px',
        fontSize:15, lineHeight:1.7, maxWidth:'80%',
        fontFamily:'var(--hl-font-body)',
      }}>{msg.text}</div>
    </div>
  );
};

const DotsLoader = () => {
  const c = useTokens();
  return (
    <span style={{display:'inline-flex', gap:4}}>
      {[0,1,2].map(i => (
        <span key={i} style={{
          width:6, height:6, borderRadius:'50%', background:c.inkMuted,
          animation: `haolin-bounce 1.2s ease-in-out ${i*0.15}s infinite`,
        }}/>
      ))}
    </span>
  );
};

const TypingIndicator = () => {
  const c = useTokens();
  return (
    <div style={{display:'flex', gap:12, alignItems:'flex-start'}}>
      <div style={{width:32, height:32, borderRadius:'50%', background:c.accentSoft, display:'flex', alignItems:'center', justifyContent:'center'}}>
        <IconSparkle size={15} stroke={c.accent}/>
      </div>
      <div style={{background:c.paper, padding:'14px 18px', borderRadius:'4px 18px 18px 18px', border:`1px solid ${c.line}`}}>
        <DotsLoader/>
      </div>
    </div>
  );
};

const NeedCard = ({ label, value, icon }) => {
  const c = useTokens();
  return (
    <div style={{
      background:c.paper, padding:'12px 14px',
      borderRadius:'var(--hl-radius-md)',
      border:`1px solid ${c.line}`,
      animation:'haolin-slide-in 340ms ease-out',
    }}>
      <div style={{display:'flex', alignItems:'center', gap:6, marginBottom:4}}>
        {icon && <span style={{color:c.primary}}>{icon}</span>}
        <span style={{fontSize:11, color:c.inkMuted, letterSpacing:'0.1em', textTransform:'uppercase', fontWeight:600}}>{label}</span>
      </div>
      <div style={{fontSize:13, color:c.ink, lineHeight:1.6}}>{value}</div>
    </div>
  );
};

const RecommendCard = ({ group, reason, rank, onOpen }) => {
  const c = useTokens();
  const cat = window.HAOLIN_DATA.categories.find(x => x.key === group.cat);
  return (
    <div style={{
      background:c.paper, borderRadius:'var(--hl-radius-xl)',
      border:`1px solid ${c.line}`, overflow:'hidden',
      animation:'haolin-slide-in 500ms ease-out',
    }}>
      <div style={{padding:'20px 22px', display:'flex', gap:16, alignItems:'flex-start'}}>
        <div style={{
          width:36, height:36, borderRadius:'50%',
          background: rank===1 ? c.primary : (rank===2 ? c.accent : c.gold), color:'#fff',
          display:'flex', alignItems:'center', justifyContent:'center',
          fontFamily:'var(--hl-font-heading)', fontSize:17, fontWeight:500,
          flexShrink:0,
        }}>{rank}</div>
        <div style={{flex:1}}>
          <div style={{display:'flex', gap:8, marginBottom:6}}>
            <Tag tone="primary">{cat.label}</Tag>
            <Tag>{group.region}</Tag>
          </div>
          <h4 style={{fontFamily:'var(--hl-font-heading)', fontSize:19, color:c.ink, margin:'0 0 6px', fontWeight:500}}>{group.name}</h4>
          <p style={{fontSize:13, color:c.inkSoft, margin:0, lineHeight:1.65}}>{group.tagline}</p>
        </div>
      </div>
      <div style={{padding:'14px 22px', background:c.bgAlt, borderTop:`1px dashed ${c.line}`}}>
        <div style={{display:'flex', gap:8, alignItems:'flex-start'}}>
          <IconSparkle size={14} stroke={c.accent} style={{marginTop:3, flexShrink:0}}/>
          <div>
            <div style={{fontSize:11, color:c.accent, fontWeight:600, marginBottom:4, letterSpacing:'0.05em'}}>好鄰的推薦理由</div>
            <p style={{fontSize:13, color:c.inkSoft, margin:0, lineHeight:1.7}}>{reason}</p>
          </div>
        </div>
      </div>
      <div style={{padding:'14px 22px', display:'flex', gap:10}}>
        <Button variant="primary" size="sm" style={{flex:1}} icon={<IconChat size={14}/>}>立即聯絡主揪</Button>
        <Button variant="ghost" size="sm" onClick={onOpen}>看詳細 <IconArrow size={14}/></Button>
      </div>
    </div>
  );
};

Object.assign(window, { AIMatchPage });
