/* B28 HospeX — Pesquisas de satisfação / NPS */
function ViewSurveys({ hotelId }) {
  const [surveys, setSurveys] = useState([]);
  const [selectedSurveyId, setSelectedSurveyId] = useState(null);
  const [responses, setResponses] = useState([]);
  const [loading, setLoading] = useState(true);
  const [newSurveyName, setNewSurveyName] = useState('');

  async function fetchSurveys() {
    const url = hotelId ? `/api/surveys?hotel_id=${encodeURIComponent(hotelId)}` : '/api/surveys';
    const res = await fetch(url);
    const json = await res.json();
    const list = Array.isArray(json?.surveys) ? json.surveys : [];
    setSurveys(list);
    if (!selectedSurveyId && list.length) setSelectedSurveyId(list[0].id);
  }

  async function fetchResponses(surveyId) {
    if (!surveyId) {
      setResponses([]);
      return;
    }
    const res = await fetch(`/api/surveys/${surveyId}/responses`);
    const json = await res.json();
    setResponses(Array.isArray(json?.responses) ? json.responses : []);
  }

  useEffect(() => {
    let canceled = false;
    async function load() {
      try {
        await fetchSurveys();
      } catch (e) {
        if (!canceled) setSurveys([]);
      } finally {
        if (!canceled) setLoading(false);
      }
    }
    load();
    return () => { canceled = true; };
  }, [hotelId]);

  useEffect(() => {
    fetchResponses(selectedSurveyId);
  }, [selectedSurveyId]);

  async function createSurvey() {
    if (!hotelId) return alert('Selecione um hotel no topo para criar pesquisas.');
    if (!newSurveyName.trim()) return;

    const res = await fetch('/api/surveys', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ hotel_id: hotelId, name: newSurveyName.trim(), is_active: true })
    });
    if (res.ok) {
      setNewSurveyName('');
      await fetchSurveys();
    }
  }

  const total = responses.length;
  const promoters = responses.filter(r => r.score >= 9).length;
  const passives = responses.filter(r => r.score >= 7 && r.score <= 8).length;
  const detractors = responses.filter(r => r.score <= 6).length;
  const nps = total ? Math.round(((promoters - detractors) / total) * 100) : null;

  const pct = (x) => total ? Math.round((x / total) * 100) : 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={nps ?? '—'} icon="sentiment_satisfied" accent="var(--primary)" />
        <Stat label="Respostas" value={total} icon="rate_review" accent="var(--secondary)" />
        <Stat label="Detratores" value={pct(detractors)} unit="%" icon="trending_down" accent="var(--error)" />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "360px 1fr", gap: 18, marginBottom: 22 }}>
        <Card pad={22}>
          <SectionHead eyebrow="Pesquisas" title="Lista" />

          <div style={{ display: 'flex', gap: 8, marginBottom: 14 }}>
            <input value={newSurveyName} onChange={e => setNewSurveyName(e.target.value)} placeholder="Nome da pesquisa" style={{ flex: 1, padding: '11px 12px', borderRadius: 10, border: '1px solid var(--outline-variant)', background: 'var(--surface-container-lowest)' }} />
            <button className="btn btn-primary" onClick={createSurvey} style={{ padding: '10px 14px' }}><Icon name="add" size={16} /> Criar</button>
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {surveys.length ? surveys.map(s => (
              <button key={s.id} onClick={() => setSelectedSurveyId(s.id)} className="hx-opt" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 12px', borderRadius: 12, border: '1px solid ' + (selectedSurveyId === s.id ? 'var(--primary)' : 'var(--outline-variant)'), background: 'var(--surface-container-low)', cursor: 'pointer' }}>
                <span style={{ fontSize: 13, fontWeight: 700 }}>{s.name}</span>
                <span style={{ fontSize: 11, fontWeight: 700, color: s.is_active ? 'var(--primary)' : 'var(--on-surface-variant)' }}>{s.is_active ? 'Ativa' : 'Pausada'}</span>
              </button>
            )) : (
              <div style={{ padding: 14, borderRadius: 12, background: 'var(--surface-container-low)', color: 'var(--on-surface-variant)', fontSize: 13 }}>
                Nenhuma pesquisa cadastrada ainda.
              </div>
            )}
          </div>
        </Card>

        <Card pad={26}>
          <SectionHead eyebrow="Net Promoter Score" title="Composição" right={<Chip bg="var(--surface-container-high)" color="var(--on-surface-variant)">NPS = % promotores − % detratores</Chip>} />

          <div style={{ display: "flex", alignItems: "center", gap: 24 }}>
            <Donut size={148} thickness={24} centerLabel={nps ?? '—'} centerSub="NPS" data={[
              { pct: pct(promoters), color: "var(--primary)" },
              { pct: pct(passives), color: "#e3c46a" },
              { pct: pct(detractors), color: "var(--error)" }
            ]} />
            <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: 14 }}>
              {[{ l: "Promotores", v: pct(promoters), d: "Notas 9–10", c: "var(--primary)" }, { l: "Passivos", v: pct(passives), d: "Notas 7–8", c: "#e3c46a" }, { l: "Detratores", v: pct(detractors), d: "Notas 0–6", c: "var(--error)" }].map((s, i) => (
                <div key={i}>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                    <span style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13, fontWeight: 600 }}><span style={{ width: 10, height: 10, borderRadius: 3, background: s.c }}></span>{s.l}</span>
                    <span className="font-headline" style={{ fontWeight: 800, fontSize: 16 }}>{s.v}%</span>
                  </div>
                  <div style={{ fontSize: 11.5, color: "var(--on-surface-variant)", marginLeft: 18 }}>{s.d}</div>
                </div>
              ))}
            </div>
          </div>

          <div style={{ marginTop: 22, paddingTop: 18, borderTop: "1px solid var(--outline-variant)" }}>
            <div style={{ fontSize: 12.5, fontWeight: 700, color: "var(--on-surface-variant)", marginBottom: 10 }}>Respostas recentes</div>
            {responses.length ? (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                {responses.slice(0, 10).map((r) => (
                  <div key={r.id} style={{ display: "flex", gap: 16, padding: 16, borderRadius: 14, background: "var(--surface-container-low)", alignItems: "flex-start" }}>
                    <div style={{ width: 52, height: 52, borderRadius: 12, display: "grid", placeItems: "center", flexShrink: 0, background: r.score >= 9 ? "var(--primary)" : r.score >= 7 ? "#e3c46a" : "var(--error)", color: "#fff" }}>
                      <span className="font-headline" style={{ fontSize: 22, fontWeight: 800 }}>{r.score}</span>
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap", marginBottom: 6 }}>
                        <span style={{ fontSize: 13.5, fontWeight: 700 }}>{r.guest_name || 'Anônimo'}</span>
                        <SentBadge sent={r.score >= 9 ? 'pos' : r.score >= 7 ? 'neu' : 'neg'} />
                      </div>
                      <div style={{ fontSize: 13.5, color: "var(--on-surface)", lineHeight: 1.5 }}>{r.comment || 'Sem comentário'}</div>
                      <div style={{ display: "flex", alignItems: "center", gap: 12, marginTop: 9 }}>
                        {r.area && <Chip bg="var(--surface-container-high)" color="var(--on-surface-variant)"><Icon name="label" size={12} fill={1} /> {r.area}</Chip>}
                        {r.channel && <span style={{ fontSize: 11.5, color: "var(--on-surface-variant)", display: "inline-flex", alignItems: "center", gap: 4 }}><Icon name="forum" size={13} /> {r.channel}</span>}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div style={{ padding: 16, borderRadius: 12, background: "var(--surface-container-low)", color: "var(--on-surface-variant)", fontSize: 13 }}>
                Sem respostas ainda. Use o endpoint `POST /api/surveys/:id/responses` para ingestão ou conecte os canais.
              </div>
            )}
          </div>
        </Card>
      </div>
    </div>
  );
}
window.ViewSurveys = ViewSurveys;
