// AI Assistant — conversational chat with Sofia
// As respostas vêm de window.SofiaAPI (Edge Function `sofia-chat`).
// Se a chave OpenAI não estiver configurada, o client cai automaticamente
// num fallback local (mock leve) sem quebrar a experiência.

const AIScreen = ({ state, setState, navigate, showToast, user }) => {
  // Carrega histórico salvo em state.aiMessages (persiste via cloud-sync).
  // Se não houver histórico, mostra mensagem de boas-vindas personalizada (não o mock antigo do Lucas).
  const userFirstName = (user && user.name && String(user.name).split(' ')[0])
    || (user && user.email && user.email.split('@')[0])
    || 'aí';
  const welcomeMsg = {
    from: 'ai',
    text: `Olá, ${userFirstName}! 👋 Sou a Sofia, sua assistente pessoal. Posso te ajudar com tarefas, finanças, hábitos, metas e até consultar seu cofre pessoal. O que você quer fazer agora?`,
  };
  const initialMessages = (state && Array.isArray(state.aiMessages) && state.aiMessages.length > 0)
    ? state.aiMessages
    : [welcomeMsg];
  const [messages, setMessages] = React.useState(initialMessages);
  const [input, setInput] = React.useState('');
  const [typing, setTyping] = React.useState(false);
  const [voiceMode, setVoiceMode] = React.useState(false);
  const scrollRef = React.useRef(null);

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

  // Persiste mensagens no state global (cloud-sync salva automaticamente).
  // Mantém só as últimas 50 pra não inchar (Sofia usa só as 6 mais recentes pro contexto).
  const persistMessages = (next) => {
    if (!setState) return;
    const trimmed = next.length > 50 ? next.slice(-50) : next;
    setState(s => ({ ...s, aiMessages: trimmed }));
  };

  const send = async (text) => {
    if (!text.trim()) return;
    const userMsg = { from: 'me', text };
    const afterUser = [...messages, userMsg];
    setMessages(afterUser);
    persistMessages(afterUser);
    setInput('');
    setTyping(true);

    const userName = (user && (user.name || user.email)) || (state && state.userName) || 'Lucas';
    const userState = window.SofiaAPI ? window.SofiaAPI.buildUserState(state, userName) : null;

    try {
      const res = window.SofiaAPI
        ? await window.SofiaAPI.chat({ messages, userState, newMessage: text })
        : { reply: 'Sofia ainda não está disponível. Volte daqui a pouco ✨', mode: 'mock' };
      setTyping(false);
      const afterAi = [...afterUser, { from: 'ai', text: res.reply }];
      setMessages(afterAi);
      persistMessages(afterAi);
      if (res.mode === 'rate_limit' && showToast) {
        showToast('Limite diário atingido', 'flame');
      }
    } catch (e) {
      setTyping(false);
      const afterError = [...afterUser, { from: 'ai', text: 'Tive um problema agora, tenta de novo em alguns segundos? ✨' }];
      setMessages(afterError);
      persistMessages(afterError);
    }
  };

  if (voiceMode) return <VoiceMode onClose={() => setVoiceMode(false)} onSend={(t) => { setVoiceMode(false); send(t); }} />;

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', paddingBottom: 110 }}>
      {/* Header */}
      <div style={{ padding: '4px 22px 14px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ position: 'relative' }}>
              <div style={{
                width: 46, height: 46, borderRadius: 14, background: CDV.brandGrad,
                display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff',
                boxShadow: '0 8px 24px -8px rgba(177,151,252,0.6)',
              }}><Icon name="sparkle" size={22} /></div>
              <div style={{
                position: 'absolute', bottom: -2, right: -2, width: 14, height: 14, borderRadius: 99,
                background: CDV.mint, border: `2.5px solid ${CDV.bg}`,
              }} />
            </div>
            <div>
              <div style={{ fontSize: 18, fontWeight: 700, color: CDV.text, letterSpacing: -0.3 }}>Sofia</div>
              <div style={{ fontSize: 11, color: CDV.mint, display: 'flex', alignItems: 'center', gap: 4 }}>
                <div style={{ width: 6, height: 6, borderRadius: 99, background: CDV.mint }} />
                Sua assistente pessoal · Online
              </div>
            </div>
          </div>
          <Pill color={CDV.amber} size="sm">
            <Icon name="diamond" size={10} /> Premium
          </Pill>
        </div>
      </div>

      {/* Messages */}
      <div ref={scrollRef} style={{ flex: 1, overflowY: 'auto', padding: '0 18px 16px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        <div style={{ textAlign: 'center', fontSize: 11, color: CDV.textMuted, padding: '12px 0' }}>
          Hoje, 9:24
        </div>
        {messages.map((m, i) => <Bubble key={i} message={m} />)}
        {typing && <TypingBubble />}

        {/* Suggestions chips */}
        {messages.length < 8 && !typing && (
          <div style={{ marginTop: 10 }}>
            <div style={{ fontSize: 11, color: CDV.textMuted, fontWeight: 600, letterSpacing: 0.4, textTransform: 'uppercase', marginBottom: 8, padding: '0 4px' }}>Sugestões para você</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {suggestionsAI.map((s, i) => (
                <button key={i} onClick={() => send(s)} style={{
                  padding: '12px 14px', borderRadius: 14, textAlign: 'left',
                  background: CDV.surface, border: `1px solid ${CDV.stroke}`, color: CDV.text,
                  fontSize: 13, fontFamily: 'inherit',
                  display: 'flex', alignItems: 'center', gap: 10,
                }}>
                  <Icon name="sparkle" size={14} color={CDV.brand} />
                  <span style={{ flex: 1 }}>{s}</span>
                  <Icon name="arrowRight" size={14} color={CDV.textDim} />
                </button>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* Input bar */}
      <div style={{
        margin: '0 18px',
        padding: 8, borderRadius: 24,
        background: 'rgba(20,19,28,0.78)',
        backdropFilter: 'blur(28px) saturate(180%)',
        WebkitBackdropFilter: 'blur(28px) saturate(180%)',
        border: `1px solid ${CDV.strokeHi}`,
        display: 'flex', alignItems: 'flex-end', gap: 8,
      }}>
        <button style={{
          width: 38, height: 38, borderRadius: 12, background: CDV.surfaceHi, border: 'none',
          color: CDV.textDim, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
        }}><Icon name="plus" size={18} /></button>
        <textarea
          value={input} onChange={e => setInput(e.target.value)}
          onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(input); } }}
          placeholder="Pergunte qualquer coisa..."
          rows={1}
          style={{
            flex: 1, background: 'transparent', border: 'none', outline: 'none',
            color: CDV.text, fontSize: 15, fontFamily: 'inherit', resize: 'none',
            padding: '10px 4px', maxHeight: 80,
          }} />
        {input.trim() ? (
          <button onClick={() => send(input)} style={{
            width: 38, height: 38, borderRadius: 12, background: CDV.brandGrad, border: 'none', color: '#fff',
            display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
          }}><Icon name="send" size={16} /></button>
        ) : (
          <button onClick={() => setVoiceMode(true)} style={{
            width: 38, height: 38, borderRadius: 12, background: CDV.brandGrad, border: 'none', color: '#fff',
            display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
          }}><Icon name="mic" size={18} /></button>
        )}
      </div>
    </div>
  );
};

const Bubble = ({ message }) => {
  const isMe = message.from === 'me';
  return (
    <div style={{
      display: 'flex', justifyContent: isMe ? 'flex-end' : 'flex-start',
      animation: 'slideUp .3s cubic-bezier(.2,.7,.2,1)',
    }}>
      {!isMe && (
        <div style={{
          width: 28, height: 28, borderRadius: 9, background: CDV.brandGrad, marginRight: 8, flexShrink: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff',
        }}><Icon name="sparkle" size={14} /></div>
      )}
      <div style={{
        maxWidth: '78%', padding: '11px 14px', borderRadius: 18,
        background: isMe ? CDV.brandGrad : CDV.surface,
        color: '#fff',
        border: isMe ? 'none' : `1px solid ${CDV.stroke}`,
        borderBottomRightRadius: isMe ? 6 : 18,
        borderBottomLeftRadius: !isMe ? 6 : 18,
        fontSize: 14, lineHeight: 1.4, fontWeight: isMe ? 500 : 400,
        boxShadow: isMe ? '0 4px 14px -4px rgba(177,151,252,0.4)' : 'none',
      }}>{message.text}</div>
    </div>
  );
};

const TypingBubble = () => (
  <div style={{ display: 'flex', alignItems: 'flex-end' }}>
    <div style={{
      width: 28, height: 28, borderRadius: 9, background: CDV.brandGrad, marginRight: 8, flexShrink: 0,
      display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff',
    }}><Icon name="sparkle" size={14} /></div>
    <div style={{
      padding: '14px 16px', borderRadius: 18, borderBottomLeftRadius: 6,
      background: CDV.surface, border: `1px solid ${CDV.stroke}`,
      display: 'flex', gap: 4,
    }}>
      {[0, 1, 2].map(i => (
        <div key={i} style={{
          width: 6, height: 6, borderRadius: 99, background: CDV.textDim,
          animation: `typing 1.2s ease-in-out infinite`, animationDelay: `${i * 0.15}s`,
        }} />
      ))}
    </div>
  </div>
);

// ── Voice mode (full screen) ───────────────────────────────
const VoiceMode = ({ onClose, onSend }) => {
  const [listening, setListening] = React.useState(true);
  const [transcript, setTranscript] = React.useState('Me lembra de pagar a conta amanhã às 14h');

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 95,
      background: `
        radial-gradient(800px 400px at 50% 30%, rgba(177,151,252,0.25), transparent 70%),
        radial-gradient(600px 300px at 50% 80%, rgba(255,143,177,0.15), transparent 70%),
        ${CDV.bg}`,
      display: 'flex', flexDirection: 'column', padding: '70px 22px 100px',
    }}>
      <StatusBar />
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 14 }}>
        <button onClick={onClose} style={{
          background: 'rgba(255,255,255,0.08)', border: `1px solid ${CDV.strokeHi}`,
          width: 38, height: 38, borderRadius: 99, color: CDV.text,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}><Icon name="chevronDown" size={18} /></button>
        <div style={{ fontSize: 13, color: CDV.textDim, fontWeight: 500 }}>Modo voz · Sofia</div>
        <div style={{ width: 38 }} />
      </div>

      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', gap: 36 }}>
        <div style={{ position: 'relative', width: 220, height: 220 }}>
          {[0, 1, 2].map(i => (
            <div key={i} style={{
              position: 'absolute', inset: 0, borderRadius: 99,
              border: `2px solid ${CDV.brand}`,
              animation: 'ringPulse 2.2s ease-out infinite',
              animationDelay: `${i * 0.7}s`, opacity: 0.7,
            }} />
          ))}
          <div style={{
            position: 'absolute', inset: 30, borderRadius: 99,
            background: CDV.brandGrad,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            boxShadow: '0 20px 60px -10px rgba(177,151,252,0.6)',
          }}>
            <Icon name="mic" size={64} color="#fff" />
          </div>
        </div>

        <div style={{ textAlign: 'center', maxWidth: 320 }}>
          <div style={{ fontSize: 11, color: CDV.brand, fontWeight: 700, letterSpacing: 0.5, textTransform: 'uppercase', marginBottom: 10 }}>
            Ouvindo...
          </div>
          <div style={{ fontSize: 22, color: CDV.text, fontWeight: 600, letterSpacing: -0.3, lineHeight: 1.3 }}>
            "{transcript}"
          </div>
        </div>
      </div>

      <button onClick={() => onSend(transcript)} style={{
        height: 56, borderRadius: 18, border: 'none',
        background: CDV.text, color: '#000', fontWeight: 600, fontSize: 15,
      }}>Enviar agora</button>
      <HomeIndicator light />
    </div>
  );
};

Object.assign(window, { AIScreen });
