/* Avis Google — note + derniers avis (API Google Places, clé facultative) ou, à défaut, boutons vers la fiche Google.
   Réglages dans l'admin : vue « Avis Google ». */
function GoogleStars({ value, size }) {
  const n = Math.round(Number(value) || 0);
  return (
    <span aria-label={n + ' sur 5'} style={{color:'var(--gold-500)',letterSpacing:'0.1em',fontSize:size || 16,whiteSpace:'nowrap'}}>
      {'★'.repeat(n)}<span style={{color:'var(--cream-400)'}}>{'★'.repeat(Math.max(0, 5 - n))}</span>
    </span>
  );
}

function GoogleReviewsSection() {
  const [H,    setH]    = React.useState({});
  const [cfg,  setCfg]  = React.useState(null);   // réglages du site (null = pas encore chargés)
  const [data, setData] = React.useState(null);   // avis : objet, ou false si indisponibles
  const ref = React.useRef();

  React.useEffect(() => {
    BrionServices.getHeaders().then(h => setH(h.temoignages || {}));
    BrionServices.getSiteSettings().then(setCfg).catch(() => setCfg({}));
  }, []);

  // Les avis ne sont demandés à Google que lorsque la section approche de l'écran (limite le nombre de requêtes)
  React.useEffect(() => {
    if (!cfg || !cfg.googlePlaceId || !cfg.googleApiKey || !ref.current) return;
    const load = async () => {
      const key = 'brion-greviews:' + cfg.googlePlaceId;
      try {
        const cached = sessionStorage.getItem(key);
        if (cached) { const c = JSON.parse(cached); if (Date.now() - c.t < 3600000) { setData(c.d); return; } }
      } catch (e) {}
      try {
        const d = await BrionServices.fetchGoogleReviews(cfg.googlePlaceId, cfg.googleApiKey);
        setData(d);
        try { sessionStorage.setItem(key, JSON.stringify({ t: Date.now(), d })); } catch (e) {}
      } catch (e) { setData(false); }
    };
    const obs = new IntersectionObserver(es => { if (es.some(x => x.isIntersecting)) { obs.disconnect(); load(); } }, { rootMargin: '300px' });
    obs.observe(ref.current);
    return () => obs.disconnect();
  }, [cfg]);

  // Tant que la fiche Google n'est pas renseignée dans l'admin, rien à afficher
  if (!cfg || !cfg.googlePlaceId) return <section id="temoignages" ref={ref} />;

  const id = cfg.googlePlaceId;
  const seeUrl   = 'https://www.google.com/maps/search/?api=1&query=Domaine%20de%20Brion&query_place_id=' + encodeURIComponent(id);
  const writeUrl = 'https://search.google.com/local/writereview?placeid=' + encodeURIComponent(id);
  const reviews  = (data && data.reviews) || [];
  const hasReviews = reviews.length > 0;

  return (
    <section id="temoignages" ref={ref} className="section reveal visible">
      <div className="container" style={{maxWidth:'72rem'}}>
        <div className="section-head">
          <span className="eyebrow">{H.eyebrow || 'Témoignages'}</span>
          <hr className="rule-gold rule-gold--center" />
          <h2>{H.title || 'Ce qu’ils en disent...'}</h2>
          {data && data.rating && (
            <p style={{margin:'var(--space-3) 0 0',display:'flex',alignItems:'center',justifyContent:'center',gap:10,flexWrap:'wrap'}}>
              <span style={{fontFamily:'var(--font-display)',fontSize:34,lineHeight:1}}>{String(data.rating).replace('.', ',')}</span>
              <GoogleStars value={data.rating} size={20} />
              <span className="small" style={{color:'var(--stone-50)'}}>sur {data.count} avis Google</span>
            </p>
          )}
        </div>

        {hasReviews ? (
          <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit, minmax(280px, 1fr))',gap:'var(--space-5)'}}>
            {reviews.map((r, i) => (
              <article key={i} className="card" style={{display:'flex',flexDirection:'column',gap:12}}>
                <div style={{display:'flex',alignItems:'center',gap:10}}>
                  {r.photo && <img src={r.photo} alt="" width="38" height="38" referrerPolicy="no-referrer" loading="lazy" style={{borderRadius:'50%',objectFit:'cover',flexShrink:0}} />}
                  <div style={{minWidth:0}}>
                    <div style={{fontSize:15,fontWeight:500,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>
                      {r.authorUri ? <a href={r.authorUri} target="_blank" rel="noopener noreferrer" style={{color:'inherit',textDecoration:'none'}}>{r.author}</a> : r.author}
                    </div>
                    <div className="caption">{r.when}</div>
                  </div>
                </div>
                <GoogleStars value={r.rating} />
                {r.text && <p style={{margin:0,fontSize:15,lineHeight:1.65,display:'-webkit-box',WebkitLineClamp:8,WebkitBoxOrient:'vertical',overflow:'hidden'}}>{r.text}</p>}
              </article>
            ))}
          </div>
        ) : (
          <p className="lede" style={{textAlign:'center',maxWidth:'40rem',margin:'0 auto'}}>
            Découvrez ce que nos clients disent de nous sur Google, et partagez votre propre expérience.
          </p>
        )}

        <div style={{display:'flex',justifyContent:'center',gap:'var(--space-4)',flexWrap:'wrap',marginTop:'var(--space-6)'}}>
          <a className="btn btn-secondary" href={seeUrl} target="_blank" rel="noopener noreferrer">Voir tous les avis sur Google</a>
          <a className="btn btn-primary" href={writeUrl} target="_blank" rel="noopener noreferrer">Laisser un avis</a>
        </div>
        {hasReviews && <p className="caption" style={{textAlign:'center',marginTop:'var(--space-4)'}}>Avis publiés sur Google · les {reviews.length} plus pertinents</p>}
      </div>
    </section>
  );
}
window.GoogleReviewsSection = GoogleReviewsSection;
