// Symptom Mapper — pick symptoms, see auto-highlighted vertebrae + organ connections
// Used as a new step inside variations
const { useState: useStateNM, useEffect: useEffectNM, useRef: useRefNM, useMemo: useMemoNM } = React;

function SymptomMapper({ palette, onChange, initial = { symptoms: [], focused: null }, height = 540 }) {
  const [symptoms, setSymptoms] = useStateNM(initial.symptoms || []);
  const [focused, setFocused] = useStateNM(initial.focused);
  const ref = useRefNM(null);
  const apiRef = useRefNM(null);

  // Derived: vertebrae intensity from selected symptoms
  const vertMap = useMemoNM(() => {
    const counts = {};
    symptoms.forEach((sid) => {
      const preset = window.SymptomPresets.find((p) => p.id === sid);
      if (!preset) return;
      preset.verts.forEach((v) => { counts[v] = (counts[v] || 0) + 1; });
    });
    const max = Math.max(1, ...Object.values(counts));
    const result = {};
    Object.entries(counts).forEach(([v, c]) => { result[v] = 0.4 + (c / max) * 0.6; });
    return result;
  }, [symptoms]);

  // Mount 3D spine (real GLB model — same as welcome screen)
  useEffectNM(() => {
    let cancelled = false;
    const mountFn = (window.SpineKitGLB && window.SpineKitGLB.mountSpine) || window.SpineKit.mountSpine;
    Promise.resolve(mountFn({
      container: ref.current,
      palette: { bone: palette.bone, accent: palette.accentHex, accentLight: palette.accentLight },
      modelUrl: "spine-model-2.glb",
      interactive: true,
      onPick: (n) => setFocused(n),
    })).then((api) => {
      if (cancelled) api.dispose();
      else {
        apiRef.current = api;
        api.setHighlight(vertMap);
      }
    }).catch((e) => console.error("[symptom-mapper] spine mount", e));
    return () => { cancelled = true; if (apiRef.current) apiRef.current.dispose(); };
  }, []);

  useEffectNM(() => {
    if (apiRef.current) {
      apiRef.current.setHighlight(vertMap);
      if (apiRef.current.setSelection && focused) apiRef.current.setSelection(focused);
    }
    if (onChange) onChange({ symptoms, focused, vertMap });
  }, [vertMap, focused]);

  const toggle = (id) => {
    setSymptoms((s) => s.includes(id) ? s.filter((x) => x !== id) : [...s, id]);
  };

  const focusedInfo = focused ? window.NeuroMap[focused] : null;
  const matchingSymptoms = focused
    ? window.SymptomPresets.filter((p) => p.verts.includes(focused))
    : [];

  return (
    <div style={{ display: "flex", gap: 20, height }}>
      {/* Left — symptom selection */}
      <div style={{ flex: "0 1 280px", minWidth: 190, display: "flex", flexDirection: "column" }}>
        <div style={{ fontSize: 11, color: palette.muted, letterSpacing: "0.12em", textTransform: "uppercase", marginBottom: 10 }}>
          1. Marque seus sintomas
        </div>
        <div style={{
          flex: 1, overflowY: "auto", display: "flex", flexDirection: "column", gap: 6, paddingRight: 4,
          maskImage: "linear-gradient(to bottom, #000 calc(100% - 22px), transparent)",
          WebkitMaskImage: "linear-gradient(to bottom, #000 calc(100% - 22px), transparent)",
        }}>
          {window.SymptomPresets.map((p) => {
            const sel = symptoms.includes(p.id);
            return (
              <button key={p.id} onClick={() => toggle(p.id)} style={{
                display: "flex", alignItems: "center", gap: 10,
                padding: "10px 12px", borderRadius: 12,
                background: sel ? palette.accentSoft : "#fff0ef",
                border: `1px solid ${sel ? palette.accent : palette.border}`,
                color: palette.text, cursor: "pointer", textAlign: "left",
                fontSize: 12, transition: "all 0.2s",
              }}>
                <span style={{ fontSize: 16 }}>{p.icon}</span>
                <span style={{ flex: 1, lineHeight: 1.3 }}>{p.label}</span>
                <span style={{
                  width: 16, height: 16, borderRadius: 4,
                  border: `1.5px solid ${sel ? palette.accent : palette.border}`,
                  background: sel ? palette.accent : "transparent",
                  display: "grid", placeItems: "center", flexShrink: 0,
                }}>
                  {sel && <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3"><polyline points="20 6 9 17 4 12"/></svg>}
                </span>
              </button>
            );
          })}
        </div>
      </div>

      {/* Center — 3D spine */}
      <div style={{ flex: "1 1 340px", minWidth: 300, position: "relative", borderLeft: `1px solid ${palette.border}`, borderRight: `1px solid ${palette.border}`, padding: "0 12px" }}>
        <div style={{ fontSize: 11, color: palette.muted, letterSpacing: "0.12em", textTransform: "uppercase", marginBottom: 10, textAlign: "center" }}>
          2. Vértebras prováveis · clique para detalhes
        </div>
        <div ref={ref} style={{ width: "100%", height: "calc(100% - 30px)" }} />
        {symptoms.length === 0 && (
          <div style={{
            position: "absolute", top: "50%", left: "50%", transform: "translate(-50%, -50%)",
            color: palette.muted, fontSize: 12, textAlign: "center", maxWidth: 200, pointerEvents: "none",
          }}>
            Marque sintomas ao lado para destacar as vértebras correspondentes.
          </div>
        )}
      </div>

      {/* Right — vertebra detail */}
      <div style={{ flex: "0 1 280px", minWidth: 210, display: "flex", flexDirection: "column" }}>
        <div style={{ fontSize: 11, color: palette.muted, letterSpacing: "0.12em", textTransform: "uppercase", marginBottom: 10 }}>
          3. Detalhe da vértebra
        </div>
        {!focused && (
          <div style={{
            padding: 16, borderRadius: 12,
            background: "#fff0ef", border: `1px solid ${palette.border}`,
            fontSize: 12, color: palette.muted, lineHeight: 1.5,
          }}>
            Clique numa vértebra destacada para ver quais órgãos e sintomas estão conectados a ela.
          </div>
        )}
        {focused && focusedInfo && (
          <div style={{ flex: 1, overflowY: "auto", paddingRight: 4 }}>
            <div style={{
              padding: 14, borderRadius: 12,
              background: palette.accentSoft, border: `1px solid ${palette.accent}50`,
              marginBottom: 10,
            }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                <div style={{ fontSize: 28, fontWeight: 600, color: palette.accent, fontFamily: "'JetBrains Mono', monospace" }}>{focused}</div>
                <div style={{ fontSize: 11, color: palette.muted, textTransform: "uppercase", letterSpacing: "0.1em" }}>{focusedInfo.region}</div>
              </div>
            </div>

            <div style={{ marginBottom: 14 }}>
              <div style={{ fontSize: 10, color: palette.muted, letterSpacing: "0.12em", textTransform: "uppercase", marginBottom: 6 }}>Conecta com</div>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 4 }}>
                {focusedInfo.organs.map((o) => (
                  <span key={o} style={{
                    padding: "4px 10px", borderRadius: 999,
                    background: "#fde2d7", border: `1px solid ${palette.border}`,
                    fontSize: 11, color: palette.text,
                  }}>{o}</span>
                ))}
              </div>
            </div>

            <div style={{ marginBottom: 14 }}>
              <div style={{ fontSize: 10, color: palette.muted, letterSpacing: "0.12em", textTransform: "uppercase", marginBottom: 6 }}>Sintomas comuns</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
                {focusedInfo.symptoms.map((s) => (
                  <div key={s} style={{ fontSize: 12, color: palette.text, padding: "4px 0", lineHeight: 1.3 }}>
                    · {s}
                  </div>
                ))}
              </div>
            </div>

            {matchingSymptoms.length > 0 && (
              <div>
                <div style={{ fontSize: 10, color: palette.muted, letterSpacing: "0.12em", textTransform: "uppercase", marginBottom: 6 }}>
                  Dos sintomas marcados
                </div>
                <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
                  {matchingSymptoms.filter((m) => symptoms.includes(m.id)).map((m) => (
                    <div key={m.id} style={{
                      padding: "6px 10px", borderRadius: 8,
                      background: palette.accentSoft, fontSize: 12, color: palette.accent,
                      display: "flex", alignItems: "center", gap: 8,
                    }}>
                      <span>{m.icon}</span>
                      <span>{m.label}</span>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

window.SymptomMapper = SymptomMapper;
