/* ============================================================
   Brite Bird Coach — Chat surface
   ============================================================ */

const ChatBubble = ({ from, body, leadCard, actions, onAction }) => {
  const isCoach = from === 'coach';
  const isRep = from === 'rep';
  return (
    <div style={{
      display: 'flex', gap: 10, marginBottom: 14,
      flexDirection: isRep ? 'row-reverse' : 'row',
    }}>
      {isCoach && (
        <div style={{
          width: 34, height: 34, borderRadius: 999,
          background: 'var(--bb-pink)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          flex: 'none', overflow: 'hidden',
        }}>
          <img src="shared-assets/logos/ray/core.svg" alt="" style={{ width: 28, marginTop: 2, filter: 'brightness(0) invert(1)' }} />
        </div>
      )}
      <div style={{ maxWidth: '78%' }}>
        <div style={{
          padding: '11px 14px', borderRadius: 18,
          background: isRep ? 'var(--bb-plum)' : 'white',
          color: isRep ? 'white' : 'var(--bb-plum)',
          fontSize: 14.5, fontWeight: 100, lineHeight: 1.4,
          boxShadow: isRep ? 'none' : 'var(--shadow-sm)',
          borderBottomLeftRadius: isCoach ? 4 : 18,
          borderBottomRightRadius: isRep ? 4 : 18,
        }}>{body}</div>
        {leadCard && (
          <div style={{
            marginTop: 8, padding: '12px 14px',
            background: 'var(--bb-cream)', borderRadius: 18,
            borderLeft: '4px solid var(--bb-orange)',
          }}>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--bb-orange)' }}>New lead logged</div>
            <div style={{ fontSize: 16, fontWeight: 700, marginTop: 3 }}>{leadCard.name}</div>
            <div style={{ fontSize: 13, fontWeight: 100, color: 'var(--bb-ink-60)', marginTop: 2 }}>
              {leadCard.quote} · {leadCard.package} · decide by {leadCard.decide}
            </div>
          </div>
        )}
        {actions && actions.length > 0 && (
          <div style={{ display: 'flex', gap: 6, marginTop: 8, flexWrap: 'wrap' }}>
            {actions.map((a, i) => (
              <button key={i} onClick={() => onAction && onAction(a)} style={{
                background: a.primary ? 'var(--bb-pink)' : 'transparent',
                color: a.primary ? 'white' : 'var(--bb-plum)',
                border: a.primary ? 0 : '1.5px solid var(--bb-ink-20)',
                borderRadius: 999, padding: '8px 14px',
                fontFamily: 'var(--font-family-base)',
                fontSize: 13, fontWeight: 700, letterSpacing: '0.02em',
                cursor: 'pointer',
                display: 'inline-flex', alignItems: 'center', gap: 4,
              }}>
                {a.icon && <Icon name={a.icon} size={12} stroke={2.4} />}
                {a.label}
              </button>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

const TypingIndicator = () => (
  <div style={{
    display: 'flex', gap: 10, marginBottom: 14,
  }}>
    <div style={{
      width: 34, height: 34, borderRadius: 999,
      background: 'var(--bb-pink)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      flex: 'none', overflow: 'hidden',
    }}>
      <img src="shared-assets/logos/ray/core.svg" alt="" style={{ width: 28, marginTop: 2, filter: 'brightness(0) invert(1)' }} />
    </div>
    <div style={{
      padding: '14px 18px', borderRadius: 18,
      background: 'white',
      boxShadow: 'var(--shadow-sm)',
      borderBottomLeftRadius: 4,
      display: 'inline-flex', alignItems: 'center', gap: 4,
    }}>
      <span style={{
        width: 6, height: 6, borderRadius: 999, background: 'var(--bb-ink-40)',
        animation: 'typingBounce 1.2s infinite ease-in-out',
        animationDelay: '0s',
      }} />
      <span style={{
        width: 6, height: 6, borderRadius: 999, background: 'var(--bb-ink-40)',
        animation: 'typingBounce 1.2s infinite ease-in-out',
        animationDelay: '0.18s',
      }} />
      <span style={{
        width: 6, height: 6, borderRadius: 999, background: 'var(--bb-ink-40)',
        animation: 'typingBounce 1.2s infinite ease-in-out',
        animationDelay: '0.36s',
      }} />
    </div>
    <style>{`
      @keyframes typingBounce {
        0%, 60%, 100% { transform: translateY(0); opacity: 0.3; }
        30% { transform: translateY(-4px); opacity: 1; }
      }
    `}</style>
  </div>
);

const SuggestedChip = ({ children, onClick }) => (
  <button onClick={onClick} style={{
    background: 'white', border: '1.5px solid var(--bb-ink-20)',
    color: 'var(--bb-plum)', borderRadius: 999,
    padding: '9px 14px', fontFamily: 'var(--font-family-base)',
    fontSize: 13, fontWeight: 700, cursor: 'pointer',
    whiteSpace: 'nowrap', flex: 'none',
  }}>{children}</button>
);

const ChatScreen = () => {
  const [messages, setMessages] = React.useState(CHAT_INTRO);
  const [input, setInput] = React.useState('');
  const [voiceActive, setVoiceActive] = React.useState(false);
  const [coachTyping, setCoachTyping] = React.useState(false);
  const scrollRef = React.useRef(null);

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

  const respond = (q) => {
    const lower = q.toLowerCase();
    let reply = "Got it.";
    let leadCard = null;
    let actions = null;
    if (lower.includes('frisco') || lower.includes('mike')) {
      reply = "Mike Reyes — $7,200, holiday + bistro. He just texted 'send me the financing thing' 14 min ago. Draft is queued in Today. Want me to send it now?";
      actions = [
        { label: 'Yes, send', icon: 'send', primary: true, kind: 'send-mike' },
        { label: 'Not yet', kind: 'dismiss' },
      ];
    } else if (lower.includes('snooze') && lower.includes('sarah')) {
      reply = "Done. Sarah Mitchell snoozed until Monday. I'll keep watching for replies and ping you if she texts.";
    } else if (lower.includes('hot') || lower.includes("who's")) {
      reply = "Mike Reyes (92) and Diaz (88). Sarah's at 78 but decides today — that's the squeeze.";
      actions = [
        { label: 'Open Mike', icon: 'arrow-right', kind: 'open-mike' },
        { label: 'Open Sarah', icon: 'arrow-right', kind: 'open-sarah' },
      ];
    } else if (lower.includes('tom carter') || lower.includes('draft')) {
      reply = "Drafted a soft breakup for Tom Carter — open it on Today and tap approve. Reads warm, no pressure.";
      actions = [
        { label: 'Show me', icon: 'arrow-right', primary: true, kind: 'open-tom' },
      ];
    } else if (lower.includes('john smith') || lower.includes('saw')) {
      reply = "Logged. I'll start the follow-up cadence Friday morning. Anything else from the conversation I should know?";
      leadCard = { name: 'John Smith', quote: '$5,000', package: 'Holiday + Bistro', decide: 'Friday' };
    } else {
      reply = "On it — anything specific you want me to pull up?";
    }
    return { reply, leadCard, actions };
  };

  const handleAction = (action) => {
    // For prototype: just acknowledge in chat. Real version routes to Today/deep-dive.
    setMessages(m => [...m, { from: 'rep', body: action.label }]);
    setCoachTyping(true);
    setTimeout(() => {
      setCoachTyping(false);
      let reply = "Done.";
      if (action.kind === 'send-mike') reply = "Sent. Mike will get the 0% / 24-mo plan now.";
      else if (action.kind === 'dismiss') reply = "Holding it. Tap Today when you're ready.";
      else if (action.kind && action.kind.startsWith('open-')) reply = "Opening — pull down on the lead view.";
      setMessages(m => [...m, { from: 'coach', body: reply }]);
    }, 700);
  };

  const send = (text) => {
    if (!text.trim()) return;
    setMessages(m => [...m, { from: 'rep', body: text }]);
    setInput('');
    setCoachTyping(true);
    setTimeout(() => {
      setCoachTyping(false);
      const { reply, leadCard, actions } = respond(text);
      setMessages(m => [...m, { from: 'coach', body: reply, leadCard, actions }]);
    }, 1100);
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <TopAppBar
        sub="Talk to Coach"
        title="Chat"
        right={<IconButton icon="more-horizontal" />}
      />

      <div ref={scrollRef} style={{ flex: 1, overflowY: 'auto', padding: '8px 18px 12px' }}>
        {messages.length === 1 && (
          <div style={{
            margin: '8px 0 18px', padding: '20px 18px',
            background: 'var(--bb-yellow)', borderRadius: 22,
            display: 'flex', gap: 14, alignItems: 'center',
            boxShadow: '0 4px 0 0 var(--bb-plum)',
          }}>
            <img src="shared-assets/logos/ray/core.svg" alt="" style={{ width: 56, flex: 'none' }} />
            <div>
              <div style={{ fontSize: 18, fontWeight: 700, lineHeight: 1.15, letterSpacing: '-0.01em' }}>
                Ask. Inject. Snooze.
              </div>
              <div style={{ fontSize: 13, fontWeight: 100, marginTop: 4, lineHeight: 1.4 }}>
                Voice or text. I'll do the rest.
              </div>
            </div>
          </div>
        )}

        {messages.map((m, i) => <ChatBubble key={i} {...m} onAction={handleAction} />)}

        {coachTyping && <TypingIndicator />}

        {voiceActive && (
          <div style={{
            margin: '4px 0', padding: '14px 18px',
            background: 'var(--bb-pink)', color: 'white', borderRadius: 22,
            display: 'flex', alignItems: 'center', gap: 12,
          }}>
            <Icon name="mic" size={18} color="white" stroke={2.4} />
            <div style={{ flex: 1, fontSize: 14, fontWeight: 100 }}>Listening… "snooze sarah until monday"</div>
            <div style={{ display: 'flex', gap: 2 }}>
              {[10, 18, 24, 14, 20].map((h, i) => (
                <span key={i} style={{ width: 2, height: h, background: 'white', borderRadius: 999, opacity: 0.7 }} />
              ))}
            </div>
          </div>
        )}
      </div>

      {/* Suggested prompts */}
      <div style={{
        display: 'flex', gap: 6, padding: '4px 14px 10px',
        overflowX: 'auto', scrollbarWidth: 'none',
      }}>
        {SUGGESTED_PROMPTS.map(p => (
          <SuggestedChip key={p} onClick={() => send(p)}>{p}</SuggestedChip>
        ))}
      </div>

      {/* Input bar */}
      <div style={{
        padding: '10px 12px 14px',
        background: 'white',
        borderTop: '1px solid var(--bb-ink-10)',
        display: 'flex', alignItems: 'center', gap: 8,
      }}>
        <button style={{
          width: 42, height: 42, borderRadius: 999,
          background: 'var(--bb-ink-10)', color: 'var(--bb-plum)', border: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', flex: 'none',
        }}>
          <Icon name="plus" size={20} stroke={2.4} />
        </button>
        <div style={{
          flex: 1, display: 'flex', alignItems: 'center',
          background: 'var(--bb-ink-05)', borderRadius: 999,
          padding: '0 6px 0 16px',
        }}>
          <input
            value={input}
            onChange={e => setInput(e.target.value)}
            onKeyDown={e => { if (e.key === 'Enter') send(input); }}
            placeholder="Ask Coach…"
            style={{
              flex: 1, border: 0, background: 'transparent',
              fontFamily: 'var(--font-family-base)', fontSize: 15, fontWeight: 100,
              color: 'var(--bb-plum)', padding: '11px 0', outline: 'none',
            }}
          />
        </div>
        <button onClick={() => {
          setVoiceActive(true);
          setTimeout(() => { setVoiceActive(false); send('snooze Sarah until Monday'); }, 1400);
        }} style={{
          width: 56, height: 56, borderRadius: 999,
          background: 'var(--bb-grad-sunrise)', color: 'white', border: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          cursor: 'pointer', flex: 'none',
          boxShadow: '0 4px 0 0 var(--bb-plum)',
        }}>
          <Icon name="mic" size={22} stroke={2.4} />
        </button>
      </div>
    </div>
  );
};

Object.assign(window, { ChatScreen });
