'use client'

/**
 * The help bubble: a few answers the academy wrote, and a handoff to WhatsApp for anything else.
 *
 * What this is NOT, so nobody is misled by the bubble: there is no support backend behind it and no
 * model answering. Every reply shown is one an editor typed in the CMS, matched to the question the
 * visitor picked. Anything typed in the box is not answered here — it opens WhatsApp with that text
 * already written, and a person replies. The disclaimer under the box says so, and it is a CMS field
 * so it can be worded for the audience.
 *
 * Nothing is rendered at all when the chat is switched off (NEXT_PUBLIC_CHAT_ENABLED=false) or when no
 * WhatsApp number is set: a bubble that opens on a dead end is worse than no bubble.
 */

import { useEffect, useRef, useState } from 'react'
import { Icon } from './icons'

export type ChatQA = { q: string; a: string }

type Props = {
  title: string
  greeting: string
  items: ChatQA[]
  placeholder: string
  send: string
  disclaimer: string
  close: string
  /** Digits only, no plus: what wa.me expects. */
  whatsapp: string
}

export function Chat({ title, greeting, items, placeholder, send, disclaimer, close, whatsapp }: Props) {
  const [open, setOpen] = useState(false)
  const [reply, setReply] = useState<string | null>(null)
  const [text, setText] = useState('')
  const launcher = useRef<HTMLButtonElement | null>(null)

  useEffect(() => {
    if (!open) return
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        setOpen(false)
        launcher.current?.focus()
      }
    }
    document.addEventListener('keydown', onKey)
    return () => document.removeEventListener('keydown', onKey)
  }, [open])

  if (!whatsapp) return null

  const ask = (e: React.FormEvent) => {
    e.preventDefault()
    const msg = text.trim()
    if (!msg) return
    // noopener/noreferrer on a window opened by script too: without it the new tab can reach back
    // through window.opener.
    window.open(`https://wa.me/${whatsapp}?text=${encodeURIComponent(msg)}`, '_blank', 'noopener,noreferrer')
  }

  return (
    <>
      <div className="chat-box" hidden={!open} role="dialog" aria-label={title} aria-modal="false">
        <div className="chat-head">
          <strong>{title}</strong>
          <button type="button" aria-label={close} onClick={() => { setOpen(false); launcher.current?.focus() }}>
            ×
          </button>
        </div>
        <div className="chat-body">
          <p>{greeting}</p>
          <div className="chat-options">
            {items.map((it, i) => (
              <button key={i} type="button" onClick={() => setReply(it.a)}>
                {it.q}
              </button>
            ))}
          </div>
          {/* aria-live so the answer is announced: it appears without the focus moving to it. */}
          <div className="chat-reply" hidden={!reply} aria-live="polite">
            {reply}
          </div>
          <form className="chat-form" onSubmit={ask}>
            <input value={text} onChange={(e) => setText(e.target.value)} placeholder={placeholder}
                   aria-label={placeholder} maxLength={600} />
            <button aria-label={send}>
              <Icon name="arrow" />
            </button>
          </form>
          <small className="notice">{disclaimer}</small>
        </div>
      </div>
      <button ref={launcher} className="chat-launch" type="button" aria-label={title}
              aria-expanded={open} onClick={() => setOpen((v) => !v)}>
        <Icon name={open ? 'close' : 'chat'} />
      </button>
    </>
  )
}
