/* B28 HospeX — Visão Geral (home consolidada multi-hotel) */
function ViewOverview({ hotelId, go }) {
  const [dash, setDash] = useState(null);
  const [hotels, setHotels] = useState([]);
  const [alerts, setAlerts] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let canceled = false;
    async function load() {
      try {
        const qs = hotelId ? `?hotel_id=${encodeURIComponent(hotelId)}` : '';

        const [dashRes, hotelsRes, alertsRes] = await Promise.all([
          fetch(`/api/dashboard${qs}`),
          fetch('/api/metrics/hotels_nps'),
          fetch(`/api/alerts${qs}`)
        ]);

        const dashJson = await dashRes.json();
        const hotelsJson = await hotelsRes.json();
        const alertsJson = await alertsRes.json();

        if (canceled) return;
        setDash(dashJson?.ok ? dashJson : null);
        setHotels(Array.isArray(hotelsJson?.hotels) ? hotelsJson.hotels : []);
        setAlerts(Array.isArray(alertsJson?.alerts) ? alertsJson.alerts : []);
      } catch (e) {
        if (!canceled) {
          setDash(null);
          setHotels([]);
          setAlerts([]);
        }
      } finally {
        if (!canceled) setLoading(false);
      }
    }
    load();
    return () => {
      canceled = true;
    };
  }, [hotelId]);

  const npsCurrent = dash?.nps?.current;
  const npsPrev = dash?.nps?.previous;
  const npsDelta = (npsCurrent != null && npsPrev != null) ? (npsCurrent - npsPrev) : null;

  const repAvg = dash?.reputation?.avg10;
  const reviewsTotal = dash?.reputation?.total ?? 0;

  const casesOpen = dash?.cases_open ?? 0;

  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>
  );

  return (
    <div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 18, marginBottom: 22 }}>
        <Stat label="NPS" value={npsCurrent ?? '—'} delta={npsDelta ?? 0} icon="sentiment_satisfied" accent="var(--primary)" />
        <Stat label="Reputação média" value={repAvg ?? '—'} unit="/10" icon="star" accent="#caa53a" />
        <Stat label="Casos abertos" value={casesOpen} icon="flag" accent="var(--error)" />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.35fr 1fr", gap: 18, marginBottom: 22 }}>
        <Card pad={26}>
          <SectionHead eyebrow={hotelId ? "Hotel selecionado" : "Toda a rede"} title="Ranking por NPS"
            right={<button onClick={() => go("surveys")} className="hx-link">Ver pesquisas <Icon name="arrow_forward" size={15} /></button>} />
          {hotels.length ? (
            <div>
              {[...hotels].sort((a, b) => (b.nps ?? -999) - (a.nps ?? -999)).map((h, i) => (
                <div key={h.id} style={{ display: "grid", gridTemplateColumns: "26px 1fr 120px 70px", alignItems: "center", gap: 12, padding: "11px 0", borderBottom: i < hotels.length - 1 ? "1px solid var(--outline-variant)" : "none" }}>
                  <div className="font-headline" style={{ fontSize: 14, fontWeight: 800, color: i === 0 ? "var(--primary)" : "var(--on-surface-variant)" }}>{i + 1}º</div>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: 13.5, fontWeight: 700, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{h.name}</div>
                    <div style={{ fontSize: 11.5, color: "var(--on-surface-variant)" }}>NPS calculado por respostas reais</div>
                  </div>
                  <div style={{ height: 7, borderRadius: 999, background: "var(--surface-container-high)", overflow: "hidden" }}>
                    <div style={{ width: (((Number(h.nps ?? 0) + 100) / 200) * 100) + "%", height: "100%", background: (h.nps ?? 0) >= 70 ? "var(--primary)" : (h.nps ?? 0) >= 55 ? "#caa53a" : "var(--error)" }}></div>
                  </div>
                  <div style={{ display: "flex", alignItems: "center", justifyContent: "flex-end", gap: 7 }}>
                    <span className="font-headline" style={{ fontSize: 15, fontWeight: 800 }}>{h.nps ?? '—'}</span>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div style={{ padding: 16, borderRadius: 12, background: "var(--surface-container-low)", color: "var(--on-surface-variant)", fontSize: 13 }}>
              Sem hotéis cadastrados. Crie um hotel em <b>Configurações</b> para começar.
            </div>
          )}
        </Card>

        <Card pad={26}>
          <SectionHead eyebrow="Tempo real" title="Alertas"
            right={<span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12, fontWeight: 700, color: "var(--error)" }}><span className="pulse-dot" style={{ width: 8, height: 8, borderRadius: 999, background: "var(--error)" }}></span>Ao vivo</span>} />
          {alerts.length ? (
            <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              {alerts.map((a, i) => (
                <div key={i} onClick={() => go(a.go)} style={{ display: "flex", gap: 12, padding: 12, borderRadius: 12, background: "var(--surface-container-low)", cursor: "pointer", alignItems: "flex-start" }} className="hx-alert">
                  <div style={{ width: 32, height: 32, borderRadius: 9, background: "var(--surface-container-lowest)", display: "grid", placeItems: "center", color: "var(--error)", flexShrink: 0 }}><Icon name={a.type === 'review' ? "rate_review" : "trending_down"} size={18} fill={1} /></div>
                  <div style={{ minWidth: 0, flex: 1 }}>
                    <div style={{ fontSize: 13, fontWeight: 700, lineHeight: 1.3 }}>{a.title}</div>
                    <div style={{ fontSize: 12, color: "var(--on-surface-variant)", marginTop: 2 }}>{a.subtitle}</div>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div style={{ padding: 16, borderRadius: 12, background: "var(--surface-container-low)", color: "var(--on-surface-variant)", fontSize: 13 }}>
              Nenhum alerta recente. Reviews coletadas: <b>{reviewsTotal}</b>.
            </div>
          )}
        </Card>
      </div>
    </div>
  );
}
window.ViewOverview = ViewOverview;
