// TAHAANN — Reviews section for home page and product pages
// Displays customer reviews from root reviews collection with product links

const WRAP = { maxWidth: "1280px", margin: "0 auto", padding: "0 24px" };

function ReviewCard({ review, product }) {
  const stars = (n) => Array(5).fill(0).map((_, i) => (
    <span key={i} style={{ color: i < n ? "var(--saffron)" : "rgba(11,31,58,0.15)", fontSize: "16px" }}>★</span>
  ));

  const images = review.images && Array.isArray(review.images) ? review.images : [];
  const image = images.length > 0 ? images[0] : null;

  const getCategoryLabel = (catKey) => {
    if (!catKey) return null;
    const groups = window.TAHAN_DATA?.groups || [];
    const group = groups.find(g => g.key === catKey);
    return group ? group.label : catKey;
  };

  return (
    <a href={`Product?id=${review.productId}`} style={{ display: "block", textDecoration: "none", cursor: "pointer" }}>
      <div style={{
        background: "var(--surface-card)",
        border: "1px solid var(--border-hairline)",
        borderRadius: "8px",
        overflow: "hidden",
        transition: "transform var(--dur-med) var(--ease-standard), box-shadow var(--dur-med) var(--ease-standard)",
        height: "100%",
        display: "flex",
        flexDirection: "column"
      }} className="tahan-review-card" onMouseEnter={(e) => { e.currentTarget.style.transform = "translateY(-2px)"; e.currentTarget.style.boxShadow = "var(--shadow-md)"; }} onMouseLeave={(e) => { e.currentTarget.style.transform = "none"; e.currentTarget.style.boxShadow = "0 1px 3px rgba(11,31,58,0.10)"; }}>
        {/* Image section - fixed height */}
        {image && (
          <div style={{ position: "relative", height: "280px", background: "var(--cream-200)", overflow: "hidden", display: "flex", alignItems: "center", justifyContent: "center" }}>
            <image-slot id={`tahan-review-${review.productId}-${Date.now()}`} shape="rect" fit="contain" placeholder="" src={image || ""}></image-slot>
            {images.length > 1 && (
              <div style={{ position: "absolute", bottom: "8px", right: "8px", background: "rgba(0,0,0,0.7)", color: "#fff", fontFamily: "var(--font-ui)", fontSize: "11px", fontWeight: 700, padding: "4px 8px", borderRadius: "4px" }}>
                +{images.length - 1} more
              </div>
            )}
          </div>
        )}

        {/* Review content */}
        <div style={{ padding: "16px", display: "flex", flexDirection: "column", flex: 1 }}>
          {/* Category and Product name */}
          {product && (
            <>
              {/* Category label */}
              {product.cat && getCategoryLabel(product.cat) && (
                <div style={{ fontFamily: "var(--font-ui)", fontSize: "11px", fontWeight: 700, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--text-muted)", marginBottom: "6px" }}>
                  {getCategoryLabel(product.cat)}
                </div>
              )}
              {/* Product title */}
              <div style={{ fontFamily: "var(--font-ui)", fontSize: "14px", fontWeight: 700, color: "var(--text-heading)", marginBottom: "10px" }}>
                {product.title}
              </div>
            </>
          )}

          {/* Rating */}
          <div style={{ display: "flex", gap: "2px", marginBottom: "8px" }}>
            {stars(review.rating || 5)}
          </div>

          {/* Reviewer name and type */}
          <div style={{ fontFamily: "var(--font-ui)", fontSize: "12px", fontWeight: 600, color: "var(--text-muted)", marginBottom: "6px" }}>
            {review.name || "Anonymous"}
            {review.reviewerType === "user" && <span style={{ fontSize: "10px", color: "var(--text-muted)", marginLeft: "6px" }}>✓ Verified buyer</span>}
          </div>

          {/* Review text */}
          <p style={{
            fontFamily: "var(--font-ui)",
            fontSize: "13px",
            lineHeight: 1.5,
            color: "var(--text-body)",
            margin: "0 0 auto",
            display: "-webkit-box",
            WebkitLineClamp: 3,
            WebkitBoxOrient: "vertical",
            overflow: "hidden"
          }}>
            {review.review}
          </p>
        </div>
      </div>
    </a>
  );
}

function Reviews({ data }) {
  const [reviews, setReviews] = React.useState([]);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    if (!window.firebase || !window.firebase.firestore) {
      setLoading(false);
      return;
    }

    // Query reviews: prioritize rating >= 4 with images, show random 10
    const fetchReviews = async () => {
      try {
        const products = (data && data.products) || [];
        const allQualified = [];

        // Fetch approved reviews from root collection. Only valid === true is
        // shown anywhere on the storefront — blocked (false) and legacy docs
        // without the field are filtered in the query, so they never load.
        const snapshot = await window.firebase.firestore().collection("reviews").where("valid", "==", true).get();

        snapshot.forEach((doc) => {
          const reviewData = doc.data();
          const hasImages = reviewData.images && Array.isArray(reviewData.images) && reviewData.images.length > 0;

          // Only include reviews with at least one image (any rating)
          if (hasImages) {
            const product = products.find((p) => p.id === reviewData.productId);
            const rev = { id: doc.id, ...reviewData, product: product || { id: reviewData.productId, title: "Product" } };
            allQualified.push(rev);
          }
        });

        // Randomize once here; the 10-card cap is applied at render, after
        // reviews of products that aren't on sale have been dropped.
        const shuffled = allQualified.sort(() => Math.random() - 0.5);
        setReviews(shuffled);
      } catch (err) {
        console.warn("[TAHAANN] Reviews fetch failed:", err);
      } finally {
        setLoading(false);
      }
    };

    fetchReviews();
  }, [data]);

  if (loading) {
    return (
      <section style={{ ...WRAP, paddingTop: "84px" }}>
        <div style={{ fontFamily: "var(--font-ui)", fontSize: "12px", fontWeight: 700, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--gold-500, var(--saffron))", marginBottom: "12px" }}>From the people who ordered</div>
        <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: "clamp(1.6rem, 2.6vw, 2.2rem)", letterSpacing: "-0.02em", color: "var(--text-heading)", margin: "0 0 30px" }}>Reviews</h2>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(240px, 1fr))", gap: "20px" }}>
          {[0, 1, 2, 3].map((n) => (
            <div key={n} style={{ background: "var(--surface-card)", borderRadius: "8px", padding: "16px", height: "220px" }}>
              <div style={{ display: "block", height: "12px", width: "80%", borderRadius: "2px", background: "rgba(11,31,58,0.09)", marginBottom: "12px" }}></div>
              <div style={{ display: "block", height: "40px", borderRadius: "2px", background: "rgba(11,31,58,0.06)" }}></div>
            </div>
          ))}
        </div>
      </section>
    );
  }

  // A review only shows while its product is on sale: the catalogue holds just
  // the products the storefront may show (status "live", not valid:false), so a
  // review of a draft or blocked product — which would otherwise surface as a
  // card titled "Product" linking to "not found" — is left out. Checked every
  // render against the live catalogue, so it follows the admin in real time.
  const catalog = (data && data.catalog) || [];
  const shown = reviews.filter((r) => catalog.some((p) => p.id === r.productId)).slice(0, 10);

  if (!shown.length) {
    return null;
  }

  const products = (data && data.products) || [];

  return <ReviewsCarousel reviews={shown} products={products} />;
}

const RV_GAP = 20;

// Reviews slide a page at a time, in the same idiom as the hero and the
// advertisement band: autoplay, pause on hover, dots, and swipe on touch.
function ReviewsCarousel({ reviews, products }) {
  const viewportRef = React.useRef(null);
  const [perView, setPerView] = React.useState(4);
  const [page, setPage] = React.useState(0);
  const [paused, setPaused] = React.useState(false);
  const touchX = React.useRef(null);

  // How many cards fit is measured from the carousel itself rather than the
  // window, so it stays correct inside whatever column it's placed in.
  React.useEffect(() => {
    const calc = () => {
      const w = viewportRef.current ? viewportRef.current.clientWidth : window.innerWidth;
      setPerView(w < 620 ? 1 : w < 980 ? 2 : 4);
    };
    calc();
    window.addEventListener("resize", calc);
    return () => window.removeEventListener("resize", calc);
  }, []);

  const pages = Math.max(1, Math.ceil(reviews.length / perView));
  // Rotating the device can leave the current page past the end.
  React.useEffect(() => { if (page >= pages) setPage(0); }, [pages, page]);
  React.useEffect(() => {
    if (paused || pages < 2) return;
    const t = setTimeout(() => setPage((p) => (p + 1) % pages), 6000);
    return () => clearTimeout(t);
  }, [page, paused, pages]);

  const go = (n) => setPage((n + pages) % pages);
  const onTouchStart = (e) => { touchX.current = e.touches[0].clientX; };
  const onTouchEnd = (e) => {
    if (touchX.current == null) return;
    const dx = e.changedTouches[0].clientX - touchX.current;
    touchX.current = null;
    if (pages > 1 && Math.abs(dx) > 40) go(page + (dx < 0 ? 1 : -1));
  };

  return (
    <section style={{ ...WRAP, paddingTop: "84px", paddingBottom: "76px" }}>
      <div style={{ fontFamily: "var(--font-ui)", fontSize: "12px", fontWeight: 700, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--gold-500, var(--saffron))", marginBottom: "12px" }}>From the people who ordered</div>
      <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: "clamp(1.6rem, 2.6vw, 2.2rem)", letterSpacing: "-0.02em", color: "var(--text-heading)", margin: "0 0 30px" }}>Reviews</h2>
      <div
        ref={viewportRef}
        onMouseEnter={() => setPaused(true)}
        onMouseLeave={() => setPaused(false)}
        onTouchStart={onTouchStart}
        onTouchEnd={onTouchEnd}
        style={{ overflow: "hidden" }}
      >
        {/* A page spans the viewport plus the gap that follows it, so stepping
            by (100% + gap) lands each page flush instead of drifting by one
            gap per page. */}
        <div style={{ display: "flex", gap: RV_GAP + "px", transform: `translateX(calc(${-page} * (100% + ${RV_GAP}px)))`, transition: "transform 420ms var(--ease-standard, ease)" }}>
          {reviews.map((review) => {
            const product = products.find((p) => p.id === review.productId) || review.product;
            return (
              <div key={review.id} style={{ flex: `0 0 calc(${100 / perView}% - ${(RV_GAP * (perView - 1)) / perView}px)`, minWidth: 0 }}>
                <ReviewCard review={review} product={product} />
              </div>
            );
          })}
        </div>
      </div>
      {pages > 1 && (
        <div style={{ display: "flex", justifyContent: "center", gap: "9px", marginTop: "22px" }}>
          {Array.from({ length: pages }).map((_, n) => (
            <button key={n} type="button" onClick={() => go(n)} aria-label={`Reviews page ${n + 1}`} style={{ width: n === page ? "26px" : "9px", height: "9px", borderRadius: "999px", cursor: "pointer", border: "none", padding: 0, background: n === page ? "var(--coral)" : "rgba(11,31,58,0.22)", transition: "width var(--dur-med, 240ms) var(--ease-standard, ease), background var(--dur-med, 240ms) var(--ease-standard, ease)" }}></button>
          ))}
        </div>
      )}
    </section>
  );
}

const OTP_LEN_RV = 6;

// Phone + OTP sign-in shown inline when an unauthenticated visitor submits a review.
// Mirrors login.jsx; on success it hands the signed-in user back so the pending
// review can be written without the visitor leaving the product page.
function ReviewLoginModal({ onSuccess, onClose }) {
  const [step, setStep] = React.useState("phone");
  const [phone, setPhone] = React.useState("");
  const [digits, setDigits] = React.useState(Array(OTP_LEN_RV).fill(""));
  const [err, setErr] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [left, setLeft] = React.useState(30);
  const refs = React.useRef([]);
  const confirmRef = React.useRef(null);
  const recaptchaRef = React.useRef(null);

  React.useEffect(() => {
    if (step !== "otp") return;
    setLeft(30);
    const t = setInterval(() => setLeft((n) => (n > 0 ? n - 1 : 0)), 1000);
    return () => clearInterval(t);
  }, [step]);

  React.useEffect(() => () => {
    if (recaptchaRef.current) { try { recaptchaRef.current.clear(); } catch (e) {} }
  }, []);

  const getRecaptcha = () => {
    if (!recaptchaRef.current) {
      // A container that already hosted a widget throws on re-render, so mount a fresh child.
      const host = document.getElementById("tahan-rv-recaptcha");
      if (!host) return null;
      host.innerHTML = "";
      const slot = document.createElement("div");
      host.appendChild(slot);
      recaptchaRef.current = new firebase.auth.RecaptchaVerifier(slot, { size: "invisible" });
    }
    return recaptchaRef.current;
  };

  const resetRecaptcha = () => {
    if (recaptchaRef.current) { try { recaptchaRef.current.clear(); } catch (e) {} recaptchaRef.current = null; }
    const host = document.getElementById("tahan-rv-recaptcha");
    if (host) host.innerHTML = "";
  };

  const sendOtp = async (e) => {
    e.preventDefault();
    if (!/^[6-9]\d{9}$/.test(phone)) { setErr("Enter a valid 10-digit mobile number."); return; }
    const auth = window.TAHAN_AUTH;
    if (!auth) { setErr("Sign-in is unavailable right now."); return; }
    setErr(""); setDigits(Array(OTP_LEN_RV).fill("")); setBusy(true);
    try {
      confirmRef.current = await auth.signInWithPhoneNumber("+91" + phone, getRecaptcha());
      setStep("otp");
      setTimeout(() => refs.current[0] && refs.current[0].focus(), 60);
    } catch (ex) {
      resetRecaptcha();
      const c = ex && ex.code;
      if (c === "auth/too-many-requests") setErr("Too many attempts. Try again later.");
      else if (c === "auth/operation-not-allowed") setErr("SMS is not enabled for this region yet.");
      else if (c === "auth/unauthorized-domain") setErr("This domain isn't authorised in Firebase.");
      else setErr("Could not send the code. " + ((ex && ex.message) || ""));
    } finally { setBusy(false); }
  };

  const setDigit = (i, v) => {
    const d = v.replace(/\D/g, "").slice(-1);
    const next = digits.slice();
    next[i] = d;
    setDigits(next);
    setErr("");
    if (d && i < OTP_LEN_RV - 1 && refs.current[i + 1]) refs.current[i + 1].focus();
  };

  const onKey = (i) => (e) => {
    if (e.key === "Backspace" && !digits[i] && i > 0 && refs.current[i - 1]) refs.current[i - 1].focus();
  };

  const verify = async (e) => {
    e.preventDefault();
    const code = digits.join("");
    if (code.length < OTP_LEN_RV) { setErr("Enter the full code."); return; }
    if (!confirmRef.current) { setErr("Session expired. Request a new code."); return; }
    setBusy(true);
    try {
      const res = await confirmRef.current.confirm(code);
      try {
        localStorage.setItem("tahan_session", JSON.stringify({ uid: res.user.uid, phone: res.user.phoneNumber, at: Date.now() }));
      } catch (e2) {}
      onSuccess(res.user);
    } catch (ex) {
      setErr(ex && ex.code === "auth/invalid-verification-code" ? "That code isn't right." : "Verification failed. Try again.");
      setBusy(false);
    }
  };

  const btn = { width: "100%", marginTop: "22px", border: "none", cursor: "pointer", background: "var(--navy)", color: "#FFFFFF", fontFamily: "var(--font-ui)", fontWeight: 700, fontSize: "13px", letterSpacing: "0.08em", textTransform: "uppercase", padding: "16px 20px", borderRadius: "8px" };

  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 1000, background: "rgba(11,31,58,0.55)", display: "flex", alignItems: "center", justifyContent: "center", padding: "20px" }}>
      <div onClick={(e) => e.stopPropagation()} role="dialog" aria-modal="true" style={{ width: "100%", maxWidth: "420px", background: "var(--surface-card)", border: "1px solid var(--border-hairline)", borderRadius: "10px", padding: "30px 28px 32px", boxShadow: "0 8px 30px rgba(11,31,58,0.22)" }}>
        <button type="button" onClick={onClose} aria-label="Close" style={{ float: "right", background: "none", border: "none", cursor: "pointer", fontSize: "20px", lineHeight: 1, color: "var(--text-muted)", padding: 0 }}>×</button>
        {step === "phone" && (
          <form onSubmit={sendOtp}>
            <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: "21px", color: "var(--navy)" }}>Sign in to post your review</div>
            <div style={{ fontFamily: "var(--font-ui)", fontSize: "13.5px", color: "var(--text-muted)", marginTop: "6px" }}>We'll send a 6-digit code to verify your number.</div>
            <div style={{ display: "flex", alignItems: "stretch", border: "1px solid var(--border-strong)", borderRadius: "8px", overflow: "hidden", marginTop: "22px" }}>
              <span style={{ display: "flex", alignItems: "center", padding: "0 15px", borderRight: "1px solid var(--border-hairline)", fontFamily: "var(--font-ui)", fontSize: "15px", fontWeight: 700, color: "var(--navy)", background: "var(--beige)" }}>+91</span>
              <input value={phone} onChange={(e) => { setPhone(e.target.value.replace(/\D/g, "").slice(0, 10)); setErr(""); }} inputMode="numeric" autoFocus placeholder="9999999999" style={{ width: "100%", border: "none", outline: "none", padding: "14px 15px", fontFamily: "var(--font-ui)", fontSize: "15px", color: "var(--text-body)", background: "transparent" }} />
            </div>
            {err && <div style={{ fontFamily: "var(--font-ui)", fontSize: "12.5px", color: "#D6403F", marginTop: "10px" }}>{err}</div>}
            <button type="submit" style={btn} disabled={busy}>{busy ? "Sending…" : "Send code"}</button>
          </form>
        )}
        {step === "otp" && (
          <form onSubmit={verify}>
            <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: "21px", color: "var(--navy)" }}>Enter the code</div>
            <div style={{ fontFamily: "var(--font-ui)", fontSize: "13.5px", color: "var(--text-muted)", marginTop: "6px" }}>Sent to +91 {phone} · <button type="button" onClick={() => setStep("phone")} style={{ background: "none", border: "none", padding: 0, cursor: "pointer", fontFamily: "var(--font-ui)", fontSize: "13.5px", color: "var(--brand-secondary)", textDecoration: "underline" }}>change</button></div>
            <div style={{ display: "flex", gap: "8px", marginTop: "22px" }}>
              {digits.map((d, i) => (
                <input key={i} ref={(el) => { refs.current[i] = el; }} value={d} onChange={(e) => setDigit(i, e.target.value)} onKeyDown={onKey(i)} inputMode="numeric" aria-label={`Digit ${i + 1}`} style={{ width: "100%", minWidth: 0, height: "54px", textAlign: "center", border: "1px solid var(--border-strong)", borderRadius: "8px", background: "var(--surface-card)", fontFamily: "var(--font-ui)", fontSize: "21px", fontWeight: 700, color: "var(--navy)", outline: "none" }} />
              ))}
            </div>
            {err && <div style={{ fontFamily: "var(--font-ui)", fontSize: "12.5px", color: "#D6403F", marginTop: "12px" }}>{err}</div>}
            <button type="submit" style={btn} disabled={busy}>{busy ? "Verifying…" : "Verify & post review"}</button>
            <div style={{ fontFamily: "var(--font-ui)", fontSize: "13px", color: "var(--text-muted)", marginTop: "14px" }}>
              {left > 0 ? `Resend code in ${left}s` : <button type="button" onClick={(ev) => { setStep("phone"); setTimeout(() => sendOtp(ev), 0); }} style={{ background: "none", border: "none", padding: 0, cursor: "pointer", fontFamily: "var(--font-ui)", fontSize: "13px", fontWeight: 700, color: "var(--brand-secondary)", textDecoration: "underline" }}>Resend code</button>}
            </div>
          </form>
        )}
        <div id="tahan-rv-recaptcha"></div>
      </div>
    </div>
  );
}

// Per-product reviews component (for Product.html detail pages)
function ProductReviews({ item, flash }) {
  const [reviews, setReviews] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [showForm, setShowForm] = React.useState(false);
  const [formData, setFormData] = React.useState({ rating: 5, review: "", name: "", images: [] });
  const [submitting, setSubmitting] = React.useState(false);
  const [showLogin, setShowLogin] = React.useState(false);
  const [zoomImage, setZoomImage] = React.useState(null);
  const [deleteConfirm, setDeleteConfirm] = React.useState(null);
  const [editingReview, setEditingReview] = React.useState(null);
  const [originalImages, setOriginalImages] = React.useState([]);

  React.useEffect(() => {
    if (!window.TAHAN_AUTH_SUBSCRIBE) return;
    const unsub = window.TAHAN_AUTH_SUBSCRIBE((user) => {
      let name = "";
      if (user) {
        try {
          name = (JSON.parse(localStorage.getItem("tahan-profile-v1") || "null") || {}).name || "";
        } catch (e) {}
      }
      setFormData((f) => ({ ...f, name }));
    });
    return unsub;
  }, []);

  React.useEffect(() => {
    if (!item || !window.firebase) return;

    const fetchReviews = async () => {
      try {
        // Query reviews from root collection where productId matches
        const snapshot = await window.firebase.firestore().collection("reviews").where("productId", "==", item.id).where("valid", "==", true).get();
        const fetchedReviews = [];
        snapshot.forEach((doc) => {
          fetchedReviews.push({ id: doc.id, ...doc.data() });
        });
        // Sort by createdAt in JavaScript
        fetchedReviews.sort((a, b) => (b.createdAt?.toMillis?.() || 0) - (a.createdAt?.toMillis?.() || 0));
        setReviews(fetchedReviews);
      } catch (err) {
        console.warn("[TAHAANN] Reviews fetch failed:", err);
      } finally {
        setLoading(false);
      }
    };

    fetchReviews();
  }, [item]);

  const handleSubmit = (e) => {
    e.preventDefault();

    // Firestore rules reject anything shorter, with an opaque permission error.
    if (formData.review.trim().length < 15) {
      flash("Please write at least 15 characters");
      return;
    }

    const currentUser = window.TAHAN_GET_CURRENT_USER && window.TAHAN_GET_CURRENT_USER();
    if (!currentUser) {
      setShowLogin(true);
      return;
    }

    if (editingReview) {
      submitReviewEdit(currentUser);
    } else {
      submitReview(currentUser);
    }
  };

  const submitReview = async (currentUser) => {
    setSubmitting(true);
    try {
      // Upload images FIRST to get URLs (Firestore rules block all updates)
      const imageUrls = [];
      const imagesArr = Array.from(formData.images || []);
      const tempReviewId = Date.now().toString();

      // Separate File objects from existing URLs
      const newFiles = imagesArr.filter(img => img instanceof File);
      const existingUrls = imagesArr.filter(img => typeof img === 'string');

      if (newFiles.length > 0) {
        console.log("[TAHAANN] Starting image upload for", newFiles.length, "new files");
        for (let i = 0; i < newFiles.length && imageUrls.length < 5; i++) {
          const file = newFiles[i];
          try {
            const storage = window.firebase && window.firebase.storage && window.firebase.storage();
            if (!storage) {
              flash("Photo upload unavailable - Storage not initialized");
              console.error("[TAHAANN] Storage not initialized");
              continue;
            }
            // Path: review-images/{productId}/{uid}/{tempId}/{fileName}
            const ext = file.name.split('.').pop().replace(/[^a-z0-9]/gi, '').slice(0, 3) || 'jpg';
            const path = `review-images/${item.id}/${currentUser.uid}/${tempReviewId}/${i}.${ext}`;
            console.log("[TAHAANN] Uploading to:", path, "Size:", file.size, "Type:", file.type);
            const storageRef = storage.ref(path);
            const snapshot = await storageRef.put(file, { contentType: file.type });
            const url = await snapshot.ref.getDownloadURL();
            imageUrls.push(url);
            console.log("[TAHAANN] ✓ Image uploaded:", path);
          } catch (e) {
            console.error("[TAHAANN] ✗ Image upload failed:", { code: e.code, msg: e.message, name: file.name, size: file.size });
            flash(`Photo upload failed: ${e.code || e.message}`);
          }
        }
        console.log("[TAHAANN] Upload complete. Got", imageUrls.length, 'new URLs');
      }

      // Combine new uploads with existing URLs (if editing)
      const allImages = [...imageUrls, ...existingUrls].slice(0, 5);
      console.log("[TAHAANN] Total images:", allImages.length, "(", imageUrls.length, "new +", existingUrls.length, "existing )");

      // Now create review with image URLs already included (one shot, no update)
      await window.firebase.firestore().collection("reviews").add({
        productId: item.id,
        userId: currentUser.uid,
        rating: parseInt(formData.rating),
        review: formData.review,
        name: formData.name.trim() || "Anonymous",
        reviewerType: "user",
        valid: true,
        createdAt: window.firebase.firestore.FieldValue.serverTimestamp(),
        images: allImages,
      });

      flash("Review submitted! Thank you");
      setFormData((f) => ({ ...f, rating: 5, review: "", images: [] }));
      setShowForm(false);

      // Refresh reviews
      const snapshot = await window.firebase.firestore().collection("reviews").where("productId", "==", item.id).where("valid", "==", true).get();
      const fetchedReviews = [];
      snapshot.forEach((doc) => {
        fetchedReviews.push({ id: doc.id, ...doc.data() });
      });
      fetchedReviews.sort((a, b) => (b.createdAt?.toMillis?.() || 0) - (a.createdAt?.toMillis?.() || 0));
      setReviews(fetchedReviews);
    } catch (err) {
      console.error("[TAHAANN] Review submission failed:", err);
      flash("Failed to submit review");
    } finally {
      setSubmitting(false);
    }
  };

  const handleEdit = (review) => {
    setEditingReview(review.id);
    setOriginalImages(review.images || []);
    setFormData({ rating: review.rating, review: review.review, name: review.name, images: review.images || [] });
    setShowForm(true);
    // Scroll to form after state update
    setTimeout(() => {
      const formElement = document.querySelector('[role="dialog"], form');
      if (formElement) {
        formElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
      } else {
        // Fallback: scroll to top of reviews section
        window.scrollTo({ top: 0, behavior: 'smooth' });
      }
    }, 100);
  };

  const handleDelete = async (reviewId) => {
    const review = reviews.find((r) => r.id === reviewId);
    if (!review) return;
    setDeleteConfirm(reviewId);
  };

  const confirmDelete = async () => {
    if (!deleteConfirm) return;
    try {
      const review = reviews.find((r) => r.id === deleteConfirm);
      if (!review) return;

      // Delete images from Storage if they exist
      if (review.images && review.images.length > 0) {
        const storage = window.firebase.storage();
        for (const imageUrl of review.images) {
          try {
            // Extract the path from the download URL
            // Download URL format: https://firebasestorage.../review-images%2F...?alt=media...
            const pathMatch = imageUrl.match(/\/([^/?]+%2F[^?]+)/);
            if (pathMatch) {
              const encodedPath = pathMatch[1];
              const path = decodeURIComponent(encodedPath);
              await storage.ref(path).delete();
              console.log("[TAHAANN] Deleted image:", path);
            }
          } catch (imgErr) {
            console.warn("[TAHAANN] Failed to delete image:", imgErr);
          }
        }
      }

      // Delete the review document from Firestore
      await window.firebase.firestore().collection("reviews").doc(deleteConfirm).delete();
      flash("Review deleted");
      setReviews(reviews.filter((r) => r.id !== deleteConfirm));
      setDeleteConfirm(null);
    } catch (err) {
      console.error("[TAHAANN] Delete failed:", err);
      flash("Failed to delete review");
      setDeleteConfirm(null);
    }
  };

  const handleCancelEdit = () => {
    setEditingReview(null);
    setOriginalImages([]);
    setFormData({ rating: 5, review: "", name: "", images: [] });
    setShowForm(false);
  };

  const submitReviewEdit = async (currentUser) => {
    if (!editingReview) return;
    setSubmitting(true);
    try {
      // Delete old review
      await window.firebase.firestore().collection("reviews").doc(editingReview).delete();
      // Create new review with edited data
      await submitReview(currentUser);
      setEditingReview(null);
    } catch (err) {
      console.error("[TAHAANN] Edit failed:", err);
      flash("Failed to update review");
      setSubmitting(false);
    }
  };

  if (!item) return null;

  const stars = (n) => Array(5).fill(0).map((_, i) => (
    <span key={i} style={{ color: i < n ? "var(--saffron)" : "rgba(11,31,58,0.15)", fontSize: "14px", cursor: "pointer" }}>★</span>
  ));

  // Calculate average rating and review count
  const averageRating = reviews.length > 0
    ? (reviews.reduce((sum, r) => sum + (r.rating || 5), 0) / reviews.length).toFixed(1)
    : 0;
  const reviewCount = reviews.length;

  return (
    <section style={{ ...WRAP, paddingTop: "60px", paddingBottom: "80px", borderTop: "1px solid var(--border-hairline)", marginTop: "60px" }}>
      <div style={{
        display: "grid",
        gridTemplateColumns: "1fr 1fr",
        gap: "60px",
        alignItems: "start",
      }} className="tahan-reviews-grid">
        {/* Write review form - LEFT COLUMN */}
        <div>
          {!showForm ? (
            <button onClick={() => setShowForm(true)} style={{
              width: "100%", padding: "16px 24px", background: "var(--navy)", color: "#FFFFFF", border: "none", borderRadius: "6px", fontFamily: "var(--font-ui)", fontSize: "14px", fontWeight: 700, cursor: "pointer", letterSpacing: "0.08em", textTransform: "uppercase"
            }}>
              Write a review
            </button>
          ) : (
            <form onSubmit={handleSubmit} style={{ background: "var(--surface-sunken)", padding: "24px", borderRadius: "8px" }}>
              <div style={{ marginBottom: "20px" }}>
                <label style={{ display: "block", fontFamily: "var(--font-ui)", fontSize: "12px", fontWeight: 700, marginBottom: "8px", color: "var(--text-heading)" }}>Rating</label>
                <div style={{ display: "flex", gap: "8px" }}>
                  {[1, 2, 3, 4, 5].map((n) => (
                    <button key={n} type="button" onClick={() => setFormData({ ...formData, rating: n })} style={{
                      fontSize: "28px", background: "none", border: "none", cursor: "pointer", color: formData.rating >= n ? "var(--saffron)" : "rgba(11,31,58,0.15)", padding: 0
                    }}>
                      ★
                    </button>
                  ))}
                </div>
              </div>

              <div style={{ marginBottom: "20px" }}>
                <label style={{ display: "block", fontFamily: "var(--font-ui)", fontSize: "12px", fontWeight: 700, marginBottom: "8px", color: "var(--text-heading)" }}>Your name</label>
                <input type="text" value={formData.name} onChange={(e) => setFormData({ ...formData, name: e.target.value })} placeholder="Leave blank to post as Anonymous" style={{
                  width: "100%", padding: "10px 12px", fontFamily: "var(--font-ui)", fontSize: "13px", border: "1px solid var(--border-hairline)", borderRadius: "4px", boxSizing: "border-box"
                }} />
              </div>

              <div style={{ marginBottom: "20px" }}>
                <label style={{ display: "block", fontFamily: "var(--font-ui)", fontSize: "12px", fontWeight: 700, marginBottom: "8px", color: "var(--text-heading)" }}>Your review</label>
                <textarea value={formData.review} onChange={(e) => setFormData({ ...formData, review: e.target.value })} placeholder="What did you think?" required style={{
                  width: "100%", padding: "10px 12px", fontFamily: "var(--font-ui)", fontSize: "13px", border: "1px solid var(--border-hairline)", borderRadius: "4px", boxSizing: "border-box", minHeight: "100px", resize: "vertical"
                }} />
              </div>

              <div style={{ marginBottom: "20px" }}>
                <label style={{ display: "block", fontFamily: "var(--font-ui)", fontSize: "12px", fontWeight: 700, marginBottom: "8px", color: "var(--text-heading)" }}>Add photos (up to 5)</label>
                <label
                  onDragOver={(e) => { e.preventDefault(); e.currentTarget.style.background = "var(--powder-50)"; e.currentTarget.style.borderColor = "var(--navy)"; }}
                  onDragLeave={(e) => { e.currentTarget.style.background = "transparent"; e.currentTarget.style.borderColor = "var(--border-hairline)"; }}
                  onDrop={(e) => {
                    e.preventDefault();
                    e.currentTarget.style.background = "transparent";
                    e.currentTarget.style.borderColor = "var(--border-hairline)";
                    const files = Array.from(e.dataTransfer.files).filter(f => f.type.startsWith('image/'));
                    if (files.length > 0) setFormData({ ...formData, images: files });
                  }}
                  style={{
                    display: "block", cursor: "pointer", width: "100%", padding: "24px", border: "2px dashed var(--border-hairline)", borderRadius: "8px", background: "transparent", transition: "all var(--dur-fast) var(--ease-standard)", textAlign: "center"
                  }}
                >
                  <input type="file" multiple accept="image/*" onChange={(e) => setFormData({ ...formData, images: Array.from(e.target.files || []) })} style={{ display: "none" }} />
                  <div style={{ fontFamily: "var(--font-ui)", fontSize: "13px", fontWeight: 600, color: "var(--navy)", marginBottom: "4px" }}>Drag photos here or click to browse</div>
                  <div style={{ fontFamily: "var(--font-ui)", fontSize: "12px", color: "var(--text-muted)" }}>PNG, JPG, WebP up to 5MB each</div>
                </label>
                {formData.images && formData.images.length > 0 && (
                  <div style={{ marginTop: "16px" }}>
                    <div style={{ fontFamily: "var(--font-ui)", fontSize: "11px", fontWeight: 600, color: "var(--text-muted)", marginBottom: "8px" }}>{formData.images.length} photo{formData.images.length !== 1 ? 's' : ''} selected</div>
                    <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(70px, 1fr))", gap: "8px" }}>
                      {Array.from(formData.images).map((img, i) => (
                        <div key={i} style={{ position: "relative", aspectRatio: "1", background: "var(--cream-200)", borderRadius: "6px", overflow: "hidden", border: "1px solid var(--border-hairline)" }}>
                          <img src={typeof img === 'string' ? img : URL.createObjectURL(img)} alt={`preview ${i}`} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                          <button type="button" onClick={() => setFormData({ ...formData, images: formData.images.filter((_, idx) => idx !== i) })} style={{ position: "absolute", top: "4px", right: "4px", background: "rgba(0,0,0,0.7)", color: "#fff", border: "none", width: "28px", height: "28px", borderRadius: "50%", cursor: "pointer", fontSize: "18px", lineHeight: 1, display: "flex", alignItems: "center", justifyContent: "center", hover: { background: "rgba(0,0,0,0.9)" } }}>×</button>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </div>

              <div style={{ display: "flex", gap: "10px" }}>
                <button type="submit" disabled={submitting || !formData.review} style={{
                  flex: 1, padding: "12px", background: "var(--navy)", color: "#FFFFFF", border: "none", borderRadius: "4px", fontFamily: "var(--font-ui)", fontSize: "12px", fontWeight: 700, cursor: submitting ? "not-allowed" : "pointer", opacity: submitting ? 0.6 : 1
                }}>
                  {submitting ? (editingReview ? "Updating..." : "Submitting...") : (editingReview ? "Update review" : "Submit review")}
                </button>
                <button type="button" onClick={handleCancelEdit} style={{
                  flex: 1, padding: "12px", background: "transparent", color: "var(--navy)", border: "1px solid var(--navy)", borderRadius: "4px", fontFamily: "var(--font-ui)", fontSize: "12px", fontWeight: 700, cursor: "pointer"
                }}>
                  Cancel
                </button>
              </div>
            </form>
          )}
        </div>

        {/* Reviews list - RIGHT COLUMN */}
        <div>
          <div style={{ fontFamily: "var(--font-ui)", fontSize: "12px", fontWeight: 700, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--gold-500, var(--saffron))", marginBottom: "12px" }}>Customer reviews</div>
          <h3 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: "clamp(1.4rem, 2vw, 1.8rem)", letterSpacing: "-0.02em", color: "var(--text-heading)", margin: "0 0 20px" }}>What customers say</h3>

          {reviewCount > 0 && (
            <div style={{ background: "var(--cream-50)", padding: "20px", borderRadius: "8px", marginBottom: "28px" }}>
              <div style={{ display: "flex", alignItems: "center", gap: "12px", marginBottom: "16px" }}>
                <div>
                  <div style={{ display: "flex", gap: "2px", marginBottom: "4px" }}>
                    {stars(Math.round(averageRating))}
                  </div>
                  <div style={{ fontFamily: "var(--font-display)", fontSize: "20px", fontWeight: 700, color: "var(--text-heading)" }}>
                    {averageRating} <span style={{ fontSize: "14px", fontWeight: 600, color: "var(--text-muted)" }}>out of 5</span>
                  </div>
                </div>
              </div>

              <div style={{ fontFamily: "var(--font-ui)", fontSize: "13px", color: "var(--text-muted)", marginBottom: "16px" }}>
                {reviewCount} customer {reviewCount === 1 ? "rating" : "ratings"}
              </div>

              <div style={{ display: "flex", flexDirection: "column", gap: "8px" }}>
                {[5, 4, 3, 2, 1].map(starLevel => {
                  const ratingCounts = {};
                  reviews.forEach(r => {
                    const rating = Math.round(r.rating || 5);
                    if (rating >= 1 && rating <= 5) ratingCounts[rating] = (ratingCounts[rating] || 0) + 1;
                  });
                  const count = ratingCounts[starLevel] || 0;
                  const percentage = reviewCount > 0 ? Math.round((count / reviewCount) * 100) : 0;
                  return (
                    <div key={starLevel} style={{ display: "grid", gridTemplateColumns: "40px 1fr 30px", gap: "10px", alignItems: "center" }}>
                      <span style={{ fontFamily: "var(--font-ui)", fontSize: "12px", color: "var(--text-muted)" }}>{starLevel} star</span>
                      <div style={{ background: "var(--neutral-100)", height: "8px", borderRadius: "4px", overflow: "hidden" }}>
                        <div style={{ background: "var(--saffron)", height: "100%", width: `${percentage}%`, transition: "width 0.3s ease" }}></div>
                      </div>
                      <span style={{ fontFamily: "var(--font-ui)", fontSize: "12px", fontWeight: 600, color: "var(--text-muted)", textAlign: "right" }}>{percentage}%</span>
                    </div>
                  );
                })}
              </div>
            </div>
          )}

          {loading ? (
            <div style={{ fontFamily: "var(--font-ui)", color: "var(--text-muted)" }}>Loading reviews...</div>
          ) : reviews.length > 0 ? (
            <div style={{ display: "flex", flexDirection: "column", gap: "20px" }}>
              {reviews.map((review) => (
                <div key={review.id} style={{ paddingBottom: "20px", borderBottom: "1px solid var(--border-hairline)" }}>
                  <div style={{ display: "flex", gap: "2px", marginBottom: "8px" }}>
                    {stars(review.rating || 5)}
                  </div>
                  <div style={{ fontFamily: "var(--font-ui)", fontSize: "12px", fontWeight: 600, color: "var(--text-muted)", marginBottom: "8px", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                    <div>
                      {review.name || "Anonymous"}
                      {review.reviewerType === "user" && <span style={{ fontSize: "10px", marginLeft: "6px" }}>✓ Verified buyer</span>}
                    </div>
                    {review.userId === (window.TAHAN_GET_CURRENT_USER && window.TAHAN_GET_CURRENT_USER()?.uid) && (
                      <div style={{ display: "flex", gap: "8px" }}>
                        <button type="button" onClick={() => handleEdit(review)} title="Edit review" style={{ background: "none", border: "none", color: "var(--brand-secondary)", cursor: "pointer", fontSize: "16px", padding: "4px", display: "flex", alignItems: "center", justifyContent: "center" }}>✏️</button>
                        <button type="button" onClick={() => handleDelete(review.id)} title="Delete review" style={{ background: "none", border: "none", color: "var(--coral)", cursor: "pointer", fontSize: "16px", padding: "4px", display: "flex", alignItems: "center", justifyContent: "center" }}>🗑️</button>
                      </div>
                    )}
                  </div>
                  <p style={{ fontFamily: "var(--font-ui)", fontSize: "13px", lineHeight: 1.6, color: "var(--text-body)", margin: "0 0 12px" }}>
                    {review.review}
                  </p>
                  {review.images && review.images.length > 0 && (
                    <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(80px, 1fr))", gap: "8px" }}>
                      {review.images.map((img, i) => (
                        <button key={i} type="button" onClick={() => setZoomImage(img)} style={{ aspectRatio: "1", background: "var(--cream-200)", borderRadius: "4px", overflow: "hidden", border: "none", cursor: "pointer", padding: 0 }}>
                          <img src={img} alt={`review image ${i}`} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                        </button>
                      ))}
                    </div>
                  )}
                </div>
              ))}
            </div>
          ) : (
            <div style={{ fontFamily: "var(--font-ui)", fontSize: "14px", color: "var(--text-muted)" }}>No reviews yet. Be the first to review this book!</div>
          )}
        </div>
      </div>
      {showLogin && (
        <ReviewLoginModal
          onClose={() => setShowLogin(false)}
          onSuccess={(user) => { setShowLogin(false); submitReview(user); }}
        />
      )}
      {zoomImage && (
        <div onClick={() => setZoomImage(null)} style={{ position: "fixed", inset: 0, zIndex: 999, background: "rgba(0,0,0,0.9)", display: "flex", alignItems: "center", justifyContent: "center", padding: "20px" }}>
          <div style={{ position: "relative", maxWidth: "90vw", maxHeight: "90vh" }}>
            <img src={zoomImage} alt="zoomed" style={{ width: "100%", height: "100%", objectFit: "contain" }} />
            <button type="button" onClick={() => setZoomImage(null)} aria-label="Close" style={{ position: "absolute", top: "10px", right: "10px", background: "rgba(255,255,255,0.9)", border: "none", cursor: "pointer", fontSize: "24px", lineHeight: 1, width: "40px", height: "40px", borderRadius: "50%", display: "flex", alignItems: "center", justifyContent: "center" }}>×</button>
          </div>
        </div>
      )}

      {deleteConfirm && (
        <div style={{ position: "fixed", top: 0, left: 0, right: 0, bottom: 0, background: "rgba(0,0,0,0.5)", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 998 }}>
          <div style={{ background: "var(--surface-card)", borderRadius: "8px", padding: "28px", maxWidth: "400px", boxShadow: "0 20px 60px rgba(11,31,58,0.3)" }}>
            <h4 style={{ fontFamily: "var(--font-display)", fontSize: "18px", fontWeight: 700, color: "var(--text-heading)", margin: "0 0 12px" }}>Delete review?</h4>
            <p style={{ fontFamily: "var(--font-ui)", fontSize: "14px", color: "var(--text-body)", margin: "0 0 24px", lineHeight: 1.6 }}>This will permanently delete your review and any attached images. This action cannot be undone.</p>
            <div style={{ display: "flex", gap: "12px" }}>
              <button type="button" onClick={() => setDeleteConfirm(null)} style={{ flex: 1, padding: "12px", background: "transparent", color: "var(--navy)", border: "1px solid var(--navy)", borderRadius: "4px", fontFamily: "var(--font-ui)", fontSize: "14px", fontWeight: 600, cursor: "pointer" }}>Cancel</button>
              <button type="button" onClick={confirmDelete} style={{ flex: 1, padding: "12px", background: "var(--coral)", color: "#FFFFFF", border: "none", borderRadius: "4px", fontFamily: "var(--font-ui)", fontSize: "14px", fontWeight: 600, cursor: "pointer" }}>Delete</button>
            </div>
          </div>
        </div>
      )}
    </section>
  );
}

// Make Reviews available globally for home.jsx
window.Reviews = Reviews;
// Make ProductReviews available globally for product.jsx
window.ProductReviews = ProductReviews;
