/**
 * Heartistry Stays — Voice Concierge Drawer
 *
 * A floating mic button in the bottom-right corner. Tapping it opens a drawer
 * showing the conversation state, transcripts, and Generative UI cards (quotes,
 * property cards, payment links) produced as Tara calls tools.
 *
 * Uses window.__taraAudio (voice-audio.js) for audio and WebSocket.
 * Rendered by Babel Standalone + React 18 UMD.
 */

(function () {
  'use strict';

  const { useState, useEffect, useRef, useCallback } = React;

  // ── Generative UI card components ─────────────────────────────────────────────

  function PropertyCard({ data }) {
    const props = data.properties ?? [];
    if (!props.length) return null;
    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {props.map((p) => (
          <div key={p.id} style={{
            border: '1px solid #e5e7eb', borderRadius: 10, padding: '10px 12px',
            background: '#fff', fontSize: 13,
          }}>
            <div style={{ fontWeight: 600, color: '#1a1a1a', marginBottom: 2 }}>{p.name}</div>
            {p.city && <div style={{ color: '#6b7280' }}>{p.city}{p.area ? `, ${p.area}` : ''}</div>}
            {(p.price_per_night || p.whatsapp_price_per_night) && (
              <div style={{ color: '#059669', marginTop: 4, fontWeight: 500 }}>
                ₹{(p.whatsapp_price_per_night ?? p.price_per_night).toLocaleString('en-IN')} / night
              </div>
            )}
            {p.max_guests && (
              <div style={{ color: '#6b7280', fontSize: 12 }}>Up to {p.max_guests} guests</div>
            )}
          </div>
        ))}
      </div>
    );
  }

  function QuoteCard({ data }) {
    if (data.error) return <div style={{ color: '#dc2626', fontSize: 13 }}>{data.error}</div>;
    const tax = data.gst_amount ?? data.tax_amount ?? 0;
    return (
      <div style={{
        border: '1px solid #d1fae5', borderRadius: 10, padding: '12px 14px',
        background: '#f0fdf4', fontSize: 13,
      }}>
        <div style={{ fontWeight: 600, color: '#065f46', marginBottom: 6 }}>Price Estimate</div>
        {data.check_in && (
          <div style={{ color: '#6b7280', fontSize: 12, marginBottom: 6 }}>
            {data.check_in} → {data.check_out} · {data.nights} night{data.nights !== 1 ? 's' : ''}
          </div>
        )}
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 2 }}>
          <span style={{ color: '#374151' }}>Room charges</span>
          <span style={{ fontWeight: 500 }}>₹{(data.room_subtotal ?? 0).toLocaleString('en-IN')}</span>
        </div>
        {data.extra_guest_total > 0 && (
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 2 }}>
            <span style={{ color: '#374151' }}>Extra guests</span>
            <span>₹{data.extra_guest_total.toLocaleString('en-IN')}</span>
          </div>
        )}
        {tax > 0 && (
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 2 }}>
            <span style={{ color: '#374151' }}>GST</span>
            <span>₹{tax.toLocaleString('en-IN')}</span>
          </div>
        )}
        <div style={{
          display: 'flex', justifyContent: 'space-between', paddingTop: 6,
          borderTop: '1px solid #d1fae5', marginTop: 4, fontWeight: 600, color: '#065f46',
        }}>
          <span>Total</span>
          <span>₹{(data.total ?? 0).toLocaleString('en-IN')}</span>
        </div>
        {data.advance > 0 && (
          <div style={{ color: '#6b7280', fontSize: 12, marginTop: 4 }}>
            Advance: ₹{data.advance.toLocaleString('en-IN')} · Balance: ₹{(data.balance_due ?? 0).toLocaleString('en-IN')}
          </div>
        )}
      </div>
    );
  }

  function PaymentCard({ data }) {
    if (data.error) return <div style={{ color: '#dc2626', fontSize: 13 }}>{data.error}</div>;
    return (
      <div style={{
        border: '1px solid #dbeafe', borderRadius: 10, padding: '12px 14px',
        background: '#eff6ff', fontSize: 13,
      }}>
        <div style={{ fontWeight: 600, color: '#1e3a8a', marginBottom: 8 }}>Payment Link Ready</div>
        <div style={{ color: '#374151', marginBottom: 10 }}>
          {data.phase === 'advance' ? 'Advance' : 'Balance'} payment of{' '}
          <strong>₹{(data.amount ?? data.gross_amount ?? 0).toLocaleString('en-IN')}</strong>
        </div>
        <a
          href={data.payment_url}
          target="_blank"
          rel="noopener noreferrer"
          style={{
            display: 'inline-block', background: '#1d4ed8', color: '#fff',
            borderRadius: 8, padding: '8px 16px', textDecoration: 'none',
            fontWeight: 600, fontSize: 13,
          }}
        >
          Pay Now →
        </a>
      </div>
    );
  }

  function BookingCard({ data }) {
    if (data.error) return <div style={{ color: '#dc2626', fontSize: 13 }}>{data.error}</div>;
    return (
      <div style={{
        border: '1px solid #fde68a', borderRadius: 10, padding: '12px 14px',
        background: '#fffbeb', fontSize: 13,
      }}>
        <div style={{ fontWeight: 600, color: '#78350f', marginBottom: 6 }}>Reservation Request Initiated</div>
        <div style={{ color: '#374151' }}>Ref: <strong>{data.booking_id ?? 'Pending'}</strong></div>
        {data.check_in && (
          <div style={{ color: '#6b7280', marginTop: 4 }}>
            {data.check_in} → {data.check_out}
          </div>
        )}
        {data.num_guests && (
          <div style={{ color: '#6b7280', fontSize: 12, marginTop: 2 }}>
            {data.num_guests} guest{data.num_guests !== 1 ? 's' : ''}
          </div>
        )}
        <div style={{ color: '#92400e', fontSize: 12, marginTop: 6, lineHeight: 1.5 }}>
          Subject to host confirmation and payment. A payment link will follow shortly.
        </div>
      </div>
    );
  }

  function ToolCard({ name, data }) {
    switch (name) {
      case 'list_properties': return <PropertyCard data={data} />;
      case 'get_quote':       return <QuoteCard data={data} />;
      case 'get_payment_link': return <PaymentCard data={data} />;
      case 'create_booking':  return <BookingCard data={data} />;
      default:                return null;
    }
  }

  // ── status badge ──────────────────────────────────────────────────────────────

  const STATUS_LABEL = {
    idle:         'Talk to Tara',
    connecting:   'Connecting…',
    ready:        'Listening…',
    speaking:     'Tara is speaking…',
    turn_complete: 'Your turn',
    error:        'Error',
    stopped:      'Talk to Tara',
    disconnected: 'Disconnected',
  };

  const STATUS_COLOR = {
    idle:         '#6b7280',
    connecting:   '#d97706',
    ready:        '#059669',
    speaking:     '#7c3aed',
    turn_complete: '#059669',
    error:        '#dc2626',
    stopped:      '#6b7280',
    disconnected: '#dc2626',
  };

  // ── pulse animation style ─────────────────────────────────────────────────────

  const pulseKeyframes = `
@keyframes tara-pulse {
  0%   { box-shadow: 0 0 0 0 rgba(5,150,105,0.5); }
  70%  { box-shadow: 0 0 0 10px rgba(5,150,105,0); }
  100% { box-shadow: 0 0 0 0 rgba(5,150,105,0); }
}
@keyframes tara-spin {
  to { transform: rotate(360deg); }
}
`;

  // ── main component ─────────────────────────────────────────────────────────────

  function isValidIndianMobile(val) {
    const digits = val.replace(/\D/g, '');
    // Strip leading 91 or 0 to get the 10-digit number
    const ten = digits.length === 12 && digits.startsWith('91') ? digits.slice(2)
              : digits.length === 11 && digits.startsWith('0') ? digits.slice(1)
              : digits;
    return /^[6-9]\d{9}$/.test(ten);
  }

  function VoiceConciergeDrawer() {
    const [open, setOpen] = useState(false);
    const [status, setStatus] = useState('idle');
    const [transcripts, setTranscripts] = useState([]);
    const [cards, setCards] = useState([]);
    const [errorMsg, setErrorMsg] = useState('');
    const [phone, setPhone] = useState('');
    const [phoneError, setPhoneError] = useState('');
    const [phoneConfirmed, setPhoneConfirmed] = useState(false);
    const unsubRef = useRef(null);
    const feedRef = useRef(null);

    const addTranscript = useCallback((role, text) => {
      setTranscripts((prev) => [...prev, { role, text, id: Date.now() + Math.random() }]);
    }, []);

    const addCard = useCallback((name, data) => {
      setCards((prev) => [...prev, { name, data, id: Date.now() + Math.random() }]);
    }, []);

    useEffect(() => {
      if (!window.__taraAudio) return;
      const unsub = window.__taraAudio.onEvent((e) => {
        switch (e.type) {
          case 'connecting':    setStatus('connecting'); setErrorMsg(''); break;
          case 'ready':         setStatus('ready'); break;
          case 'speaking':      setStatus('speaking'); break;
          case 'turn_complete': setStatus('ready'); break;
          case 'interrupted':   setStatus('ready'); break;
          case 'stopped':       setStatus('idle'); break;
          case 'disconnected':  setStatus('disconnected'); break;
          case 'transcript':    addTranscript(e.role, e.text); break;
          case 'tool_result':   addCard(e.name, e.data); break;
          case 'error':
            setStatus('error');
            setErrorMsg(e.message);
            break;
        }
      });
      unsubRef.current = unsub;
      return () => { if (unsubRef.current) unsubRef.current(); };
    }, [addTranscript, addCard]);

    // Auto-scroll feed
    useEffect(() => {
      if (feedRef.current) feedRef.current.scrollTop = feedRef.current.scrollHeight;
    }, [transcripts, cards]);

    function handleMicClick() {
      if (!window.__taraAudio) return;
      if (window.__taraAudio.isActive()) {
        window.__taraAudio.stop();
      } else {
        setTranscripts([]);
        setCards([]);
        setErrorMsg('');
        setOpen(true);
        // If phone not yet confirmed, show the phone gate (don't start yet)
      }
    }

    function handlePhoneSubmit(e) {
      e.preventDefault();
      if (!isValidIndianMobile(phone)) {
        setPhoneError('Please enter a valid 10-digit Indian mobile number.');
        return;
      }
      setPhoneError('');
      setPhoneConfirmed(true);
      window.__taraAudio && window.__taraAudio.start(phone.replace(/\D/g, '').slice(-10));
    }

    function handleClose() {
      setOpen(false);
      if (window.__taraAudio && window.__taraAudio.isActive()) {
        window.__taraAudio.stop();
      }
    }

    const isActive = ['connecting', 'ready', 'speaking', 'turn_complete'].includes(status);
    const color = STATUS_COLOR[status] ?? '#6b7280';

    return (
      <>
        <style>{pulseKeyframes}</style>

        {/* Floating mic button */}
        <button
          onClick={handleMicClick}
          title="Talk to Tara, our AI concierge"
          style={{
            position: 'fixed',
            bottom: 24,
            right: 24,
            width: 56,
            height: 56,
            borderRadius: '50%',
            background: isActive ? '#059669' : '#1a1a1a',
            border: 'none',
            cursor: 'pointer',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            boxShadow: '0 4px 16px rgba(0,0,0,0.3)',
            zIndex: 9998,
            animation: isActive ? 'tara-pulse 1.5s infinite' : 'none',
            transition: 'background 0.2s',
          }}
          aria-label={isActive ? 'End voice session' : 'Start voice concierge'}
        >
          {isActive ? (
            /* Waveform icon when active */
            <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
              <rect x="1" y="8" width="2" height="6" rx="1" fill="white"/>
              <rect x="5" y="5" width="2" height="12" rx="1" fill="white"/>
              <rect x="9" y="3" width="2" height="16" rx="1" fill="white"/>
              <rect x="13" y="5" width="2" height="12" rx="1" fill="white"/>
              <rect x="17" y="8" width="2" height="6" rx="1" fill="white"/>
            </svg>
          ) : (
            /* Mic icon when idle */
            <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
              <rect x="8" y="2" width="6" height="11" rx="3" fill="white"/>
              <path d="M4 11a7 7 0 0 0 14 0" stroke="white" strokeWidth="1.8" strokeLinecap="round" fill="none"/>
              <line x1="11" y1="18" x2="11" y2="21" stroke="white" strokeWidth="1.8" strokeLinecap="round"/>
              <line x1="8" y1="21" x2="14" y2="21" stroke="white" strokeWidth="1.8" strokeLinecap="round"/>
            </svg>
          )}
        </button>

        {/* Drawer panel */}
        {open && (
          <div style={{
            position: 'fixed',
            bottom: 92,
            right: 16,
            width: 320,
            maxHeight: '70vh',
            background: '#fff',
            borderRadius: 16,
            boxShadow: '0 8px 32px rgba(0,0,0,0.18)',
            display: 'flex',
            flexDirection: 'column',
            zIndex: 9997,
            overflow: 'hidden',
            fontFamily: 'inherit',
          }}>
            {/* Header */}
            <div style={{
              padding: '12px 16px',
              borderBottom: '1px solid #f3f4f6',
              display: 'flex',
              alignItems: 'center',
              gap: 10,
              background: '#fafafa',
            }}>
              <div style={{
                width: 8, height: 8, borderRadius: '50%', background: color,
                flexShrink: 0,
                animation: status === 'connecting' ? 'tara-pulse 1s infinite' : 'none',
              }} />
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: '#1a1a1a' }}>Tara</div>
                <div style={{ fontSize: 11, color: color }}>{STATUS_LABEL[status] ?? status}</div>
              </div>
              <button
                onClick={handleClose}
                style={{
                  background: 'none', border: 'none', cursor: 'pointer',
                  color: '#9ca3af', fontSize: 18, lineHeight: 1, padding: 2,
                }}
                aria-label="Close"
              >×</button>
            </div>

            {/* Feed */}
            <div
              ref={feedRef}
              style={{
                flex: 1,
                overflowY: 'auto',
                padding: 12,
                display: 'flex',
                flexDirection: 'column',
                gap: 8,
              }}
            >
              {/* Phone gate — shown until a valid number is submitted */}
              {!phoneConfirmed && (
                <form onSubmit={handlePhoneSubmit} style={{ padding: '12px 4px' }}>
                  <div style={{ fontSize: 13, color: '#374151', marginBottom: 8, lineHeight: 1.5 }}>
                    To speak with Tara, please enter your Indian mobile number.
                  </div>
                  <input
                    type="tel"
                    placeholder="10-digit mobile number"
                    value={phone}
                    onChange={(e) => { setPhone(e.target.value); setPhoneError(''); }}
                    maxLength={13}
                    style={{
                      width: '100%', boxSizing: 'border-box',
                      padding: '9px 12px', borderRadius: 8, fontSize: 14,
                      border: `1px solid ${phoneError ? '#fca5a5' : '#d1d5db'}`,
                      outline: 'none', marginBottom: 6,
                    }}
                    autoFocus
                  />
                  {phoneError && (
                    <div style={{ color: '#dc2626', fontSize: 12, marginBottom: 6 }}>{phoneError}</div>
                  )}
                  <button
                    type="submit"
                    style={{
                      width: '100%', padding: '9px 0', borderRadius: 8,
                      background: '#059669', color: '#fff', border: 'none',
                      fontSize: 14, fontWeight: 600, cursor: 'pointer',
                    }}
                  >
                    Continue →
                  </button>
                  <div style={{ fontSize: 11, color: '#9ca3af', marginTop: 8, textAlign: 'center' }}>
                    Session limited to 2 minutes · 3 sessions/hour
                  </div>
                </form>
              )}

              {phoneConfirmed && transcripts.length === 0 && cards.length === 0 && (
                <div style={{
                  color: '#9ca3af', fontSize: 13, textAlign: 'center', padding: '24px 0',
                }}>
                  {status === 'connecting'
                    ? 'Connecting to Tara…'
                    : 'Start speaking — Tara is listening.'}
                </div>
              )}

              {/* Interleave transcripts and cards in order */}
              {[...transcripts.map((t) => ({ ...t, _kind: 'transcript' })),
                ...cards.map((c) => ({ ...c, _kind: 'card' }))]
                .sort((a, b) => a.id - b.id)
                .map((item) => item._kind === 'transcript' ? (
                  <div
                    key={item.id}
                    style={{
                      alignSelf: item.role === 'user' ? 'flex-end' : 'flex-start',
                      maxWidth: '85%',
                      background: item.role === 'user' ? '#f3f4f6' : '#ecfdf5',
                      borderRadius: item.role === 'user' ? '12px 12px 2px 12px' : '12px 12px 12px 2px',
                      padding: '8px 12px',
                      fontSize: 13,
                      color: '#1a1a1a',
                      lineHeight: 1.4,
                    }}
                  >
                    {item.text}
                  </div>
                ) : (
                  <div key={item.id}>
                    <ToolCard name={item.name} data={item.data} />
                  </div>
                ))
              }

              {errorMsg && (
                <div style={{
                  background: '#fef2f2', border: '1px solid #fca5a5',
                  borderRadius: 8, padding: '8px 12px', color: '#dc2626', fontSize: 12,
                }}>
                  {errorMsg}
                </div>
              )}
            </div>

            {/* Footer */}
            <div style={{
              padding: '8px 12px',
              borderTop: '1px solid #f3f4f6',
              fontSize: 11,
              color: '#9ca3af',
              textAlign: 'center',
            }}>
              AI concierge · May make mistakes · Confirm before booking
            </div>
          </div>
        )}
      </>
    );
  }

  // ── mount ──────────────────────────────────────────────────────────────────────

  function mount() {
    const root = document.getElementById('tara-voice-root');
    if (!root) return;
    const reactRoot = ReactDOM.createRoot(root);
    reactRoot.render(React.createElement(VoiceConciergeDrawer));
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', mount);
  } else {
    mount();
  }
})();
