/**
 * ITS-Böhmer Chat Widget
 * Floating chat button + slide-in panel with AI assistant
 * Integrates via data-chat-trigger on any element
 */

import { getSessionState, processMessage } from './booking-agent'

interface ChatMessage {
  role: 'user' | 'assistant'
  text: string
  timestamp: number
}

interface ChatState {
  isOpen: boolean
  messages: ChatMessage[]
  isTyping: boolean
  lastFocusedElement: HTMLElement | null
}

// Global chat state
const state: ChatState = {
  isOpen: false,
  messages: [],
  isTyping: false,
  lastFocusedElement: null,
}

// Quick action buttons shown in initial assistant message
const QUICK_ACTIONS = [
  { label: 'Termin buchen', action: 'book', icon: '📅' },
  { label: 'Rückruf anfordern', action: 'callback', icon: '📞' },
  { label: 'Komponenten', action: 'components', icon: '🔧' },
]

// CSS for the widget (injected once)
const CHAT_CSS = `
:root {
  --chat-bg: rgba(5, 8, 7, 0.97);
  --chat-surface: rgba(255, 255, 255, 0.07);
  --chat-surface-hover: rgba(255, 255, 255, 0.11);
  --chat-border: rgba(255, 255, 255, 0.1);
  --chat-accent: #65f0dd;
  --chat-accent-dim: rgba(101, 240, 221, 0.18);
  --chat-text: #f4fbf8;
  --chat-muted: #8fa8a2;
  --chat-muted-light: #a5b7b1;
  --chat-radius: 14px;
  --chat-radius-sm: 8px;
  --chat-shadow: 0 24px 80px rgba(0, 0, 0, 0.55);
  --chat-panel-w: 390px;
  --chat-panel-h: 580px;
}

.chat-widget {
  position: fixed;
  bottom: max(28px, env(safe-area-inset-bottom));
  right: max(28px, env(safe-area-inset-right));
  z-index: 9000;
  font-family: Inter, ui-sans-serif, system-ui, -apple-system, sans-serif;
}
/* Note: mobile-nav-open hiding is handled in site.css for smooth transitions */

.chat-trigger {
  width: 60px;
  height: 60px;
  border-radius: 999px;
  background: linear-gradient(135deg, #0f766e, #0d5f59);
  border: none;
  cursor: pointer;
  display: grid;
  place-items: center;
  box-shadow: 0 8px 32px rgba(15, 118, 110, 0.45), 0 2px 8px rgba(0,0,0,0.3);
  transition: transform 0.22s cubic-bezier(.34,1.56,.64,1), box-shadow 0.22s ease;
  position: relative;
}
.chat-trigger::after {
  content: 'Beratung';
  position: absolute;
  right: 70px;
  top: 50%;
  transform: translateY(-50%);
  background: rgba(5, 8, 7, 0.92);
  border: 1px solid rgba(101, 240, 221, 0.26);
  border-radius: 999px;
  color: var(--chat-text);
  font-size: 13px;
  font-weight: 800;
  padding: 8px 12px;
  white-space: nowrap;
}
.chat-trigger:hover {
  transform: scale(1.1);
  box-shadow: 0 12px 40px rgba(15, 118, 110, 0.55), 0 4px 12px rgba(0,0,0,0.35);
}
.chat-trigger:active { transform: scale(0.97); }
.chat-trigger svg { width: 26px; height: 26px; fill: white; transition: transform 0.3s ease; }
.chat-trigger.is-open svg { transform: rotate(90deg); }

.chat-trigger .chat-notify {
  position: absolute;
  top: 4px;
  right: 4px;
  width: 14px;
  height: 14px;
  border-radius: 50%;
  background: var(--chat-accent);
  border: 2.5px solid #0f766e;
  animation: chatPulse 2.2s ease-in-out infinite;
}
.chat-trigger.is-open .chat-notify { display: none; }

@keyframes chatPulse {
  0%, 100% { transform: scale(1); opacity: 1; }
  50% { transform: scale(1.4); opacity: 0.6; }
}

.chat-panel {
  position: absolute;
  bottom: 74px;
  right: 0;
  width: var(--chat-panel-w);
  height: var(--chat-panel-h);
  background: var(--chat-bg);
  border: 1px solid var(--chat-border);
  border-radius: var(--chat-radius);
  box-shadow: var(--chat-shadow);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  transform-origin: bottom right;
  transform: scale(0.85) translateY(24px);
  opacity: 0;
  pointer-events: none;
  transition: transform 0.35s cubic-bezier(.34,1.2,.64,1), opacity 0.28s ease;
}
.chat-panel.is-open {
  transform: scale(1) translateY(0);
  opacity: 1;
  pointer-events: all;
}

.chat-panel-head {
  padding: 18px 20px 16px;
  background: rgba(101, 240, 221, 0.06);
  border-bottom: 1px solid var(--chat-border);
  display: flex;
  align-items: center;
  gap: 14px;
  flex-shrink: 0;
}
.chat-panel-head .chat-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: linear-gradient(135deg, #0f766e, #29a7c8);
  display: grid;
  place-items: center;
  flex-shrink: 0;
}
.chat-panel-head .chat-avatar svg { width: 20px; height: 20px; fill: white; }
.chat-panel-head-text { flex: 1; }
.chat-panel-head-text strong {
  color: var(--chat-text);
  font-size: 15px;
  font-weight: 800;
  display: block;
}
.chat-panel-head-text span {
  color: var(--chat-accent);
  font-size: 12px;
  font-weight: 700;
  display: flex;
  align-items: center;
  gap: 5px;
  margin-top: 2px;
}
.chat-panel-head-text span::before {
  content: '';
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: var(--chat-accent);
  animation: chatPulse 2s ease-in-out infinite;
}
.chat-panel-close {
  background: none;
  border: none;
  cursor: pointer;
  padding: 6px;
  border-radius: 6px;
  color: var(--chat-muted-light);
  transition: background 0.15s, color 0.15s;
}
.chat-panel-close:hover { background: var(--chat-surface); color: var(--chat-text); }
.chat-panel-close svg { width: 18px; height: 18px; display: block; }

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 18px 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
  scroll-behavior: smooth;
}
.chat-messages::-webkit-scrollbar { width: 4px; }
.chat-messages::-webkit-scrollbar-track { background: transparent; }
.chat-messages::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.15); border-radius: 2px; }

.chat-message {
  max-width: 85%;
  display: flex;
  flex-direction: column;
  gap: 4px;
  animation: msgIn 0.3s cubic-bezier(.34,1.2,.64,1) both;
}
@keyframes msgIn {
  from { opacity: 0; transform: translateY(10px) scale(0.97); }
  to { opacity: 1; transform: translateY(0) scale(1); }
}
.chat-message.user { align-self: flex-end; }
.chat-message.assistant { align-self: flex-start; }

.chat-bubble {
  padding: 11px 15px;
  border-radius: var(--chat-radius-sm);
  font-size: 14.5px;
  line-height: 1.55;
  word-break: break-word;
}
.chat-message.user .chat-bubble {
  background: var(--chat-accent);
  color: #051513;
  border-bottom-right-radius: 3px;
  font-weight: 600;
}
.chat-message.assistant .chat-bubble {
  background: var(--chat-surface);
  color: var(--chat-text);
  border-bottom-left-radius: 3px;
}

.chat-typing {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 11px 15px;
  background: var(--chat-surface);
  border-radius: var(--chat-radius-sm);
  border-bottom-left-radius: 3px;
  align-self: flex-start;
}
.chat-typing-dot {
  width: 7px;
  height: 7px;
  border-radius: 50%;
  background: var(--chat-muted-light);
  animation: typingBounce 1.4s ease-in-out infinite;
}
.chat-typing-dot:nth-child(2) { animation-delay: 0.18s; }
.chat-typing-dot:nth-child(3) { animation-delay: 0.36s; }
@keyframes typingBounce {
  0%, 60%, 100% { transform: translateY(0); }
  30% { transform: translateY(-7px); }
}

.chat-quick-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  padding: 0 16px 14px;
  flex-shrink: 0;
}
.chat-quick-btn {
  background: var(--chat-surface);
  border: 1px solid var(--chat-border);
  border-radius: 999px;
  color: var(--chat-text);
  font-size: 13px;
  font-weight: 700;
  padding: 8px 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: background 0.15s, border-color 0.15s, transform 0.15s;
}
.chat-quick-btn:hover {
  background: var(--chat-surface-hover);
  border-color: var(--chat-accent);
  color: var(--chat-accent);
  transform: translateY(-1px);
}

.chat-input-area {
  padding: 14px 16px 16px;
  background: rgba(5, 8, 7, 0.6);
  border-top: 1px solid var(--chat-border);
  display: flex;
  gap: 10px;
  align-items: flex-end;
  flex-shrink: 0;
}
.chat-input {
  flex: 1;
  background: var(--chat-surface);
  border: 1px solid var(--chat-border);
  border-radius: var(--chat-radius-sm);
  color: var(--chat-text);
  font-family: inherit;
  font-size: 14px;
  padding: 11px 14px;
  resize: none;
  outline: none;
  max-height: 120px;
  transition: border-color 0.2s;
  line-height: 1.5;
}
.chat-input::placeholder { color: var(--chat-muted); }
.chat-input:focus { border-color: var(--chat-accent); }
.chat-send-btn {
  width: 42px;
  height: 42px;
  border-radius: var(--chat-radius-sm);
  background: var(--chat-accent);
  border: none;
  cursor: pointer;
  display: grid;
  place-items: center;
  flex-shrink: 0;
  transition: background 0.15s, transform 0.15s;
}
.chat-send-btn:hover { background: #7ef3ea; transform: scale(1.06); }
.chat-send-btn:active { transform: scale(0.94); }
.chat-send-btn svg { width: 18px; height: 18px; fill: #051513; }

@media (max-width: 640px) {
  .chat-widget {
    bottom: max(14px, env(safe-area-inset-bottom));
    right: max(14px, env(safe-area-inset-right));
  }
  .chat-trigger { width: 56px; height: 56px; }
  .chat-trigger::after { display: none; }
  .chat-panel {
    position: fixed;
    inset: auto max(10px, env(safe-area-inset-right)) max(78px, calc(env(safe-area-inset-bottom) + 78px)) max(10px, env(safe-area-inset-left));
    width: auto;
    height: min(640px, calc(100dvh - 96px));
    max-height: calc(100dvh - 96px);
    border-radius: 18px;
    transform-origin: bottom right;
  }
  .chat-panel-head { padding: 14px 16px; }
  .chat-messages { padding: 14px 12px; }
  .chat-input-area { padding: 12px; }
  .chat-input { min-height: 44px; font-size: 16px; }
  .chat-send-btn { width: 46px; height: 46px; }
}

@media (max-width: 380px) {
  .chat-panel {
    inset-left: max(6px, env(safe-area-inset-left));
    inset-right: max(6px, env(safe-area-inset-right));
  }
  .quick-actions { grid-template-columns: 1fr; }
}
`

function injectStyles() {
  if (document.getElementById('chat-widget-styles')) return
  const style = document.createElement('style')
  style.id = 'chat-widget-styles'
  style.textContent = CHAT_CSS
  document.head.appendChild(style)
}

function buildWidget(): HTMLElement {
  const widget = document.createElement('div')
  widget.className = 'chat-widget'
  widget.innerHTML = `
    <div class="chat-panel" id="chatPanel" role="dialog" aria-label="Chat mit ITS-Böhmer Assistant" aria-modal="true" aria-hidden="true">
      <div class="chat-panel-head">
        <div class="chat-avatar">
          <svg viewBox="0 0 24 24"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 14.5v-9l6 4.5-6 4.5z"/></svg>
        </div>
        <div class="chat-panel-head-text">
          <strong>ITS-Böhmer Assistant</strong>
          <span>Online — wir sind für Sie da</span>
        </div>
        <button class="chat-panel-close" type="button" aria-label="Chat schließen" id="chatCloseBtn" tabindex="-1">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
            <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
          </svg>
        </button>
      </div>
      <div class="chat-messages" id="chatMessages"></div>
      <div class="chat-quick-actions" id="chatQuickActions"></div>
      <div class="chat-input-area">
        <textarea class="chat-input" id="chatInput" placeholder="Nachricht schreiben…" rows="1" aria-label="Nachricht eingeben" tabindex="-1"></textarea>
        <button class="chat-send-btn" type="button" id="chatSendBtn" aria-label="Nachricht senden" tabindex="-1">
          <svg viewBox="0 0 24 24"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/></svg>
        </button>
      </div>
    </div>
    <button class="chat-trigger" type="button" id="chatTrigger" aria-label="Beratungschat öffnen" aria-expanded="false" aria-controls="chatPanel">
      <div class="chat-notify"></div>
      <svg viewBox="0 0 24 24" id="chatTriggerIcon">
        <path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H5.17L4 17.17V4h16v12z"/>
        <path d="M7 9h10v2H7zm0-3h7v2H7z"/>
      </svg>
    </button>
  `
  return widget
}

function scrollMessagesToBottom() {
  const container = document.getElementById('chatMessages')
  if (container) container.scrollTop = container.scrollHeight
}

function renderMessages() {
  const container = document.getElementById('chatMessages')
  if (!container) return

  container.innerHTML = state.messages
    .map(
      (msg) => `
        <div class="chat-message ${msg.role}">
          <div class="chat-bubble">${escapeHtml(msg.text)}</div>
        </div>
      `,
    )
    .join('')

  // Typing indicator
  if (state.isTyping) {
    const typing = document.createElement('div')
    typing.className = 'chat-message assistant'
    typing.innerHTML = `
      <div class="chat-typing">
        <div class="chat-typing-dot"></div>
        <div class="chat-typing-dot"></div>
        <div class="chat-typing-dot"></div>
      </div>
    `
    container.appendChild(typing)
  }

  scrollMessagesToBottom()
}

function renderQuickActions() {
  const container = document.getElementById('chatQuickActions')
  if (!container) return
  container.innerHTML = QUICK_ACTIONS.map(
    (qa) => `
      <button class="chat-quick-btn" type="button" data-action="${qa.action}">
        <span>${qa.icon}</span> ${qa.label}
      </button>
    `,
  ).join('')
}

function escapeHtml(text: string): string {
  return text
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;')
    .replace(/\n/g, '<br>')
}

function addMessage(role: 'user' | 'assistant', text: string) {
  state.messages.push({ role, text, timestamp: Date.now() })
  renderMessages()
}

function setTyping(typing: boolean) {
  state.isTyping = typing
  renderMessages()
}

// Auto-grow textarea
function autoGrow(el: HTMLTextAreaElement) {
  el.style.height = 'auto'
  el.style.height = Math.min(el.scrollHeight, 120) + 'px'
}

// Handle quick actions
function handleQuickAction(action: string) {
  switch (action) {
    case 'book':
      addMessage('user', 'Ich möchte einen Termin buchen.')
      void handleBookingMessage('Termin buchen')
      break
    case 'callback':
      addMessage('user', 'Ich möchte einen Rückruf anfordern.')
      void handleBookingMessage('Rückruf anfordern')
      break
    case 'components':
      addMessage('user', 'Ich möchte mehr über die Komponenten erfahren.')
      simulateResponse('Wir bieten Komponenten für Zutritt, Alarm & Sicherheit, Licht, Beschattung, Klima und Energie. Welches Thema interessiert Sie?')
      break
  }
}

function simulateResponse(text: string, delayMs = 1400) {
  setTyping(true)
  setTimeout(() => {
    setTyping(false)
    addMessage('assistant', text)
  }, delayMs)
}

function isBookingMessage(text: string): boolean {
  const lower = text.toLowerCase().trim()
  const activeState = getSessionState('default')
  if (activeState !== 'IDLE' && activeState !== 'BOOKED') return true

  return [
    'termin',
    'buch',
    'beratung',
    'kalender',
    'rückruf',
    'rueckruf',
    'anruf',
    'telefon',
    'callback',
  ].some((keyword) => lower.includes(keyword))
}

async function handleBookingMessage(text: string) {
  setTyping(true)
  try {
    const reply = await processMessage(text)
    setTyping(false)
    if (reply) addMessage('assistant', reply)
  } catch (error) {
    console.error('Booking assistant failed', error)
    setTyping(false)
    addMessage(
      'assistant',
      'Entschuldigung, der Terminassistent ist gerade nicht erreichbar. Sie können direkt über Cal.com buchen: https://cal.com/its-boehmer/beratung',
    )
  }
}

// Process user message
function processUserMessage(text: string) {
  const lower = text.toLowerCase().trim()

  if (isBookingMessage(text)) {
    void handleBookingMessage(text)
    return
  }

  // Smart routing based on keywords
  if (lower.includes('preis') || lower.includes('kost') || lower.includes('angebot')) {
    simulateResponse('Die Kosten hängen von Ihrem Gebäude, der Verkabelung und den gewünschten Funktionen ab. Für Smart Home Siegen, Homematic IP Betzdorf oder Gebäudeautomatisierung Freudenberg nutzen Sie am besten unseren Gebäudeplaner — oder wir klären es direkt in einer kurzen Beratung.')
    return
  }
  if (lower.includes('komponent') || lower.includes('baustein') || lower.includes('produkt')) {
    simulateResponse('Wir planen Homematic IP Komponenten für Zutritt, Alarm & Sicherheit, Licht, Beschattung, Klima und Energie — passend für Bestandsbauten, Neubau und Smart Office Wissen. Welcher Bereich ist für Sie gerade am wichtigsten?')
    return
  }
  if (lower.includes('knx') || lower.includes('verkabel') || lower.includes('neubau')) {
    simulateResponse('Bei Neubau oder Kernsanierung lohnt sich ein Blick auf KNX Programmierung im Siegerland und strukturierte Verkabelung. Für Bestandsbauten ist Homematic IP oft schneller und wirtschaftlicher nachrüstbar. Ich kann Ihnen die passende Variante einordnen.')
    return
  }
  if (lower.includes('danke') || lower.includes('perfekt') || lower.includes('super')) {
    simulateResponse('Sehr gerne! Wenn Sie weitere Fragen haben, sind wir jederzeit für Sie da. 😊')
    return
  }
  if (lower.includes('hallo') || lower.includes('hi') || lower.includes('guten tag')) {
    simulateResponse('Hallo und willkommen bei ITS-Böhmer! Wie kann ich Ihnen helfen? Ich kann Sie zu Terminen, Komponenten oder Ihrem Smart-Home-Projekt beraten.')
    return
  }

  // Default response
  simulateResponse('Danke für Ihre Nachricht! Unser Team meldet sich in Kürze bei Ihnen. Sie können auch direkt einen Termin buchen oder uns unter info@its-boehmer.de erreichen.')
}

function setPanelAccessibility(open: boolean) {
  const panel = document.getElementById('chatPanel')
  if (!panel) return
  panel.setAttribute('aria-hidden', String(!open))
  panel.querySelectorAll<HTMLElement>('button, textarea, a, [tabindex]').forEach((el) => {
    if (open) el.removeAttribute('tabindex')
    else el.setAttribute('tabindex', '-1')
  })
}

function openChat(options: { intent?: string } = {}) {
  const wasOpen = state.isOpen
  if (!wasOpen) state.lastFocusedElement = document.activeElement as HTMLElement | null
  state.isOpen = true
  const panel = document.getElementById('chatPanel')
  const trigger = document.getElementById('chatTrigger')
  panel?.classList.add('is-open')
  setPanelAccessibility(true)
  trigger?.classList.add('is-open')
  trigger?.setAttribute('aria-expanded', 'true')
  trigger?.setAttribute('aria-label', 'Beratungschat schließen')

  // On small screens, CTAs usually sit in the mobile navigation. Wait until
  // the menu has closed and then bring the chat panel into view without
  // unexpectedly opening the on-screen keyboard.
  window.requestAnimationFrame(() => {
    panel?.scrollIntoView({ block: 'end', inline: 'nearest', behavior: 'smooth' })
    if (window.matchMedia('(min-width: 641px)').matches) {
      document.getElementById('chatInput')?.focus()
    } else if (!wasOpen) {
      const firstQuickAction = document.querySelector<HTMLElement>('.chat-quick-btn')
      firstQuickAction?.focus({ preventScroll: true })
    }
  })

  if (options.intent) {
    handleCtaIntent(options.intent)
  }
}

function closeChat() {
  state.isOpen = false
  const panel = document.getElementById('chatPanel')
  const trigger = document.getElementById('chatTrigger')
  panel?.classList.remove('is-open')
  setPanelAccessibility(false)
  trigger?.classList.remove('is-open')
  trigger?.setAttribute('aria-expanded', 'false')
  trigger?.setAttribute('aria-label', 'Beratungschat öffnen')
  state.lastFocusedElement?.focus?.({ preventScroll: true })
  state.lastFocusedElement = null
}

function toggleChat() {
  if (state.isOpen) {
    closeChat()
  } else {
    openChat()
  }
}

function handleCtaIntent(intent: string) {
  const alreadyAnswered = state.messages.some((message) => (
    message.role === 'assistant' && message.text.includes('Ihr Projekt kurz einordnen')
  ))

  if (alreadyAnswered) return

  switch (intent) {
    case 'project':
      addMessage(
        'assistant',
        'Gerne — ich kann Ihr Projekt kurz einordnen. Geht es um ein Eigenheim, einen Neubau, eine Nachrüstung, Smart Office Wissen oder Gebäudeautomatisierung Freudenberg im Raum Siegen, Betzdorf oder Wissen?',
      )
      break
    case 'planner':
      addMessage(
        'assistant',
        'Der Gebäudeplaner ist ideal für eine erste Material- und Raumübersicht. Wenn Sie möchten, können Sie mir hier kurz Objektart, Räume und gewünschte Funktionen nennen.',
      )
      break
    case 'booking':
      addMessage(
        'assistant',
        'Für eine Beratung können wir direkt einen Termin abstimmen. Schreiben Sie mir kurz Ihr Anliegen oder nutzen Sie die Schnellaktion „Termin buchen“.',
      )
      break
  }
}

function sendMessage() {
  const input = document.getElementById('chatInput') as HTMLTextAreaElement | null
  if (!input || !input.value.trim()) return

  const text = input.value.trim()
  input.value = ''
  autoGrow(input)
  addMessage('user', text)
  processUserMessage(text)
}

// Global function to open chat from planner or other scripts
function openChatWidget() {
  openChat()
}

// Expose globally so planner.ts and other scripts can call it
;(window as unknown as Record<string, unknown>).openChatWidget = openChatWidget

function initChat() {
  if (document.querySelector('.chat-widget')) return

  injectStyles()

  const widget = buildWidget()
  document.body.appendChild(widget)

  // Send greeting after a short delay (only if no messages yet)
  if (state.messages.length === 0) {
    setTimeout(() => {
      addMessage(
        'assistant',
        'Hallo! 👋 Schön, dass Sie da sind. Ich bin der ITS-Böhmer Assistant für Smart Home im Siegerland. Ob Smart Home in Siegen, Homematic IP in Betzdorf, Smart Office in Wissen oder Gebäudeautomatisierung in Freudenberg — ich helfe Ihnen gerne weiter. Was kann ich für Sie tun?',
      )
      renderQuickActions()
    }, 600)
  }

  widget.addEventListener('chat:close', closeChat)

  // Trigger button
  document.getElementById('chatTrigger')?.addEventListener('click', toggleChat)

  // Close button
  document.getElementById('chatCloseBtn')?.addEventListener('click', closeChat)

  document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape' && state.isOpen) closeChat()

    if (e.key === 'Tab' && state.isOpen) {
      const panel = document.getElementById('chatPanel')
      if (!panel) return
      const focusable = Array.from(panel.querySelectorAll<HTMLElement>('button:not([disabled]), textarea:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])'))
      if (!focusable.length) return
      const first = focusable[0]
      const last = focusable[focusable.length - 1]
      if (e.shiftKey && document.activeElement === first) {
        e.preventDefault()
        last.focus()
      } else if (!e.shiftKey && document.activeElement === last) {
        e.preventDefault()
        first.focus()
      }
    }
  })
  document.addEventListener('itsb:mobile-nav-open', closeChat)

  // Send button
  document.getElementById('chatSendBtn')?.addEventListener('click', sendMessage)

  // Enter to send (Shift+Enter for newline)
  const input = document.getElementById('chatInput') as HTMLTextAreaElement | null
  input?.addEventListener('keydown', (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      sendMessage()
    }
  })
  input?.addEventListener('input', () => {
    if (input) autoGrow(input)
  })

  // Quick action buttons
  document.getElementById('chatQuickActions')?.addEventListener('click', (e) => {
    const btn = (e.target as HTMLElement).closest('.chat-quick-btn') as HTMLElement | null
    if (btn) handleQuickAction(btn.dataset.action ?? '')
  })

  // Global trigger: any element with data-chat-trigger
  document.addEventListener('click', (e) => {
    const trigger = (e.target as HTMLElement).closest('[data-chat-trigger]') as HTMLElement | null
    if (!trigger) return
    // Only intercept if the chat panel is actually available; otherwise let the
    // native link/button behavior (e.g. href="/kontakt/") work as a fallback.
    const panel = document.getElementById('chatPanel')
    if (panel) {
      e.preventDefault()
      openChat({ intent: trigger.dataset.chatIntent })
    }
  })
}

// Init when DOM is ready
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', initChat)
} else {
  initChat()
}
