// Saraya Events — Saraya Assistant chatbot widget

const { useState: useStateCB, useEffect: useEffectCB } = React;

/* ---- Menu options ---- */
const CUSTOMER_OPTIONS = [
  { id: 'event_planning', icon: 'calendar-heart',  en: 'I need event planning help',           ar: 'أحتاج مساعدة في تخطيط فعالية',      leadType: 'customer_quote' },
  { id: 'rental',         icon: 'armchair',         en: 'Rent furniture or equipment',           ar: 'استئجار أثاث أو معدات',              leadType: 'rental_inquiry' },
  { id: 'service',        icon: 'briefcase',         en: 'Book a service',                        ar: 'حجز خدمة',                           leadType: 'service_booking' },
  { id: 'flowers',        icon: 'flower-2',          en: 'Flowers, gifts, or décor',              ar: 'زهور وهدايا وديكور',                 leadType: 'customer_quote' },
  { id: 'quote',          icon: 'file-text',         en: 'Request a quote',                       ar: 'طلب عرض سعر',                        leadType: 'customer_quote' },
  { id: 'track',          icon: 'package-search',    en: 'Track an order',                        ar: 'تتبع طلب',                           leadType: 'support' },
  { id: 'complaint',      icon: 'alert-circle',      en: 'I have a complaint',                    ar: 'لديّ شكوى',                          leadType: 'complaint' },
];

const VENDOR_OPTIONS = [
  { id: 'join',           icon: 'store',             en: 'Join as a vendor',                      ar: 'الانضمام كمورد',                     leadType: 'vendor_application' },
  { id: 'packages',       icon: 'credit-card',       en: 'See vendor packages',                   ar: 'عرض باقات الموردين',                 leadType: 'vendor_application' },
  { id: 'list_rental',    icon: 'archive',           en: 'List rental items',                     ar: 'إدراج قطع للإيجار',                  leadType: 'vendor_application' },
  { id: 'list_service',   icon: 'settings-2',        en: 'List services',                         ar: 'إدراج خدمات',                        leadType: 'vendor_application' },
  { id: 'vendor_support', icon: 'headset',           en: 'Vendor support',                        ar: 'دعم الموردين',                       leadType: 'support' },
];

/* ---- Quick navigation actions ---- */
const QUICK_ROUTES = {
  track:         'store',
  packages:      'vendor-packages',
  join:          'partner',
  complaint:     'complaints',
  list_rental:   'partner',
  list_service:  'partner',
};

/* ====================================================================
   SARAYA ASSISTANT — floating chatbot
   Position: bottom-left (opposite of WhatsApp button on bottom-right)
   ==================================================================== */
function SarayaAssistant() {
  const { lang } = useLang();
  const { go } = useNav();
  const ar = lang === 'ar';

  const [open, setOpen]           = useStateCB(false);
  const [step, setStep]           = useStateCB('welcome');  // welcome | options | form | done
  const [mode, setMode]           = useStateCB(null);       // 'customer' | 'vendor'
  const [selected, setSelected]   = useStateCB(null);       // selected option object

  const reset = () => { setStep('welcome'); setMode(null); setSelected(null); };

  const openChat = () => {
    setOpen(true);
    window.sarayaTrack('chatbot_open', { lang });
  };

  const closeChat = () => { setOpen(false); reset(); };

  const selectMode = (m) => {
    setMode(m);
    setStep('options');
    window.sarayaTrack('chatbot_mode_select', { mode: m });
  };

  const selectOption = (opt) => {
    setSelected(opt);
    // For quick routes, navigate directly and skip form
    if (QUICK_ROUTES[opt.id]) {
      window.sarayaTrack('chatbot_quick_nav', { option: opt.id });
      go(QUICK_ROUTES[opt.id]);
      closeChat();
      return;
    }
    setStep('form');
    window.sarayaTrack('chatbot_option_select', { option: opt.id, lead_type: opt.leadType });
  };

  const options = mode === 'vendor' ? VENDOR_OPTIONS : CUSTOMER_OPTIONS;

  /* ---- Panel position: bottom-left in LTR, stays left physically ---- */
  const triggerStyle = {
    position: 'fixed',
    left: 18,
    bottom: 18,
    zIndex: 80,
  };

  const panelStyle = {
    position: 'fixed',
    left: 18,
    bottom: 88,
    zIndex: 80,
    width: 'min(356px, calc(100vw - 36px))',
    maxHeight: 'calc(100vh - 120px)',
    background: 'var(--white)',
    borderRadius: 20,
    boxShadow: '0 12px 48px rgba(42,31,26,0.22)',
    border: '1px solid var(--line)',
    display: 'flex',
    flexDirection: 'column',
    overflow: 'hidden',
    animation: 'sarayaPop 280ms var(--ease-out)',
  };

  return (
    <>
      {/* Panel */}
      {open && (
        <div style={panelStyle} dir={ar ? 'rtl' : 'ltr'}>

          {/* Header */}
          <div style={{ background: 'var(--espresso)', padding: '16px 18px', display: 'flex', alignItems: 'center', gap: 12, flexShrink: 0 }}>
            <div style={{ width: 38, height: 38, borderRadius: '50%', background: 'var(--gold)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <Icon name="sparkles" size={18} style={{ color: 'var(--espresso)' }} />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: 'var(--font-serif)', fontSize: 15, fontWeight: 600, color: 'var(--ivory)' }}>
                {ar ? 'مساعد سرايا' : 'Saraya Assistant'}
              </div>
              <div style={{ fontSize: 11.5, color: 'rgba(250,246,240,0.65)', marginTop: 1 }}>
                {ar ? 'عادةً يرد خلال دقائق' : 'Usually replies within minutes'}
              </div>
            </div>
            <button onClick={closeChat} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'rgba(250,246,240,0.7)', padding: 4, display: 'flex' }}>
              <Icon name="x" size={20} />
            </button>
          </div>

          {/* Body */}
          <div style={{ flex: 1, overflowY: 'auto', padding: '18px 16px', display: 'flex', flexDirection: 'column', gap: 14 }}>

            {/* Welcome bubble */}
            <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
              <div style={{ width: 30, height: 30, borderRadius: '50%', background: 'var(--cream)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, marginTop: 2 }}>
                <Icon name="sparkles" size={14} style={{ color: 'var(--gold-deep)' }} />
              </div>
              <div style={{ background: 'var(--cream)', borderRadius: '0 14px 14px 14px', padding: '12px 14px', maxWidth: '85%' }}>
                <p style={{ fontSize: 14, lineHeight: 1.6, margin: 0, color: 'var(--fg-primary)' }}>
                  {ar
                    ? 'مرحباً بك في سرايا للفعاليات. كيف يمكننا مساعدتك؟'
                    : 'Welcome to Saraya Events. How can we help you today?'}
                </p>
              </div>
            </div>

            {/* WELCOME STEP — mode selector */}
            {step === 'welcome' && (
              <div style={{ display: 'grid', gap: 10, marginTop: 4 }}>
                <button onClick={() => selectMode('customer')} style={optBtnStyle('#FAF6F0', 'var(--espresso)')}>
                  <Icon name="user" size={18} style={{ color: 'var(--gold-deep)' }} />
                  <div style={{ textAlign: 'start' }}>
                    <div style={{ fontWeight: 600, fontSize: 14 }}>{ar ? 'أنا عميل' : "I'm a Customer"}</div>
                    <div style={{ fontSize: 12, color: 'var(--fg-secondary)', marginTop: 2 }}>{ar ? 'تخطيط، حجز، استفسار' : 'Planning, booking, inquiries'}</div>
                  </div>
                  <Icon name="chevron-right" size={16} style={{ color: 'var(--fg-muted)', marginInlineStart: 'auto', flexShrink: 0 }} />
                </button>
                <button onClick={() => selectMode('vendor')} style={optBtnStyle('#FAF6F0', 'var(--espresso)')}>
                  <Icon name="store" size={18} style={{ color: 'var(--gold-deep)' }} />
                  <div style={{ textAlign: 'start' }}>
                    <div style={{ fontWeight: 600, fontSize: 14 }}>{ar ? 'أنا مورد / شريك' : "I'm a Vendor / Supplier"}</div>
                    <div style={{ fontSize: 12, color: 'var(--fg-secondary)', marginTop: 2 }}>{ar ? 'انضمام، قوائم، دعم' : 'Joining, listings, support'}</div>
                  </div>
                  <Icon name="chevron-right" size={16} style={{ color: 'var(--fg-muted)', marginInlineStart: 'auto', flexShrink: 0 }} />
                </button>
              </div>
            )}

            {/* OPTIONS STEP */}
            {step === 'options' && (
              <div style={{ display: 'grid', gap: 8 }}>
                <p style={{ fontSize: 13, color: 'var(--fg-secondary)', margin: 0 }}>
                  {ar ? 'اختر ما يناسبك:' : 'What can we help you with?'}
                </p>
                {options.map((opt) => (
                  <button key={opt.id} onClick={() => selectOption(opt)} style={optBtnStyle('var(--white)', 'var(--fg-primary)')}>
                    <Icon name={opt.icon} size={16} style={{ color: 'var(--gold-deep)', flexShrink: 0 }} />
                    <span style={{ fontSize: 13.5, fontWeight: 500 }}>{ar ? opt.ar : opt.en}</span>
                    <Icon name="chevron-right" size={14} style={{ color: 'var(--fg-muted)', marginInlineStart: 'auto', flexShrink: 0 }} />
                  </button>
                ))}
                <button onClick={reset} style={{ fontSize: 12.5, color: 'var(--fg-muted)', background: 'none', border: 'none', cursor: 'pointer', textAlign: 'start', padding: '6px 0', textDecoration: 'underline' }}>
                  {ar ? 'رجوع' : 'Back'}
                </button>
              </div>
            )}

            {/* FORM STEP */}
            {step === 'form' && selected && (
              <div>
                <div style={{ background: 'var(--cream)', borderRadius: 10, padding: '10px 14px', marginBottom: 14, display: 'flex', gap: 8, alignItems: 'center' }}>
                  <Icon name={selected.icon} size={16} style={{ color: 'var(--gold-deep)', flexShrink: 0 }} />
                  <span style={{ fontSize: 13.5, fontWeight: 500 }}>{ar ? selected.ar : selected.en}</span>
                </div>
                <LeadCapture
                  leadType={selected.leadType}
                  source="chatbot"
                  campaign={selected.id}
                  compact
                  ar={ar}
                  onDone={() => setStep('done')}
                />
                <button onClick={() => setStep('options')} style={{ fontSize: 12.5, color: 'var(--fg-muted)', background: 'none', border: 'none', cursor: 'pointer', textDecoration: 'underline', padding: '8px 0 0', display: 'block' }}>
                  {ar ? 'رجوع' : 'Back'}
                </button>
              </div>
            )}

            {/* DONE STEP */}
            {step === 'done' && (
              <div style={{ textAlign: 'center', padding: '8px 0 16px' }}>
                <span style={{ display: 'inline-flex', width: 48, height: 48, borderRadius: '50%', background: '#DCFCE7', alignItems: 'center', justifyContent: 'center', marginBottom: 12 }}>
                  <Icon name="check-circle-2" size={24} style={{ color: '#16A34A' }} />
                </span>
                <p style={{ fontSize: 14, fontWeight: 600, margin: '0 0 6px' }}>
                  {ar ? 'تم استلام طلبك!' : 'Request received!'}
                </p>
                <p style={{ fontSize: 13, color: 'var(--fg-secondary)', lineHeight: 1.55, margin: '0 0 16px' }}>
                  {ar ? 'سيتواصل معك فريق سرايا قريبًا.' : 'The Saraya team will contact you shortly.'}
                </p>
                <div style={{ display: 'grid', gap: 8 }}>
                  <a href={window.SARAYA.waLink(ar ? "مرحبًا سرايا، لقد أرسلت طلبًا وأودّ المتابعة." : "Hello Saraya Events, I submitted a request and would like to follow up.")}
                    target="_blank" rel="noopener noreferrer"
                    onClick={() => window.sarayaTrack('whatsapp_click', { source: 'chatbot_done' })}
                    style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, padding: '10px', borderRadius: 9, background: '#25D366', color: 'white', fontWeight: 600, fontSize: 13.5, textDecoration: 'none' }}>
                    <Icon name="message-circle" size={15} />
                    {ar ? 'تابع عبر واتساب' : 'Continue on WhatsApp'}
                  </a>
                  <button onClick={reset} style={{ padding: '9px', borderRadius: 9, border: '1.5px solid var(--line)', background: 'var(--white)', fontFamily: 'var(--font-body)', fontSize: 13.5, cursor: 'pointer', color: 'var(--fg-primary)' }}>
                    {ar ? 'طلب آخر' : 'Submit Another'}
                  </button>
                </div>
              </div>
            )}
          </div>

          {/* Footer */}
          <div style={{ borderTop: '1px solid var(--line)', padding: '10px 16px', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <span style={{ fontSize: 11, color: 'var(--fg-muted)' }}>
              {ar ? 'سرايا للفعاليات · أبوظبي' : 'Saraya Events · Abu Dhabi'}
            </span>
          </div>
        </div>
      )}

      {/* Trigger button */}
      <div style={triggerStyle}>
        <button
          onClick={open ? closeChat : openChat}
          aria-label={ar ? 'مساعد سرايا' : 'Saraya Assistant'}
          style={{
            width: 56, height: 56, borderRadius: 999, border: 'none', cursor: 'pointer',
            background: open ? 'var(--fg-secondary)' : 'var(--espresso)',
            color: 'var(--ivory)',
            boxShadow: '0 6px 20px rgba(42,31,26,0.30)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            transition: 'transform 220ms var(--ease-out), background 200ms',
            transform: open ? 'rotate(90deg)' : 'none',
          }}>
          <Icon name={open ? 'x' : 'message-square'} size={24} stroke={2} />
        </button>
        {!open && (
          <span style={{
            position: 'absolute', top: -6, insetInlineEnd: -6, width: 18, height: 18,
            borderRadius: '50%', background: 'var(--gold)', border: '2px solid var(--white)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 10, fontWeight: 700, color: 'var(--espresso)',
          }}>!</span>
        )}
      </div>
    </>
  );
}

/* Shared option button style */
function optBtnStyle(bg, color) {
  return {
    display: 'flex', alignItems: 'center', gap: 10, width: '100%', padding: '11px 13px',
    borderRadius: 10, border: '1.5px solid var(--line)', background: bg, color: color,
    cursor: 'pointer', fontFamily: 'var(--font-body)', textAlign: 'start',
    transition: 'border-color 150ms', boxSizing: 'border-box',
  };
}

window.SarayaAssistant = SarayaAssistant;
