// Klyvio — Questionnaire interactif (dark theme Klyvio)

function Questionnaire({ answers, setAnswers, onFinish, onExit, company }) {
  const questions = window.KLYVIO_QUESTIONS;
  const dims = window.KLYVIO_DIMENSIONS;
  const [idx, setIdx] = useState(0);
  const [paused, setPaused] = useState(false);
  const [savedAt, setSavedAt] = useState(null);
  const [elapsed, setElapsed] = useState(0);
  const startRef = useRef(Date.now());

  const q = questions[idx];
  const dim = dims.find(d => d.id === q.dim);
  const currentAnswer = answers[q.id];

  useEffect(() => {
    if (paused) return;
    const interval = setInterval(() => setElapsed(Math.floor((Date.now() - startRef.current) / 1000)), 1000);
    return () => clearInterval(interval);
  }, [paused]);

  useEffect(() => {
    setSavedAt(Date.now());
    const t = setTimeout(() => setSavedAt(null), 2000);
    return () => clearTimeout(t);
  }, [answers]);

  const answer = (val) => setAnswers({ ...answers, [q.id]: val });

  const pct = Math.round(((idx + 1) / questions.length) * 100);
  const remaining = Math.max(0, Math.round((questions.length - idx - 1) * 0.5));
  const canNext = q.optional || (currentAnswer !== undefined && currentAnswer !== null && currentAnswer !== "" && !(Array.isArray(currentAnswer) && currentAnswer.length === 0));

  const next = () => { if (idx < questions.length - 1) setIdx(idx + 1); else onFinish(); };
  const prev = () => { if (idx > 0) setIdx(idx - 1); };

  useEffect(() => {
    const handler = (e) => {
      if (paused) return;
      if (e.key === "ArrowRight" && canNext) next();
      else if (e.key === "ArrowLeft") prev();
      else if (e.key >= "1" && e.key <= "9" && (q.type === "scale" || q.type === "single")) {
        const n = parseInt(e.key, 10) - 1;
        const opts = q.type === "scale" ? q.scale : q.options;
        if (opts && n < opts.length) answer(n);
      }
    };
    window.addEventListener("keydown", handler);
    return () => window.removeEventListener("keydown", handler);
  }, [idx, currentAnswer, paused]);

  return (
    <div style={{ flex: 1, display: "flex", flexDirection: "column", position: "relative", minHeight: "calc(100vh - 60px)", background: "var(--bg)" }}>

      {/* Progress header */}
      <div style={{
        padding: "14px 28px",
        borderBottom: "1px solid var(--border)",
        background: "rgba(8,15,26,0.92)",
        backdropFilter: "blur(12px)",
        display: "flex", alignItems: "center", gap: 20,
        position: "sticky", top: 60, zIndex: 10,
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{
            width: 28, height: 28, borderRadius: 8,
            background: `${dim.color}20`,
            border: `1px solid ${dim.color}40`,
            color: dim.color,
            display: "flex", alignItems: "center", justifyContent: "center",
          }}>
            <Icon name={dim.icon} size={13} />
          </div>
          <div>
            <div style={{ fontSize: 10, color: "var(--text-mute)", letterSpacing: "0.1em", textTransform: "uppercase", fontWeight: 600 }}>
              {dim.label}
            </div>
            <div style={{ fontSize: 12, color: "var(--white)", fontWeight: 500 }}>
              Question {idx + 1} / {questions.length}
            </div>
          </div>
        </div>

        <div className="progress" style={{ flex: 1 }}>
          <span style={{ width: `${pct}%`, background: dim.color }} />
        </div>

        <div style={{ display: "flex", alignItems: "center", gap: 12, fontSize: 12, color: "var(--gray)" }}>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
            <Icon name="clock" size={12} />
            ~{remaining} min restant
          </span>
          <span style={{ width: 1, height: 14, background: "var(--gray-dim)" }} />
          {savedAt ? (
            <span style={{ display: "inline-flex", alignItems: "center", gap: 5, color: "var(--success)" }}>
              <Icon name="check" size={12} /> Sauvegardé
            </span>
          ) : (
            <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
              <Icon name="save" size={12} /> Sauvegarde auto
            </span>
          )}
          <button className="btn btn-ghost btn-sm" onClick={() => setPaused(true)}>
            <Icon name="pause" size={12} /> Pause
          </button>
          <button className="btn btn-ghost btn-sm" onClick={onExit}>
            <Icon name="x" size={12} />
          </button>
        </div>
      </div>

      {/* Question body */}
      <div style={{ flex: 1, padding: "56px 28px", display: "flex", justifyContent: "center", overflowY: "auto" }}>
        <div style={{ width: "100%", maxWidth: 760 }} className="fade-in" key={q.id}>
          <div style={{ fontSize: 12, color: "var(--text-mute)", marginBottom: 16, letterSpacing: "0.06em", fontWeight: 600 }}>
            {String(idx + 1).padStart(2, "0")} · {dim.label}
          </div>
          <h2 className="display" style={{ fontSize: 36, margin: "0 0 12px", lineHeight: 1.12, color: "var(--white)" }}>
            {q.q}
          </h2>
          {q.hint && (
            <div style={{
              display: "flex", gap: 10, alignItems: "flex-start",
              padding: "12px 14px",
              background: "var(--accent-dim)",
              border: "1px solid var(--border)",
              color: "var(--accent)",
              borderRadius: 10,
              fontSize: 13, marginBottom: 28, marginTop: 12,
              lineHeight: 1.5,
            }}>
              <Icon name="info" size={14} style={{ flexShrink: 0, marginTop: 1 }} />
              {q.hint}
            </div>
          )}
          <div style={{ marginTop: q.hint ? 0 : 32 }}>
            <QuestionInput q={q} value={currentAnswer} onChange={answer} />
          </div>
        </div>
      </div>

      {/* Footer navigation */}
      <div style={{
        position: "sticky", bottom: 0,
        padding: "14px 28px",
        borderTop: "1px solid var(--border)",
        background: "rgba(8,15,26,0.95)",
        backdropFilter: "blur(12px)",
        display: "flex", alignItems: "center", justifyContent: "space-between",
      }}>
        <button className="btn btn-ghost" onClick={prev} disabled={idx === 0} style={{ opacity: idx === 0 ? 0.35 : 1 }}>
          <Icon name="arrowLeft" size={13} /> Précédent
        </button>

        <div style={{ fontSize: 11, color: "var(--text-mute)" }}>
          <span className="mono">←</span> / <span className="mono">→</span> pour naviguer
          {(q.type === "scale" || q.type === "single") && <> · <span className="mono">1–9</span> pour répondre</>}
        </div>

        <button className="btn btn-primary" onClick={next}
          disabled={!canNext}
          style={{ opacity: canNext ? 1 : 0.35, cursor: canNext ? "pointer" : "not-allowed" }}>
          {idx === questions.length - 1 ? "Générer mon rapport" : "Suivant"}
          <Icon name="arrowRight" size={13} />
        </button>
      </div>

      {/* Pause modal */}
      {paused && <PauseModal onResume={() => setPaused(false)} onSave={onExit} elapsed={elapsed} pct={pct} />}
    </div>
  );
}

function QuestionInput({ q, value, onChange }) {

  /* ── SCALE ── */
  if (q.type === "scale") {
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        {q.scale.map((opt, i) => {
          const active = value === i;
          return (
            <button key={i} onClick={() => onChange(i)}
              style={{
                display: "flex", alignItems: "center", gap: 14,
                padding: "15px 20px",
                border: active ? "1.5px solid var(--accent)" : "1px solid var(--gray-dim)",
                background: active ? "var(--accent-dim)" : "rgba(255,255,255,0.02)",
                color: active ? "var(--white)" : "var(--gray)",
                borderRadius: 12, cursor: "pointer",
                textAlign: "left", fontSize: 14, fontWeight: 400,
                transition: "all .15s ease",
              }}
              onMouseEnter={e => { if (!active) { e.currentTarget.style.borderColor = "var(--border-hover)"; e.currentTarget.style.color = "var(--white)"; }}}
              onMouseLeave={e => { if (!active) { e.currentTarget.style.borderColor = "var(--gray-dim)"; e.currentTarget.style.color = "var(--gray)"; }}}
            >
              <div style={{
                width: 26, height: 26, borderRadius: 7, flexShrink: 0,
                background: active ? "var(--accent)" : "rgba(255,255,255,0.05)",
                border: active ? "none" : "1px solid var(--gray-dim)",
                color: active ? "#000" : "var(--text-mute)",
                display: "flex", alignItems: "center", justifyContent: "center",
                fontSize: 11, fontWeight: 600,
              }}>{i + 1}</div>
              <span style={{ flex: 1 }}>{opt}</span>
              {active && <Icon name="check" size={14} color="var(--accent)" />}
            </button>
          );
        })}
      </div>
    );
  }

  /* ── SINGLE ── */
  if (q.type === "single") {
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        {q.options.map((opt, i) => {
          const active = value === i;
          return (
            <button key={i} onClick={() => onChange(i)}
              style={{
                display: "flex", alignItems: "center", gap: 14,
                padding: "14px 18px",
                border: active ? "1.5px solid var(--accent)" : "1px solid var(--gray-dim)",
                background: active ? "var(--accent-dim)" : "rgba(255,255,255,0.02)",
                color: active ? "var(--white)" : "var(--gray)",
                borderRadius: 12, cursor: "pointer",
                textAlign: "left", fontSize: 14,
                transition: "all .15s ease",
              }}
              onMouseEnter={e => { if (!active) { e.currentTarget.style.borderColor = "var(--border-hover)"; e.currentTarget.style.color = "var(--white)"; }}}
              onMouseLeave={e => { if (!active) { e.currentTarget.style.borderColor = "var(--gray-dim)"; e.currentTarget.style.color = "var(--gray)"; }}}
            >
              <div style={{
                width: 20, height: 20, borderRadius: "50%", flexShrink: 0,
                border: active ? "2px solid var(--accent)" : "1.5px solid var(--gray-dim)",
                background: "transparent",
                position: "relative",
              }}>
                {active && <div style={{ position: "absolute", inset: 3, borderRadius: "50%", background: "var(--accent)" }} />}
              </div>
              <span style={{ flex: 1 }}>{opt}</span>
              <span className="mono" style={{ fontSize: 10, color: active ? "var(--accent)" : "var(--text-mute)" }}>{i + 1}</span>
            </button>
          );
        })}
      </div>
    );
  }

  /* ── MULTI ── */
  if (q.type === "multi") {
    const sel = Array.isArray(value) ? value : [];
    const maxSelect = q.maxSelect || Infinity;
    const limitReached = sel.length >= maxSelect;

    const toggle = (i) => {
      if (sel.includes(i)) {
        // Toujours autoriser la désélection
        onChange(sel.filter(x => x !== i));
      } else if (!limitReached) {
        // N'ajouter que si la limite n'est pas atteinte
        onChange([...sel, i]);
      }
    };

    return (
      <div>
        {/* Compteur affiché uniquement si maxSelect est défini */}
        {q.maxSelect && (
          <div style={{
            display: "flex", alignItems: "center", justifyContent: "space-between",
            marginBottom: 12,
          }}>
            <div style={{ fontSize: 12, color: "var(--text-mute)" }}>
              {sel.length} / {q.maxSelect} sélectionné{sel.length > 1 ? "s" : ""}
            </div>
            {limitReached && (
              <div style={{
                fontSize: 11, color: "var(--accent)",
                background: "var(--accent-dim)",
                border: "1px solid var(--accent)",
                borderRadius: 6, padding: "2px 8px",
              }}>
                Maximum atteint
              </div>
            )}
          </div>
        )}

        <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 8 }}>
          {q.options.map((opt, i) => {
            const active = sel.includes(i);
            // Grisé si limite atteinte ET non sélectionné
            const dimmed = limitReached && !active;

            return (
              <button key={i} onClick={() => toggle(i)}
                disabled={dimmed}
                style={{
                  display: "flex", alignItems: "center", gap: 12,
                  padding: "14px 16px",
                  border: active ? "1.5px solid var(--accent)" : "1px solid var(--gray-dim)",
                  background: active ? "var(--accent-dim)" : "rgba(255,255,255,0.02)",
                  color: active ? "var(--white)" : dimmed ? "var(--text-mute)" : "var(--gray)",
                  borderRadius: 12,
                  cursor: dimmed ? "not-allowed" : "pointer",
                  textAlign: "left", fontSize: 13,
                  opacity: dimmed ? 0.4 : 1,
                  transition: "all .15s ease",
                }}
                onMouseEnter={e => { if (!active && !dimmed) { e.currentTarget.style.borderColor = "var(--border-hover)"; e.currentTarget.style.color = "var(--white)"; }}}
                onMouseLeave={e => { if (!active && !dimmed) { e.currentTarget.style.borderColor = "var(--gray-dim)"; e.currentTarget.style.color = "var(--gray)"; }}}
              >
                <div style={{
                  width: 18, height: 18, borderRadius: 5, flexShrink: 0,
                  border: active ? "none" : "1.5px solid var(--gray-dim)",
                  background: active ? "var(--accent)" : "transparent",
                  display: "flex", alignItems: "center", justifyContent: "center",
                }}>
                  {active && <Icon name="check" size={10} color="#000" strokeWidth={3} />}
                </div>
                <span style={{ flex: 1 }}>{opt}</span>
              </button>
            );
          })}
        </div>
      </div>
    );
  }

  /* ── SLIDER ── */
  if (q.type === "slider") {
    const v = value !== undefined && value !== null ? value : q.default;

    // Initialisation propre — seulement si la clé n'existe pas encore dans answers
    useEffect(() => {
      if (value === undefined || value === null) {
        onChange(q.default);
      }
    }, [q.id]); // dépend de q.id pour ne pas re-déclencher sur re-render

    const pct = ((v - q.min) / (q.max - q.min)) * 100;
    const displayVal = q.format === "currency-m" ? `${v}\u202fM€` : `${v}`;
    return (
      <div>
        <div style={{ display: "flex", alignItems: "baseline", gap: 8, marginBottom: 28 }}>
          <div className="display" style={{ fontSize: 72, color: "var(--white)", fontVariantNumeric: "tabular-nums" }}>
            {displayVal}
          </div>
          {q.unit && q.format !== "currency-m" && (
            <div style={{ fontSize: 20, color: "var(--gray)" }}>{q.unit}</div>
          )}
        </div>
        <input
          type="range" min={q.min} max={q.max} step={q.step} value={v}
          onChange={e => onChange(parseFloat(e.target.value))}
          style={{
            width: "100%", height: 6, appearance: "none",
            background: `linear-gradient(to right, var(--accent) 0%, var(--accent) ${pct}%, var(--gray-dim) ${pct}%, var(--gray-dim) 100%)`,
            borderRadius: 999, cursor: "pointer", outline: "none",
          }}
        />
        <style>{`
          input[type="range"]::-webkit-slider-thumb {
            appearance: none; width: 22px; height: 22px; border-radius: 50%;
            background: var(--bg2); border: 2px solid var(--accent);
            cursor: pointer; box-shadow: 0 0 0 4px rgba(0,174,239,0.15);
          }
          input[type="range"]::-moz-range-thumb {
            width: 22px; height: 22px; border-radius: 50%;
            background: var(--bg2); border: 2px solid var(--accent);
            cursor: pointer;
          }
        `}</style>
        <div style={{ display: "flex", justifyContent: "space-between", marginTop: 14, fontSize: 12, color: "var(--text-mute)" }}>
          <span>{q.min}{q.unit && q.format !== "currency-m" ? `\u202f${q.unit}` : q.format === "currency-m" ? "\u202fM€" : ""}</span>
          <span>{q.max}{q.unit && q.format !== "currency-m" ? `\u202f${q.unit}` : q.format === "currency-m" ? "\u202fM€" : ""}</span>
        </div>
      </div>
    );
  }

  /* ── TEXT ── */
  if (q.type === "text") {
    // Garantit que la valeur est toujours une string — jamais un tableau ou un nombre parasite
    const safeValue = typeof value === "string" ? value : "";
    return (
      <textarea
        className="textarea"
        rows={4}
        placeholder={q.placeholder}
        value={safeValue}
        onChange={e => onChange(e.target.value)}
        style={{ minHeight: 120, resize: "vertical", padding: "14px 16px", fontSize: 15 }}
      />
    );
  }

  /* ── CARDS-SORT ── */
  if (q.type === "cards-sort") {
    const order = Array.isArray(value) ? value : q.cards.map(c => c.id);

    // Initialisation propre — seulement si la clé n'existe pas encore
    useEffect(() => {
      if (!Array.isArray(value)) {
        onChange(q.cards.map(c => c.id));
      }
    }, [q.id]); // dépend de q.id pour ne pas re-déclencher sur re-render
    const move = (id, dir) => {
      const i = order.indexOf(id);
      const j = i + dir;
      if (j < 0 || j >= order.length) return;
      const copy = [...order];
      [copy[i], copy[j]] = [copy[j], copy[i]];
      onChange(copy);
    };
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        {order.map((id, i) => {
          const card = q.cards.find(c => c.id === id);
          const isTop = i < 2;
          return (
            <div key={id} style={{
              display: "flex", alignItems: "center", gap: 14,
              padding: "14px 16px",
              border: isTop ? "1px solid var(--accent)" : "1px solid var(--gray-dim)",
              background: isTop ? "var(--accent-dim)" : "rgba(255,255,255,0.02)",
              borderRadius: 12,
              transition: "all .2s ease",
            }}>
              <div style={{
                width: 28, height: 28, borderRadius: 8, flexShrink: 0,
                background: i === 0 ? "var(--accent)" : i === 1 ? "rgba(0,174,239,0.3)" : "rgba(255,255,255,0.05)",
                color: i < 2 ? (i === 0 ? "#000" : "var(--accent)") : "var(--text-mute)",
                display: "flex", alignItems: "center", justifyContent: "center",
                fontSize: 11, fontWeight: 700,
              }}>{i + 1}</div>
              <div style={{ flex: 1, fontSize: 14, fontWeight: isTop ? 500 : 400, color: isTop ? "var(--white)" : "var(--gray)" }}>
                {card.label}
              </div>
              <div style={{ display: "flex", gap: 4 }}>
                <button className="btn btn-ghost btn-sm" onClick={() => move(id, -1)} disabled={i === 0} style={{ opacity: i === 0 ? 0.3 : 1 }}>↑</button>
                <button className="btn btn-ghost btn-sm" onClick={() => move(id, 1)} disabled={i === order.length - 1} style={{ opacity: i === order.length - 1 ? 0.3 : 1 }}>↓</button>
              </div>
            </div>
          );
        })}
        <div style={{ fontSize: 12, color: "var(--text-mute)", marginTop: 4 }}>
          → Les 2 premiers sont considérés prioritaires pour votre roadmap.
        </div>
      </div>
    );
  }

  /* ── TOOL-SEARCH ── */
  if (q.type === "tool-search") {
    const tools = window.KLYVIO_COMPUTE?.TOOLS_DB || [];
    const raw   = typeof value === "string" ? value : "";

    const suggestions = raw.length >= 2
      ? tools
          .filter(t => t.name.toLowerCase().includes(raw.toLowerCase()))
          .slice(0, 6)
      : [];

    return (
      <div style={{ position: "relative", maxWidth: 480 }}>
        <input
          type="text"
          value={raw}
          onChange={e => onChange(e.target.value)}
          placeholder={`Ex : ${q.hint?.split("—")[0]?.replace("Tapez le nom exact", "").trim() || "HubSpot, Sage, Excel…"}`}
          autoComplete="off"
          style={{
            width: "100%", padding: "14px 16px",
            background: "rgba(255,255,255,0.04)",
            border: "1px solid var(--gray-dim)",
            borderRadius: 12, color: "var(--white)",
            fontSize: 15, outline: "none",
            boxSizing: "border-box",
          }}
          onFocus={e => { e.currentTarget.style.borderColor = "var(--accent)"; }}
          onBlur={e => { e.currentTarget.style.borderColor = "var(--gray-dim)"; }}
        />

        {/* Suggestions — nom uniquement, sans statut */}
        {suggestions.length > 0 && (
          <div style={{
            position: "absolute", top: "calc(100% + 6px)", left: 0, right: 0,
            background: "var(--bg2)", border: "1px solid var(--border)",
            borderRadius: 12, overflow: "hidden", zIndex: 50,
          }}>
            {suggestions.map((t, i) => (
              <button key={i}
                onMouseDown={e => { e.preventDefault(); onChange(t.name); }}
                style={{
                  display: "flex", alignItems: "center",
                  width: "100%", padding: "12px 16px",
                  background: "transparent", border: "none",
                  borderBottom: i < suggestions.length - 1 ? "1px solid var(--gray-dim)" : "none",
                  color: "var(--white)", cursor: "pointer", textAlign: "left",
                  fontSize: 14,
                }}
                onMouseEnter={e => e.currentTarget.style.background = "rgba(255,255,255,0.05)"}
                onMouseLeave={e => e.currentTarget.style.background = "transparent"}
              >
                {t.name}
              </button>
            ))}
          </div>
        )}

        {/* Confirmation discrète si outil non répertorié — sans mention de statut */}
        {raw.length >= 2 && suggestions.length === 0 && (
          <div style={{ marginTop: 10, fontSize: 13, color: "var(--text-mute)" }}>
            Outil enregistré — nous vérifierons la compatibilité.
          </div>
        )}
      </div>
    );
  }

  return null;
}

function PauseModal({ onResume, onSave, elapsed, pct }) {
  const mins = Math.floor(elapsed / 60);
  const secs = elapsed % 60;
  return (
    <div style={{
      position: "fixed", inset: 0,
      background: "rgba(8,15,26,0.75)",
      backdropFilter: "blur(8px)",
      display: "flex", alignItems: "center", justifyContent: "center",
      zIndex: 100,
    }}>
      <div className="card" style={{ width: 440, padding: "36px 36px 28px", textAlign: "center" }}>
        <div style={{
          width: 52, height: 52, margin: "0 auto 20px",
          borderRadius: 14,
          background: "var(--accent-dim)",
          border: "1px solid var(--border)",
          color: "var(--accent)",
          display: "flex", alignItems: "center", justifyContent: "center",
        }}>
          <Icon name="pause" size={20} />
        </div>
        <h3 className="display" style={{ fontSize: 28, margin: "0 0 8px", color: "var(--white)" }}>Pause</h3>
        <p style={{ fontSize: 14, color: "var(--gray)", margin: "0 0 24px", lineHeight: 1.6 }}>
          Votre progression est sauvegardée. Vous pouvez reprendre plus tard avec votre lien d'accès.
        </p>

        <div style={{ display: "flex", gap: 12, marginBottom: 24 }}>
          <div style={{ flex: 1, padding: "14px", background: "rgba(255,255,255,0.03)", border: "1px solid var(--gray-dim)", borderRadius: 10 }}>
            <div style={{ fontSize: 10, fontWeight: 600, color: "var(--text-mute)", letterSpacing: "0.1em", textTransform: "uppercase", marginBottom: 4 }}>Temps</div>
            <div className="display" style={{ fontSize: 26, color: "var(--white)" }}>{mins}:{String(secs).padStart(2, "0")}</div>
          </div>
          <div style={{ flex: 1, padding: "14px", background: "rgba(255,255,255,0.03)", border: "1px solid var(--gray-dim)", borderRadius: 10 }}>
            <div style={{ fontSize: 10, fontWeight: 600, color: "var(--text-mute)", letterSpacing: "0.1em", textTransform: "uppercase", marginBottom: 4 }}>Progression</div>
            <div className="display" style={{ fontSize: 26, color: "var(--accent)" }}>{pct}%</div>
          </div>
        </div>

        <div style={{ display: "flex", gap: 8 }}>
          <button className="btn btn-ghost btn-lg" style={{ flex: 1 }} onClick={onSave}>
            Reprendre plus tard
          </button>
          <button className="btn btn-primary btn-lg" style={{ flex: 1 }} onClick={onResume}>
            <Icon name="play" size={13} /> Reprendre
          </button>
        </div>
      </div>
    </div>
  );
}

window.Questionnaire = Questionnaire;
