/* eslint-disable */
// HAIQ — Chatbot widget. Two states:
// 1) Passive: bot icon FAB (bottom-right)
// 2) Active: chat panel auto-opens after 10s OR on icon click

const CHAT_COPY = {
  ua: {
    title: "HAIQ Bot",
    subtitle: "Зазвичай відповідаємо за хвилину",
    greeting: "Привіт 👋 Я AI-помічник HAIQ. Допоможу обрати рішення для вашого магазину або відповім на запитання — про що поговоримо?",
    quick: ["Розкажіть про послуги", "Скільки це коштує?", "Хочу безкоштовний аудит"],
    placeholder: "Напишіть повідомлення…",
    send: "Надіслати",
    autoReply: "Дякую! Передам менеджеру — він напише вам у Telegram упродовж 15 хвилин 🙌",
  },
  en: {
    title: "HAIQ Bot",
    subtitle: "We usually reply within a minute",
    greeting: "Hi 👋 I'm HAIQ's AI assistant. I can help you pick the right solution for your store or answer any question — what would you like to talk about?",
    quick: ["Tell me about your services", "How much does it cost?", "I want a free audit"],
    placeholder: "Type a message…",
    send: "Send",
    autoReply: "Thanks! I'll pass this to a manager — they'll reach out on Telegram within 15 minutes 🙌",
  },
};

function Chatbot({lang = 'ua'}) {
  const [open, setOpen] = React.useState(false);
  const [pulse, setPulse] = React.useState(false);
  const [messages, setMessages] = React.useState([]);
  const [input, setInput] = React.useState('');
  const [typing, setTyping] = React.useState(false);
  const c = CHAT_COPY[lang] || CHAT_COPY.en;
  const scrollRef = React.useRef(null);
  const dismissed = React.useRef(false);

  // Auto-open after 10s (only if user hasn't dismissed)
  React.useEffect(() => {
    const dismissedFlag = sessionStorage.getItem('haiq_chat_dismissed') === '1';
    if (dismissedFlag) { dismissed.current = true; return; }
    const timer = setTimeout(() => {
      if (!dismissed.current) {
        setOpen(true);
        setPulse(true);
      }
    }, 10000);
    return () => clearTimeout(timer);
  }, []);

  // Seed greeting whenever opened
  React.useEffect(() => {
    if (open && messages.length === 0) {
      setMessages([{ role: 'bot', text: c.greeting }]);
    }
  }, [open]);

  // Refresh greeting language if lang changes mid-session
  React.useEffect(() => {
    if (messages.length > 0 && messages[0].role === 'bot') {
      setMessages((m) => [{ role: 'bot', text: c.greeting }, ...m.slice(1)]);
    }
  }, [lang]);

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

  function send(text) {
    const v = (text || input).trim();
    if (!v) return;
    setMessages((m) => [...m, { role: 'user', text: v }]);
    setInput('');
    setTyping(true);
    setTimeout(() => {
      setTyping(false);
      setMessages((m) => [...m, { role: 'bot', text: c.autoReply }]);
    }, 1100);
  }

  function close() {
    setOpen(false);
    setPulse(false);
    dismissed.current = true;
    sessionStorage.setItem('haiq_chat_dismissed', '1');
  }

  return (
    <div style={{position:'fixed', right:24, bottom:24, zIndex:200, fontFamily:'var(--font-sans)'}}>
      {/* Passive bot icon */}
      {!open && (
        <button onClick={() => { setOpen(true); setPulse(true); }} aria-label="Open chat"
          style={{
            width:62, height:62, borderRadius:'50%', cursor:'pointer',
            background:'#fff', color:'#000', border:'none',
            display:'flex', alignItems:'center', justifyContent:'center',
            boxShadow:'0 12px 30px rgba(0,0,0,0.6), 0 0 0 1px rgba(255,255,255,0.1), 0 0 30px rgba(255,255,255,0.08)',
            transition:'transform 0.4s cubic-bezier(0.16,1,0.3,1)',
            position:'relative',
          }}
          onMouseEnter={e => e.currentTarget.style.transform = 'scale(1.08)'}
          onMouseLeave={e => e.currentTarget.style.transform = 'scale(1)'}
        >
          {/* Bot icon */}
          <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
            <rect x="4" y="7" width="16" height="12" rx="3"/>
            <path d="M12 7V3"/>
            <circle cx="12" cy="3" r="1.2" fill="currentColor"/>
            <circle cx="9" cy="13" r="1" fill="currentColor"/>
            <circle cx="15" cy="13" r="1" fill="currentColor"/>
            <path d="M9.5 16.5h5"/>
            <path d="M2 12h2"/>
            <path d="M20 12h2"/>
          </svg>
          {/* Pulse ring */}
          <span style={{
            position:'absolute', inset:-4, borderRadius:'50%',
            border:'1px solid rgba(255,255,255,0.5)',
            animation:'haiqChatPulse 2.4s ease-out infinite',
            pointerEvents:'none',
          }}/>
          {/* Notification dot */}
          <span style={{
            position:'absolute', top:2, right:2,
            width:12, height:12, borderRadius:'50%',
            background:'#7BFFA8',
            border:'2px solid #fff',
            boxShadow:'0 0 10px rgba(123,255,168,0.6)',
          }}/>
        </button>
      )}

      {/* Active chat panel */}
      {open && (
        <div style={{
          width:340, maxWidth:'calc(100vw - 32px)',
          height:480, maxHeight:'calc(100vh - 100px)',
          borderRadius:20, overflow:'hidden',
          background:'#0A0A0A',
          border:'1px solid rgba(255,255,255,0.1)',
          boxShadow:'0 30px 80px rgba(0,0,0,0.7), 0 0 60px rgba(255,255,255,0.04)',
          display:'flex', flexDirection:'column',
          animation:`haiqChatIn 0.5s cubic-bezier(0.16,1,0.3,1)`,
          transformOrigin:'bottom right',
        }}>
          {/* Header */}
          <div style={{
            padding:'18px 18px 16px',
            borderBottom:'1px solid rgba(255,255,255,0.06)',
            display:'flex', alignItems:'center', gap:12,
          }}>
            <div style={{
              width:40, height:40, borderRadius:'50%', background:'#fff', color:'#000',
              display:'flex', alignItems:'center', justifyContent:'center',
              flexShrink:0,
            }}>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
                <rect x="4" y="7" width="16" height="12" rx="3"/>
                <path d="M12 7V3"/>
                <circle cx="12" cy="3" r="1.2" fill="currentColor"/>
                <circle cx="9" cy="13" r="1" fill="currentColor"/>
                <circle cx="15" cy="13" r="1" fill="currentColor"/>
                <path d="M9.5 16.5h5"/>
              </svg>
            </div>
            <div style={{flex:1, minWidth:0}}>
              <div style={{display:'flex', alignItems:'center', gap:8}}>
                <span style={{fontSize:14, fontWeight:600, color:'#fff'}}>{c.title}</span>
                <span style={{
                  width:6, height:6, borderRadius:'50%', background:'#7BFFA8',
                  boxShadow:'0 0 8px rgba(123,255,168,0.6)',
                }}/>
              </div>
              <div style={{fontSize:11, color:'rgba(255,255,255,0.45)', marginTop:2}}>{c.subtitle}</div>
            </div>
            <button onClick={close} aria-label="Close" style={{
              background:'none', border:'none', cursor:'pointer',
              color:'rgba(255,255,255,0.5)', padding:4,
              fontSize:18, lineHeight:1,
            }} onMouseEnter={e=>e.currentTarget.style.color='#fff'}
               onMouseLeave={e=>e.currentTarget.style.color='rgba(255,255,255,0.5)'}>×</button>
          </div>

          {/* Messages */}
          <div ref={scrollRef} style={{
            flex:1, padding:'16px 16px 8px',
            overflowY:'auto', display:'flex', flexDirection:'column', gap:10,
            background:'#000',
          }}>
            {messages.map((m, i) => (
              <div key={i} style={{
                alignSelf: m.role === 'user' ? 'flex-end' : 'flex-start',
                maxWidth:'82%',
                padding:'10px 14px', borderRadius:14,
                background: m.role === 'user' ? '#fff' : 'rgba(255,255,255,0.06)',
                color: m.role === 'user' ? '#000' : '#fff',
                fontSize:13, lineHeight:1.5,
                border: m.role === 'user' ? 'none' : '1px solid rgba(255,255,255,0.08)',
                animation:'haiqMsgIn 0.35s cubic-bezier(0.16,1,0.3,1)',
              }}>{m.text}</div>
            ))}
            {typing && (
              <div style={{
                alignSelf:'flex-start', padding:'12px 14px', borderRadius:14,
                background:'rgba(255,255,255,0.06)',
                border:'1px solid rgba(255,255,255,0.08)',
                display:'flex', gap:4,
              }}>
                {[0,1,2].map(i => (
                  <span key={i} style={{
                    width:6, height:6, borderRadius:'50%', background:'rgba(255,255,255,0.6)',
                    animation:`haiqDot 1.2s ease-in-out ${i*0.15}s infinite`,
                  }}/>
                ))}
              </div>
            )}

            {/* Quick replies — show only if no user msg sent yet */}
            {messages.length > 0 && !messages.some(m => m.role === 'user') && (
              <div style={{display:'flex', flexDirection:'column', gap:6, marginTop:6}}>
                {c.quick.map((q, i) => (
                  <button key={i} onClick={() => send(q)} style={{
                    alignSelf:'flex-start',
                    padding:'8px 12px', borderRadius:100, cursor:'pointer',
                    background:'transparent',
                    border:'1px solid rgba(255,255,255,0.15)',
                    color:'rgba(255,255,255,0.85)',
                    fontFamily:'var(--font-sans)', fontSize:12,
                    transition:'all 0.3s ease',
                  }}
                  onMouseEnter={e => { e.currentTarget.style.background = 'rgba(255,255,255,0.08)'; e.currentTarget.style.color = '#fff'; }}
                  onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'rgba(255,255,255,0.85)'; }}
                  >{q}</button>
                ))}
              </div>
            )}
          </div>

          {/* Input */}
          <form onSubmit={(e) => { e.preventDefault(); send(); }} style={{
            padding:'12px 14px',
            borderTop:'1px solid rgba(255,255,255,0.06)',
            display:'flex', gap:8, background:'#0A0A0A',
          }}>
            <input
              value={input}
              onChange={e => setInput(e.target.value)}
              placeholder={c.placeholder}
              style={{
                flex:1, padding:'10px 14px', borderRadius:100,
                background:'rgba(255,255,255,0.04)',
                border:'1px solid rgba(255,255,255,0.08)',
                color:'#fff', fontFamily:'var(--font-sans)', fontSize:13,
                outline:'none',
              }}
              onFocus={e => e.currentTarget.style.borderColor = 'rgba(255,255,255,0.25)'}
              onBlur={e => e.currentTarget.style.borderColor = 'rgba(255,255,255,0.08)'}
            />
            <button type="submit" style={{
              padding:'10px 14px', borderRadius:100, cursor:'pointer',
              background:'#fff', color:'#000', border:'none',
              fontFamily:'var(--font-sans)', fontSize:13, fontWeight:500,
              display:'flex', alignItems:'center', gap:4,
            }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <line x1="22" y1="2" x2="11" y2="13"/>
                <polygon points="22 2 15 22 11 13 2 9 22 2"/>
              </svg>
            </button>
          </form>
        </div>
      )}
    </div>
  );
}

window.Chatbot = Chatbot;
