/* DNA da Assistente — config da personalidade e comportamento da IA */

const SliderField = ({ label, value, onChange, min = 0, max = 100, leftLabel, rightLabel, color }) => {
  const t = useTheme();
  const isBloom = t.name === 'BLOOM';
  const pct = ((value - min) / (max - min)) * 100;
  return (
    <div style={{ marginBottom: 22 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10 }}>
        <span style={{ fontSize: 13, fontWeight: 600, color: t.text }}>{label}</span>
        <span style={{ fontFamily: t.fontMono, fontSize: 12, color: color || t.primary, fontWeight: 700 }}>{value}</span>
      </div>
      <div style={{ position: 'relative' }}>
        <div style={{
          height: 6, borderRadius: 99,
          background: isBloom ? t.surfaceAlt : 'rgba(255,255,255,0.05)',
          border: isBloom ? `1.5px solid ${t.border}` : 'none',
        }}>
          <div style={{ height: '100%', width: pct + '%', borderRadius: 99, background: color || t.primary }}/>
        </div>
        <div style={{
          position: 'absolute', left: `calc(${pct}% - 8px)`, top: -5,
          width: 16, height: 16, borderRadius: '50%', background: t.surface,
          border: isBloom ? `1.5px solid ${t.border}` : `2px solid ${color || t.primary}`,
          boxShadow: isBloom ? '2px 2px 0 0 #14131A' : '0 2px 8px rgba(0,0,0,0.4)',
        }}/>
        <input type="range" min={min} max={max} value={value} onChange={e => onChange(+e.target.value)}
          style={{ position: 'absolute', inset: 0, opacity: 0, cursor: 'pointer', width: '100%' }}/>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 7, fontSize: 11, color: t.textMuted, fontFamily: t.fontMono, letterSpacing: '0.04em' }}>
        <span>{leftLabel}</span><span>{rightLabel}</span>
      </div>
    </div>
  );
};

const Toggle = ({ on, onToggle, label, sub, icon: I }) => {
  const t = useTheme();
  const isBloom = t.name === 'BLOOM';
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 0',
      borderBottom: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
    }}>
      {I && <div style={{
        width: 32, height: 32, borderRadius: isBloom ? 8 : 8,
        background: isBloom ? t.surfaceAlt : 'rgba(255,255,255,0.04)',
        border: isBloom ? `1.5px solid ${t.border}` : 'none',
        display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
      }}><I size={15} stroke={t.textMuted}/></div>}
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: t.text }}>{label}</div>
        {sub && <div style={{ fontSize: 11.5, color: t.textMuted, marginTop: 2 }}>{sub}</div>}
      </div>
      <button onClick={onToggle} style={{
        width: 38, height: 22, borderRadius: 99, position: 'relative',
        background: on ? t.green : (isBloom ? t.surfaceAlt : 'rgba(255,255,255,0.08)'),
        border: isBloom ? `1.5px solid ${t.border}` : 'none', cursor: 'pointer',
      }}>
        <span style={{
          position: 'absolute', top: 1.5, left: on ? 17 : 2,
          width: 16, height: 16, borderRadius: '50%', background: '#fff',
          border: isBloom ? `1.5px solid ${t.border}` : 'none',
          transition: 'left 0.15s',
        }}/>
      </button>
    </div>
  );
};

const DnaAssistente = () => {
  const t = useTheme();
  const isBloom = t.name === 'BLOOM';
  const { data: aiConfig } = useAiConfig();
  const { data: triggersData } = useAiTriggers();
  const saveTrigger = useSaveAiTrigger();
  const deleteTrigger = useDeleteAiTrigger();
  const updateAiConfig = useUpdateAiConfig();
  const [tone, setTone] = React.useState('amigavel');
  const [name, setName] = React.useState('Assistente');
  const [companyName, setCompanyName] = React.useState('FluxoZap');
  const [mission, setMission] = React.useState('');
  const [limits, setLimits] = React.useState([]);
  const [newLimitForm, setNewLimitForm] = React.useState(false);
  const [newLimitText, setNewLimitText] = React.useState('');
  const [showSimulator, setShowSimulator] = React.useState(false);
  const [simMessages, setSimMessages] = React.useState([]);
  const [simInput, setSimInput] = React.useState('');
  const [simLoading, setSimLoading] = React.useState(false);
  const [behavior, setBehavior] = React.useState({ formalidade: 35, proatividade: 72, empatia: 88, emoji: 50 });
  const [saving, setSaving] = React.useState(false);
  const [newTriggerForm, setNewTriggerForm] = React.useState(false);
  const [newTriggerText, setNewTriggerText] = React.useState('');
  const [newTriggerAction, setNewTriggerAction] = React.useState('');

  React.useEffect(() => {
    if (aiConfig) {
      setTone(aiConfig.tone || 'amigavel');
      setName(aiConfig.name || 'Assistente');
      setCompanyName(aiConfig.companyName || 'FluxoZap');
      setMission(aiConfig.mission || '');
      setLimits(aiConfig.limits || []);
      
      const b = aiConfig.behavior || {};
      setBehavior({
        formalidade: b.formalidade ?? 35,
        proatividade: b.proatividade ?? 72,
        empatia: b.empatia ?? 88,
        emoji: b.emoji ?? 50
      });
    }
  }, [aiConfig]);

  const handleSave = async () => {
    setSaving(true);
    await updateAiConfig({ name, companyName, tone, mission, limits, behavior });
    setSaving(false);
  };

  const handleAddTrigger = async () => {
    if (!newTriggerText || !newTriggerAction) return;
    setSaving(true);
    await saveTrigger({
      trigger: newTriggerText,
      action: newTriggerAction,
      color: '#5B8DEF'
    });
    setNewTriggerText('');
    setNewTriggerAction('');
    setNewTriggerForm(false);
    setSaving(false);
  };

  const handleAddLimit = () => {
    if (!newLimitText) return;
    setLimits([...limits, { id: Date.now().toString(), label: newLimitText, on: true }]);
    setNewLimitText('');
    setNewLimitForm(false);
  };

  const handleSimulate = async () => {
    if (!simInput) return;
    const msgs = [...simMessages, { from: 'me', text: simInput }];
    setSimMessages(msgs);
    setSimInput('');
    setSimLoading(true);
    try {
      const response = await window.FluxoApi.post('/ai/simulate', { messages: msgs });
      setSimMessages([...msgs, { from: 'ia', text: response?.reply || '...' }]);
    } catch (e) {
      setSimMessages([...msgs, { from: 'ia', text: 'Erro ao simular.' }]);
    }
    setSimLoading(false);
  };

  const triggers = triggersData || [];

  if (!aiConfig) return <div style={{padding:40, color: t.text}}>Carregando DNA...</div>;

  const tones = [
    { id: 'formal', label: 'Formal', sample: 'Prezada Ana, agradecemos seu contato...' },
    { id: 'amigavel', label: 'Amigável', sample: 'Oi Ana, tudo bem? 🌞 Vamos ver isso juntinhas!' },
    { id: 'casual', label: 'Casual', sample: 'E aí Ana! Bora resolver isso 🚀' },
    { id: 'consultivo', label: 'Consultivo', sample: 'Ana, com base no que você compartilhou, sugiro...' },
  ];

  return (
    <div style={{ padding: '24px 28px 40px', maxWidth: 1320, margin: '0 auto' }}>
      <div style={{ marginBottom: 20 }}>
        <div style={{ fontSize: 11, color: t.textMuted, letterSpacing: '0.14em', fontFamily: t.fontMono, marginBottom: 4 }}>
          INTELIGÊNCIA · PERSONALIDADE
        </div>
        <h1 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 32, fontWeight: 700, letterSpacing: '-0.03em', color: t.text }}>
          DNA da Assistente
        </h1>
        <div style={{ marginTop: 8, fontSize: 14, color: t.textMuted, maxWidth: 640 }}>
          Defina a personalidade, conhecimento e regras da Assistente. Cada ajuste vai refletir em todas as conversas em até 30 segundos.
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.4fr', gap: 18 }}>
        {/* Left: identity */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <Card style={{ padding: 26, textAlign: 'center', position: 'relative', overflow: 'hidden' }}>
            <div style={{
              position: 'absolute', inset: 0,
              background: `radial-gradient(circle at 50% 0%, ${t.primarySoft} 0%, transparent 60%)`,
            }}/>
            <div style={{ position: 'relative' }}>
              <div style={{
                width: 96, height: 96, borderRadius: isBloom ? 24 : '50%', margin: '0 auto 14px',
                background: `linear-gradient(135deg, ${t.green} 0%, ${t.primary} 50%, ${t.purple} 100%)`,
                border: isBloom ? `1.5px solid ${t.border}` : 'none',
                boxShadow: isBloom ? '4px 4px 0 0 #14131A' : '0 12px 40px -8px rgba(91,141,239,0.5)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                position: 'relative',
              }}>
                <Icons.Sparkles size={36} stroke="#fff"/>
                <span style={{
                  position: 'absolute', bottom: -4, right: -4, padding: '3px 9px', borderRadius: 99,
                  background: t.green, color: '#fff', fontSize: 10, fontWeight: 700, fontFamily: t.fontMono,
                  border: isBloom ? `1.5px solid ${t.border}` : `2px solid ${t.surface}`,
                  letterSpacing: '0.06em',
                }}>v3.2</span>
              </div>
              <h2 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 28, fontWeight: 700, letterSpacing: '-0.02em', color: t.text }}>
                {name}
              </h2>
              <div style={{ marginTop: 10 }}>
                <input 
                  type="text" 
                  value={name} 
                  onChange={e => setName(e.target.value)} 
                  style={{
                    background: isBloom ? t.surfaceAlt : 'rgba(255,255,255,0.05)',
                    border: `1px solid ${t.border}`,
                    color: t.text,
                    padding: '6px 12px',
                    borderRadius: 6,
                    fontSize: 14,
                    textAlign: 'center'
                  }}
                />
              </div>
              
              <div style={{ fontSize: 13, color: t.textMuted, marginTop: 14, marginBottom: 4 }}>Empresa que representa:</div>
              <div>
                <input 
                  type="text" 
                  value={companyName} 
                  onChange={e => setCompanyName(e.target.value)} 
                  placeholder="Ex: FluxoZap"
                  style={{
                    background: isBloom ? t.surfaceAlt : 'rgba(255,255,255,0.05)',
                    border: `1px solid ${t.border}`,
                    color: t.text,
                    padding: '6px 12px',
                    borderRadius: 6,
                    fontSize: 14,
                    textAlign: 'center',
                    width: '100%',
                    boxSizing: 'border-box'
                  }}
                />
              </div>

              <div style={{ fontSize: 13, color: t.textMuted, marginTop: 14 }}>Assistente comercial · IA da loja</div>
              <div style={{ display: 'flex', justifyContent: 'center', gap: 6, marginTop: 14, flexWrap: 'wrap' }}>
                <Pill soft={t.primarySoft} color={isBloom ? t.text : t.primary}>0 conversas</Pill>
                <Pill soft={t.purpleSoft} color={isBloom ? t.text : t.purple}>NPS -</Pill>
              </div>
            </div>
          </Card>

          <Card style={{ padding: 22 }}>
            <h3 style={{ margin: '0 0 14px', fontFamily: t.fontDisplay, fontSize: 16, fontWeight: 700, color: t.text, letterSpacing: '-0.02em' }}>
              Tom de voz
            </h3>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
              {tones.map(tn => (
                <button key={tn.id} onClick={() => setTone(tn.id)} style={{
                  padding: 12, textAlign: 'left', cursor: 'pointer',
                  borderRadius: t.radiusMd,
                  background: tone === tn.id
                    ? (isBloom ? t.primary : 'rgba(91,141,239,0.13)')
                    : (isBloom ? t.bg : 'rgba(255,255,255,0.025)'),
                  color: tone === tn.id && isBloom ? '#fff' : t.text,
                  border: isBloom ? `1.5px solid ${t.border}` : `1px solid ${tone === tn.id ? 'rgba(91,141,239,0.3)' : t.border}`,
                  boxShadow: isBloom && tone === tn.id ? '3px 3px 0 0 #14131A' : 'none',
                }}>
                  <div style={{ fontSize: 13, fontWeight: 700, marginBottom: 5 }}>{tn.label}</div>
                  <div style={{ fontSize: 11, opacity: 0.8, lineHeight: 1.4 }}>"{tn.sample}"</div>
                </button>
              ))}
            </div>
          </Card>

          <Card style={{ padding: 22 }}>
            <h3 style={{ margin: '0 0 6px', fontFamily: t.fontDisplay, fontSize: 16, fontWeight: 700, color: t.text, letterSpacing: '-0.02em' }}>
              Comportamento
            </h3>
            <div style={{ fontSize: 12, color: t.textMuted, marginBottom: 6 }}>Ajuste fino da personalidade</div>
            <SliderField label="Formalidade" value={behavior.formalidade} onChange={v => setBehavior({...behavior, formalidade: v})} leftLabel="descontraído" rightLabel="formal" color={t.primary}/>
            <SliderField label="Proatividade" value={behavior.proatividade} onChange={v => setBehavior({...behavior, proatividade: v})} leftLabel="reativa" rightLabel="vendedora" color={t.orange}/>
            <SliderField label="Empatia" value={behavior.empatia} onChange={v => setBehavior({...behavior, empatia: v})} leftLabel="objetiva" rightLabel="acolhedora" color={t.pink}/>
            <SliderField label="Uso de emoji 🙂" value={behavior.emoji} onChange={v => setBehavior({...behavior, emoji: v})} leftLabel="nunca" rightLabel="sempre" color={t.purple}/>
          </Card>
        </div>

        {/* Right: rules + boundaries */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <Card style={{ padding: 22 }}>
            <h3 style={{ margin: '0 0 6px', fontFamily: t.fontDisplay, fontSize: 16, fontWeight: 700, color: t.text, letterSpacing: '-0.02em' }}>
              Missão da Assistente
            </h3>
            <div style={{ fontSize: 12, color: t.textMuted, marginBottom: 12 }}>Como você descreveria o trabalho dela?</div>
            <div style={{
              padding: 14, borderRadius: t.radiusMd,
              background: isBloom ? t.bg : 'rgba(255,255,255,0.03)',
              border: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
              fontSize: 14, lineHeight: 1.6, color: t.text, fontFamily: t.fontBody,
            }} contentEditable suppressContentEditableWarning
              onBlur={(e) => setMission(e.target.innerText)}>
              {mission || "Você é o Kiko, assistente comercial da FluxoZap. Sua missão é acolher quem chega no WhatsApp, entender o que a pessoa precisa, indicar o plano certo e fechar a venda"}
            </div>
            <div style={{ marginTop: 10, fontSize: 11, color: t.textMuted, fontFamily: t.fontMono, display: 'flex', justifyContent: 'space-between' }}>
              <span>247 caracteres · clique para editar</span>
              <Btn variant="ghost" size="sm" icon={<Icons.Sparkles size={11}/>}>Reescrever com IA</Btn>
            </div>
          </Card>

          <Card style={{ padding: 22 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 12 }}>
              <div>
                <h3 style={{ margin: '0 0 4px', fontFamily: t.fontDisplay, fontSize: 16, fontWeight: 700, color: t.text, letterSpacing: '-0.02em' }}>
                  Limites & Regras
                </h3>
                <div style={{ fontSize: 12, color: t.textMuted }}>O que a Assistente pode e não pode fazer sozinha</div>
              </div>
              <Btn variant="ghost" size="sm" onClick={() => setNewLimitForm(!newLimitForm)} icon={<Icons.Plus size={11}/>}>Adicionar</Btn>
            </div>

            {newLimitForm && (
              <div style={{
                padding: 14, marginBottom: 12, borderRadius: t.radiusMd,
                background: isBloom ? t.bg : 'rgba(255,255,255,0.03)',
                border: isBloom ? `1.5px dashed ${t.primary}` : `1px dashed ${t.primary}`,
              }}>
                <div style={{ marginBottom: 10 }}>
                  <label style={{ display: 'block', fontSize: 11, fontWeight: 600, color: t.textMuted, marginBottom: 4 }}>Qual a nova regra ou limite?</label>
                  <input type="text" value={newLimitText} onChange={e => setNewLimitText(e.target.value)} placeholder='Ex: Pode dar descontos' style={{
                    width: '100%', padding: '8px 10px', borderRadius: t.radiusSm, fontSize: 13,
                    background: isBloom ? t.surface : 'rgba(0,0,0,0.2)', border: isBloom ? `1px solid ${t.border}` : '1px solid rgba(255,255,255,0.1)', color: t.text
                  }}/>
                </div>
                <div style={{ display: 'flex', gap: 6, justifyContent: 'flex-end' }}>
                  <Btn variant="ghost" size="sm" onClick={() => setNewLimitForm(false)}>Cancelar</Btn>
                  <Btn variant="primary" size="sm" onClick={handleAddLimit}>Adicionar Regra</Btn>
                </div>
              </div>
            )}

            {limits.length === 0 && !newLimitForm && (
              <div style={{ fontSize: 13, color: t.textMuted, fontStyle: 'italic', padding: '10px 0' }}>Nenhuma regra configurada.</div>
            )}

            {limits.map((l, i) => (
              <div key={l.id} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
                <Toggle on={l.on} label={l.label} 
                  onToggle={() => {
                    const newLimits = [...limits];
                    newLimits[i].on = !newLimits[i].on;
                    setLimits(newLimits);
                  }}
                />
                <button onClick={() => setLimits(limits.filter((_, idx) => idx !== i))} style={{
                  background: 'none', border: 'none', cursor: 'pointer', padding: 4, opacity: 0.5, marginLeft: 10
                }}>
                  <Icons.Trash size={14} stroke={t.red}/>
                </button>
              </div>
            ))}
          </Card>

          <Card style={{ padding: 22 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 12 }}>
              <div>
                <h3 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 16, fontWeight: 700, color: t.text, letterSpacing: '-0.02em' }}>
                  Frases-gatilho
                </h3>
                <div style={{ fontSize: 12, color: t.textMuted, marginTop: 2 }}>Quando ouvir isso, a Assistente faz algo específico</div>
              </div>
              <Btn variant="ghost" size="sm" onClick={() => setNewTriggerForm(!newTriggerForm)} icon={<Icons.Plus size={11}/>}>Adicionar</Btn>
            </div>
            
            {newTriggerForm && (
              <div style={{
                padding: 14, marginBottom: 12, borderRadius: t.radiusMd,
                background: isBloom ? t.bg : 'rgba(255,255,255,0.03)',
                border: isBloom ? `1.5px dashed ${t.primary}` : `1px dashed ${t.primary}`,
              }}>
                <div style={{ marginBottom: 10 }}>
                  <label style={{ display: 'block', fontSize: 11, fontWeight: 600, color: t.textMuted, marginBottom: 4 }}>O que o cliente diz (separado por vírgula)</label>
                  <input type="text" value={newTriggerText} onChange={e => setNewTriggerText(e.target.value)} placeholder='"desconto", "cupom"' style={{
                    width: '100%', padding: '8px 10px', borderRadius: t.radiusSm, fontSize: 13,
                    background: isBloom ? t.surface : 'rgba(0,0,0,0.2)', border: isBloom ? `1px solid ${t.border}` : '1px solid rgba(255,255,255,0.1)', color: t.text
                  }}/>
                </div>
                <div style={{ marginBottom: 10 }}>
                  <label style={{ display: 'block', fontSize: 11, fontWeight: 600, color: t.textMuted, marginBottom: 4 }}>Qual a ação da IA?</label>
                  <input type="text" value={newTriggerAction} onChange={e => setNewTriggerAction(e.target.value)} placeholder='Aplicar desconto se possível' style={{
                    width: '100%', padding: '8px 10px', borderRadius: t.radiusSm, fontSize: 13,
                    background: isBloom ? t.surface : 'rgba(0,0,0,0.2)', border: isBloom ? `1px solid ${t.border}` : '1px solid rgba(255,255,255,0.1)', color: t.text
                  }}/>
                </div>
                <div style={{ display: 'flex', gap: 6, justifyContent: 'flex-end' }}>
                  <Btn variant="ghost" size="sm" onClick={() => setNewTriggerForm(false)}>Cancelar</Btn>
                  <Btn variant="primary" size="sm" onClick={handleAddTrigger}>Salvar Gatilho</Btn>
                </div>
              </div>
            )}

            {triggers.map((r, i) => (
              <div key={i} style={{
                padding: '12px 14px', marginBottom: 8, borderRadius: t.radiusMd,
                background: isBloom ? t.bg : 'rgba(255,255,255,0.025)',
                border: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
                borderLeft: `3px solid ${r.color || t.primary}`,
                display: 'flex', justifyContent: 'space-between', alignItems: 'center'
              }}>
                <div>
                  <div style={{ fontSize: 12.5, color: t.text, fontWeight: 600, marginBottom: 3, fontFamily: t.fontMono }}>{r.trigger}</div>
                  <div style={{ fontSize: 12, color: t.textMuted, display: 'flex', alignItems: 'center', gap: 6 }}>
                    <Icons.ArrowRight size={11} stroke={r.color || t.primary}/> {r.action}
                  </div>
                </div>
                <button onClick={() => deleteTrigger(r.id)} style={{
                  background: 'none', border: 'none', cursor: 'pointer', padding: 4, opacity: 0.5
                }}>
                  <Icons.Trash size={14} stroke={t.red}/>
                </button>
              </div>
            ))}
          </Card>

          <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
            <Btn variant="secondary" icon={<Icons.Sparkles size={14}/>} onClick={() => setShowSimulator(true)}>Testar no simulador</Btn>
            <Btn variant="primary" onClick={handleSave} loading={saving} icon={<Icons.Check size={14} stroke="#fff"/>}>
              {saving ? 'Salvando...' : 'Publicar DNA'}
            </Btn>
          </div>
        </div>
      </div>

      {showSimulator && (
        <div style={{
          position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(4px)',
          display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 9999
        }}>
          <Card style={{ width: 400, maxWidth: '90vw', display: 'flex', flexDirection: 'column', height: 500, background: t.surface }}>
            <div style={{ padding: 16, borderBottom: `1px solid ${t.border}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div style={{ fontWeight: 600, fontSize: 15, color: t.text, display: 'flex', alignItems: 'center', gap: 8 }}>
                <Icons.Sparkles size={16} stroke={t.primary}/> Simulador: {name}
              </div>
              <button onClick={() => setShowSimulator(false)} style={{ background: 'none', border: 'none', color: t.textMuted, cursor: 'pointer' }}>✕</button>
            </div>
            
            <div style={{ flex: 1, padding: 16, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 12 }}>
              {simMessages.length === 0 && (
                <div style={{ margin: 'auto', textAlign: 'center', color: t.textMuted, fontSize: 13 }}>
                  Mande um "Oi" para testar como a assistente responde baseado no DNA.
                </div>
              )}
              {simMessages.map((m, i) => (
                <div key={i} style={{ alignSelf: m.from === 'me' ? 'flex-end' : 'flex-start', maxWidth: '85%' }}>
                  <div style={{ fontSize: 10, color: t.textMuted, marginBottom: 2, textAlign: m.from === 'me' ? 'right' : 'left' }}>
                    {m.from === 'me' ? 'Você (Cliente)' : name}
                  </div>
                  <div style={{
                    padding: '8px 12px', borderRadius: 12, fontSize: 13, color: m.from === 'me' ? '#fff' : t.text,
                    background: m.from === 'me' ? t.primary : (isBloom ? t.bg : 'rgba(255,255,255,0.05)'),
                    border: m.from === 'ia' && isBloom ? `1px solid ${t.border}` : 'none'
                  }}>
                    {m.text}
                  </div>
                </div>
              ))}
              {simLoading && <div style={{ fontSize: 12, color: t.textMuted }}>Digitando...</div>}
            </div>

            <div style={{ padding: 16, borderTop: `1px solid ${t.border}`, display: 'flex', gap: 8 }}>
              <input 
                type="text" 
                value={simInput} 
                onChange={e => setSimInput(e.target.value)}
                onKeyDown={e => e.key === 'Enter' && handleSimulate()}
                placeholder="Digite algo como cliente..."
                style={{
                  flex: 1, background: isBloom ? t.bg : 'rgba(255,255,255,0.05)', border: `1px solid ${t.border}`,
                  padding: '8px 12px', borderRadius: 8, color: t.text, fontSize: 13
                }}
              />
              <Btn variant="primary" onClick={handleSimulate} disabled={simLoading}>Enviar</Btn>
            </div>
          </Card>
        </div>
      )}
    </div>
  );
};

window.DnaAssistente = DnaAssistente;
