/* MaliTech – Google Reviews component
   Fetches reviews via /api/google-reviews (server-side proxy to Google Places).
   This means the user's browser never contacts Google directly — no third-
   party transfer from the visitor's IP, so no Cookie-Consent is required.
   Falls back to a small static set if the endpoint is unreachable. */

const REVIEWS_ENDPOINT = (typeof window !== 'undefined' && window.MALITECH_API_BASE ? window.MALITECH_API_BASE : '') + '/api/google-reviews';

const REVIEW_FALLBACK = {
  reviews: [
    {
      author_name: "Lukas Gross",
      rating: 5,
      text: "Endlich IT, die einfach funktioniert. MaliTech Solutions hat uns echt überzeugt. Keine leeren Versprechen, sondern praxisnahe Beratung und Lösungen, die zu unserem Unternehmen top gepasst haben. Besonders stark: moderne IT-Strukturen, ohne gleich das ganze Budget zu sprengen. Technisch top, super transparent und dabei angenehm unkompliziert.",
      relative_time_description: "vor 12 Monaten",
      profile_photo_url: "" },

    {
      author_name: "Frau Schero",
      rating: 5,
      text: "Ich kann MaliTech Solutions nur weiterempfehlen. Die Betreuung ist erstklassig und die Preis-Leistung stimmt absolut. Alle Anliegen wurden in kürzester Zeit professionell und zuverlässig erledigt und sogar darüber hinaus. Ein Service wie man ihn sich wünscht: schnell, kompetent und kundenorientiert. Absolut Top.",
      relative_time_description: "vor 11 Monaten",
      profile_photo_url: "" },

    {
      author_name: "Jr Brungs",
      rating: 5,
      text: "MaliTech Solutions hat unsere IT komplett überarbeitet – alles lief reibungslos und ohne Unterbrechung. Super Kommunikation, schnelle Reaktion im Support und durchdachte Lösungen, die uns im Alltag echt helfen. Kann ich jedem Unternehmen nur empfehlen.",
      relative_time_description: "vor 10 Monaten",
      profile_photo_url: "" },

    {
      author_name: "Philipp",
      rating: 5,
      text: "Mega zuverlässiger IT-Dienstleister. Absprache und Abwicklung waren super. Ganz klare Empfehlung für jeden mit Bedarf an professionellen IT-Lösungen.",
      relative_time_description: "vor 10 Monaten",
      profile_photo_url: "" },

    {
      author_name: "Mauritz M",
      rating: 5,
      text: "Schnelle Umsetzung und verlässlicher Service — genau so, wie ich mir ein IT-Haus vorstelle!",
      relative_time_description: "vor 10 Monaten",
      profile_photo_url: "" }],


  averageRating: 5.0,
  reviewCount: 5
};



function GoogleLogo() {
  return (
    <svg viewBox="0 0 24 24" width="22" height="22" aria-hidden="true">
      <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4" />
      <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-1 .67-2.28 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853" />
      <path d="M5.84 14.09c-.22-.67-.35-1.39-.35-2.09s.13-1.42.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l3.66-2.84z" fill="#FBBC05" />
      <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335" />
    </svg>);

}

function StarRow({ count = 5, size = 14 }) {
  const filled = Math.round(count);
  return (
    <span className="gr-stars" aria-label={`${filled} von 5 Sternen`} style={{ fontSize: size }}>
      {'★'.repeat(filled)}{'☆'.repeat(Math.max(0, 5 - filled))}
    </span>);

}

function initials(name) {
  if (!name) return "?";
  return name.trim().split(/\s+/).map((p) => p[0]).join("").slice(0, 2).toUpperCase();
}

function GoogleReviewCard({ review }) {
  const text = review.text || "";
  const truncated = text.length > 280 ? text.slice(0, 280).trimEnd() + "…" : text;
  return (
    <article className="gr-card">
      <header className="gr-card-head">
        <StarRow count={review.rating} size={15} />
        <span className="gr-card-date">{review.relative_time_description || "Kürzlich"}</span>
      </header>
      <p className="gr-card-quote">„{truncated}"</p>
      <footer className="gr-card-author">
        {review.profile_photo_url ?
        <img className="gr-avatar-img" src={review.profile_photo_url} alt={review.author_name} loading="lazy" /> :

        <span className="gr-avatar-fb">{initials(review.author_name)}</span>
        }
        <div className="gr-author-info">
          <strong>{review.author_name}</strong>
          <span><GoogleLogo /> Google Rezension</span>
        </div>
      </footer>
    </article>);

}

async function fetchGoogleReviews() {
  try {
    const response = await fetch(REVIEWS_ENDPOINT, { headers: { Accept: 'application/json' } });
    if (!response.ok) throw new Error('Reviews endpoint ' + response.status);
    const data = await response.json();
    if (!data || !Array.isArray(data.reviews)) throw new Error('Bad payload');
    return {
      reviews: data.reviews,
      averageRating: data.averageRating != null ? data.averageRating : REVIEW_FALLBACK.averageRating,
      reviewCount:   data.reviewCount   != null ? data.reviewCount   : REVIEW_FALLBACK.reviewCount
    };
  } catch (err) {
    console.warn('[GoogleReviews] using fallback –', err.message);
    return REVIEW_FALLBACK;
  }
}

function GoogleReviewsCarousel() {
  const [data, setData] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [idx, setIdx] = React.useState(0);
  const [paused, setPaused] = React.useState(false);
  const trackRef = React.useRef(null);

  // Reviews load via our own /api/google-reviews endpoint, which proxies
  // Google Places server-side. The visitor's browser never contacts Google.
  React.useEffect(() => {
    let alive = true;
    fetchGoogleReviews().then((d) => {
      if (!alive) return;
      setData(d);
      setLoading(false);
    });
    return () => {alive = false;};
  }, []);

  const reviews = data?.reviews || [];
  const N = reviews.length;
  // Duplicate the list for a seamless wrap. When idx crosses into the
  // duplicate half, we silently snap back to the equivalent slot in the
  // first half so the loop continues forever without a visible jump.
  const list = N > 0 ? [...reviews, ...reviews] : [];

  // Scroll to current idx whenever it changes (scroll the carousel track
  // ONLY, never let it bubble up to the document scroll)
  React.useEffect(() => {
    if (!N) return;
    const t = trackRef.current;
    if (!t) return;
    const cards = t.querySelectorAll(".gr-card");
    const target = cards[idx];
    if (target) {
      const left = target.offsetLeft - t.offsetLeft;
      t.scrollTo({ left, behavior: "smooth" });
    }
  }, [idx, N]);

  // When idx lands in the duplicate half, snap back invisibly after the
  // smooth scroll completes.
  React.useEffect(() => {
    if (!N || idx < N) return;
    const timer = setTimeout(() => {
      const t = trackRef.current;
      if (!t) return;
      const cards = t.querySelectorAll(".gr-card");
      const target = cards[idx - N];
      if (target) {
        // Direct scrollLeft assignment is instant and only affects the
        // carousel — it never bubbles to the document.
        t.scrollLeft = target.offsetLeft - t.offsetLeft;
      }
      setIdx((i) => i - N);
    }, 650);
    return () => clearTimeout(timer);
  }, [idx, N]);

  // Auto-rotate every 15s (pause on hover or while loading)
  React.useEffect(() => {
    if (!N || paused || loading) return;
    const id = setInterval(() => setIdx((i) => i + 1), 15000);
    return () => clearInterval(id);
  }, [N, paused, loading]);

  const next = () => setIdx((i) => i + 1);
  const prev = () => {
    if (!N) return;
    if (idx === 0) {
      // Jump invisibly to the start of the duplicate half, then animate
      // back one card so the previous review slides in from the left.
      const t = trackRef.current;
      if (!t) return;
      const cards = t.querySelectorAll(".gr-card");
      const target = cards[N];
      if (target) {
        t.scrollLeft = target.offsetLeft - t.offsetLeft;
      }
      setIdx(N - 1);
    } else {
      setIdx((i) => i - 1);
    }
  };

  const avg = data?.averageRating ?? 4.9;
  const count = data?.reviewCount ?? 0;

  return (
    <div
      className="google-reviews"
      onMouseEnter={() => setPaused(true)}
      onMouseLeave={() => setPaused(false)}>
      <div className="gr-header">
        <div className="gr-header-meta">
          <div className="gr-brand">
            <GoogleLogo />
            <span>Google Reviews</span>
          </div>
          <div className="gr-rating-row">
            <StarRow count={avg} size={18} />
            <strong className="gr-rating-score">{avg.toFixed(1)}</strong>
            <span className="gr-rating-count">
              {loading ? "lädt …" : `(${count} Bewertungen)`}
            </span>
          </div>
        </div>
        <div className="gr-nav">
          <button type="button" className="gr-nav-btn" onClick={prev} aria-label="Vorherige Bewertungen">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="15 18 9 12 15 6" /></svg>
          </button>
          <button type="button" className="gr-nav-btn" onClick={next} aria-label="Nächste Bewertungen">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 18 15 12 9 6" /></svg>
          </button>
        </div>
      </div>

      <div className="gr-track-wrap">
        <div className="gr-track" ref={trackRef}>
          {loading ?
          [0, 1, 2].map((i) =>
          <div key={i} className="gr-card gr-card-skeleton">
                <div className="gr-skel gr-skel-row" />
                <div className="gr-skel gr-skel-block" />
                <div className="gr-skel gr-skel-row short" />
              </div>
          ) :

          list.map((r, i) => <GoogleReviewCard key={i} review={r} />)
          }
        </div>
      </div>
    </div>);

}

/* Wrapper. Reviews werden serverseitig über /api/google-reviews geladen,
   nicht aus dem Browser des Nutzers — kein Cookie-Consent erforderlich. */
function GoogleReviews() {
  return <GoogleReviewsCarousel/>;
}

window.GoogleReviews = GoogleReviews;
