/* ── SUPPORT CHAT WIDGET ──
   Usage:
     <SupportChat isDark={isDark} t={t} open={chatOpen} setOpen={setChatOpen} />
   Or use the global helper:
     window.openSupportChat()  // opens the chat from anywhere on the page
*/

const SupportChat = ({ isDark, t, open, setOpen }) => {
  const [step, setStep] = React.useState('compose'); // 'compose' | 'sent'
  const [email, setEmail] = React.useState('');
  const [message, setMessage] = React.useState('');
  const [emailErr, setEmailErr] = React.useState('');
  const [msgErr, setMsgErr] = React.useState('');

  // Expose global opener
  React.useEffect(() => {
    window.openSupportChat = () => setOpen(true);
    return () => { delete window.openSupportChat; };
  }, [setOpen]);

  // Esc closes
  React.useEffect(() => {
    if (!open) return;
    const h = (e) => { if (e.key === 'Escape') setOpen(false); };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [open, setOpen]);

  const validateEmail = (v) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v);

  const handleSend = () => {
    let valid = true;
    if (!validateEmail(email)) { setEmailErr('Please enter a valid email address.'); valid = false; }
    if (!message.trim() || message.trim().length < 5) { setMsgErr('Please enter a message (at least 5 characters).'); valid = false; }
    if (!valid) return;
    // In production this would POST to a backend / Formspree / mailto fallback.
    // For now, simulate success.
    setStep('sent');
  };

  const reset = () => {
    setStep('compose');
    setEmail('');
    setMessage('');
    setEmailErr('');
    setMsgErr('');
  };

  const FAB_SIZE = 56;
  const greenText = isDark ? '#070d1a' : '#fff';

  return (
    <>
      {/* Floating Action Button */}
      <button
        onClick={() => setOpen(o => !o)}
        aria-label="Open support chat"
        style={{
          position: 'fixed', right: 24, bottom: 24, zIndex: 800,
          width: FAB_SIZE, height: FAB_SIZE, borderRadius: '50%',
          background: t.green, color: greenText, border: 'none',
          boxShadow: '0 8px 24px rgba(0,0,0,0.25), 0 2px 8px rgba(0,0,0,0.15)',
          cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
          transition: 'transform 0.2s ease, box-shadow 0.2s ease',
        }}
        onMouseEnter={e => { e.currentTarget.style.transform = 'scale(1.06)'; }}
        onMouseLeave={e => { e.currentTarget.style.transform = 'scale(1)'; }}
      >
        {open ? (
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round">
            <line x1="6" y1="6" x2="18" y2="18" /><line x1="6" y1="18" x2="18" y2="6" />
          </svg>
        ) : (
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" 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>
        )}
      </button>

      {/* Chat Panel */}
      {open && (
        <div style={{
          position: 'fixed', right: 24, bottom: 24 + FAB_SIZE + 12, zIndex: 799,
          width: 360, maxWidth: 'calc(100vw - 48px)',
          background: isDark ? '#111d30' : '#ffffff',
          border: '1px solid ' + t.border,
          borderRadius: 14,
          boxShadow: '0 24px 60px rgba(0,0,0,0.3), 0 4px 16px rgba(0,0,0,0.15)',
          overflow: 'hidden',
          fontFamily: 'DM Sans, sans-serif',
          animation: 'tradersEdgeChatIn 0.22s ease',
        }}>
          {/* Header */}
          <div style={{
            padding: '16px 18px',
            background: t.green,
            color: greenText,
            display: 'flex', alignItems: 'center', gap: 12,
          }}>
            <div style={{
              width: 38, height: 38, borderRadius: '50%',
              background: 'rgba(255,255,255,0.2)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: 'DM Mono, monospace', fontSize: 13, fontWeight: 700, letterSpacing: '0.04em',
            }}>TE</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 700, lineHeight: 1.2 }}>Traders Edge Support</div>
              <div style={{ fontSize: 11, opacity: 0.75, marginTop: 2 }}>
                <span style={{
                  display: 'inline-block', width: 6, height: 6, borderRadius: '50%',
                  background: greenText, marginRight: 6, verticalAlign: 'middle',
                }}></span>
                Typically replies within 24h
              </div>
            </div>
          </div>

          {/* Body */}
          <div style={{ padding: '18px', maxHeight: '60vh', overflowY: 'auto' }}>
            {step === 'compose' && (
              <>
                <div style={{
                  background: isDark ? 'rgba(255,255,255,0.04)' : '#f4f6f4',
                  border: '1px solid ' + t.border,
                  borderRadius: 10, padding: '12px 14px', marginBottom: 16,
                }}>
                  <div style={{ fontSize: 13, color: t.text, lineHeight: 1.55 }}>
                    Hey! Drop your email and message below — I&apos;ll get back to you as soon as I can.
                  </div>
                </div>

                <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: t.text, marginBottom: 6 }}>
                  Your email
                </label>
                <input
                  type="email"
                  value={email}
                  onChange={e => { setEmail(e.target.value); setEmailErr(''); }}
                  placeholder="you@example.com"
                  style={{
                    width: '100%', padding: '10px 12px', borderRadius: 8,
                    background: isDark ? '#0d1628' : '#fff',
                    border: '1.5px solid ' + (emailErr ? '#ff4d6d' : t.border),
                    color: t.text, fontSize: 13, fontFamily: 'DM Sans, sans-serif',
                    outline: 'none', marginBottom: emailErr ? 4 : 12,
                  }}
                />
                {emailErr && <div style={{ fontSize: 11, color: '#ff4d6d', marginBottom: 12 }}>{emailErr}</div>}

                <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: t.text, marginBottom: 6 }}>
                  Message
                </label>
                <textarea
                  value={message}
                  onChange={e => { setMessage(e.target.value); setMsgErr(''); }}
                  placeholder="License issue? Question about an indicator? Let me know..."
                  rows={5}
                  style={{
                    width: '100%', padding: '10px 12px', borderRadius: 8,
                    background: isDark ? '#0d1628' : '#fff',
                    border: '1.5px solid ' + (msgErr ? '#ff4d6d' : t.border),
                    color: t.text, fontSize: 13, fontFamily: 'DM Sans, sans-serif',
                    outline: 'none', resize: 'vertical', minHeight: 90,
                    marginBottom: msgErr ? 4 : 14,
                  }}
                />
                {msgErr && <div style={{ fontSize: 11, color: '#ff4d6d', marginBottom: 14 }}>{msgErr}</div>}

                <button
                  onClick={handleSend}
                  style={{
                    width: '100%', padding: '12px 16px', borderRadius: 8,
                    background: t.green, color: greenText, border: 'none',
                    fontSize: 14, fontWeight: 700, fontFamily: 'DM Sans, sans-serif',
                    cursor: 'pointer', transition: 'opacity 0.15s',
                  }}
                  onMouseEnter={e => { e.currentTarget.style.opacity = '0.9'; }}
                  onMouseLeave={e => { e.currentTarget.style.opacity = '1'; }}
                >
                  Send Message
                </button>

                <div style={{ marginTop: 12, fontSize: 11, color: t.textMuted, textAlign: 'center', lineHeight: 1.5 }}>
                  Or join the <a href="#" style={{ color: t.green, textDecoration: 'none', fontWeight: 600 }}>TE Discord</a> for community help.
                </div>
              </>
            )}

            {step === 'sent' && (
              <div style={{ textAlign: 'center', padding: '12px 0' }}>
                <div style={{ marginBottom: 14 }}>
                  <svg width="48" height="48" viewBox="0 0 48 48" fill="none">
                    <circle cx="24" cy="24" r="24" fill={t.green} fillOpacity="0.15" />
                    <circle cx="24" cy="24" r="17" fill={t.green} fillOpacity="0.2" />
                    <polyline points="15,24 21,30 33,18" stroke={t.green} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" fill="none" />
                  </svg>
                </div>
                <div style={{ fontSize: 16, fontWeight: 700, color: t.text, marginBottom: 6 }}>Message sent!</div>
                <div style={{ fontSize: 13, color: t.textSub, lineHeight: 1.6, marginBottom: 18 }}>
                  Thanks — I&apos;ll get back to you at<br />
                  <strong style={{ color: t.text, fontFamily: 'DM Mono, monospace', fontSize: 12 }}>{email}</strong> within 24 hours.
                </div>
                <button
                  onClick={reset}
                  style={{
                    padding: '9px 18px', borderRadius: 8,
                    background: 'transparent', color: t.green,
                    border: '1.5px solid ' + t.green,
                    fontSize: 13, fontWeight: 600, cursor: 'pointer',
                    fontFamily: 'DM Sans, sans-serif',
                  }}
                >
                  Send another
                </button>
              </div>
            )}
          </div>
        </div>
      )}

      <style>{`
        @keyframes tradersEdgeChatIn {
          from { opacity: 0; transform: translateY(8px); }
          to { opacity: 1; transform: translateY(0); }
        }
      `}</style>
    </>
  );
};

window.SupportChat = SupportChat;
