// ============================================================
// Saraya Events — Vendor Support Meeting requests
//
// Vendor-facing: VendorMeetingSection (dashboard Support/Help) with an INLINE
// request form (no popup). Admin-facing: AdminMeetingRequests (view + manage).
//
// Backend: Supabase table public.vendor_meeting_requests + edge function
// `vendor-meeting` (validates the UAE window, stores the request, generates an
// iCalendar .ics invite for sales@sarayaevents.com, and sends bilingual emails).
//
// Booking window: Sunday–Thursday, 1:00–4:00 PM UAE time (Asia/Dubai) only.
// Everything reads/writes through window.SarayaDB (RLS: vendor sees own,
// admin sees all).
// ============================================================

const { useState: useStateVM, useEffect: useEffectVM } = React;

window.MEETING_REASONS = [
  { key: 'onboarding',      en: 'Onboarding support',       ar: 'دعم الإعداد والانضمام' },
  { key: 'listing_setup',   en: 'Listing setup help',       ar: 'مساعدة في إعداد القوائم' },
  { key: 'store_profile',   en: 'Store profile help',       ar: 'مساعدة في ملف المتجر' },
  { key: 'subscription',    en: 'Subscription questions',   ar: 'أسئلة عن الاشتراك' },
  { key: 'payment_banking', en: 'Payment or banking support', ar: 'دعم الدفع والحسابات البنكية' },
  { key: 'general',         en: 'General vendor support',   ar: 'دعم عام للموردين' },
];
window.MEETING_TYPES = [
  { key: 'teams', en: 'Microsoft Teams', ar: 'مايكروسوفت تيمز', icon: 'video',   note: { en: 'A Teams link will be shared on confirmation.', ar: 'سيتم مشاركة رابط تيمز عند التأكيد.' } },
  { key: 'zoom',  en: 'Zoom meeting',    ar: 'اجتماع زوم',      icon: 'monitor', note: { en: 'A Zoom link will be shared on confirmation.', ar: 'سيتم مشاركة رابط زوم عند التأكيد.' } },
  { key: 'phone', en: 'Phone call',      ar: 'مكالمة هاتفية',   icon: 'phone',   note: { en: 'Our team will call the number below.', ar: 'سيتصل فريقنا على الرقم أدناه.' } },
];
window.MEETING_STATUS = {
  pending:   { en: 'Pending',   ar: 'قيد الانتظار', color: '#B45309', bg: '#FEF3C7' },
  confirmed: { en: 'Confirmed', ar: 'مؤكد',         color: '#047857', bg: '#D1FAE5' },
  completed: { en: 'Completed', ar: 'مكتمل',        color: '#1D4ED8', bg: '#DBEAFE' },
  cancelled: { en: 'Cancelled', ar: 'ملغى',         color: '#B91C1C', bg: '#FEE2E2' },
};

function vmFmtSlot(iso, ar) {
  try {
    return new Intl.DateTimeFormat(ar ? 'ar-AE' : 'en-GB', { timeZone: 'Asia/Dubai', weekday: 'short', day: 'numeric', month: 'short', hour: 'numeric', minute: '2-digit', hour12: true }).format(new Date(iso));
  } catch (e) { return iso; }
}
function vmLabel(list, key, ar) { const it = list.find((x) => x.key === key); return it ? (ar ? it.ar : it.en) : key; }

// Generate bookable slots: Sun–Thu, 13:00–15:30 UAE (last meeting ends 16:00),
// on the half hour, for the next `daysAhead` days. Times use the fixed +04:00
// UAE offset so the user's own timezone can never shift them.
window.buildMeetingSlots = function (daysAhead) {
  daysAhead = daysAhead || 21;
  const out = [];
  const now = new Date();
  const times = ['13:00', '13:30', '14:00', '14:30', '15:00', '15:30'];
  for (let i = 0; i < daysAhead; i++) {
    const d = new Date(now.getTime() + i * 86400000);
    const parts = Object.fromEntries(new Intl.DateTimeFormat('en-GB', { timeZone: 'Asia/Dubai', weekday: 'short', year: 'numeric', month: '2-digit', day: '2-digit' }).formatToParts(d).map((p) => [p.type, p.value]));
    if (parts.weekday === 'Fri' || parts.weekday === 'Sat') continue;
    const daySlots = [];
    for (const t of times) {
      const iso = parts.year + '-' + parts.month + '-' + parts.day + 'T' + t + ':00+04:00';
      const dt = new Date(iso);
      if (dt.getTime() < now.getTime() + 30 * 60000) continue;
      const hh = parseInt(t.slice(0, 2), 10), mn = t.slice(3);
      const h12 = ((hh + 11) % 12) + 1;
      daySlots.push({ iso, timeLabel: h12 + ':' + mn + ' ' + (hh >= 12 ? 'PM' : 'AM') });
    }
    if (daySlots.length) {
      out.push({
        key: parts.year + '-' + parts.month + '-' + parts.day,
        dateLabelEn: new Intl.DateTimeFormat('en-GB', { timeZone: 'Asia/Dubai', weekday: 'short', day: 'numeric', month: 'short' }).format(d),
        dateLabelAr: new Intl.DateTimeFormat('ar-AE', { timeZone: 'Asia/Dubai', weekday: 'short', day: 'numeric', month: 'short' }).format(d),
        slots: daySlots,
      });
    }
  }
  return out;
};

async function vmCall(payload) {
  const supaUrl = (window.SARAYA_SUPABASE_URL || '').replace(/\/$/, '');
  const anon = window.SARAYA_SUPABASE_ANON_KEY || '';
  let token = anon;
  try { const { data } = await window.SarayaDB.auth.getSession(); if (data && data.session && data.session.access_token) token = data.session.access_token; } catch (e) {}
  const resp = await fetch(supaUrl + '/functions/v1/vendor-meeting', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'apikey': anon, 'Authorization': 'Bearer ' + token },
    body: JSON.stringify(payload),
  });
  const data = await resp.json().catch(() => ({}));
  if (!resp.ok) throw new Error(data.error || ('Request failed (' + resp.status + ')'));
  return data;
}
window.vmCall = vmCall;

function vmFieldLabel(text) {
  return <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--fg-secondary)', display: 'block', marginBottom: 7 }}>{text}</span>;
}
const vmInputStyle = { boxSizing: 'border-box', width: '100%', maxWidth: '100%' };

// ---------------- Vendor: INLINE request form ----------------
function VendorMeetingForm({ ar, prefill, presetReason, onDone, onCancel }) {
  prefill = prefill || {};
  const [reason, setReason] = useStateVM(presetReason || '');
  const [mtype, setMtype] = useStateVM('');
  const [dayKey, setDayKey] = useStateVM('');
  const [slotIso, setSlotIso] = useStateVM('');
  const [name, setName] = useStateVM(prefill.name || '');
  const [company, setCompany] = useStateVM(prefill.company || '');
  const [email, setEmail] = useStateVM(prefill.email || '');
  const [phone, setPhone] = useStateVM(prefill.phone || '');
  const [busy, setBusy] = useStateVM(false);
  const [error, setError] = useStateVM('');
  const [done, setDone] = useStateVM(false);

  const days = window.buildMeetingSlots(21);
  const day = days.find((d) => d.key === dayKey);
  const gold = 'var(--gold)', line = 'var(--line)';
  const canSubmit = reason && mtype && slotIso && name.trim() && email.trim() && (mtype !== 'phone' || phone.trim());

  const submit = async () => {
    if (!canSubmit || busy) return;
    setBusy(true); setError('');
    try {
      await vmCall({ action: 'request', reason, meeting_type: mtype, slot_start: slotIso, lang: ar ? 'ar' : 'en', name: name.trim(), company: company.trim(), email: email.trim(), phone: phone.trim() });
      setDone(true);
      if (onDone) onDone();
    } catch (e) {
      const map = { slot_outside_window: ar ? 'الموعد خارج ساعات العمل (الأحد–الخميس ١–٤ مساءً بتوقيت الإمارات).' : 'That time is outside our support hours (Sun–Thu, 1–4 PM UAE).', slot_in_past: ar ? 'يرجى اختيار موعد مستقبلي.' : 'Please choose a future time.' };
      setError(map[e.message] || e.message || (ar ? 'تعذر إرسال الطلب.' : 'Could not submit the request.'));
    } finally { setBusy(false); }
  };

  const chip = (active) => ({ padding: '9px 14px', borderRadius: 10, border: '1.5px solid ' + (active ? gold : line), background: active ? 'rgba(201,169,97,0.10)' : 'var(--white)', color: 'var(--fg-primary)', fontFamily: 'var(--font-body)', fontSize: 13.5, fontWeight: active ? 700 : 500, cursor: 'pointer', whiteSpace: 'nowrap' });
  const card = { background: 'var(--white)', border: '1px solid ' + line, borderRadius: 14, overflow: 'hidden', width: '100%' };

  if (done) {
    return (
      <div style={card} dir={ar ? 'rtl' : 'ltr'}>
        <div style={{ padding: '34px 24px', textAlign: 'center' }}>
          <span style={{ display: 'inline-flex', width: 56, height: 56, borderRadius: '50%', background: '#D1FAE5', alignItems: 'center', justifyContent: 'center', marginBottom: 14 }}><Icon name="check" size={28} style={{ color: '#047857' }} /></span>
          <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 21, fontWeight: 500, margin: '0 0 8px' }}>{ar ? 'تم إرسال طلبك' : 'Request submitted'}</h3>
          <p style={{ fontSize: 14, color: 'var(--fg-secondary)', lineHeight: 1.6, margin: '0 auto', maxWidth: 420 }}>
            {ar ? 'أرسلنا لك رسالة تأكيد مع دعوة تقويم. سيؤكد فريق سرايا الموعد قريبًا.' : 'We’ve emailed you a confirmation with a calendar invite. The Saraya team will confirm your slot shortly.'}
          </p>
          <div style={{ marginTop: 20 }}><Button variant="primary" onClick={() => { if (onCancel) onCancel(); }}>{ar ? 'تم' : 'Done'}</Button></div>
        </div>
      </div>
    );
  }

  return (
    <div style={card} dir={ar ? 'rtl' : 'ltr'}>
      <div style={{ background: 'var(--espresso)', color: 'var(--ivory)', padding: '15px 20px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <Icon name="headset" size={19} style={{ color: gold }} />
          <span style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 500 }}>{ar ? 'طلب اجتماع دعم' : 'Request a Support Meeting'}</span>
        </div>
        {onCancel && <button onClick={onCancel} aria-label="Close" style={{ background: 'none', border: 'none', color: 'var(--ivory)', cursor: 'pointer', padding: 4 }}><Icon name="x" size={19} /></button>}
      </div>

      <div style={{ padding: '20px 22px 24px', display: 'grid', gap: 18, gridTemplateColumns: 'minmax(0, 1fr)' }}>
        <p style={{ fontSize: 13, color: 'var(--fg-secondary)', margin: 0, display: 'flex', alignItems: 'center', gap: 7 }}>
          <Icon name="clock" size={14} style={{ color: 'var(--gold-deep)' }} />
          {ar ? 'مواعيد الدعم: الأحد إلى الخميس، ١:٠٠–٤:٠٠ مساءً بتوقيت الإمارات.' : 'Support hours: Sunday to Thursday, 1:00–4:00 PM UAE time.'}
        </p>

        <div>
          {vmFieldLabel(ar ? '١. سبب الاجتماع' : '1. Meeting purpose')}
          <Select value={reason} onChange={(e) => setReason(e.target.value)} style={vmInputStyle}>
            <option value="">{ar ? 'اختر سببًا…' : 'Choose a reason…'}</option>
            {window.MEETING_REASONS.map((r) => <option key={r.key} value={r.key}>{ar ? r.ar : r.en}</option>)}
          </Select>
        </div>

        <div>
          {vmFieldLabel(ar ? '٢. نوع الاجتماع' : '2. Meeting type')}
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {window.MEETING_TYPES.map((t) => (
              <button key={t.key} onClick={() => setMtype(t.key)} style={{ ...chip(mtype === t.key), display: 'inline-flex', alignItems: 'center', gap: 7 }}>
                <Icon name={t.icon} size={15} />{ar ? t.ar : t.en}
              </button>
            ))}
          </div>
          {mtype && <p style={{ fontSize: 12, color: 'var(--fg-muted)', margin: '7px 2px 0' }}>{ar ? window.MEETING_TYPES.find((t) => t.key === mtype).note.ar : window.MEETING_TYPES.find((t) => t.key === mtype).note.en}</p>}
        </div>

        <div>
          {vmFieldLabel(ar ? '٣. اختر اليوم' : '3. Pick a day')}
          <div style={{ display: 'flex', gap: 8, overflowX: 'auto', paddingBottom: 4 }}>
            {days.length === 0 && <span style={{ fontSize: 13, color: 'var(--fg-muted)' }}>{ar ? 'لا توجد مواعيد متاحة حاليًا.' : 'No slots available right now.'}</span>}
            {days.map((d) => (
              <button key={d.key} onClick={() => { setDayKey(d.key); setSlotIso(''); }} style={{ ...chip(dayKey === d.key), flexShrink: 0 }}>{ar ? d.dateLabelAr : d.dateLabelEn}</button>
            ))}
          </div>
        </div>

        {day && (
          <div>
            {vmFieldLabel(ar ? '٤. اختر الوقت (بتوقيت الإمارات)' : '4. Pick a time (UAE)')}
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              {day.slots.map((s) => (
                <button key={s.iso} onClick={() => setSlotIso(s.iso)} style={chip(slotIso === s.iso)}>{s.timeLabel}</button>
              ))}
            </div>
          </div>
        )}

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(min(100%, 340px), 1fr))', gap: 14, minWidth: 0 }}>
          <div style={{ minWidth: 0 }}>{vmFieldLabel(ar ? 'الاسم' : 'Your name')}<TextInput value={name} onChange={(e) => setName(e.target.value)} style={vmInputStyle} /></div>
          <div style={{ minWidth: 0 }}>{vmFieldLabel(ar ? 'اسم الشركة' : 'Company name')}<TextInput value={company} onChange={(e) => setCompany(e.target.value)} style={vmInputStyle} /></div>
          <div style={{ minWidth: 0 }}>{vmFieldLabel(ar ? 'البريد الإلكتروني' : 'Email')}<TextInput type="email" value={email} onChange={(e) => setEmail(e.target.value)} style={vmInputStyle} /></div>
          <div style={{ minWidth: 0 }}>{vmFieldLabel(ar ? 'رقم الهاتف' : 'Phone number')}<TextInput value={phone} onChange={(e) => setPhone(e.target.value)} dir="ltr" style={vmInputStyle} /></div>
        </div>

        {error && <div style={{ padding: '10px 14px', borderRadius: 9, background: '#FEF2F2', border: '1px solid #FCA5A5', color: '#B91C1C', fontSize: 13 }}>{error}</div>}

        {slotIso && (
          <div style={{ padding: '10px 14px', borderRadius: 9, background: 'var(--cream)', border: '1px solid ' + line, fontSize: 13, color: 'var(--fg-primary)' }}>
            <Icon name="calendar" size={14} style={{ color: 'var(--gold-deep)', verticalAlign: 'middle', marginInlineEnd: 6 }} />
            {vmFmtSlot(slotIso, ar)} · {vmLabel(window.MEETING_TYPES, mtype, ar) || ''}
          </div>
        )}

        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
          <Button variant="primary" disabled={!canSubmit || busy} onClick={submit}>
            {busy ? (ar ? 'جارٍ الإرسال…' : 'Submitting…') : (ar ? 'إرسال طلب الاجتماع' : 'Request Meeting')}
          </Button>
          {onCancel && <Button variant="secondary" onClick={onCancel}>{ar ? 'إلغاء' : 'Cancel'}</Button>}
        </div>
      </div>
    </div>
  );
}
window.VendorMeetingForm = VendorMeetingForm;

// ---------------- Vendor: dashboard Support section ----------------
function VendorMeetingSection({ ar, presetReason }) {
  const auth = window.useAuth ? window.useAuth() : {};
  const user = auth.user, profile = auth.profile || {};
  const [vp, setVp] = useStateVM(null);
  const [rows, setRows] = useStateVM(null);
  const [showForm, setShowForm] = useStateVM(false);
  const formRef = React.useRef(null);

  const load = async () => {
    if (!user) return;
    try {
      const { data } = await window.SarayaDB.from('vendor_meeting_requests').select('*').eq('vendor_id', user.id).order('slot_start', { ascending: false });
      setRows(data || []);
    } catch (e) { setRows([]); }
  };
  useEffectVM(() => {
    if (!user) return;
    window.SarayaDB.from('vendor_profiles').select('trade_name, whatsapp').eq('id', user.id).maybeSingle().then(({ data }) => setVp(data || {}));
    load();
  }, [user && user.id]);

  const openForm = () => { setShowForm(true); setTimeout(() => { try { formRef.current && formRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' }); } catch (e) {} }, 60); };

  const prefill = { name: profile.full_name || profile.display_name || '', company: (vp && vp.trade_name) || '', email: profile.email || (user && user.email) || '', phone: profile.phone || (vp && vp.whatsapp) || '' };
  const line = 'var(--line)';

  return (
    <div style={{ display: 'grid', gap: 20 }}>
      <div style={{ background: 'linear-gradient(135deg, var(--espresso) 0%, #3d2b1f 100%)', color: 'var(--ivory)', borderRadius: 16, padding: 'clamp(22px,3vw,30px)' }}>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 20, alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ maxWidth: 460 }}>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, background: 'rgba(201,169,97,0.18)', color: 'var(--gold-light)', padding: '4px 12px', borderRadius: 999, fontSize: 12, fontWeight: 700, marginBottom: 12 }}>
              <Icon name="headset" size={14} />{ar ? 'الدعم والمساعدة' : 'Support & Help'}
            </div>
            <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 'clamp(20px,3vw,26px)', fontWeight: 500, margin: '0 0 8px' }}>{ar ? 'هل تحتاج مساعدة؟ احجز اجتماعًا مع فريقنا' : 'Need help? Book a meeting with our team'}</h2>
            <p style={{ fontSize: 14, color: 'rgba(250,246,240,0.78)', lineHeight: 1.6, margin: 0 }}>
              {ar ? 'احجز مكالمة قصيرة للإعداد، أو إعداد القوائم، أو الاشتراك، أو الدفع، أو أي دعم عام. المواعيد المتاحة: الأحد–الخميس ١–٤ مساءً بتوقيت الإمارات.' : 'Book a short call for onboarding, listing setup, subscription, payment, or general help. Available Sun–Thu, 1–4 PM UAE time.'}
            </p>
          </div>
          {!showForm && (
            <button onClick={openForm} style={{ display: 'inline-flex', alignItems: 'center', gap: 9, padding: '13px 24px', borderRadius: 10, background: 'var(--gold)', color: 'var(--espresso)', fontFamily: 'var(--font-body)', fontSize: 15, fontWeight: 700, border: 'none', cursor: 'pointer', whiteSpace: 'nowrap' }}>
              <Icon name="calendar-plus" size={17} />{ar ? 'طلب اجتماع دعم' : 'Request Support Meeting'}
            </button>
          )}
        </div>
      </div>

      <div ref={formRef} />
      {showForm && <VendorMeetingForm ar={ar} prefill={prefill} presetReason={presetReason} onDone={load} onCancel={() => setShowForm(false)} />}

      <div style={{ background: 'var(--white)', border: '1px solid ' + line, borderRadius: 14, padding: '18px 20px' }}>
        <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 600, margin: '0 0 4px' }}>{ar ? 'اجتماعاتك' : 'Your meetings'}</h3>
        <p style={{ fontSize: 13, color: 'var(--fg-muted)', margin: '0 0 14px' }}>{ar ? 'طلبات الاجتماعات وحالتها.' : 'Your meeting requests and their status.'}</p>
        {rows === null ? (
          <p style={{ fontSize: 13, color: 'var(--fg-muted)' }}>{ar ? 'جارٍ التحميل…' : 'Loading…'}</p>
        ) : rows.length === 0 ? (
          <div style={{ textAlign: 'center', color: 'var(--fg-muted)', padding: '18px 0' }}>
            <Icon name="calendar" size={30} stroke={1} />
            <p style={{ fontSize: 13.5, marginTop: 8 }}>{ar ? 'لا توجد اجتماعات بعد. اطلب اجتماعًا أعلاه.' : 'No meetings yet. Request one above.'}</p>
          </div>
        ) : (
          <div style={{ display: 'grid', gap: 10 }}>
            {rows.map((r) => {
              const st = window.MEETING_STATUS[r.status] || window.MEETING_STATUS.pending;
              return (
                <div key={r.id} style={{ display: 'flex', flexWrap: 'wrap', gap: 10, alignItems: 'center', justifyContent: 'space-between', border: '1px solid ' + line, borderRadius: 11, padding: '12px 14px' }}>
                  <div>
                    <div style={{ fontSize: 14, fontWeight: 600 }}>{vmLabel(window.MEETING_REASONS, r.reason, ar)}</div>
                    <div style={{ fontSize: 12.5, color: 'var(--fg-secondary)', marginTop: 3 }}>
                      <Icon name="calendar" size={12} style={{ verticalAlign: 'middle', marginInlineEnd: 5, color: 'var(--gold-deep)' }} />
                      {vmFmtSlot(r.slot_start, ar)} · {vmLabel(window.MEETING_TYPES, r.meeting_type, ar)}
                    </div>
                  </div>
                  <span style={{ fontSize: 12, fontWeight: 700, color: st.color, background: st.bg, padding: '4px 12px', borderRadius: 999 }}>{ar ? st.ar : st.en}</span>
                </div>
              );
            })}
          </div>
        )}
        <p style={{ fontSize: 12, color: 'var(--fg-muted)', marginTop: 14, lineHeight: 1.6 }}>
          {ar ? 'للمساعدة العاجلة، راسلنا على ' : 'For urgent help, email '}<a href="mailto:sales@sarayaevents.com" style={{ color: 'var(--gold-deep)' }}>sales@sarayaevents.com</a>.
        </p>
      </div>
    </div>
  );
}
window.VendorMeetingSection = VendorMeetingSection;

// ---------------- Admin: meeting requests manager ----------------
function AdminMeetingRequests({ ar }) {
  const [rows, setRows] = useStateVM(null);
  const [filter, setFilter] = useStateVM('all');
  const [busyId, setBusyId] = useStateVM('');
  const [notesById, setNotesById] = useStateVM({});
  const [err, setErr] = useStateVM('');

  const load = async () => {
    try {
      const { data } = await window.SarayaDB.from('vendor_meeting_requests').select('*').order('slot_start', { ascending: false });
      setRows(data || []);
      const n = {}; (data || []).forEach((r) => { n[r.id] = r.admin_notes || ''; }); setNotesById(n);
    } catch (e) { setRows([]); }
  };
  useEffectVM(() => { load(); }, []);

  const setStatus = async (r, status) => {
    setBusyId(r.id); setErr('');
    try {
      await vmCall({ action: 'status', id: r.id, status, admin_notes: notesById[r.id] || '' });
      await load();
    } catch (e) { setErr(e.message || 'Update failed'); }
    finally { setBusyId(''); }
  };

  const line = 'var(--line)';
  const shown = (rows || []).filter((r) => filter === 'all' || r.status === filter);
  const counts = {};
  (rows || []).forEach((r) => { counts[r.status] = (counts[r.status] || 0) + 1; });

  return (
    <div style={{ display: 'grid', gap: 16 }}>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10, alignItems: 'center', justifyContent: 'space-between' }}>
        <div>
          <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 500, margin: 0 }}>{ar ? 'طلبات اجتماعات الموردين' : 'Vendor Meeting Requests'}</h2>
          <p style={{ fontSize: 13, color: 'var(--fg-muted)', margin: '4px 0 0' }}>{ar ? 'عرض وإدارة طلبات اجتماعات الدعم.' : 'View and manage vendor support meeting requests.'}</p>
        </div>
        <button onClick={load} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '9px 14px', borderRadius: 9, border: '1px solid ' + line, background: 'var(--white)', color: 'var(--fg-secondary)', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}><Icon name="refresh-cw" size={14} />{ar ? 'تحديث' : 'Refresh'}</button>
      </div>

      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
        {['all', 'pending', 'confirmed', 'completed', 'cancelled'].map((f) => {
          const active = filter === f;
          const lbl = f === 'all' ? (ar ? 'الكل' : 'All') : (ar ? window.MEETING_STATUS[f].ar : window.MEETING_STATUS[f].en);
          const c = f === 'all' ? (rows || []).length : (counts[f] || 0);
          return <button key={f} onClick={() => setFilter(f)} style={{ padding: '7px 13px', borderRadius: 999, border: '1.5px solid ' + (active ? 'var(--gold)' : line), background: active ? 'rgba(201,169,97,0.10)' : 'var(--white)', color: 'var(--fg-primary)', fontSize: 12.5, fontWeight: active ? 700 : 500, cursor: 'pointer' }}>{lbl} ({c})</button>;
        })}
      </div>

      {err && <div style={{ padding: '10px 14px', borderRadius: 9, background: '#FEF2F2', border: '1px solid #FCA5A5', color: '#B91C1C', fontSize: 13 }}>{err}</div>}

      {rows === null ? (
        <p style={{ fontSize: 13, color: 'var(--fg-muted)' }}>{ar ? 'جارٍ التحميل…' : 'Loading…'}</p>
      ) : shown.length === 0 ? (
        <div style={{ textAlign: 'center', color: 'var(--fg-muted)', padding: '30px 0', border: '1px dashed ' + line, borderRadius: 12 }}>
          <Icon name="calendar" size={34} stroke={1} /><p style={{ fontSize: 14, marginTop: 8 }}>{ar ? 'لا توجد طلبات.' : 'No requests.'}</p>
        </div>
      ) : (
        <div style={{ display: 'grid', gap: 12 }}>
          {shown.map((r) => {
            const st = window.MEETING_STATUS[r.status] || window.MEETING_STATUS.pending;
            const busy = busyId === r.id;
            return (
              <div key={r.id} style={{ border: '1px solid ' + line, borderRadius: 12, padding: '16px 18px', background: 'var(--white)' }}>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 12, justifyContent: 'space-between', alignItems: 'flex-start' }}>
                  <div style={{ minWidth: 220, flex: '1 1 240px' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 9, flexWrap: 'wrap' }}>
                      <span style={{ fontSize: 15, fontWeight: 700 }}>{r.vendor_name}</span>
                      {r.company_name && <span style={{ fontSize: 13, color: 'var(--fg-muted)' }}>· {r.company_name}</span>}
                      <span style={{ fontSize: 11.5, fontWeight: 700, color: st.color, background: st.bg, padding: '3px 10px', borderRadius: 999 }}>{ar ? st.ar : st.en}</span>
                    </div>
                    <div style={{ fontSize: 13, color: 'var(--fg-secondary)', marginTop: 8, display: 'grid', gap: 4 }}>
                      <span><Icon name="calendar" size={13} style={{ verticalAlign: 'middle', marginInlineEnd: 6, color: 'var(--gold-deep)' }} />{vmFmtSlot(r.slot_start, ar)} <strong style={{ color: 'var(--fg-primary)' }}>({ar ? 'توقيت الإمارات' : 'UAE'})</strong></span>
                      <span><Icon name="video" size={13} style={{ verticalAlign: 'middle', marginInlineEnd: 6, color: 'var(--gold-deep)' }} />{vmLabel(window.MEETING_TYPES, r.meeting_type, ar)} · {vmLabel(window.MEETING_REASONS, r.reason, ar)}</span>
                      <span><Icon name="mail" size={13} style={{ verticalAlign: 'middle', marginInlineEnd: 6, color: 'var(--gold-deep)' }} /><a href={'mailto:' + r.email} style={{ color: 'var(--fg-secondary)' }}>{r.email}</a>{r.phone ? ' · ' : ''}{r.phone && <a href={'tel:' + r.phone} style={{ color: 'var(--fg-secondary)' }} dir="ltr">{r.phone}</a>}</span>
                    </div>
                  </div>
                  <div style={{ display: 'grid', gap: 8, flex: '1 1 210px', minWidth: 200, maxWidth: 320 }}>
                    <Select value={r.status} disabled={busy} onChange={(e) => setStatus(r, e.target.value)} style={vmInputStyle}>
                      {['pending', 'confirmed', 'completed', 'cancelled'].map((s) => <option key={s} value={s}>{ar ? window.MEETING_STATUS[s].ar : window.MEETING_STATUS[s].en}</option>)}
                    </Select>
                    <TextInput placeholder={ar ? 'رابط الاجتماع / ملاحظات (تُرسل للمورد)' : 'Meeting link / notes (emailed to vendor)'} value={notesById[r.id] || ''} onChange={(e) => setNotesById({ ...notesById, [r.id]: e.target.value })} style={vmInputStyle} />
                    <div style={{ display: 'flex', gap: 8 }}>
                      <button disabled={busy} onClick={() => setStatus(r, 'confirmed')} style={{ flex: 1, padding: '9px 0', borderRadius: 9, border: 'none', background: 'var(--gold)', color: 'var(--espresso)', fontSize: 13, fontWeight: 700, cursor: busy ? 'default' : 'pointer' }}>{busy ? '…' : (ar ? 'تأكيد' : 'Confirm')}</button>
                      <button disabled={busy} onClick={() => setStatus(r, 'cancelled')} style={{ flex: 1, padding: '9px 0', borderRadius: 9, border: '1px solid #FCA5A5', background: '#FEF2F2', color: '#B91C1C', fontSize: 13, fontWeight: 600, cursor: busy ? 'default' : 'pointer' }}>{ar ? 'إلغاء' : 'Cancel'}</button>
                    </div>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
window.AdminMeetingRequests = AdminMeetingRequests;
