// Lawyerit public website chat widget.
// A floating, brand-matched assistant that answers visitors' general questions
// about privacy / regulation / Lawyerit's services and funnels interested
// visitors to a booking call. It calls the `ask-public` Supabase edge function
// (autonomous, firm-wide knowledge only, general info — never personalized legal
// advice; those route to a call). Self-contained, same pattern as CookieBanner.
//
// Sits on the corner OPPOSITE the cookie banner so the two never collide.

function ChatWidget() {
  const lang = typeof useLang !== 'undefined' ? useLang() : 'he';
  const isEn = lang === 'en';

  const ENDPOINT = (typeof window !== 'undefined' && window.LAWYERIT_BOT_ENDPOINT)
    || 'https://jpbqphuwxvsmpurvykbv.supabase.co/functions/v1/ask-public';
  const BOOKING_URL = 'https://www.cal.eu/lawyer-it/30min';

  const greeting = isEn
    ? "Hi! I'm Lawyerit's digital assistant. Ask me about privacy, AI regulation, compliance, or how we work."
    : 'היי! אני העוזר הדיגיטלי של Lawyerit. אפשר לשאול אותי על פרטיות, רגולציה, או על השירותים שלנו.';

  const [open, setOpen] = React.useState(false);
  const [messages, setMessages] = React.useState([{ role: 'assistant', content: greeting }]);
  const [input, setInput] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [booking, setBooking] = React.useState(false);
  const scrollRef = React.useRef(null);

  // Anonymous session id to group a conversation (for the insights dashboard).
  const sessionId = React.useMemo(() => {
    try {
      let s = localStorage.getItem('lawyerit-bot-session');
      if (!s) { s = 'w' + Date.now().toString(36) + Math.random().toString(36).slice(2, 8); localStorage.setItem('lawyerit-bot-session', s); }
      return s;
    } catch { return 'anon'; }
  }, []);

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages, loading, open]);

  const track = (name) => { try { if (window.clarity) window.clarity('event', name); } catch (e) {} };

  const toggle = () => { setOpen(o => { const next = !o; if (next) track('bot_open'); return next; }); };

  const send = async () => {
    const q = input.trim();
    if (!q || loading) return;
    const history = messages.filter(m => m.role === 'user' || m.role === 'assistant').slice(-6)
      .map(m => ({ role: m.role, content: m.content }));
    setMessages(m => [...m, { role: 'user', content: q }]);
    setInput('');
    setLoading(true);
    try {
      const res = await fetch(ENDPOINT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ question: q, history, lang, sessionId }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok || !data.answer) {
        const errMsg = res.status === 429
          ? (isEn ? 'A moment — too many messages. Please try again shortly.' : 'רגע אחד — יותר מדי הודעות. נסו שוב עוד רגע.')
          : (isEn ? "Sorry, something went wrong. You're welcome to book a call." : 'מצטערים, משהו השתבש. אפשר לקבוע שיחת היכרות ונשמח לעזור.');
        setMessages(m => [...m, { role: 'assistant', content: errMsg }]);
        setBooking(true);
      } else {
        setMessages(m => [...m, { role: 'assistant', content: data.answer }]);
        if (data.suggestBooking) { setBooking(true); track('bot_booking_suggested'); }
      }
    } catch (e) {
      setMessages(m => [...m, { role: 'assistant', content: isEn ? "Sorry, I couldn't reach the assistant. You're welcome to book a call." : 'מצטערים, לא הצלחתי להגיע לשרת. אפשר לקבוע שיחת היכרות.' }]);
      setBooking(true);
    } finally {
      setLoading(false);
    }
  };

  const onKey = (e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } };
  const bookNow = () => { track('bot_booking_click'); window.open(BOOKING_URL, '_blank', 'noopener,noreferrer'); };

  // Chat sits opposite the cookie banner: HE banner=right → chat=left; EN banner=left → chat=right.
  // Stacked above the WhatsApp widget bubble (which sits at bottom:24 in that same
  // corner) so the two bubbles never overlap. The panel opens sideways at
  // WhatsApp's own height, not upward from this bubble, so it never covers either
  // bubble regardless of which one is open.
  const side = isEn ? { right: 24 } : { left: 24 };
  const BUBBLE_GAP = 72; // WhatsApp bubble (56px) + 16px breathing room

  return (
    <div style={{ position: 'fixed', bottom: 24 + BUBBLE_GAP, ...side, zIndex: 9998, fontFamily: 'inherit' }}>
      {/* Panel */}
      {open && (
        <div style={{
          position: 'absolute', bottom: -BUBBLE_GAP, [isEn ? 'right' : 'left']: BUBBLE_GAP,
          width: 'min(370px, calc(100vw - 48px))', height: 'min(540px, calc(100vh - 120px))',
          background: 'var(--bg, #fff)', borderRadius: 18,
          boxShadow: '0 24px 56px -12px rgba(15,17,21,0.32)',
          border: '1px solid var(--border, #E5E5E5)',
          display: 'flex', flexDirection: 'column', overflow: 'hidden',
          animation: 'lw-bot-in 0.32s cubic-bezier(0.16,1,0.3,1)',
          direction: isEn ? 'ltr' : 'rtl',
        }}>
          {/* Header */}
          <div style={{ background: 'var(--ink, #0F1115)', color: '#fff', padding: '14px 18px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div>
              <div style={{ fontSize: 15, fontWeight: 800, letterSpacing: '-0.02em' }}>
                Lawyer<span style={{ color: 'var(--turquoise, #47CBCB)' }}>¶</span>t
              </div>
              <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.6)', marginTop: 2 }}>
                {isEn ? 'General info · not legal advice' : 'מידע כללי · לא ייעוץ משפטי'}
              </div>
            </div>
            <button onClick={toggle} aria-label="close" style={{ background: 'transparent', border: 'none', color: 'rgba(255,255,255,0.7)', cursor: 'pointer', fontSize: 20, lineHeight: 1, padding: 4, fontFamily: 'inherit' }}>×</button>
          </div>

          {/* Messages */}
          <div ref={scrollRef} style={{ flex: 1, overflowY: 'auto', padding: '16px', background: 'var(--bg-2, #F7F7F5)', display: 'flex', flexDirection: 'column', gap: 10 }}>
            {messages.map((m, i) => (
              <div key={i} style={{ alignSelf: m.role === 'user' ? (isEn ? 'flex-end' : 'flex-start') : (isEn ? 'flex-start' : 'flex-end'), maxWidth: '85%' }}>
                <div style={{
                  background: m.role === 'user' ? 'var(--turquoise, #47CBCB)' : '#fff',
                  color: m.role === 'user' ? 'var(--ink, #0F1115)' : 'var(--ink-2, #1A1A1A)',
                  border: m.role === 'user' ? 'none' : '1px solid var(--border, #E5E5E5)',
                  borderRadius: 14, padding: '10px 14px', fontSize: 13.5, lineHeight: 1.65, whiteSpace: 'pre-wrap',
                }}>{m.content}</div>
              </div>
            ))}
            {loading && (
              <div style={{ alignSelf: isEn ? 'flex-start' : 'flex-end' }}>
                <div style={{ background: '#fff', border: '1px solid var(--border, #E5E5E5)', borderRadius: 14, padding: '12px 16px', display: 'flex', gap: 4 }}>
                  <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--turquoise, #47CBCB)', animation: 'lw-bot-blink 1s infinite 0s' }} />
                  <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--turquoise, #47CBCB)', animation: 'lw-bot-blink 1s infinite 0.2s' }} />
                  <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--turquoise, #47CBCB)', animation: 'lw-bot-blink 1s infinite 0.4s' }} />
                </div>
              </div>
            )}
            {booking && !loading && (
              <button onClick={bookNow} style={{
                alignSelf: 'stretch', marginTop: 4,
                background: 'var(--turquoise, #47CBCB)', color: 'var(--ink, #0A2A2A)',
                border: 'none', borderRadius: 12, padding: '11px 16px', fontSize: 13.5, fontWeight: 700,
                cursor: 'pointer', fontFamily: 'inherit',
              }}>
                {isEn ? 'Book a free intro call →' : 'לקביעת שיחת היכרות →'}
              </button>
            )}
          </div>

          {/* Input */}
          <div style={{ display: 'flex', gap: 8, padding: 12, background: 'var(--bg, #fff)', borderTop: '1px solid var(--border, #E5E5E5)' }}>
            <input
              value={input}
              onChange={e => setInput(e.target.value)}
              onKeyDown={onKey}
              placeholder={isEn ? 'Type your question…' : 'כתבו את השאלה שלכם…'}
              style={{ flex: 1, border: '1px solid var(--border, #E5E5E5)', borderRadius: 10, padding: '10px 12px', fontSize: 13.5, fontFamily: 'inherit', outline: 'none', background: 'var(--bg-2, #F7F7F5)', color: 'var(--ink, #0F1115)' }}
            />
            <button onClick={send} disabled={loading || !input.trim()} aria-label="send" style={{
              background: 'var(--turquoise, #47CBCB)', border: 'none', borderRadius: 10, width: 42, cursor: loading || !input.trim() ? 'default' : 'pointer',
              opacity: loading || !input.trim() ? 0.5 : 1, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
            }}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" style={{ transform: isEn ? 'none' : 'scaleX(-1)' }}>
                <path d="M4 12l16-8-6 8 6 8-16-8z" fill="var(--ink, #0F1115)" />
              </svg>
            </button>
          </div>
        </div>
      )}

      {/* Bubble */}
      <button onClick={toggle} aria-label={isEn ? 'Chat with Lawyerit' : "צ'אט עם Lawyerit"} style={{
        width: 56, height: 56, borderRadius: '50%', background: 'var(--turquoise, #47CBCB)', border: 'none',
        boxShadow: '0 12px 28px -6px rgba(71,203,203,0.55)', cursor: 'pointer',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        {open ? (
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none"><path d="M6 6l12 12M18 6L6 18" stroke="var(--ink, #0F1115)" strokeWidth="2" strokeLinecap="round" /></svg>
        ) : (
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none"><path d="M21 11.5a8.5 8.5 0 0 1-12.3 7.6L3 21l1.9-5.7A8.5 8.5 0 1 1 21 11.5z" stroke="var(--ink, #0F1115)" strokeWidth="1.8" strokeLinejoin="round" /></svg>
        )}
      </button>

      <style>{`
        @keyframes lw-bot-in { from { opacity: 0; transform: translateY(16px); } to { opacity: 1; transform: translateY(0); } }
        @keyframes lw-bot-blink { 0%, 100% { opacity: 0.3; } 50% { opacity: 1; } }
      `}</style>
    </div>
  );
}

Object.assign(window, { ChatWidget });
