// Saraya Events -- RFQ feature: customer request-a-quote modal (product cards)
// and the vendor-facing RFQ board (list open RFQs, submit offers).
// Written with React.createElement (no JSX) to avoid tag-transform edge cases.

function RFQBoardTab(props) {
    var db = props.db, user = props.user;
    var e = React.createElement;
    var rfqState = React.useState([]); var rfqList = rfqState[0], setRfqList = rfqState[1];
    var loadingState = React.useState(true); var loadingRfq = loadingState[0], setLoadingRfq = loadingState[1];
    var offersState = React.useState({}); var myOffers = offersState[0], setMyOffers = offersState[1];
    var offerForState = React.useState(null); var offerFor = offerForState[0], setOfferFor = offerForState[1];
    var priceState = React.useState(''); var price = priceState[0], setPrice = priceState[1];
    var noteState = React.useState(''); var note = noteState[0], setNote = noteState[1];
    var sendingState = React.useState(false); var sending = sendingState[0], setSending = sendingState[1];

    var loadRfqs = React.useCallback(function () {
          if (!db || !user) { setLoadingRfq(false); return; }
          setLoadingRfq(true);
          db.from('rfqs').select('*').eq('status', 'published').order('created_at', { ascending: false }).then(function (res) {
                  setRfqList(res.data || []);
                  return db.from('rfq_offers').select('rfq_id, status').eq('vendor_id', user.id);
                }).then(function (res2) {
                  var map = {};
                  (res2 && res2.data ? res2.data : []).forEach(function (o) { map[o.rfq_id] = o.status; });
                  setMyOffers(map);
                  setLoadingRfq(false);
                });
        }, [db, user]);

    React.useEffect(function () { loadRfqs(); }, [loadRfqs]);

    var submitOffer = function () {
          if (!price || !offerFor || !db || !user) return;
          setSending(true);
          db.from('rfq_offers').insert({ rfq_id: offerFor.id, vendor_id: user.id, price: Number(price), description: note || null, status: 'pending' }).then(function () {
                  setSending(false);
                  setOfferFor(null); setPrice(''); setNote('');
                  loadRfqs();
                });
        };


    if (loadingRfq) return e('p', { style: { color: 'var(--fg-muted)', fontSize: 14 } }, 'Loading...');

    if (rfqList.length === 0) {
          if (window.VDPlaceholder) {
                  return e(window.VDPlaceholder, { icon: 'file-question', title: 'RFQ Requests', desc: 'No open RFQs right now. New customer requests will appear here as soon as they are published.', items: [] });
                }
          return e('p', { style: { color: 'var(--fg-muted)', fontSize: 14 } }, 'No open RFQs right now.');
        }

    var cards = rfqList.map(function (r) {
          var mine = myOffers[r.id];
          var metaBits = [];
          if (r.event_type) metaBits.push(r.event_type);
          metaBits.push(r.event_date || 'No date set');
          if (r.budget_max) metaBits.push('Up to AED ' + r.budget_max);
          return e('div', { key: r.id, style: { padding: '16px 18px', borderRadius: 12, background: 'var(--white)', border: '1px solid var(--line)' } },
                         e('div', { style: { display: 'flex', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap', alignItems: 'flex-start' } },
                                   e('div', null,
                                               e('div', { style: { fontWeight: 700, fontSize: 15 } }, r.title),
                                               e('div', { style: { fontSize: 12.5, color: 'var(--fg-muted)', marginTop: 4 } }, metaBits.join(' - ')),
                                               r.description ? e('p', { style: { fontSize: 13.5, color: 'var(--fg-secondary)', marginTop: 8, maxWidth: 520 } }, r.description) : null
                                             ),
                                   e('div', { style: { flexShrink: 0 } },
                                               mine
                                                 ? e('span', { style: { fontSize: 12.5, fontWeight: 600, padding: '6px 12px', borderRadius: 999, background: 'var(--cream)', color: 'var(--gold-deep)' } }, 'Your offer: ' + mine)
                                                 : e('button', { onClick: function () { setOfferFor(r); }, style: { padding: '9px 18px', borderRadius: 8, border: 'none', background: 'var(--gold)', color: 'var(--espresso)', fontWeight: 700, fontSize: 13, cursor: 'pointer' } }, 'Submit Offer')
                                             )
                                 )
                       );
        });


    var modal = offerFor ? e('div', { style: { position: 'fixed', inset: 0, zIndex: 300, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 } },
                                 e('div', { onClick: function () { setOfferFor(null); }, style: { position: 'absolute', inset: 0, background: 'var(--scrim)' } }),
                                 e('div', { style: { position: 'relative', background: 'var(--white)', borderRadius: 16, padding: 28, width: '100%', maxWidth: 420 } },
                                         e('div', { style: { fontWeight: 700, fontSize: 17, marginBottom: 4 } }, 'Submit an offer'),
                                         e('div', { style: { fontSize: 13, color: 'var(--fg-muted)', marginBottom: 16 } }, offerFor.title),
                                         e('label', { style: { fontSize: 12, fontWeight: 700, color: 'var(--fg-muted)', textTransform: 'uppercase' } }, 'Price (AED) *'),
                                         e('input', { type: 'number', value: price, onChange: function (ev) { setPrice(ev.target.value); }, style: { width: '100%', padding: '11px 14px', borderRadius: 9, border: '1.5px solid var(--line-strong)', marginTop: 6, marginBottom: 14, boxSizing: 'border-box' } }),
                                         e('label', { style: { fontSize: 12, fontWeight: 700, color: 'var(--fg-muted)', textTransform: 'uppercase' } }, 'Notes'),
                                         e('textarea', { value: note, onChange: function (ev) { setNote(ev.target.value); }, rows: 3, style: { width: '100%', padding: '11px 14px', borderRadius: 9, border: '1.5px solid var(--line-strong)', marginTop: 6, marginBottom: 18, boxSizing: 'border-box', resize: 'vertical' } }),
                                         e('div', { style: { display: 'flex', gap: 10 } },
                                                   e('button', { onClick: function () { setOfferFor(null); }, style: { flex: 1, padding: '11px 0', borderRadius: 9, border: '1.5px solid var(--line-strong)', background: 'var(--white)', cursor: 'pointer', fontWeight: 600 } }, 'Cancel'),
                                                   e('button', { onClick: submitOffer, disabled: !price || sending, style: { flex: 1, padding: '11px 0', borderRadius: 9, border: 'none', background: price ? 'var(--gold)' : 'var(--line-strong)', color: 'var(--espresso)', cursor: price ? 'pointer' : 'default', fontWeight: 700 } }, sending ? '...' : 'Send Offer')
                                                 )
                                       )
                               ) : null;

    return e('div', { style: { display: 'grid', gap: 14 } }, cards, modal);
  }

Object.assign(window, { RFQBoardTab: RFQBoardTab });


/* ---------- Customer-facing: Request a Quote modal, opened from product cards ---------- */
function ItemRFQModal() {
    var e = React.createElement;
    var openState = React.useState(false); var open = openState[0], setOpen = openState[1];
    var itemState = React.useState(null); var item = itemState[0], setItem = itemState[1];
    var noteState = React.useState(''); var note = noteState[0], setNote = noteState[1];
    var dateState = React.useState(''); var date = dateState[0], setDate = dateState[1];
    var sendingState = React.useState(false); var sending = sendingState[0], setSending = sendingState[1];
    var doneState = React.useState(false); var done = doneState[0], setDone = doneState[1];
    var errState = React.useState(''); var err = errState[0], setErr = errState[1];

    React.useEffect(function () {
          window.openItemRFQModal = function (it) {
                  setItem(it); setNote(''); setDate(''); setDone(false); setErr(''); setOpen(true);
                };
          return function () { window.openItemRFQModal = null; };
        }, []);

    if (!open) return null;

    var auth = window.useAuth ? window.useAuth() : null;
    var db = window.SarayaDB;
    var close = function () { setOpen(false); };
    var needsAuth = !auth || !auth.user;

    var submit = function () {
          if (needsAuth) { if (auth && auth.openAuthModal) auth.openAuthModal('login'); return; }
          if (!db || !item) return;
          setSending(true); setErr('');
          var itemName = (item.name && (item.name.en || item.name.ar)) || item.id || 'Marketplace item';
          var desc = 'Enquiry about: ' + itemName + (item.price ? (' (AED ' + item.price + ')') : '') + (note ? ('. Note: ' + note) : '');
          db.from('rfqs').insert({ customer_id: auth.user.id, title: 'RFQ: ' + itemName, description: desc, event_date: date || null, status: 'published' }).then(function (res) {
                  setSending(false);
                  if (res && res.error) { setErr(res.error.message || 'Something went wrong.'); return; }
                  setDone(true);
                });
        };

    var needsAuth2 = !auth || !auth.user;

    var doneBody = e('div', { style: { textAlign: 'center', padding: '20px 0' } },
                         e('div', { style: { fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 500, marginBottom: 8 } }, 'Request sent'),
                         e('p', { style: { fontSize: 14, color: 'var(--fg-muted)', marginBottom: 20 } }, 'Vendors on Saraya Events will review your request and respond with quotes soon.'),
                         e('button', { onClick: close, style: { padding: '11px 28px', borderRadius: 9, border: 'none', background: 'var(--gold)', color: 'var(--espresso)', fontWeight: 700, cursor: 'pointer' } }, 'Done')
                       );

    var formBody = e(React.Fragment, null,
                         e('div', { style: { fontWeight: 700, fontSize: 18, marginBottom: 4 } }, 'Request a Quote'),
                         e('div', { style: { fontSize: 13, color: 'var(--fg-muted)', marginBottom: 18 } }, item ? ((item.name && (item.name.en || item.name.ar)) || '') : ''),
                         needsAuth2 ? e('div', { style: { padding: '14px 16px', borderRadius: 10, background: 'var(--cream)', fontSize: 13.5, color: 'var(--fg-secondary)', marginBottom: 16 } }, 'Please sign in to submit a quote request. Vendors respond only to verified customer accounts.') : null,
                         e('label', { style: { fontSize: 12, fontWeight: 700, color: 'var(--fg-muted)', textTransform: 'uppercase' } }, 'Event date (optional)'),
                         e('input', { type: 'date', value: date, onChange: function (ev) { setDate(ev.target.value); }, style: { width: '100%', padding: '11px 14px', borderRadius: 9, border: '1.5px solid var(--line-strong)', marginTop: 6, marginBottom: 14, boxSizing: 'border-box' } }),
                         e('label', { style: { fontSize: 12, fontWeight: 700, color: 'var(--fg-muted)', textTransform: 'uppercase' } }, 'Message (optional)'),
                         e('textarea', { value: note, onChange: function (ev) { setNote(ev.target.value); }, rows: 3, placeholder: 'Any details vendors should know...', style: { width: '100%', padding: '11px 14px', borderRadius: 9, border: '1.5px solid var(--line-strong)', marginTop: 6, marginBottom: 18, boxSizing: 'border-box', resize: 'vertical' } }),
                         err ? e('p', { style: { color: '#c0392b', fontSize: 13, marginBottom: 12 } }, err) : null,
                         e('div', { style: { display: 'flex', gap: 10 } },
                                 e('button', { onClick: close, style: { flex: 1, padding: '11px 0', borderRadius: 9, border: '1.5px solid var(--line-strong)', background: 'var(--white)', cursor: 'pointer', fontWeight: 600 } }, 'Cancel'),
                                 needsAuth2
                                   ? e('button', { onClick: function () { auth && auth.openAuthModal && auth.openAuthModal('login'); }, style: { flex: 1, padding: '11px 0', borderRadius: 9, border: 'none', background: 'var(--gold)', color: 'var(--espresso)', cursor: 'pointer', fontWeight: 700 } }, 'Sign In')
                                   : e('button', { onClick: submit, disabled: sending, style: { flex: 1, padding: '11px 0', borderRadius: 9, border: 'none', background: 'var(--gold)', color: 'var(--espresso)', cursor: 'pointer', fontWeight: 700 } }, sending ? '...' : 'Send Request')
                               )
                       );

    return e('div', { style: { position: 'fixed', inset: 0, zIndex: 250, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 } },
                 e('div', { onClick: close, style: { position: 'absolute', inset: 0, background: 'var(--scrim)' } }),
                 e('div', { style: { position: 'relative', background: 'var(--bg-canvas)', borderRadius: 20, padding: '32px 30px', width: '100%', maxWidth: 440 } },
                         e('button', { onClick: close, style: { position: 'absolute', top: 14, insetInlineEnd: 14, background: 'none', border: 'none', cursor: 'pointer', color: 'var(--fg-muted)', fontSize: 18 } }, 'x'),
                         done ? doneBody : formBody
                       )
               );
  }

Object.assign(window, { ItemRFQModal: ItemRFQModal });
