/* B28 HospeX — Reputação online */
function ViewReputation({ hotelId }) {
  const [reviews, setReviews] = useState([]);
  const [loading, setLoading] = useState(true);
  const [sel, setSel] = useState(null);
  const [replyText, setReplyText] = useState("");
  const [isReplying, setIsReplying] = useState(false);
  const [publishExternal, setPublishExternal] = useState(true);

  const fetchReviews = async () => {
    try {
      const url = hotelId ? `/api/reviews?hotel_id=${encodeURIComponent(hotelId)}` : '/api/reviews';
      const res = await fetch(url);
      const json = await res.json();
      if (json.reviews) {
        setReviews(json.reviews);
        if (json.reviews.length > 0 && !sel) setSel(json.reviews[0].id);
      }
    } catch (e) {
      console.error("Erro ao carregar avaliações", e);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchReviews();
  }, []);

  const review = reviews.find(r => r.id === sel) || (reviews.length > 0 ? reviews[0] : null);

  async function handleReply() {
    if (!review || !replyText) return;
    setIsReplying(true);
    try {
      const res = await fetch(`/api/reviews/${review.id}/reply`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ content: replyText, publish: publishExternal && (review.channel === 'Google' || review.channel === 'Booking.com') })
      });
      if (res.ok) {
        setReplyText("");
        fetchReviews();
      }
    } catch (e) {
      console.error("Erro ao responder", e);
    } finally {
      setIsReplying(false);
    }
  }

  function draftFor(r) {
    if (!r) return { tone: "—", lang: "PT", text: "" };
    if (r.reply_content) return { tone: "Respondido", lang: r.language?.toUpperCase() || "PT", text: r.reply_content };
    
    const lang = r.language?.toUpperCase() || "PT";
    const author = r.author_name || "Hóspede";
    const hotel = r.hotel_name || "Hotel";

    if (r.sentiment === "pos" || r.rating >= 4) return {
      tone: "Cordial · caloroso", lang: lang,
      text: lang === "EN"
        ? `Dear ${author}, thank you so much for your kind words about ${hotel}. It means a lot to our team. We can't wait to welcome you back. Warm regards, Equipe Costa Viva.`
        : `Olá, ${author}! Muito obrigado por compartilhar sua experiência no ${hotel}. Ficamos felizes que tenha gostado da estadia. Será um prazer receber você novamente. Abraço, Equipe Costa Viva.`,
    };
    return {
      tone: "Cordial · resolutivo", lang: lang,
      text: lang === "ES"
        ? `Estimada ${author}, gracias por sus comentarios sobre ${hotel}. Lamentamos lo ocurrido e já estamos trabalhando para melhorarlo. Nos encantaría recibirle de nuevo. Un cordial saludo, Equipo Costa Viva.`
        : `Olá, ${author}. Agradecemos seu retorno sobre o ${hotel}. Lamentamos o ocorrido — já estamos atuando para corrigir. Adoraríamos receber você novamente para mostrar a evolução. Abraço, Equipe Costa Viva.`,
    };
  }

  const draft = draftFor(review);

  useEffect(() => {
    if (review && !review.reply_content) {
      setReplyText(draft.text);
    } else if (review && review.reply_content) {
      setReplyText(review.reply_content);
    }
  }, [review]);

  useEffect(() => {
    if (!review) return;
    setPublishExternal(review.channel === 'Google' || review.channel === 'Booking.com');
  }, [review?.id]);

  if (loading) return (
    <div style={{ display: 'grid', placeItems: 'center', height: '40vh' }}>
      <Icon name="progress_activity" size={40} className="hx-spin" style={{ color: 'var(--primary)' }} />
    </div>
  );

  const displayReviews = reviews;

  const otaColors = {
    'Booking.com': '#003580',
    'Google': '#34a853',
    'TripAdvisor': '#00aa6c',
    'Facebook': '#1877f2',
    'Expedia': '#ffc94d',
    'Airbnb': '#ff5a5f'
  };

  const responseRate = reviews.length ? Math.round((reviews.filter(r => r.reply_content).length / reviews.length) * 100) : 0;
  const avg10 = reviews.length
    ? Math.round(
        (reviews.reduce((acc, r) => acc + (Number(r.rating || 0) / Number(r.max_rating || 10)) * 10, 0) / reviews.length) * 10
      ) / 10
    : 0;

  return (
    <div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 18, marginBottom: 22 }}>
        <Stat label="Avaliações" value={reviews.length} icon="reviews" accent="var(--secondary)" />
        <Stat label="Taxa de resposta" value={responseRate} unit="%" icon="reply_all" accent="#caa53a" />
        <Stat label="Nota média" value={avg10} unit="/10" icon="star" accent="#caa53a" />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 18, marginBottom: 22 }}>
        {/* Reviews feed */}
        <Card pad={26}>
          <SectionHead eyebrow="Coleta automática · Booking · Google · TripAdvisor · Facebook" title="Avaliações centralizadas"
            right={<button className="hx-link" onClick={fetchReviews}>Atualizar <Icon name="refresh" size={15} /></button>} />
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            {displayReviews.map(r => (
              <div key={r.id} onClick={() => setSel(r.id)} className="hx-review"
                style={{ padding: 18, borderRadius: 14, cursor: "pointer", border: "1.5px solid " + (sel === r.id ? "var(--primary)" : "transparent"), background: sel === r.id ? "color-mix(in srgb, var(--primary) 5%, var(--surface-container-low))" : "var(--surface-container-low)" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 10 }}>
                  <Avatar name={r.author_name || r.author} size={40} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                      <span style={{ fontSize: 13.5, fontWeight: 700 }}>{r.author_name || r.author}</span>
                      <span style={{ fontSize: 10.5, fontWeight: 700, padding: "2px 7px", borderRadius: 999, background: "var(--surface-container-high)" }}>{r.language || r.lang || 'PT'}</span>
                    </div>
                    <div style={{ fontSize: 11.5, color: "var(--on-surface-variant)" }}>{r.hotel_name || r.hotel} · {r.date || 'Recente'}</div>
                  </div>
                  <div style={{ textAlign: "right" }}>
                    <OtaTag ota={r.channel || r.ota} color={otaColors[r.channel || r.ota] || "#888"} size={11.5} />
                    <div style={{ marginTop: 4, display: "flex", alignItems: "center", gap: 3, justifyContent: "flex-end" }}>
                      {(r.max_rating || r.scale) === 5
                        ? [1, 2, 3, 4, 5].map(s => <Icon key={s} name="star" size={14} fill={s <= r.rating ? 1 : 0} style={{ color: s <= r.rating ? "#e3a72f" : "var(--outline-variant)" }} />)
                        : <span className="font-headline" style={{ fontWeight: 800, fontSize: 15 }}>{r.rating}<span style={{ fontSize: 11, color: "var(--on-surface-variant)" }}>/{r.max_rating || r.scale || 10}</span></span>}
                    </div>
                  </div>
                </div>
                <div style={{ fontSize: 13.5, lineHeight: 1.55, color: "var(--on-surface)" }}>{r.content || r.text}</div>
                <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 11, flexWrap: "wrap" }}>
                  <SentBadge sent={r.sentiment || r.sent} />
                  {(r.themes || []).map((t, i) => <Chip key={i} bg="var(--surface-container-high)" color="var(--on-surface-variant)">{t}</Chip>)}
                  <span style={{ marginLeft: "auto", fontSize: 11.5, fontWeight: 700, color: (r.reply_content || r.replied) ? "var(--primary)" : "var(--error)", display: "inline-flex", alignItems: "center", gap: 4 }}>
                    <Icon name={(r.reply_content || r.replied) ? "check_circle" : "schedule"} size={14} fill={1} />{(r.reply_content || r.replied) ? "Respondida" : "Aguardando resposta"}
                  </span>
                </div>
              </div>
            ))}
          </div>
        </Card>

        {/* Smart reply + IRO */}
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          <Card pad={24} style={{ background: "var(--inverse-surface)", border: "none" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 14 }}>
              <span style={{ width: 32, height: 32, borderRadius: 9, background: "var(--primary)", display: "grid", placeItems: "center" }}><Icon name="auto_awesome" size={18} fill={1} style={{ color: "#fff" }} /></span>
              <div>
                <div className="font-headline" style={{ fontSize: 15, fontWeight: 800, color: "#fff" }}>Smart Reply</div>
                <div style={{ fontSize: 11, color: "var(--primary-fixed-dim)" }}>{review?.reply_content ? "Resposta enviada" : "Resposta gerada por IA"}</div>
              </div>
            </div>
            <div style={{ display: "flex", gap: 8, marginBottom: 14, flexWrap: "wrap" }}>
              <span style={{ fontSize: 11, fontWeight: 700, padding: "5px 11px", borderRadius: 999, background: "rgba(255,255,255,0.08)", color: "var(--primary-fixed-dim)" }}><Icon name="translate" size={12} style={{ verticalAlign: "-2px", marginRight: 4 }} />{draft.lang}</span>
              <span style={{ fontSize: 11, fontWeight: 700, padding: "5px 11px", borderRadius: 999, background: "rgba(255,255,255,0.08)", color: "var(--primary-fixed-dim)" }}><Icon name="graphic_eq" size={12} style={{ verticalAlign: "-2px", marginRight: 4 }} />{draft.tone}</span>
            </div>
            
            <textarea 
              value={replyText} 
              onChange={e => setReplyText(e.target.value)}
              disabled={review?.reply_content || isReplying}
              style={{ 
                width: "100%", 
                background: "rgba(255,255,255,0.05)", 
                borderRadius: 12, 
                padding: 16, 
                fontSize: 13, 
                lineHeight: 1.6, 
                color: "rgba(255,255,255,0.92)", 
                height: 180, 
                border: "1px solid rgba(255,255,255,0.1)",
                resize: "none",
                fontFamily: "inherit"
              }} 
            />

            <div style={{ display: "flex", gap: 10, marginTop: 16 }}>
              {!review?.reply_content ? (
                <button 
                  className="btn btn-primary" 
                  onClick={handleReply}
                  disabled={isReplying || !replyText}
                  style={{ flex: 1, justifyContent: "center", fontSize: 13.5, padding: "11px 18px" }}
                >
                  {isReplying ? <Icon name="progress_activity" size={16} className="hx-spin" /> : <Icon name="send" size={16} />} Publicar
                </button>
              ) : (
                <div style={{ flex: 1, color: "var(--primary-fixed-dim)", fontSize: 13, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 6 }}>
                  <Icon name="check_circle" size={16} /> Resposta publicada com sucesso
                </div>
              )}
              {!review?.reply_content && (
                <>
                  <button onClick={() => setReplyText(draft.text)} style={{ width: 44, height: 44, borderRadius: 999, border: "none", background: "rgba(255,255,255,0.1)", color: "#fff", cursor: "pointer", display: "grid", placeItems: "center" }}><Icon name="refresh" size={19} /></button>
                </>
              )}
            </div>

            {!review?.reply_content && (review?.channel === 'Google' || review?.channel === 'Booking.com') && (
              <label style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 14, cursor: 'pointer', userSelect: 'none' }}>
                <span onClick={() => setPublishExternal(p => !p)} style={{ width: 20, height: 20, borderRadius: 6, border: '1.5px solid ' + (publishExternal ? 'var(--primary-fixed-dim)' : 'rgba(255,255,255,0.25)'), background: publishExternal ? 'var(--primary)' : 'transparent', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                  {publishExternal && <Icon name="check" size={14} style={{ color: '#fff' }} />}
                </span>
                <span style={{ fontSize: 12.5, color: 'rgba(255,255,255,0.75)' }}>Publicar resposta no canal ({review.channel})</span>
              </label>
            )}
          </Card>

          <Card pad={24}>
            <Eyebrow style={{ marginBottom: 8 }}>Integrações de canais</Eyebrow>
            <div className="font-headline" style={{ fontSize: 16, fontWeight: 800, marginBottom: 6 }}>Recebimento e resposta dentro do sistema</div>
            <div style={{ fontSize: 13, color: "var(--on-surface-variant)", lineHeight: 1.55 }}>
              Para dados 100% reais, conecte os canais em <b>Integrações</b> (Google/Booking/TripAdvisor) e/ou envie reviews via webhook.
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}
window.ViewReputation = ViewReputation;
