// Floating AI chat widget. Proxies through /api/chat → HostMoat public-chat.
// Visual style matches the Karaway design system (ocean/terracotta/cream).

const { useState: useStateC, useEffect: useEffectC, useRef: useRefC } = React;

const SESSION_KEY = 'kw_chat_session';
const HISTORY_KEY = 'kw_chat_history';
const OPEN_KEY    = 'kw_chat_open';

const loadSession = () => {
  try { return localStorage.getItem(SESSION_KEY); } catch { return null; }
};
const saveSession = (t) => {
  try { if (t) localStorage.setItem(SESSION_KEY, t); } catch {}
};
const loadHistory = () => {
  try {
    const raw = localStorage.getItem(HISTORY_KEY);
    return raw ? JSON.parse(raw) : [];
  } catch { return []; }
};
const saveHistory = (h) => {
  try { localStorage.setItem(HISTORY_KEY, JSON.stringify(h.slice(-30))); } catch {}
};

const ChatWidget = () => {
  const content = window.useContent ? window.useContent() : null;
  const configured = !!content?.settings?.hostmoat_property_id;

  const [open, setOpen] = useStateC(() => {
    try { return localStorage.getItem(OPEN_KEY) === '1'; } catch { return false; }
  });
  const [messages, setMessages] = useStateC(() => loadHistory());
  const [input, setInput] = useStateC('');
  const [sending, setSending] = useStateC(false);
  const [error, setError] = useStateC(null);
  const [unavailable, setUnavailable] = useStateC(false);
  const scrollRef = useRefC(null);
  const inputRef = useRefC(null);

  useEffectC(() => {
    try { localStorage.setItem(OPEN_KEY, open ? '1' : '0'); } catch {}
  }, [open]);

  useEffectC(() => {
    saveHistory(messages);
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }
  }, [messages, open]);

  useEffectC(() => {
    if (open && inputRef.current) inputRef.current.focus();
  }, [open]);

  const send = async (e) => {
    e?.preventDefault();
    const text = input.trim();
    if (!text || sending) return;

    const userMsg = { role: 'user', text, ts: Date.now() };
    setMessages(prev => [...prev, userMsg]);
    setInput('');
    setSending(true);
    setError(null);

    try {
      const r = await fetch('/api/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ message: text, sessionToken: loadSession() || undefined }),
      });
      const data = await r.json().catch(() => ({}));
      if (!r.ok) {
        if (r.status === 503) setUnavailable(true);
        throw new Error(data.error || `HTTP ${r.status}`);
      }
      if (data.sessionToken) saveSession(data.sessionToken);
      const replyText = data.response || data.reply || '(no response)';
      setMessages(prev => [...prev, { role: 'assistant', text: replyText, ts: Date.now() }]);
    } catch (e) {
      setError(String(e.message || e));
    } finally {
      setSending(false);
    }
  };

  const clear = () => {
    setMessages([]);
    try { localStorage.removeItem(SESSION_KEY); } catch {}
  };

  // Hide entirely if the HostMoat property_id isn't configured yet,
  // or if a first request returned 503 with no prior conversation.
  if (!configured) return null;
  if (unavailable && messages.length === 0) return null;

  const btnStyle = {
    position: 'fixed', bottom: 20, right: 20, zIndex: 450,
    background: '#0f2326', color: '#faf6ef', border: 'none',
    borderRadius: 100, padding: '14px 22px',
    display: 'flex', alignItems: 'center', gap: 10,
    cursor: 'pointer', boxShadow: '0 8px 32px rgba(15,35,38,0.25)',
    fontFamily: "'Inter', sans-serif", fontSize: 13, letterSpacing: '0.08em',
  };

  return (
    <>
      {!open && (
        <button onClick={() => setOpen(true)} style={btnStyle} aria-label="Open chat">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
            <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
          </svg>
          <span>Ask Karaway</span>
        </button>
      )}

      {open && (
        <div style={{
          position: 'fixed', bottom: 20, right: 20, zIndex: 450,
          width: 380, maxWidth: 'calc(100vw - 40px)',
          height: 560, maxHeight: 'calc(100vh - 40px)',
          background: '#faf6ef', color: '#1e2a2e',
          borderRadius: 6, overflow: 'hidden',
          display: 'flex', flexDirection: 'column',
          boxShadow: '0 18px 60px rgba(15,35,38,0.28)',
          fontFamily: "'Inter', sans-serif",
          border: '1px solid #e3dcc9',
        }}>
          <div style={{
            background: '#0f2326', color: '#faf6ef',
            padding: '16px 20px',
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          }}>
            <div>
              <div style={{fontSize: 10, letterSpacing: '0.22em', textTransform: 'uppercase', color: 'rgba(250,246,239,0.6)', marginBottom: 2}}>Ask Karaway</div>
              <div style={{fontFamily: "'EB Garamond', Georgia, serif", fontSize: 20, fontWeight: 400}}>We're here to help.</div>
            </div>
            <div style={{display: 'flex', gap: 4}}>
              {messages.length > 0 && (
                <button onClick={clear} title="Clear chat" style={{background: 'none', border: 'none', color: 'rgba(250,246,239,0.6)', cursor: 'pointer', padding: 6, fontSize: 11}}>Clear</button>
              )}
              <button onClick={() => setOpen(false)} aria-label="Close" style={{background: 'none', border: 'none', color: '#faf6ef', cursor: 'pointer', padding: 6, display: 'flex'}}>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><line x1="6" y1="6" x2="18" y2="18"/><line x1="18" y1="6" x2="6" y2="18"/></svg>
              </button>
            </div>
          </div>

          <div ref={scrollRef} style={{flex: 1, overflowY: 'auto', padding: '20px', background: '#faf6ef'}}>
            {messages.length === 0 && (
              <div style={{textAlign: 'center', color: '#8a8075', paddingTop: 40}}>
                <p style={{fontFamily: "'EB Garamond', Georgia, serif", fontSize: 18, fontWeight: 300, lineHeight: 1.5, marginBottom: 14}}>Hola. I can answer questions about the villa, staff, availability, and the area.</p>
                <p style={{fontSize: 12, lineHeight: 1.6, color: '#a89b8a'}}>For bookings, use the Book Stay button — I'll hand you off there.</p>
              </div>
            )}
            {messages.map((m, i) => (
              <div key={i} style={{marginBottom: 14, display: 'flex', justifyContent: m.role === 'user' ? 'flex-end' : 'flex-start'}}>
                <div style={{
                  maxWidth: '82%',
                  padding: '10px 14px',
                  borderRadius: m.role === 'user' ? '12px 12px 2px 12px' : '12px 12px 12px 2px',
                  background: m.role === 'user' ? '#0f2326' : '#f4ecdc',
                  color: m.role === 'user' ? '#faf6ef' : '#1e2a2e',
                  fontSize: 14, lineHeight: 1.55,
                  whiteSpace: 'pre-wrap', wordBreak: 'break-word',
                }}>{m.text}</div>
              </div>
            ))}
            {sending && (
              <div style={{display: 'flex', justifyContent: 'flex-start', marginBottom: 14}}>
                <div style={{padding: '10px 14px', background: '#f4ecdc', borderRadius: '12px 12px 12px 2px', fontSize: 14, color: '#8a8075'}}>
                  <span className="karaway-chat-dot">•</span><span className="karaway-chat-dot" style={{animationDelay: '0.15s'}}>•</span><span className="karaway-chat-dot" style={{animationDelay: '0.3s'}}>•</span>
                </div>
              </div>
            )}
            {error && <div style={{padding: '10px 14px', background: '#f8dad6', color: '#a0403a', fontSize: 12, borderRadius: 4}}>{error}</div>}
          </div>

          <form onSubmit={send} style={{display: 'flex', gap: 8, padding: 14, borderTop: '1px solid #e3dcc9', background: '#fff'}}>
            <input
              ref={inputRef}
              type="text"
              value={input}
              onChange={e => setInput(e.target.value)}
              placeholder="Ask about the villa…"
              disabled={sending}
              style={{flex: 1, padding: '10px 12px', fontSize: 14, border: '1px solid #e3dcc9', borderRadius: 3, fontFamily: 'inherit', color: '#1e2a2e', background: '#faf6ef'}}
              maxLength={2000}
            />
            <button type="submit" disabled={sending || !input.trim()} style={{padding: '10px 16px', fontSize: 12, letterSpacing: '0.14em', textTransform: 'uppercase', background: '#c8704a', color: '#faf6ef', border: 'none', borderRadius: 3, cursor: sending ? 'default' : 'pointer', opacity: sending || !input.trim() ? 0.5 : 1}}>Send</button>
          </form>
          <style>{`
            @keyframes kwChatDot { 0%,80%,100%{opacity:.2} 40%{opacity:1} }
            .karaway-chat-dot { display: inline-block; animation: kwChatDot 1s infinite; margin: 0 1px; }
          `}</style>
        </div>
      )}
    </>
  );
};

Object.assign(window, { ChatWidget });
