// src/compare.jsx
// Saraya Events -- "Compare Prices" UI: floating CompareBar + CompareModal + CompareCheckbox.
// Depends on window.SarayaCompare (src/compare-config.js) and the existing RFQ modal (window.openItemRFQModal).
// Client-side only per spec; does not alter existing listing creation/detail logic or routes.

function useCompareItems() {
  const [items, setItems] = React.useState(function () {
    return window.SarayaCompare ? window.SarayaCompare.getItems() : [];
  });
  React.useEffect(function () {
    if (!window.SarayaCompare) return undefined;
    return window.SarayaCompare.subscribe(setItems);
  }, []);
  return items;
}

function CompareCheckbox({ listingType, item }) {
  const { lang } = useLang();
  const ar = lang === 'ar';
  useCompareItems();
  const [warn, setWarn] = React.useState(null);

  if (!window.SarayaCompare || !item || item.id == null) return null;
  const selected = window.SarayaCompare.isSelected(listingType, item.id);

  function onChange(e) {
    e.stopPropagation();
    const res = window.SarayaCompare.toggleItem(listingType, item);
    if (!res.ok) {
      setWarn(res.message);
      window.setTimeout(function () { setWarn(null); }, 3200);
    }
  }

  return (
    <label
      onClick={function (e) { e.stopPropagation(); }}
      style={{
        display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12, fontWeight: 600,
        color: 'var(--fg-secondary)', cursor: 'pointer', userSelect: 'none',
        background: 'var(--white)', border: '1px solid var(--line)', borderRadius: 999,
        padding: '4px 10px', position: 'relative',
      }}
    >
      <input type="checkbox" checked={selected} onChange={onChange} style={{ margin: 0, cursor: 'pointer' }} />
      {ar ? 'مقارنة' : 'Compare'}
      {warn && (
        <span style={{
          position: 'absolute', bottom: '100%', insetInlineStart: 0, marginBottom: 6,
          background: 'var(--fg-primary)', color: 'var(--white)', fontSize: 11, fontWeight: 500,
          padding: '6px 10px', borderRadius: 8, width: 190, zIndex: 40, boxShadow: '0 8px 20px rgba(0,0,0,0.18)',
        }}>
          {warn}
        </span>
      )}
    </label>
  );
}

function CompareBar() {
  const { lang } = useLang();
  const ar = lang === 'ar';
  const items = useCompareItems();
  const [modalOpen, setModalOpen] = React.useState(false);

  if (items.length < 2) return null;

  return (
    <React.Fragment>
      <div style={{
        position: 'fixed', insetInlineStart: '50%', transform: 'translateX(-50%)', bottom: 18,
        zIndex: 85, background: 'var(--fg-primary)', color: 'var(--white)', borderRadius: 999,
        boxShadow: '0 12px 32px rgba(0,0,0,0.28)', padding: '10px 10px 10px 18px',
        display: 'flex', alignItems: 'center', gap: 12, maxWidth: 'calc(100vw - 24px)', flexWrap: 'wrap',
        justifyContent: 'center',
      }}>
        <span style={{ fontSize: 13, fontWeight: 600 }}>
          {items.length} {ar ? 'عناصر محددة للمقارنة' : 'items selected for comparison'}
        </span>
        <button
          onClick={function () { setModalOpen(true); }}
          style={{ background: '#C9A24B', color: 'var(--fg-primary)', border: 'none', borderRadius: 999, padding: '9px 16px', fontSize: 13, fontWeight: 700, cursor: 'pointer' }}
        >
          {ar ? 'قارن الأسعار' : 'Compare Prices'}
        </button>
        <button
          onClick={function () { window.SarayaCompare.clear(); setModalOpen(false); }}
          style={{ background: 'transparent', color: 'var(--white)', border: '1px solid rgba(255,255,255,0.4)', borderRadius: 999, padding: '9px 14px', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}
        >
          {ar ? 'مسح' : 'Clear'}
        </button>
      </div>
      {modalOpen && <CompareModal items={items} onClose={function () { setModalOpen(false); }} />}
    </React.Fragment>
  );
}

function CompareModal({ items, onClose }) {
  const { lang } = useLang();
  const ar = lang === 'ar';
  const [vendorNames, setVendorNames] = React.useState({});

  React.useEffect(function () {
    let cancelled = false;
    (async function () {
      if (!window.SarayaCompare) return;
      const out = {};
      for (const it of items) {
        if (!it.vendorId) continue;
        out[it.vendorId] = await window.SarayaCompare.getVendorName(it.vendorId);
      }
      if (!cancelled) setVendorNames(out);
    })();
    return function () { cancelled = true; };
  }, [items]);

  React.useEffect(function () {
    function onKey(e) { if (e.key === 'Escape') onClose(); }
    document.addEventListener('keydown', onKey);
    return function () { document.removeEventListener('keydown', onKey); };
  }, []);

  if (!items || items.length < 2) return null;
  const S = window.SarayaCompare;
  const type = items[0].listingType;

  function labelFor(it) {
    if (!it.name) return '—';
    return ar ? (it.name.ar || it.name.en) : (it.name.en || it.name.ar);
  }

  function catLabel(it) {
    if (!it.categoryLabel) return '—';
    return ar ? (it.categoryLabel.ar || it.categoryLabel.en) : (it.categoryLabel.en || it.categoryLabel.ar);
  }

  const rows = [];
  rows.push({ label: ar ? 'الصورة' : 'Image', render: function (it) {
    return it.image
      ? <img src={it.image} alt="" style={{ width: '100%', maxWidth: 120, aspectRatio: '4 / 3', objectFit: 'cover', borderRadius: 8 }} />
      : <span style={{ color: 'var(--fg-muted)' }}>—</span>;
  } });
  rows.push({ label: ar ? 'الاسم' : 'Name', render: function (it) { return <strong>{labelFor(it)}</strong>; } });
  rows.push({ label: ar ? 'المورد' : 'Vendor', render: function (it) {
    if (!it.vendorId) return '—';
    return vendorNames[it.vendorId] || (ar ? 'جاري التحميل…' : 'Loading…');
  } });
  if (type === 'product') {
    rows.push({ label: ar ? 'الفئة' : 'Category', render: catLabel });
  }
  if (type === 'rental') {
    rows.push({ label: ar ? 'الفئة الرئيسية' : 'Main Category', render: catLabel });
    rows.push({ label: ar ? 'الفئة الفرعية' : 'Subcategory', render: function (it) { return it.subCategorySlug || '—'; } });
  }
  if (type === 'service') {
    rows.push({ label: ar ? 'فئة الخدمة' : 'Service Category', render: catLabel });
  }
  rows.push({ label: ar ? 'السعر' : 'Price', render: function (it) {
    const p = S.priceDisplay(it);
    return ar ? p.ar : p.en;
  } });
  if (type === 'rental') {
    rows.push({ label: ar ? 'السعر / أسبوع' : 'Price / Week', render: function (it) { return it.pricePerWeek != null ? S.money(it.pricePerWeek) : '—'; } });
    rows.push({ label: ar ? 'السعر / مناسبة' : 'Price / Event', render: function (it) { return it.pricePerEvent != null ? S.money(it.pricePerEvent) : '—'; } });
    rows.push({ label: ar ? 'مبلغ التأمين' : 'Security Deposit', render: function (it) { return it.deposit != null ? S.money(it.deposit) : '—'; } });
    rows.push({ label: ar ? 'الحد الأدنى لأيام الإيجار' : 'Minimum Rental Days', render: function (it) { return it.minDays || '—'; } });
  }
  rows.push({ label: ar ? 'التوفر' : 'Availability', render: function (it) {
    return it.available
      ? <span style={{ color: '#2E7D32', fontWeight: 600 }}>{ar ? 'متاح' : 'Available'}</span>
      : <span style={{ color: '#B00020', fontWeight: 600 }}>{ar ? 'غير متاح' : 'Unavailable'}</span>;
  } });

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(20,16,10,0.55)', zIndex: 150, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16 }}>
      <div onClick={function (e) { e.stopPropagation(); }} style={{ background: 'var(--white)', borderRadius: 'var(--radius-lg)', width: '100%', maxWidth: 920, maxHeight: '90vh', overflowY: 'auto', boxShadow: '0 20px 60px rgba(0,0,0,0.3)', padding: 20 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
          <div>
            <h2 style={{ margin: 0, fontSize: 20, fontWeight: 800 }}>{ar ? 'قارن الأسعار' : 'Compare Prices'}</h2>
            <p style={{ margin: '4px 0 0', fontSize: 13, color: 'var(--fg-muted)' }}>
              {ar ? 'راجع القوائم المتشابهة جنبًا إلى جنب قبل إرسال طلبك.' : 'Review similar listings side by side before sending your request.'}
            </p>
          </div>
          <button onClick={onClose} aria-label="Close" style={{ border: 'none', background: 'transparent', fontSize: 22, cursor: 'pointer', lineHeight: 1, color: 'var(--fg-muted)' }}>×</button>
        </div>

        <div style={{ marginTop: 16, overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 560 }}>
            <tbody>
              {rows.map(function (row, ri) {
                return (
                  <tr key={ri} style={{ borderTop: '1px solid var(--line)' }}>
                    <td style={{ padding: 8, fontSize: 12, fontWeight: 700, color: 'var(--fg-muted)', verticalAlign: 'top', whiteSpace: 'nowrap' }}>
                      {row.label}
                    </td>
                    {items.map(function (it) {
                      return (
                        <td key={it.listingType + '-' + it.id} style={{ padding: 8, fontSize: 13, verticalAlign: 'top' }}>
                          {row.render(it)}
                        </td>
                      );
                    })}
                  </tr>
                );
              })}
              <tr style={{ borderTop: '1px solid var(--line)' }}>
                <td style={{ padding: 8 }} />
                {items.map(function (it) {
                  return (
                    <td key={it.listingType + '-' + it.id} style={{ padding: 8 }}>
                      <button
                        onClick={function () { onClose(); if (window.openItemRFQModal) window.openItemRFQModal(it.raw); }}
                        style={{ width: '100%', padding: '9px 12px', borderRadius: 'var(--radius-md)', border: 'none', background: 'var(--fg-primary)', color: 'var(--white)', fontSize: 12, fontWeight: 700, cursor: 'pointer' }}
                      >
                        {ar ? 'اطلب عرض سعر' : 'Request a Quote'}
                      </button>
                    </td>
                  );
                })}
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

function CompareRoot() {
  return <CompareBar />;
}

window.CompareCheckbox = CompareCheckbox;
window.CompareRoot = CompareRoot;
