// Saraya Events — Product Reviews & Ratings
// Exports: ProductReviews, ReviewForm, StarRating
// Depends on: window.SarayaDB, window.useAuth, window.useLang

const { useState: useStateRev, useEffect: useEffectRev, useCallback: useCallbackRev } = React;

/* ---- Star display ---- */
function StarRating({ value, max = 5, size = 16, interactive = false, onChange }) {
  const [hover, setHover] = useStateRev(0);
  return (
    <div style={{ display: 'inline-flex', gap: 2 }}>
      {Array.from({ length: max }, (_, i) => i + 1).map((star) => (
        <span
          key={star}
          onClick={interactive ? () => onChange && onChange(star) : undefined}
          onMouseEnter={interactive ? () => setHover(star) : undefined}
          onMouseLeave={interactive ? () => setHover(0) : undefined}
          style={{
            fontSize: size,
            color: star <= (hover || value) ? '#C9A961' : 'var(--line)',
            cursor: interactive ? 'pointer' : 'default',
            lineHeight: 1,
            transition: 'color 120ms',
          }}
        >★</span>
      ))}
    </div>
  );
}
window.StarRating = StarRating;

/* ---- Write a review form ---- */
function ReviewForm({ productId, vendorId, orderId, onSubmitted }) {
  const db = window.SarayaDB;
  const { user } = window.useAuth ? window.useAuth() : { user: null };
  const { lang } = window.useLang ? window.useLang() : { lang: 'en' };
  const ar = lang === 'ar';

  const [rating, setRating] = useStateRev(0);
  const [title, setTitle]   = useStateRev('');
  const [body, setBody]     = useStateRev('');
  const [busy, setBusy]     = useStateRev(false);
  const [done, setDone]     = useStateRev(false);
  const [error, setError]   = useStateRev('');

  const submit = async (e) => {
    e.preventDefault();
    if (!rating) { setError(ar ? 'يرجى تحديد التقييم' : 'Please select a rating'); return; }
    if (!user) { setError(ar ? 'يجب تسجيل الدخول للتعليق' : 'Sign in to leave a review'); return; }
    setBusy(true); setError('');
    const { error: err } = await db.from('reviews').insert({
      customer_id: user.id,
      vendor_id: vendorId || null,
      product_id: productId || null,
      order_id: orderId || null,
      rating,
      title: title.trim() || null,
      body: body.trim() || null,
      status: 'published',
    });
    setBusy(false);
    if (err) { setError(err.message || (ar ? 'حدث خطأ' : 'Something went wrong')); return; }
    setDone(true);
    onSubmitted && onSubmitted();
  };

  if (done) return (
    <div style={{ textAlign: 'center', padding: '20px 0', color: 'var(--fg-secondary)', fontSize: 14 }}>
      <span style={{ fontSize: 28 }}>⭐</span>
      <p style={{ marginTop: 8 }}>{ar ? 'شكراً على تقييمك!' : 'Thank you for your review!'}</p>
    </div>
  );

  return (
    <form onSubmit={submit} style={{ display: 'grid', gap: 14 }}>
      <div>
        <label style={{ display: 'block', fontSize: 13, fontWeight: 600, color: 'var(--fg-secondary)', marginBottom: 6 }}>
          {ar ? 'تقييمك' : 'Your Rating'}
        </label>
        <StarRating value={rating} size={28} interactive onChange={setRating} />
      </div>
      <div>
        <label style={{ display: 'block', fontSize: 13, fontWeight: 600, color: 'var(--fg-secondary)', marginBottom: 6 }}>
          {ar ? 'العنوان (اختياري)' : 'Title (optional)'}
        </label>
        <input
          value={title}
          onChange={(e) => setTitle(e.target.value)}
          maxLength={120}
          placeholder={ar ? 'ملخص تجربتك' : 'Summarise your experience'}
          style={{ width: '100%', padding: '9px 12px', borderRadius: 8, border: '1.5px solid var(--line)', fontFamily: 'var(--font-body)', fontSize: 14, background: 'var(--white)', color: 'var(--fg-primary)', boxSizing: 'border-box' }}
        />
      </div>
      <div>
        <label style={{ display: 'block', fontSize: 13, fontWeight: 600, color: 'var(--fg-secondary)', marginBottom: 6 }}>
          {ar ? 'تعليقك' : 'Review'}
        </label>
        <textarea
          value={body}
          onChange={(e) => setBody(e.target.value)}
          rows={4}
          maxLength={1000}
          placeholder={ar ? 'أخبر الآخرين عن تجربتك...' : 'Tell others about your experience...'}
          style={{ width: '100%', padding: '9px 12px', borderRadius: 8, border: '1.5px solid var(--line)', fontFamily: 'var(--font-body)', fontSize: 14, background: 'var(--white)', color: 'var(--fg-primary)', resize: 'vertical', boxSizing: 'border-box' }}
        />
      </div>
      {error && <p style={{ color: 'var(--error)', fontSize: 13, margin: 0 }}>{error}</p>}
      <button
        type="submit"
        disabled={busy || !rating}
        style={{ padding: '11px 24px', borderRadius: 10, border: 'none', background: rating ? 'var(--gold)' : 'var(--line)', color: rating ? 'var(--ink)' : 'var(--fg-muted)', fontFamily: 'var(--font-body)', fontSize: 14, fontWeight: 700, cursor: rating ? 'pointer' : 'default', transition: 'background 160ms' }}
      >
        {busy ? (ar ? 'جارٍ الإرسال...' : 'Submitting...') : (ar ? 'إرسال التقييم' : 'Submit Review')}
      </button>
    </form>
  );
}
window.ReviewForm = ReviewForm;

/* ---- Review list + summary ---- */
function ProductReviews({ productId, vendorId, showWriteForm = true }) {
  const db = window.SarayaDB;
  const { user } = window.useAuth ? window.useAuth() : { user: null };
  const { lang } = window.useLang ? window.useLang() : { lang: 'en' };
  const ar = lang === 'ar';

  const [reviews, setReviews]       = useStateRev([]);
  const [loading, setLoading]       = useStateRev(true);
  const [showForm, setShowForm]     = useStateRev(false);
  const [refreshKey, setRefreshKey] = useStateRev(0);

  const avgRating = reviews.length ? (reviews.reduce((s, r) => s + r.rating, 0) / reviews.length) : 0;
  const distrib   = [5, 4, 3, 2, 1].map((star) => ({ star, count: reviews.filter((r) => r.rating === star).length }));

  useEffectRev(() => {
    if (!db) { setLoading(false); return; }
    let q = db.from('reviews').select('*, profiles(full_name, avatar_url)').eq('status', 'published');
    if (productId) q = q.eq('product_id', productId);
    if (vendorId)  q = q.eq('vendor_id', vendorId);
    q.order('created_at', { ascending: false }).then(({ data }) => {
      setReviews(data || []);
      setLoading(false);
    });
  }, [db, productId, vendorId, refreshKey]);

  if (loading) return <div style={{ padding: '24px 0', textAlign: 'center', color: 'var(--fg-muted)', fontSize: 14 }}>{ar ? 'جارٍ التحميل...' : 'Loading reviews...'}</div>;

  return (
    <div style={{ display: 'grid', gap: 24 }}>
      {/* Summary bar */}
      {reviews.length > 0 && (
        <div style={{ display: 'flex', gap: 24, flexWrap: 'wrap', alignItems: 'center', padding: '20px 24px', background: 'var(--cream)', borderRadius: 14 }}>
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 48, fontWeight: 500, color: 'var(--gold-deep)', lineHeight: 1 }}>{avgRating.toFixed(1)}</div>
            <StarRating value={Math.round(avgRating)} size={18} />
            <div style={{ fontSize: 12, color: 'var(--fg-muted)', marginTop: 4 }}>{reviews.length} {ar ? 'تقييم' : 'reviews'}</div>
          </div>
          <div style={{ flex: 1, minWidth: 160 }}>
            {distrib.map(({ star, count }) => (
              <div key={star} style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
                <span style={{ fontSize: 12, color: 'var(--fg-secondary)', minWidth: 20 }}>{star}★</span>
                <div style={{ flex: 1, height: 6, borderRadius: 3, background: 'var(--line)', overflow: 'hidden' }}>
                  <div style={{ height: '100%', borderRadius: 3, background: 'var(--gold)', width: reviews.length ? `${(count / reviews.length) * 100}%` : '0%', transition: 'width 400ms' }} />
                </div>
                <span style={{ fontSize: 12, color: 'var(--fg-muted)', minWidth: 20 }}>{count}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Write review */}
      {showWriteForm && user && (
        <div>
          {!showForm ? (
            <button
              onClick={() => setShowForm(true)}
              style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '10px 20px', borderRadius: 10, border: '1.5px solid var(--gold)', background: 'transparent', color: 'var(--gold-deep)', fontFamily: 'var(--font-body)', fontSize: 13.5, fontWeight: 600, cursor: 'pointer' }}
            >
              ★ {ar ? 'اكتب تقييماً' : 'Write a Review'}
            </button>
          ) : (
            <div style={{ padding: '20px 24px', borderRadius: 14, border: '1.5px solid var(--gold)', background: 'var(--white)' }}>
              <h4 style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 500, margin: '0 0 16px' }}>{ar ? 'تقييمك' : 'Your Review'}</h4>
              <ReviewForm
                productId={productId}
                vendorId={vendorId}
                onSubmitted={() => { setShowForm(false); setRefreshKey((k) => k + 1); }}
              />
            </div>
          )}
        </div>
      )}

      {/* Review cards */}
      {reviews.length === 0 ? (
        <div style={{ textAlign: 'center', padding: '32px 0', color: 'var(--fg-muted)', fontSize: 14 }}>
          {ar ? 'لا توجد تقييمات بعد. كن أول من يقيّم!' : 'No reviews yet. Be the first to review!'}
        </div>
      ) : reviews.map((r) => (
        <div key={r.id} style={{ padding: '18px 22px', borderRadius: 14, border: '1px solid var(--line)', background: 'var(--white)' }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12, marginBottom: 8 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <div style={{ width: 36, height: 36, borderRadius: '50%', background: 'var(--cream)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-display)', fontSize: 16, color: 'var(--gold-deep)', fontWeight: 600 }}>
                {(r.profiles?.full_name || 'A')[0].toUpperCase()}
              </div>
              <div>
                <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--fg-primary)' }}>{r.profiles?.full_name || (ar ? 'عميل' : 'Customer')}</div>
                <div style={{ fontSize: 11, color: 'var(--fg-muted)' }}>{new Date(r.created_at).toLocaleDateString(ar ? 'ar-AE' : 'en-AE', { year: 'numeric', month: 'short', day: 'numeric' })}</div>
              </div>
            </div>
            <StarRating value={r.rating} size={14} />
          </div>
          {r.title && <p style={{ fontWeight: 700, fontSize: 14, color: 'var(--fg-primary)', margin: '0 0 6px' }}>{r.title}</p>}
          {r.body  && <p style={{ fontSize: 13.5, color: 'var(--fg-secondary)', lineHeight: 1.65, margin: 0 }}>{r.body}</p>}
        </div>
      ))}
    </div>
  );
}
window.ProductReviews = ProductReviews;
