// survey.jsx — встроенный интерактивный опрос

function Survey({ visible }) {
  if (!visible) return null;

  const schema = window.SURVEY_SCHEMA;
  const isMiniApp = Boolean(window.__TG_INIT_DATA);
  const questions = isMiniApp ? schema.questions.filter((q) => q.kind !== "contact") : schema.questions;
  const sections = schema.sections.reduce((acc, section) => ({ ...acc, [section.id]: section }), {});
  const draftKey = `ekokrug-survey-draft-${schema.schema_version}`;
  const params = new URLSearchParams(window.location.search);
  const startParam = params.get("tgWebAppStartParam") || window.__TG_WEB_APP?.initDataUnsafe?.start_param || "";
  const source = params.get("source") || (isMiniApp ? "tg" : "");

  const [step, setStep] = React.useState(0);
  const [answers, setAnswers] = React.useState(() => {
    try {
      return JSON.parse(localStorage.getItem(draftKey) || "{}");
    } catch (e) {
      return {};
    }
  });
  const [website, setWebsite] = React.useState(""); // honeypot
  const [sending, setSending] = React.useState(false);
  const [totalResponses, setTotalResponses] = React.useState(null);
  const total = questions.length;

  React.useEffect(() => {
    localStorage.setItem(draftKey, JSON.stringify(publicAnswers()));
  }, [answers]);

  React.useEffect(() => {
    if (step !== 0) return;
    fetch("/api/results.php")
      .then((r) => r.json())
      .then((d) => { if (d && d.ok) setTotalResponses(d.count); })
      .catch(() => {});
  }, [step]);

  const setAns = (id, v) => setAnswers((a) => ({ ...a, [id]: v }));

  const getContact = () => {
    const raw = answers.contact || {};
    if (raw.intent === "Пока без контакта") return null;
    if (!raw.value || !raw.value.trim()) return null;
    return {
      intent: raw.intent || "Хочу получить итоги",
      value: raw.value.trim()
    };
  };

  const publicAnswers = () => {
    const copy = { ...answers };
    delete copy.contact;
    return copy;
  };

  const submit = async () => {
    setSending(true);
    try {
      const headers = { "Content-Type": "application/json" };
      if (window.__TG_INIT_DATA) {
        headers["X-Telegram-Init-Data"] = window.__TG_INIT_DATA;
      }
      await fetch("/api/survey.php", {
        method: "POST",
        headers,
        body: JSON.stringify({
          schema_version: schema.schema_version,
          source,
          start_param: startParam,
          answers: publicAnswers(),
          contact: getContact(),
          website
        })
      });
      localStorage.removeItem(draftKey);
    } catch (e) {
      // Всё равно показываем спасибо: не оставляем человека в тупике.
    }
    setSending(false);
    setStep(total + 1);
  };

  const next = () => {
    if (step === total) { submit(); return; }
    setStep((s) => Math.min(s + 1, total + 1));
  };
  const prev = () => setStep((s) => Math.max(s - 1, 0));

  const progress = step === 0 ? 0 : step > total ? 100 : Math.round(step / total * 100);

  if (step === 0) {
    return (
      <section id="survey" className="section-bg-soft">
        <div className="wrap">
          <div className="section-head">
            <div>
              <div className="eyebrow">{schema.intro.eyebrow}</div>
              <h2 className="display h2" style={{ marginTop: 16 }}>{schema.intro.heading}</h2>
              <button className="btn btn-primary survey-start-top" onClick={next}>
                Начать опрос <span className="arrow">→</span>
              </button>
            </div>
            <p className="lead">{schema.intro.lead}</p>
          </div>

          <div className="survey-card">
            <div className="survey-intro">
              <div className="survey-emoji">✦</div>
              <h3 className="display" style={{ fontSize: 30, fontWeight: 500, margin: 0 }}>
                {schema.title}
              </h3>
              <button className="btn btn-primary survey-start-main" onClick={next}>
                Начать опрос <span className="arrow">→</span>
              </button>
              <p className="lead" style={{ marginTop: 18, fontSize: 16 }}>
                {total} вопросов. Можно отвечать коротко, но честно. Если вопрос не про вас — так и напишите.
              </p>
              {isMiniApp &&
                <p className="survey-private" style={{ maxWidth: "52ch", margin: "14px auto 0" }}>
                  Контакт возьмём из Telegram автоматически, вручную вводить его не нужно.
                </p>
              }
              <div className="survey-promise">
                {schema.intro.promises.map((item) =>
                  <div className="prom" key={item.title}><b>{item.title}</b>{item.text}</div>
                )}
              </div>
              {totalResponses !== null && totalResponses > 0 &&
                <div className="survey-counter">
                  <span className="dot" />
                  <span><b>{totalResponses}</b> {ruPersonCount(totalResponses)} уже {ruSharedVerb(totalResponses)} опытом</span>
                </div>
              }
            </div>
          </div>
        </div>
      </section>
    );
  }

  if (step > total) {
    return (
      <section id="survey" className="section-bg-soft">
        <div className="wrap">
          <div className="survey-card done">
            <div className="survey-done">
              <div className="check" aria-hidden="true">
                <svg viewBox="0 0 64 64" width="64" height="64">
                  <circle cx="32" cy="32" r="30" fill="none" stroke="var(--accent)" strokeWidth="2" />
                  <path d="M 18 34 L 28 44 L 46 22" fill="none" stroke="var(--accent)" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
              </div>
              <h3 className="display" style={{ fontSize: 36, fontWeight: 500, margin: "20px 0 12px" }}>
                Спасибо!
              </h3>
              <p className="lead" style={{ maxWidth: "46ch", margin: "0 auto" }}>
                Ваши ответы помогут сделать ЭкоКруг ближе к реальной жизни.
                Мы используем результаты только в обобщённом виде, а контакты не публикуем.
              </p>
              <div style={{ display: "flex", gap: 12, justifyContent: "center", marginTop: 24, flexWrap: "wrap" }}>
                {isMiniApp
                  ? <button className="btn btn-primary" onClick={() => window.__TG_WEB_APP?.close?.()}>
                      Вернуться в Telegram <span className="arrow">→</span>
                    </button>
                  : <a href="#results" className="btn btn-primary">Посмотреть результаты <span className="arrow">→</span></a>
                }
                <button className="btn btn-ghost" onClick={() => { setStep(0); setAnswers({}); }}>
                  Пройти ещё раз
                </button>
              </div>
            </div>
          </div>
        </div>
      </section>
    );
  }

  const idx = step - 1;
  const q = questions[idx];
  const a = answers[q.id];
  const section = sections[q.section];
  const canNext = canAnswer(q, a);

  return (
    <section id="survey" className="section-bg-soft">
      <div className="wrap">
        <div className="survey-card">
          <div className="survey-prog">
            <div className="survey-prog-bar" style={{ width: `${progress}%` }} />
            <div className="survey-prog-label mono">Вопрос {step} из {total}</div>
          </div>

          <div className="survey-q-wrap" key={step}>
            {section &&
              <div className="survey-section">
                <span>{section.title}</span>
                <small>{section.subtitle}</small>
              </div>
            }
            <div className="survey-q-num mono">{String(step).padStart(2, "0")}</div>
            <h3 className="display survey-q">{q.q}</h3>
            {q.hint && <p className="survey-hint">{q.hint}</p>}

            {q.kind === "single" && <SingleQuestion q={q} value={a} setAns={setAns} next={next} />}
            {q.kind === "multi" && <MultiQuestion q={q} value={a || []} otherValue={answers[`${q.id}_other`] || ""} setAns={setAns} />}
            {q.kind === "text" && <TextQuestion q={q} value={a || ""} setAns={setAns} />}
            {q.kind === "contact" && <ContactQuestion q={q} value={a || {}} setAns={setAns} />}
          </div>

          <div className={`survey-nav ${step === 1 ? "first" : ""}`}>
            <button className="btn btn-ghost" onClick={prev} style={{ visibility: step === 1 ? "hidden" : "visible" }}>
              ← Назад
            </button>
            <button className="btn btn-primary" onClick={next} disabled={!canNext || sending} style={{ opacity: canNext && !sending ? 1 : 0.45 }}>
              {sending ? "Отправляем…" : step === total ? "Отправить" : "Дальше"}
              {!sending && <span className="arrow">→</span>}
            </button>
          </div>

          <input
            type="text"
            name="website"
            autoComplete="off"
            tabIndex="-1"
            value={website}
            onChange={(e) => setWebsite(e.target.value)}
            style={{ position: "absolute", left: "-9999px", width: 1, height: 1, opacity: 0 }}
            aria-hidden="true"
          />
        </div>
      </div>
    </section>
  );
}

function SingleQuestion({ q, value, setAns, next }) {
  return (
    <div className="survey-opts">
      {q.opts.map((opt) =>
        <button key={opt} className={`survey-opt ${value === opt ? "sel" : ""}`} onClick={() => { setAns(q.id, opt); setTimeout(next, 250); }}>
          <span className="survey-opt-r" />
          <span>{opt}</span>
        </button>
      )}
    </div>
  );
}

function MultiQuestion({ q, value, otherValue, setAns }) {
  const selected = Array.isArray(value) ? value : [];
  const otherKey = `${q.id}_other`;
  return (
    <>
      <div className="survey-opts">
        {q.opts.map((opt) => {
          const sel = selected.includes(opt);
          return (
            <button key={opt} className={`survey-opt ${sel ? "sel" : ""}`} onClick={() => {
              setAns(q.id, sel ? selected.filter((x) => x !== opt) : [...selected, opt]);
            }}>
              <span className="survey-opt-c" />
              <span>{opt}</span>
            </button>
          );
        })}
      </div>
      {q.other && selected.includes("Другое") &&
        <input
          className="survey-input"
          placeholder="Напишите свой вариант"
          value={otherValue}
          onChange={(e) => setAns(otherKey, e.target.value)}
        />
      }
    </>
  );
}

function TextQuestion({ q, value, setAns }) {
  return (
    <textarea className="survey-text" placeholder={q.placeholder} value={value} onChange={(e) => setAns(q.id, e.target.value)} rows="5" />
  );
}

function ContactQuestion({ q, value, setAns }) {
  const current = value || {};
  const update = (patch) => setAns(q.id, { ...current, ...patch });
  return (
    <div className="survey-contact">
      <div className="survey-opts">
        {["Хочу получить итоги", "Хочу попробовать прототип", "Пока без контакта"].map((intent) =>
          <button key={intent} className={`survey-opt ${current.intent === intent ? "sel" : ""}`} onClick={() => {
            update(intent === "Пока без контакта" ? { intent, value: "" } : { intent });
          }}>
            <span className="survey-opt-r" />
            <span>{intent}</span>
          </button>
        )}
      </div>
      {current.intent !== "Пока без контакта" &&
        <input
          className="survey-input"
          placeholder={q.placeholder}
          value={current.value || ""}
          onChange={(e) => update({ value: e.target.value })}
        />
      }
      <p className="survey-private">Контакт хранится отдельно от ответов и не попадает в публичную аналитику.</p>
    </div>
  );
}

function canAnswer(q, value) {
  if (q.required === false) return true;
  if (q.kind === "text") return true;
  if (q.kind === "multi") return Array.isArray(value) && value.length > 0;
  if (q.kind === "contact") return true;
  return !!value;
}

window.Survey = Survey;

function ruPersonCount(n) {
  const value = Math.abs(Number(n) || 0);
  const mod10 = value % 10;
  const mod100 = value % 100;
  if (mod100 >= 11 && mod100 <= 14) return "человек";
  if (mod10 === 1) return "человек";
  if (mod10 >= 2 && mod10 <= 4) return "человека";
  return "человек";
}

function ruSharedVerb(n) {
  const value = Math.abs(Number(n) || 0);
  return value % 10 === 1 && value % 100 !== 11 ? "поделился" : "поделились";
}
