// Survey state — shared across all 3 directions
// One unified flow + one useSurvey hook each direction reads from.

const SURVEY_QUESTIONS = [
  { id: 'q1', kind: 'rating', required: true,
    text: 'באיזו מידה תמליצ/י לחבריך / עמיתיך להיות לקוח של וקסמן גרופ על בסיס השירותים שקיבלת עד כה בפרויקט?',
    minLabel: 'במידה מועטה מאוד', maxLabel: 'במידה רבה מאוד' },
  { id: 'q2', kind: 'rating', required: true,
    text: 'באיזו מידה הינך מרוצה מצוות הפרויקט?',
    minLabel: 'לא מרוצה כלל', maxLabel: 'מרוצה מאוד' },
  { id: 'q3', kind: 'rating', required: true,
    text: 'באיזו מידה הפרויקט עומד בלוחות הזמנים?',
    minLabel: 'לא עומד', maxLabel: 'עומד במלואו' },
  { id: 'q4', kind: 'choice', required: true,
    text: 'באיזה תחום ראית את ההשפעה הגדולה ביותר?',
    options: ['ניהול הפרויקט', 'איכות הביצוע', 'תקשורת ושקיפות', 'יחס עלות-תועלת', 'אחר'] },
  { id: 'q5', kind: 'text', required: false,
    text: 'משהו שהיית רוצה לשפר?',
    placeholder: 'המשוב שלך חשוב לנו — ספר/י לנו כיצד נוכל להשתפר' },
];

// pages: 0=intro, 1..N=questions, N+1=thanks
const TOTAL_PAGES = SURVEY_QUESTIONS.length + 2;

function useSurvey(opts = {}) {
  const { initialPage = 0, initialAnswers = null } = opts;
  const [page, setPage] = React.useState(initialPage);
  const DEMO_ANSWERS = { q1: 9, q2: 8, q3: 7, q4: 'איכות הביצוע', q5: 'תקשורת בין הצוותים מצוינת. אשמח לעדכוני התקדמות שבועיים יותר מסודרים.' };
  const [answers, setAnswers] = React.useState(initialAnswers === 'demo' ? DEMO_ANSWERS : initialAnswers || {});
  const [direction, setDirection] = React.useState(1); // for animations
  const [isSubmitting, setSubmitting] = React.useState(false);

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

  const goNext = () => {
    setDirection(1);
    if (page === SURVEY_QUESTIONS.length) {
      setSubmitting(true);
      setTimeout(() => { setSubmitting(false); setPage(p => p + 1); }, 700);
    } else {
      setPage(p => Math.min(p + 1, TOTAL_PAGES - 1));
    }
  };
  const goPrev = () => { setDirection(-1); setPage(p => Math.max(p - 1, 0)); };
  const restart = () => { setDirection(-1); setPage(0); setAnswers({}); };

  const currentQ = page > 0 && page <= SURVEY_QUESTIONS.length ? SURVEY_QUESTIONS[page - 1] : null;
  const currentAnswered = !currentQ || !currentQ.required || answers[currentQ.id] != null && answers[currentQ.id] !== '';
  const progress = page === 0 ? 0 : page > SURVEY_QUESTIONS.length ? 1 : page / SURVEY_QUESTIONS.length;

  return { page, setPage, direction, answers, setAnswer, goNext, goPrev, restart,
    currentQ, currentAnswered, progress, isSubmitting,
    qIdx: page - 1, total: SURVEY_QUESTIONS.length };
}

Object.assign(window, { SURVEY_QUESTIONS, TOTAL_PAGES, useSurvey });
