// GS Car — Inbox + AI Agent + Booking + Auth screens

const ScreenInbox = ({ onOpenChat, onOpenAI }) => {
  const aiConvo = DATA.conversations.find(c => c.isAI);
  const others = DATA.conversations.filter(c => !c.isAI);
  return (
  <div className="screen screen-enter">
    <StatusBar />
    <div className="nav-bar">
      <div className="nav-title">Inbox</div>
      <div className="nav-icons">
        <button className="icon-btn"><Icons.Edit size={16} /></button>
      </div>
    </div>
    <div style={{ padding: '0 20px 12px' }}>
      <div style={{
        background: 'var(--bg-2)', borderRadius: 12,
        display: 'flex', alignItems: 'center', gap: 8,
        padding: '10px 14px',
      }}>
        <Icons.Search size={14} />
        <span style={{ fontSize: 13, color: 'var(--ink-3)' }}>搜尋對話</span>
      </div>
    </div>

    <div className="scroll" style={{ paddingBottom: 100 }}>
      {/* AI Agent — featured hero card */}
      {aiConvo && (
        <div style={{ padding: '4px 16px 16px' }}>
          <button onClick={onOpenAI} className="ai-hero-card" style={{
            width: '100%', textAlign: 'left',
            position: 'relative',
            borderRadius: 18,
            padding: '14px 16px',
            display: 'flex', gap: 12, alignItems: 'center',
            isolation: 'isolate',
          }}>
            {/* breathing glow */}
            <span className="ai-hero-glow" />
            <div style={{
              width: 52, height: 52, borderRadius: '50%',
              background: 'linear-gradient(135deg, #a78bfa, #7c3aed)',
              display: 'grid', placeItems: 'center', flexShrink: 0,
              boxShadow: '0 0 24px rgba(167, 139, 250, 0.55), inset 0 0 0 2px rgba(255,255,255,0.15)',
              position: 'relative', zIndex: 1,
            }}>
              <Icons.Sparkle size={24} />
            </div>
            <div style={{ flex: 1, minWidth: 0, position: 'relative', zIndex: 1 }}>
              <div style={{
                display: 'inline-flex', alignItems: 'center', gap: 6, marginBottom: 4,
                background: 'rgba(10, 5, 20, 0.55)',
                backdropFilter: 'blur(8px)',
                WebkitBackdropFilter: 'blur(8px)',
                padding: '3px 8px 3px 4px',
                borderRadius: 8,
              }}>
                <span style={{ fontSize: 15, fontWeight: 700, letterSpacing: '-0.01em', color: '#fff' }}>{aiConvo.name}</span>
                <span style={{
                  fontSize: 8, padding: '2px 6px', borderRadius: 4,
                  background: 'rgba(167, 139, 250, 0.35)',
                  color: '#fff',
                  fontWeight: 700, letterSpacing: '0.05em',
                }}>AI</span>
                <span style={{
                  fontSize: 8, fontFamily: 'var(--font-mono)', letterSpacing: '0.1em',
                  color: '#e9d5ff',
                  display: 'flex', alignItems: 'center', gap: 4, marginLeft: 4,
                }}>
                  <span style={{ width: 5, height: 5, borderRadius: '50%', background: '#a78bfa', boxShadow: '0 0 8px #a78bfa' }} />
                  ONLINE
                </span>
              </div>
              <div style={{
                fontSize: 11, color: '#fff', lineHeight: 1.45, marginBottom: 6,
                textShadow: '0 1px 4px rgba(0,0,0,0.7)',
                fontWeight: 500,
              }}>
                {aiConvo.preview}
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <span style={{
                  fontSize: 10, fontFamily: 'var(--font-mono)', color: '#c4b5fd',
                  letterSpacing: '0.08em',
                  textShadow: '0 1px 3px rgba(0,0,0,0.6)',
                }}>個人 AI 助理</span>
                {aiConvo.unread > 0 && (
                  <span style={{
                    fontSize: 9, fontWeight: 700, color: '#fff',
                    background: 'linear-gradient(135deg, #a78bfa, #7c3aed)', padding: '2px 6px', borderRadius: 6,
                    boxShadow: '0 2px 8px rgba(124, 58, 237, 0.5)',
                  }}>{aiConvo.unread} 個新建議</span>
                )}
              </div>
            </div>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ color: 'var(--ink-2)', flexShrink: 0, position: 'relative', zIndex: 1 }}>
              <path d="M9 6l6 6-6 6" />
            </svg>
          </button>
        </div>
      )}

      {/* Section divider */}
      <div style={{
        padding: '4px 20px 8px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <span style={{
          fontSize: 10, fontFamily: 'var(--font-mono)',
          letterSpacing: '0.15em', color: 'var(--ink-3)',
          textTransform: 'uppercase',
        }}>對話 · {others.length}</span>
        <span style={{ fontSize: 10, color: 'var(--ink-3)' }}>全部已讀</span>
      </div>

      {others.map(c => (
        <button key={c.id} onClick={() => onOpenChat(c)}
          style={{
            width: '100%', padding: '12px 20px',
            display: 'flex', gap: 12, alignItems: 'center',
            borderBottom: '0.5px solid var(--line-soft)',
            textAlign: 'left',
          }}>
          <div style={{ position: 'relative' }}>
            <Avatar name={c.avatar} size={48} />
            {c.online && (
              <div style={{
                position: 'absolute', bottom: 0, right: 0,
                width: 12, height: 12, borderRadius: '50%',
                background: 'var(--green)', border: '2px solid var(--bg-0)',
              }} />
            )}
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div style={{ display: 'flex', alignItems: 'center', fontSize: 14, fontWeight: c.unread ? 700 : 600 }}>
                {c.name}
                {c.verified && <VerifiedDot size={12} color="var(--accent)" />}
                {c.merchant && <span className="badge badge-verified" style={{ marginLeft: 6, fontSize: 8, padding: '2px 5px' }}>商戶</span>}
              </div>
              <span style={{ fontSize: 10, color: c.unread ? 'var(--accent)' : 'var(--ink-3)' }}>{c.time}</span>
            </div>
            {c.car && <div style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 2 }}>{c.car}</div>}
            <div style={{
              fontSize: 12, color: c.unread ? 'var(--ink-1)' : 'var(--ink-2)',
              marginTop: 3,
              fontWeight: c.unread ? 500 : 400,
              overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
            }}>{c.preview}</div>
          </div>
          {c.unread > 0 && (
            <div style={{
              minWidth: 18, height: 18, padding: '0 6px',
              borderRadius: 9, background: 'var(--accent)',
              display: 'grid', placeItems: 'center',
              fontSize: 10, fontWeight: 700, color: '#fff',
            }}>{c.unread}</div>
          )}
        </button>
      ))}
    </div>
  </div>
  );
};

const ScreenAIAgent = ({ onBack, onOpenMerchant, script }) => {
  const [messages, setMessages] = React.useState([]);
  const [input, setInput] = React.useState('');
  const scrollRef = React.useRef(null);
  const useScript = script || DATA.aiScript;

  React.useEffect(() => {
    let cancelled = false;
    let i = 0;
    const tick = () => {
      if (cancelled || i >= useScript.length) return;
      const m = useScript[i];
      setMessages(prev => [...prev.filter(p => !p.typing), m]);
      i++;
      setTimeout(tick, m.delay || 600);
    };
    setMessages([]);
    setTimeout(tick, 400);
    return () => { cancelled = true; };
  }, [useScript]);

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

  return (
    <div className="screen screen-enter">
      <StatusBar />
      <div className="nav-bar" style={{ borderBottom: '0.5px solid var(--line)', paddingBottom: 12 }}>
        <button className="icon-btn" onClick={onBack}><Icons.Back size={18} /></button>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{
            width: 32, height: 32, borderRadius: '50%',
            background: 'linear-gradient(135deg, #a78bfa, #7c3aed)',
            display: 'grid', placeItems: 'center',
          }}><Icons.Sparkle size={16} /></div>
          <div>
            <div style={{ fontSize: 13, fontWeight: 700, display: 'flex', alignItems: 'center', gap: 4 }}>
              GS Agent <span style={{
                fontSize: 8, padding: '2px 5px', borderRadius: 4,
                background: 'rgba(167, 139, 250, 0.2)', color: '#c4b5fd',
                fontWeight: 700, letterSpacing: '0.05em',
              }}>BETA</span>
            </div>
            <div style={{ fontSize: 10, color: 'var(--green)' }}>● 在線 · Claude Sonnet 4.6</div>
          </div>
        </div>
        <button className="icon-btn"><Icons.More size={16} /></button>
      </div>

      <div ref={scrollRef} className="scroll" style={{ padding: '16px 16px 100px' }}>
        <div style={{
          textAlign: 'center', marginBottom: 20,
          fontSize: 10, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)',
          letterSpacing: '0.1em',
        }}>● 今日 14:32</div>
        <div style={{
          padding: 12, background: 'rgba(225,10,23,0.06)',
          border: '1px solid rgba(225,10,23,0.2)', borderRadius: 12,
          fontSize: 11, color: 'var(--ink-1)', lineHeight: 1.5,
          marginBottom: 20,
        }}>
          👋 我係 <b>GS Agent</b>。我可以幫你揾啱嘅商戶、比較服務、預約 booking。
          試吓問我「我架車想做氛圍燈」「邊度可以做 PPF」。
        </div>

        {messages.map((m, i) => (
          <Message key={i} message={m} onOpenMerchant={onOpenMerchant} />
        ))}
      </div>

      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0,
        padding: '12px 16px 28px',
        background: 'rgba(8,8,10,0.95)', backdropFilter: 'blur(20px)',
        borderTop: '0.5px solid var(--line)',
      }}>
        <div style={{
          background: 'var(--bg-2)', borderRadius: 22,
          display: 'flex', alignItems: 'center', gap: 8,
          padding: '6px 6px 6px 16px',
          border: '1px solid var(--line)',
        }}>
          <input value={input} onChange={(e) => setInput(e.target.value)}
            placeholder="問 GS Agent 任何問題…"
            style={{ flex: 1, fontSize: 13, padding: '8px 0' }} />
          <button style={{
            width: 34, height: 34, borderRadius: '50%',
            background: input ? 'var(--accent)' : 'var(--bg-3)',
            display: 'grid', placeItems: 'center',
            color: '#fff',
          }}><Icons.Send size={14} /></button>
        </div>
      </div>
    </div>
  );
};

const Message = ({ message, onOpenMerchant }) => {
  if (message.from === 'user') {
    return (
      <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 10 }}>
        <div style={{
          maxWidth: '78%',
          background: 'var(--accent)', color: '#fff',
          padding: '10px 14px', borderRadius: '16px 16px 4px 16px',
          fontSize: 13, lineHeight: 1.5, letterSpacing: '-0.01em',
        }}>{message.text}</div>
      </div>
    );
  }
  if (message.typing) {
    return (
      <div style={{ display: 'flex', marginBottom: 10, gap: 8 }}>
        <div style={{
          width: 26, height: 26, borderRadius: '50%',
          background: 'linear-gradient(135deg, #a78bfa, #7c3aed)',
          display: 'grid', placeItems: 'center', flexShrink: 0,
        }}><Icons.Sparkle size={12} /></div>
        <div style={{
          background: 'var(--bg-2)', borderRadius: '16px 16px 16px 4px',
          padding: '12px 14px', display: 'flex', gap: 4, alignItems: 'center',
          border: '1px solid var(--line-soft)',
        }}>
          {[0, 1, 2].map(i => (
            <div key={i} style={{
              width: 6, height: 6, borderRadius: '50%', background: 'var(--ink-3)',
              animation: `bounce 1.2s infinite ${i * 0.15}s`,
            }} />
          ))}
          <style>{`@keyframes bounce { 0%, 60%, 100% { opacity: 0.3; transform: translateY(0); } 30% { opacity: 1; transform: translateY(-3px); } }`}</style>
        </div>
      </div>
    );
  }
  if (message.card) {
    return (
      <div style={{ marginBottom: 10, marginLeft: 34 }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {DATA.merchants.slice(0, 3).map((m, i) => (
            <div key={m.id} onClick={() => onOpenMerchant(m)}
              style={{
                background: i === 0
                  ? 'linear-gradient(135deg, rgba(225,10,23,0.12), rgba(225,10,23,0.04))'
                  : 'var(--bg-2)',
                border: i === 0 ? '1px solid rgba(225,10,23,0.4)' : '1px solid var(--line)',
                borderRadius: 14, padding: 12, cursor: 'pointer',
              }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 6 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                  <span style={{
                    width: 18, height: 18, borderRadius: '50%',
                    background: i === 0 ? 'var(--accent)' : 'var(--bg-4)',
                    color: '#fff', fontSize: 10, fontWeight: 700,
                    display: 'grid', placeItems: 'center',
                  }}>{i + 1}</span>
                  <span style={{ fontSize: 13, fontWeight: 700 }}>{m.name}</span>
                </div>
                {i === 0 && <span className="badge" style={{ background: 'var(--accent)', color: '#fff', fontSize: 8 }}>BEST</span>}
              </div>
              <div style={{ fontSize: 10, color: 'var(--ink-3)', display: 'flex', gap: 8, marginBottom: 8 }}>
                <Stars rating={m.rating} size={10} />
                <span>· {m.distance}</span>
                <span>· {m.priceRange.split(' — ')[0]} 起</span>
              </div>
              <div style={{ display: 'flex', gap: 6 }}>
                <button className="btn-primary" style={{ flex: 1, padding: '7px', fontSize: 11 }}>
                  <Icons.Direction size={11} /> 導航
                </button>
                <button className="btn-secondary" style={{ flex: 1, padding: '7px', fontSize: 11 }}>
                  <Icons.Chat size={11} /> 預約
                </button>
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }
  return (
    <div style={{ display: 'flex', marginBottom: 10, gap: 8 }}>
      <div style={{
        width: 26, height: 26, borderRadius: '50%',
        background: 'linear-gradient(135deg, #a78bfa, #7c3aed)',
        display: 'grid', placeItems: 'center', flexShrink: 0,
      }}><Icons.Sparkle size={12} /></div>
      <div style={{
        maxWidth: '78%',
        background: 'var(--bg-2)', color: 'var(--ink-0)',
        padding: '10px 14px', borderRadius: '16px 16px 16px 4px',
        fontSize: 13, lineHeight: 1.5, letterSpacing: '-0.01em',
        border: '1px solid var(--line-soft)',
      }}>{message.text}</div>
    </div>
  );
};

const ScreenChat = ({ conversation, onBack }) => {
  const [text, setText] = React.useState('');
  const messages = [
    { from: 'them', text: '你好，多謝有興趣 M3', time: '14:20' },
    { from: 'me', text: '車況點？有事故記錄嗎', time: '14:22' },
    { from: 'them', text: '原廠保養紀錄齊全，無事故，可以同你睇 carfax 報告', time: '14:25' },
    { from: 'them', text: '可以約聽日下午睇車', time: '14:32' },
  ];
  return (
    <div className="screen screen-enter">
      <StatusBar />
      <div className="nav-bar" style={{ borderBottom: '0.5px solid var(--line)', paddingBottom: 12 }}>
        <button className="icon-btn" onClick={onBack}><Icons.Back size={18} /></button>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <Avatar name={conversation.avatar} size={32} />
          <div>
            <div style={{ fontSize: 13, fontWeight: 700, display: 'flex', alignItems: 'center' }}>
              {conversation.name}{conversation.verified && <VerifiedDot size={11} color="var(--accent)" />}
            </div>
            <div style={{ fontSize: 10, color: conversation.online ? 'var(--green)' : 'var(--ink-3)' }}>
              {conversation.online ? '● 在線' : '上次見於 1 小時前'}
            </div>
          </div>
        </div>
        <button className="icon-btn"><Icons.Phone size={14} /></button>
      </div>
      {conversation.car && (
        <div style={{ padding: '10px 16px', background: 'var(--bg-1)', borderBottom: '0.5px solid var(--line)' }}>
          <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>傾緊：</div>
          <div style={{ fontSize: 12, color: 'var(--ink-0)', fontWeight: 600 }}>{conversation.car}</div>
        </div>
      )}
      <div className="scroll" style={{ padding: '16px', display: 'flex', flexDirection: 'column', gap: 8, paddingBottom: 100 }}>
        {messages.map((m, i) => (
          <div key={i} style={{ display: 'flex', justifyContent: m.from === 'me' ? 'flex-end' : 'flex-start' }}>
            <div style={{
              maxWidth: '78%',
              background: m.from === 'me' ? 'var(--accent)' : 'var(--bg-2)',
              color: m.from === 'me' ? '#fff' : 'var(--ink-0)',
              padding: '9px 13px',
              borderRadius: m.from === 'me' ? '16px 16px 4px 16px' : '16px 16px 16px 4px',
              fontSize: 13, lineHeight: 1.4,
            }}>{m.text}</div>
          </div>
        ))}
      </div>
      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0,
        padding: '12px 16px 28px',
        background: 'rgba(8,8,10,0.95)', backdropFilter: 'blur(20px)',
        borderTop: '0.5px solid var(--line)',
      }}>
        <div style={{
          background: 'var(--bg-2)', borderRadius: 22,
          display: 'flex', alignItems: 'center', gap: 8,
          padding: '6px 6px 6px 16px',
        }}>
          <input value={text} onChange={(e) => setText(e.target.value)}
            placeholder="訊息…" style={{ flex: 1, fontSize: 13, padding: '8px 0' }} />
          <button style={{
            width: 34, height: 34, borderRadius: '50%',
            background: 'var(--accent)', display: 'grid', placeItems: 'center', color: '#fff',
          }}><Icons.Send size={14} /></button>
        </div>
      </div>
    </div>
  );
};

const ScreenBooking = ({ merchant, onClose, onConfirm }) => {
  const [day, setDay] = React.useState(2);
  const [time, setTime] = React.useState(2);
  const days = ['今日', '聽日', '周六', '周日', '下周一', '下周二', '下周三'];
  const times = ['10:00', '11:30', '14:00', '15:30', '17:00', '19:00'];
  return (
    <div className="screen screen-enter">
      <StatusBar />
      <div className="nav-bar">
        <button className="icon-btn" onClick={onClose}><Icons.Close size={18} /></button>
        <div style={{ fontSize: 13, fontWeight: 600 }}>預約服務</div>
        <div style={{ width: 36 }} />
      </div>
      <div className="scroll" style={{ padding: '0 20px 100px' }}>
        <div style={{
          padding: 14, background: 'var(--bg-1)', borderRadius: 14,
          border: '1px solid var(--line)',
          display: 'flex', gap: 10, alignItems: 'center',
        }}>
          <div style={{
            width: 44, height: 44, borderRadius: 10,
            background: 'linear-gradient(135deg, #a78bfa, #7c3aed)',
            display: 'grid', placeItems: 'center',
          }}><Icons.Sparkle size={20} /></div>
          <div>
            <div style={{ fontSize: 13, fontWeight: 700 }}>{merchant.name}</div>
            <div style={{ fontSize: 10, color: 'var(--ink-3)' }}>{merchant.distance} · {merchant.hours}</div>
          </div>
        </div>

        <div style={{ marginTop: 20 }}>
          <div className="meta" style={{ marginBottom: 10 }}>選擇服務</div>
          <div style={{ padding: 14, background: 'var(--bg-2)', borderRadius: 12, border: '1px solid var(--accent)' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{merchant.services[0]}</div>
                <div style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 2 }}>~ 3 小時</div>
              </div>
              <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--accent-bright)' }}>HK$3,800</div>
            </div>
          </div>
        </div>

        <div style={{ marginTop: 20 }}>
          <div className="meta" style={{ marginBottom: 10 }}>日期</div>
          <div className="hscroll" style={{ display: 'flex', gap: 6, margin: '0 -20px', padding: '0 20px' }}>
            {days.map((d, i) => (
              <button key={i} onClick={() => setDay(i)}
                style={{
                  flexShrink: 0, padding: '12px 14px', minWidth: 64,
                  background: day === i ? 'var(--accent)' : 'var(--bg-2)',
                  border: `1px solid ${day === i ? 'var(--accent)' : 'var(--line)'}`,
                  borderRadius: 10,
                  display: 'flex', flexDirection: 'column', gap: 2,
                  color: day === i ? '#fff' : 'var(--ink-1)',
                }}>
                <span style={{ fontSize: 11, opacity: 0.8 }}>{d}</span>
                <span style={{ fontSize: 16, fontWeight: 700 }}>{28 + i}</span>
              </button>
            ))}
          </div>
        </div>

        <div style={{ marginTop: 20 }}>
          <div className="meta" style={{ marginBottom: 10 }}>時間</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
            {times.map((t, i) => (
              <button key={i} onClick={() => setTime(i)}
                style={{
                  padding: '12px', borderRadius: 10,
                  background: time === i ? 'var(--accent)' : 'var(--bg-2)',
                  border: `1px solid ${time === i ? 'var(--accent)' : 'var(--line)'}`,
                  fontSize: 13, fontWeight: 600,
                  color: time === i ? '#fff' : 'var(--ink-1)',
                }}>{t}</button>
            ))}
          </div>
        </div>

        <div style={{ marginTop: 20, padding: 14, background: 'var(--bg-1)', borderRadius: 12, border: '1px solid var(--line)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: 'var(--ink-2)', marginBottom: 6 }}>
            <span>服務費</span><span>HK$3,800</span>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: 'var(--ink-2)', marginBottom: 6 }}>
            <span>訂金（10%）</span><span>HK$380</span>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', paddingTop: 8, borderTop: '0.5px solid var(--line)' }}>
            <span style={{ fontSize: 12 }}>立即支付</span>
            <span style={{ fontSize: 16, fontWeight: 700, color: 'var(--accent-bright)' }}>HK$380</span>
          </div>
        </div>
      </div>
      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0,
        padding: '14px 20px 32px',
        background: 'rgba(8,8,10,0.95)', backdropFilter: 'blur(20px)',
        borderTop: '0.5px solid var(--line)',
      }}>
        <button onClick={onConfirm} className="btn-primary" style={{ width: '100%' }}>
          確認預約 · {days[day]} {times[time]}
        </button>
      </div>
    </div>
  );
};

window.ScreenInbox = ScreenInbox;
window.ScreenAIAgent = ScreenAIAgent;
window.ScreenChat = ScreenChat;
window.ScreenBooking = ScreenBooking;
