// Testimonials — one featured pull-quote (static) + smaller chips in a carousel
const GOOGLE_REVIEWS_URL = "https://search.google.com/local/reviews?placeid=ChIJd5W-4F0xK4gRUDeVOTEneu8";
const GOOGLE_WRITE_REVIEW_URL = "https://g.page/r/CVA3lTkxJ3rvEAI/review";

// Display-only truncation limits — never mutate the quote data itself, only how much of it is shown.
const FEATURED_QUOTE_CHAR_LIMIT = 220;
const REST_QUOTE_CHAR_LIMIT = 140;

// Clips at the last whole word inside the limit so words aren't cut mid-way.
const truncateQuote = (text, limit) => {
  const clipped = text.slice(0, limit);
  const lastSpace = clipped.lastIndexOf(" ");
  const safe = lastSpace > 0 ? clipped.slice(0, lastSpace) : clipped;
  return safe.trimEnd() + "...";
};

const TestimonialDialog = ({ item, featured, onClose }) => {
  const closeRef = React.useRef(null);

  React.useEffect(() => {
    const onKeyDown = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKeyDown);
    if (closeRef.current) closeRef.current.focus();
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKeyDown);
      document.body.style.overflow = prevOverflow;
    };
  }, [onClose]);

  return (
    <div className="scl-modal-overlay" onMouseDown={onClose}>
      <div
        className="scl-modal"
        role="dialog"
        aria-modal="true"
        aria-labelledby="scl-testimonial-dialog-name"
        onMouseDown={(e) => e.stopPropagation()}
      >
        <button
          type="button"
          className="scl-modal__close"
          aria-label={t("testimonials.closeAria")}
          onClick={onClose}
          ref={closeRef}
        >
          <Icon name="close" size={18} />
        </button>

        <div className="scl-modal__head">
          <Icon name="quote" size={22} />
          <div className="scl-testimonial__stars" aria-label={`${item.rating || 5}/5`}>
            {Array.from({ length: 5 }).map((_, i) => (
              <Icon key={i} name="star" size={14} className={i < (item.rating || 5) ? "" : "is-empty"} />
            ))}
          </div>
        </div>

        <div className="scl-modal__body">
          <p className="scl-modal__quote">{featured ? item.quote : `"${item.quote}"`}</p>
        </div>

        <div className="scl-testimonial__by__col" id="scl-testimonial-dialog-name">
          <div>
            <div className="scl-testimonial__name">{item.name}</div>
            {/* <div className="scl-testimonial__meta">{item.place}</div> */}
          </div>
          {/* <div className="scl-testimonial__tag">{item.case}</div> */}
        </div>

        <a
          href={item.reviewUrl || GOOGLE_REVIEWS_URL}
          target="_blank"
          rel="noopener noreferrer"
          className="scl-testimonial__link"
        >
          {t("testimonials.viewOnGoogle")}{" "}
          <Icon name="arrow-up-right" size={12} />
        </a>
      </div>
    </div>
  );
};

const Testimonials = () => {
  const items = t("testimonials.items").filter((m) => !m.disabled);
  const featured = items.filter((m) => m.featured);
  const rest = items.filter((m) => !m.featured);
  const [openTestimonial, setOpenTestimonial] = React.useState(null);
  const {
    trackRef,
    setCardRef,
    atStart,
    atEnd,
    edge,
    updateEdges,
    scrollByCard,
    scrollable,
    dragHandlers,
    isDragging,
  } = window.useCardCarousel(rest.length);

  const renderBy = (item, featured) => (
    <>
      <div
        className={
          featured ? "scl-testimonial__by" : "scl-testimonial__by__col"
        }
      >
        <div>
          <div className="scl-testimonial__name">{item.name}</div>
          {/* <div className="scl-testimonial__meta">{item.place}</div> */}
        </div>
        {/* <div className="scl-testimonial__tag">{item.case}</div> */}
      </div>
      <a
        href={item.reviewUrl || GOOGLE_REVIEWS_URL}
        target="_blank"
        rel="noopener noreferrer"
        className="scl-testimonial__link"
        style={featured && {color: "white"}}
      >
        {t("testimonials.viewOnGoogle")}{" "}
        <Icon name="arrow-up-right" size={12} />
      </a>
    </>
  );

  const renderStars = (rating = 5) => (
    <div className="scl-testimonial__stars" aria-label={`${rating}/5`}>
      {Array.from({ length: 5 }).map((_, i) => (
        <Icon
          key={i}
          name="star"
          size={14}
          className={i < rating ? "" : "is-empty"}
        />
      ))}
    </div>
  );

  const renderQuote = (item, limit, featured) => {
    const isTruncated = item.quote.length > limit;
    const displayText = isTruncated ? truncateQuote(item.quote, limit) : item.quote;
    return (
      <>
        <p className="scl-testimonial__quote">
          {featured ? displayText : `"${displayText}"`}
        </p>
        {isTruncated && (
          <button
            type="button"
            className="scl-testimonial__read-more"
            onClick={() => setOpenTestimonial({ item, featured })}
          >
            {t("testimonials.readMore")}
          </button>
        )}
      </>
    );
  };

  return (
    <section id="depoimentos" className="scl-section scl-section--paper">
      <div className="scl-container">
        <div className="scl-section__head">
          <div>
            <div className="scl-eyebrow">
              <span className="scl-rule" /> {t("testimonials.eyebrow")}
            </div>
            <h2 className="scl-h2">{t("testimonials.title")}</h2>
          </div>
          <div>
            <p className="scl-lead scl-section__head-sub">
              {t("testimonials.sub")}
            </p>
            <a
              href={GOOGLE_REVIEWS_URL}
              target="_blank"
              rel="noopener noreferrer"
              className="scl-btn scl-btn--ghost"
              style={{ marginTop: 16 }}
            >
              {t("testimonials.googleReviewsCta")}{" "}
              <Icon name="arrow-up-right" size={14} />
            </a>
          </div>
        </div>

        {featured.map((item, i) => (
          <article
            key={i}
            className="scl-testimonial scl-testimonial--featured"
          >
            <Icon name="quote" size={28} />
            {renderQuote(item, FEATURED_QUOTE_CHAR_LIMIT, true)}
            {renderStars(item.rating)}
            {renderBy(item, true)}

          </article>
        ))}

        <div
          className={
            "scl-carousel-fade scl-testimonials-carousel-wrap" +
            (atEnd ? " is-end" : "")
          }
        >
          <div
            className={
              "scl-testimonials-carousel" + (isDragging ? " is-dragging" : "")
            }
            ref={trackRef}
            onScroll={updateEdges}
            {...dragHandlers}
          >
            {rest.map((item, i) => {
              const isPrevEdge = i === edge.first && !atStart;
              const isNextEdge = i === edge.last && !atEnd;
              const goEdge = (e) => {
                if (e.target.closest("a") || e.target.closest("button")) return;
                if (isPrevEdge) scrollByCard(-1);
                else if (isNextEdge) scrollByCard(1);
              };
              return (
                <article
                  key={i}
                  ref={setCardRef(i)}
                  className={
                    "scl-testimonial" +
                    (isPrevEdge || isNextEdge ? " scl-carousel-card--edge" : "")
                  }
                  onClick={isPrevEdge || isNextEdge ? goEdge : undefined}
                >
                  {renderStars(item.rating)}
                  {renderQuote(item, REST_QUOTE_CHAR_LIMIT, false)}
                  {renderBy(item)}
                </article>
              );
            })}
          </div>
        </div>

        {scrollable && (
          <div className="scl-carousel-nav scl-carousel-nav--below">
            <button
              type="button"
              className="scl-carousel-nav-btn"
              onClick={() => scrollByCard(-1)}
              disabled={atStart}
              aria-label={t("testimonials.prevAria")}
            >
              <Icon name="chevron-left" size={18} />
            </button>
            <button
              type="button"
              className="scl-carousel-nav-btn scl-carousel-nav-btn--next"
              onClick={() => scrollByCard(1)}
              disabled={atEnd}
              aria-label={t("testimonials.nextAria")}
            >
              <Icon name="chevron-right" size={20} />
            </button>
          </div>
        )}

        <div className="scl-testimonials__cta">
          <div className="scl-h5">{t("testimonials.ctaTitle")}</div>
          <div className="scl-testimonials__cta-actions">
            <a
              href={GOOGLE_WRITE_REVIEW_URL}
              target="_blank"
              rel="noopener noreferrer"
              className="scl-btn scl-btn--secondary"
            >
              {t("testimonials.writeReviewCta")}
            </a>
            <a
              href={scWhatsAppHref()}
              target="_blank"
              rel="noopener noreferrer"
              className="scl-btn scl-btn--primary"
            >
              {t("common.ctaPrimary")} <Icon name="arrow-right" size={16} />
            </a>
          </div>
        </div>
      </div>

      {openTestimonial && (
        <TestimonialDialog
          item={openTestimonial.item}
          featured={openTestimonial.featured}
          onClose={() => setOpenTestimonial(null)}
        />
      )}
    </section>
  );
};

window.Testimonials = Testimonials;
