function renderMd(text) {
  if (!text || typeof text !== 'string') return text || '';
  var parts = [];
  var remaining = text;
  var key = 0;

  while (remaining.length > 0) {
    var boldIdx = remaining.indexOf('**');
    var codeIdx = remaining.indexOf('`');
    var nextSpecial = -1;
    var nextType = '';

    if (boldIdx !== -1 && (codeIdx === -1 || boldIdx <= codeIdx)) {
      nextSpecial = boldIdx;
      nextType = 'bold';
    } else if (codeIdx !== -1) {
      nextSpecial = codeIdx;
      nextType = 'code';
    }

    if (nextSpecial === -1) {
      parts.push(remaining);
      break;
    }

    if (nextSpecial > 0) {
      parts.push(remaining.slice(0, nextSpecial));
    }

    if (nextType === 'bold') {
      var closeB = remaining.indexOf('**', nextSpecial + 2);
      if (closeB === -1) {
        parts.push(remaining.slice(nextSpecial));
        break;
      }
      var boldText = remaining.slice(nextSpecial + 2, closeB);
      parts.push(React.createElement('strong', { key: 'md-' + key, style: { color: 'var(--amber, #d4a84b)', fontWeight: 700 } }, boldText));
      key++;
      remaining = remaining.slice(closeB + 2);
    } else {
      var closeC = remaining.indexOf('`', nextSpecial + 1);
      if (closeC === -1) {
        parts.push(remaining.slice(nextSpecial));
        break;
      }
      var codeText = remaining.slice(nextSpecial + 1, closeC);
      parts.push(React.createElement('code', { key: 'md-' + key, style: { background: 'rgba(255,255,255,0.08)', padding: '1px 4px', borderRadius: '2px', fontSize: '12px' } }, codeText));
      key++;
      remaining = remaining.slice(closeC + 1);
    }
  }

  return parts;
}

var AiChat = function (props) {
  var MAX_MESSAGES = 50;

  var _stOpen = React.useState(false);
  var open = _stOpen[0];
  var setOpen = _stOpen[1];

  var _stMessages = React.useState([
    { role: 'assistant', content: 'Ask me anything about AI security techniques from FORGE, the Cheat Sheet, or RAGdrag.', sources: null }
  ]);
  var messages = _stMessages[0];
  var setMessages = _stMessages[1];

  var _stInput = React.useState('');
  var input = _stInput[0];
  var setInput = _stInput[1];

  var _stLoading = React.useState(false);
  var loading = _stLoading[0];
  var setLoading = _stLoading[1];

  var messagesEndRef = React.useRef(null);
  var inputRef = React.useRef(null);
  var isMobile = window.__IBA_MOBILE;

  React.useEffect(function () {
    if (messagesEndRef.current) {
      messagesEndRef.current.scrollIntoView({ behavior: 'smooth' });
    }
  }, [messages, loading]);

  React.useEffect(function () {
    if (open && inputRef.current) {
      inputRef.current.focus();
    }
  }, [open]);

  var handleSubmit = function () {
    var q = input.trim();
    if (!q || loading) return;

    var userMsg = { role: 'user', content: q, sources: null };
    var next = messages.concat([userMsg]);
    if (next.length > MAX_MESSAGES) {
      next = next.slice(next.length - MAX_MESSAGES);
    }
    setMessages(next);
    setInput('');
    setLoading(true);

    fetch('/api/ai-search?action=ask&q=' + encodeURIComponent(q))
      .then(function (res) {
        if (!res.ok) throw new Error('HTTP ' + res.status);
        return res.json();
      })
      .then(function (data) {
        if (data && data.error) throw new Error(data.error);
        var content = (data && data.answer != null && data.answer !== '') ? data.answer : 'No results found. Try rephrasing your question.';
        var sources = null;
        if (data && data.sources && data.sources.length > 0) {
          sources = [];
          for (var i = 0; i < data.sources.length; i++) {
            var s = data.sources[i];
            var id = (s.metadata && s.metadata.id) ? s.metadata.id : s.key;
            var route = (s.metadata && s.metadata.route) ? s.metadata.route : null;
            if (id) {
              sources.push({ id: id, route: route });
            }
          }
          if (sources.length === 0) sources = null;
        }
        var assistantMsg = { role: 'assistant', content: content, sources: sources };
        setMessages(function (prev) {
          var updated = prev.concat([assistantMsg]);
          if (updated.length > MAX_MESSAGES) {
            updated = updated.slice(updated.length - MAX_MESSAGES);
          }
          return updated;
        });
        setLoading(false);
      })
      .catch(function () {
        var errMsg = { role: 'assistant', content: 'Something went wrong. Try again.', sources: null };
        setMessages(function (prev) {
          var updated = prev.concat([errMsg]);
          if (updated.length > MAX_MESSAGES) {
            updated = updated.slice(updated.length - MAX_MESSAGES);
          }
          return updated;
        });
        setLoading(false);
      });
  };

  var handleKeyDown = function (e) {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSubmit();
    }
  };

  var handleSourceClick = function (route) {
    if (props.navigate && route) {
      var clean = route.replace(/^\/+/, '');
      props.navigate(clean);
      setOpen(false);
    }
  };

  // Collapsed button
  if (!open) {
    return (
      <button
        type="button"
        onClick={function () { setOpen(true); }}
        aria-label="Open AI chat"
        style={{
          position: 'fixed',
          bottom: '24px',
          right: isMobile ? '16px' : '24px',
          width: '56px',
          height: '56px',
          borderRadius: '50%',
          background: 'var(--bg-2, #141410)',
          border: '1px solid var(--amber-dim, #6b5a2e)',
          cursor: 'pointer',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          zIndex: 8000,
          transition: 'transform 0.2s ease, box-shadow 0.2s ease',
          padding: 0
        }}
        onMouseEnter={function (e) {
          e.currentTarget.style.transform = 'scale(1.08)';
          e.currentTarget.style.boxShadow = '0 0 20px rgba(212,168,75,0.3)';
        }}
        onMouseLeave={function (e) {
          e.currentTarget.style.transform = 'scale(1)';
          e.currentTarget.style.boxShadow = 'none';
        }}
      >
        <img src="/assets/images/taribai-logo.png" width="36" height="36" alt="AI Chat" style={{ imageRendering: 'pixelated' }} />
      </button>
    );
  }

  // Expanded chat window
  var windowStyle = {
    position: 'fixed',
    bottom: isMobile ? '16px' : '24px',
    right: isMobile ? '16px' : '24px',
    width: isMobile ? 'auto' : '380px',
    left: isMobile ? '16px' : 'auto',
    height: '500px',
    maxHeight: 'calc(100vh - 48px)',
    background: 'var(--bg, #0a0a0a)',
    border: '1px solid var(--amber-dim, #6b5a2e)',
    borderRadius: '8px',
    boxShadow: '0 8px 32px rgba(0,0,0,0.5)',
    zIndex: 8000,
    display: 'flex',
    flexDirection: 'column',
    overflow: 'hidden'
  };

  var headerStyle = {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    padding: '12px 16px',
    borderBottom: '1px solid var(--border, #2a2a20)',
    flexShrink: 0
  };

  var messagesStyle = {
    flex: 1,
    overflowY: 'auto',
    padding: '12px 16px',
    display: 'flex',
    flexDirection: 'column',
    gap: '10px'
  };

  var inputAreaStyle = {
    display: 'flex',
    alignItems: 'center',
    padding: '10px 16px',
    borderTop: '1px solid var(--border, #2a2a20)',
    gap: '8px',
    flexShrink: 0
  };

  var messageEls = [];
  for (var i = 0; i < messages.length; i++) {
    var msg = messages[i];
    var isUser = msg.role === 'user';
    var msgStyle = {
      maxWidth: isUser ? '80%' : '85%',
      alignSelf: isUser ? 'flex-end' : 'flex-start',
      padding: '8px 12px',
      borderRadius: '6px',
      fontFamily: 'var(--font-mono, monospace)',
      fontSize: '13px',
      lineHeight: '1.5',
      wordBreak: 'break-word',
      whiteSpace: 'pre-wrap'
    };

    if (isUser) {
      msgStyle.background = 'var(--amber, #d4a84b)';
      msgStyle.color = '#0a0a0a';
    } else {
      msgStyle.background = 'var(--surface, #1a1a14)';
      msgStyle.border = '1px solid var(--border, #2a2a20)';
      msgStyle.color = 'var(--text, #e8e0cc)';
    }

    var sourceEls = null;
    if (!isUser && msg.sources && msg.sources.length > 0) {
      var sourceLinks = [];
      for (var j = 0; j < msg.sources.length; j++) {
        var src = msg.sources[j];
        (function (srcItem) {
          sourceLinks.push(
            <span
              key={'src-' + j + '-' + srcItem.id}
              onClick={function () { handleSourceClick(srcItem.route); }}
              style={{
                cursor: srcItem.route && props.navigate ? 'pointer' : 'default',
                color: 'var(--amber-dim, #6b5a2e)',
                fontSize: '11px',
                fontFamily: 'var(--font-mono, monospace)',
                textDecoration: srcItem.route && props.navigate ? 'underline' : 'none',
                marginRight: '8px'
              }}
            >
              {srcItem.id}
            </span>
          );
        })(src);
      }
      sourceEls = (
        <div style={{ marginTop: '4px', display: 'flex', flexWrap: 'wrap', gap: '2px' }}>
          {sourceLinks}
        </div>
      );
    }

    messageEls.push(
      <div key={'msg-' + i} style={msgStyle}>
        {isUser ? msg.content : renderMd(msg.content)}
        {sourceEls}
      </div>
    );
  }

  if (loading) {
    messageEls.push(
      <div key="loading" style={{
        alignSelf: 'flex-start',
        padding: '8px 12px',
        borderRadius: '6px',
        background: 'var(--surface, #1a1a14)',
        border: '1px solid var(--border, #2a2a20)',
        color: 'var(--amber-dim, #6b5a2e)',
        fontFamily: 'var(--font-mono, monospace)',
        fontSize: '13px',
        animation: 'ib-pulse 1.2s ease-in-out infinite'
      }}>
        ...
      </div>
    );
  }

  return (
    <div style={windowStyle}>
      {/* Header */}
      <div style={headerStyle}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
          <img src="/assets/images/taribai-logo.png" width="24" height="24" alt="" style={{ imageRendering: 'pixelated' }} />
          <span style={{ fontFamily: 'var(--font-mono, monospace)', fontSize: '14px', color: 'var(--text, #e8e0cc)', fontWeight: 600 }}>itsbroken.ai</span>
        </div>
        <button
          type="button"
          onClick={function () { setOpen(false); }}
          aria-label="Close chat"
          style={{
            background: 'none',
            border: 'none',
            color: 'var(--text-muted, #8a8070)',
            cursor: 'pointer',
            fontFamily: 'var(--font-mono, monospace)',
            fontSize: '18px',
            padding: '0 4px',
            lineHeight: 1
          }}
        >
          {'✕'}
        </button>
      </div>

      {/* Messages */}
      <div style={messagesStyle}>
        {messageEls}
        <div ref={messagesEndRef} />
      </div>

      {/* Input */}
      <div style={inputAreaStyle}>
        <span style={{ color: 'var(--amber, #d4a84b)', fontFamily: 'var(--font-mono, monospace)', fontSize: '14px', flexShrink: 0 }}>{'$ '}</span>
        <input
          ref={inputRef}
          type="text"
          value={input}
          onChange={function (e) { setInput(e.target.value); }}
          onKeyDown={handleKeyDown}
          disabled={loading}
          placeholder="ask about AI security..."
          style={{
            flex: 1,
            background: 'transparent',
            border: 'none',
            outline: 'none',
            color: 'var(--text, #e8e0cc)',
            fontFamily: 'var(--font-mono, monospace)',
            fontSize: '13px',
            caretColor: 'var(--amber, #d4a84b)',
            padding: 0
          }}
        />
        <button
          type="button"
          onClick={handleSubmit}
          disabled={loading || !input.trim()}
          aria-label="Send message"
          style={{
            background: 'none',
            border: 'none',
            color: (loading || !input.trim()) ? 'var(--text-muted, #8a8070)' : 'var(--amber, #d4a84b)',
            cursor: (loading || !input.trim()) ? 'default' : 'pointer',
            fontFamily: 'var(--font-mono, monospace)',
            fontSize: '16px',
            fontWeight: 'bold',
            padding: '0 4px',
            flexShrink: 0
          }}
        >
          {'>'}
        </button>
      </div>
    </div>
  );
};

window.AiChat = AiChat;
