// quiz-connection-quest.jsx
// Connection Quest: problem card + two helper cards, auto-explained pairing.

const CONNECTION_QUESTS = [
  {
    id: "stuck-rover",
    icon: "🛞",
    title: "The rover is stuck.",
    need: "Help it cross bumpy moon rocks.",
  },
  {
    id: "sleepy-alien",
    icon: "😴",
    title: "A little alien cannot sleep.",
    need: "Make a calm bedtime helper.",
  },
  {
    id: "lost-star",
    icon: "🌟",
    title: "A star got lost.",
    need: "Help it find the way home.",
  },
  {
    id: "snack-trip",
    icon: "🍎",
    title: "The astronaut needs a snack trip.",
    need: "Carry food across a crater.",
  },
  {
    id: "dark-cave",
    icon: "🌑",
    title: "The Moon cave is dark.",
    need: "Find a safe path inside.",
  },
];

const CONNECTION_THINKING_PROMPTS = [
  "What is the same?",
  "What is different?",
  "Which helper works first?",
  "What else could this plan help?",
];

function connectionQuestExplanation(quest, first, second) {
  if (!first || !second) {
    return "Pick two helper cards. Any pair can become an idea.";
  }
  return `${first.label} ${first.power}, and ${second.label} ${second.power}. Together they can ${quest.need.toLowerCase()}`;
}

function connectionThinkingCue(first, second) {
  if (!first || !second) return "Choose two helpers and look for a connection.";
  if (first.trait === second.trait) {
    return `Same idea: they both ${first.trait}.`;
  }
  return `Different ideas: one ${first.trait}; one ${second.trait}. That can still work.`;
}

function connectionFlexCue(madeConnections) {
  if (!madeConnections.length) {
    return "Can you solve it one way first?";
  }
  if (madeConnections.length === 1) {
    return "Can you solve the same problem another way?";
  }
  return "Now your brain has more than one path.";
}

function connectionSequenceCue(first, second) {
  if (!first || !second) return "";
  return `First use ${first.label}. Then add ${second.label}.`;
}

function ConnectionQuestLevel({ onExit }) {
  const [questIndex, setQuestIndex] = useState(0);
  const [selectedIds, setSelectedIds] = useState([]);
  const [madeConnections, setMadeConnections] = useState([]);
  const [thinkingPromptIndex, setThinkingPromptIndex] = useState(0);
  const quest = CONNECTION_QUESTS[questIndex];
  const selectedItems = selectedIds
    .map((id) => MASHUP_ITEMS.find((item) => item.id === id))
    .filter(Boolean);
  const [first, second] = selectedItems;
  const complete = selectedItems.length === 2;
  const questComplete = madeConnections.length >= 3;
  const explanation = connectionQuestExplanation(quest, first, second);
  const currentPairKey = complete ? `${quest.id}:${selectedIds.join("+")}` : "";
  const currentSaved = madeConnections.some((item) => item.key === currentPairKey);
  const currentThinkingPrompt =
    CONNECTION_THINKING_PROMPTS[
      thinkingPromptIndex % CONNECTION_THINKING_PROMPTS.length
    ];

  const toggleItem = (id) => {
    setSelectedIds((current) => {
      if (current.includes(id)) return current.filter((item) => item !== id);
      if (current.length >= 2) return [current[1], id];
      return [...current, id];
    });
    playKidSound("boop");
  };

  const nextQuest = () => {
    setQuestIndex((index) => (index + 1) % CONNECTION_QUESTS.length);
    setSelectedIds([]);
    setMadeConnections([]);
    setThinkingPromptIndex(0);
    playKidSound("boop");
  };

  const celebrateConnection = () => {
    if (!complete) return;
    setMadeConnections((current) => {
      if (current.some((item) => item.key === currentPairKey)) return current;
      return [
        ...current.slice(-2),
        {
          key: currentPairKey,
          icons: `${first.icon}${second.icon}`,
          name: `${first.nameBit}-${second.nameBit}`,
        },
      ];
    });
    setThinkingPromptIndex((index) => index + 1);
    playKidSound("chime");
  };

  const tryAnotherPair = () => {
    setSelectedIds([]);
    setThinkingPromptIndex((index) => index + 1);
    playKidSound("boop");
  };

  const surprisePair = () => {
    const firstIndex = (questIndex + thinkingPromptIndex) % MASHUP_ITEMS.length;
    const secondIndex = (firstIndex + 3) % MASHUP_ITEMS.length;
    setSelectedIds([MASHUP_ITEMS[firstIndex].id, MASHUP_ITEMS[secondIndex].id]);
    setThinkingPromptIndex((index) => index + 1);
    playKidSound("chime");
  };

  return (
    <section className="connection-quest-level" aria-label="Connection Quest game">
      <Starfield count={240} />
      <button className="planet-sort-back" onClick={onExit}>
        ← Back to planets
      </button>
      <div className="connection-quest-shell">
        <div className="connection-quest-problem">
          <span>Connection Quest</span>
          <h1>{quest.title}</h1>
          <p>{quest.need}</p>
          <div className="connection-problem-icon" aria-hidden="true">
            {quest.icon}
          </div>
          <button onClick={nextQuest}>New problem</button>
        </div>

        <div className="connection-quest-board" aria-live="polite">
          {questComplete ? (
            <div className="connection-brain-spark">
              <span>Brain stretch!</span>
              <strong>You made three different plans.</strong>
              <button onClick={nextQuest}>Try a new problem</button>
            </div>
          ) : null}
          <div className={`connection-build ${complete ? "ready" : ""}`}>
            <div className="connection-pair">
              <span>{first ? first.icon : "?"}</span>
              <i>+</i>
              <span>{second ? second.icon : "?"}</span>
            </div>
            <h2>
              {complete
                ? `${first.nameBit}-${second.nameBit} Plan`
                : "Choose two helpers"}
            </h2>
            <p>{explanation}</p>
            <div className="connection-thinking-cue">
              {connectionThinkingCue(first, second)}
            </div>
            {complete ? (
              <div className="connection-parent-prompt">
                Ask: {currentThinkingPrompt}
              </div>
            ) : null}
            {complete ? (
              <div className="connection-sequence-cue">
                {connectionSequenceCue(first, second)}
              </div>
            ) : null}
            <div className="connection-idea-path" aria-label="Connection idea path">
              <span className="ready">
                <em>{quest.icon}</em>
                Problem
              </span>
              <span className={first ? "ready" : ""}>
                <em>{first ? first.icon : "?"}</em>
                Helper 1
              </span>
              <span className={second ? "ready" : ""}>
                <em>{second ? second.icon : "?"}</em>
                Helper 2
              </span>
              <span className={complete ? "ready" : ""}>
                <em>{complete ? "✓" : "•"}</em>
                Plan
              </span>
            </div>
            <div className="connection-actions">
              <button
                onClick={() => {
                  setSelectedIds([]);
                  playKidSound("pop");
                }}
              >
                Clear
              </button>
              <button onClick={celebrateConnection} disabled={!complete || currentSaved}>
                {currentSaved ? "Saved idea" : "That could work"}
              </button>
              <button onClick={tryAnotherPair} disabled={!complete}>
                New pair
              </button>
              <button onClick={surprisePair}>Surprise pair</button>
            </div>
          </div>
          <div className="connection-counter" aria-label="Connections made">
            {[0, 1, 2].map((index) => (
              <span key={index} className={index < madeConnections.length ? "on" : ""} />
            ))}
          </div>
          <div className="connection-flex-cue">
            {connectionFlexCue(madeConnections)}
          </div>
          {madeConnections.length ? (
            <div className="connection-made-list" aria-label="Saved connection ideas">
              {madeConnections.map((item) => (
                <span key={item.key}>
                  <b>{item.icons}</b>
                  {item.name}
                </span>
              ))}
            </div>
          ) : null}
        </div>

        <div className="connection-card-grid" aria-label="Choose helper cards">
          {MASHUP_ITEMS.map((item) => {
            const selected = selectedIds.includes(item.id);
            return (
              <button
                key={item.id}
                className={`connection-card ${selected ? "selected" : ""}`}
                onClick={() => toggleItem(item.id)}
                aria-pressed={selected ? "true" : "false"}
              >
                <span>{item.icon}</span>
                <strong>{item.label}</strong>
                <small>{item.power}</small>
              </button>
            );
          })}
        </div>
      </div>
    </section>
  );
}
