// quiz-alien-language.jsx
// Alien Language: friendly alien dance-copy patterns with unlock archive and field guide.
// Persists unlocks under planets_alien_language_unlocked in localStorage.

const ALIEN_DANCE_PADS = {
  blue: { icon: "💙", kid: "Blue", color: "#62f3ff" },
  yellow: { icon: "⭐", kid: "Gold", color: "#ffd66b" },
  green: { icon: "🟢", kid: "Green", color: "#7cffce" },
  pink: { icon: "💗", kid: "Pink", color: "#ff8ee7" },
};

const ALIEN_LANGUAGE_CASES = [
  {
    id: "hello-wave",
    title: "Hello Wiggle",
    civilization: "Friendly Moon Dancer",
    kind: "Dance pattern",
    prompt: "The friendly alien wiggles blue, gold, blue.",
    evidence: ["blue wiggle", "gold hop", "blue wiggle"],
    options: ["blue", "yellow", "green", "pink"],
    answer: "hello friend",
    sequence: ["blue", "yellow", "blue"],
    note: "You copied the hello dance.",
    difficulty: 1,
    sensitivity: 1,
    success: 100,
    primaryGlyphs: ["💙", "⭐", "💙"],
    alienLabel: "hello dance",
    warning: "Blue, gold, blue is the friendly hello dance.",
  },
  {
    id: "help-me",
    title: "Help Hop",
    civilization: "Tiny Crater Crew",
    kind: "Dance pattern",
    prompt: "The alien hops pink, green, gold to ask for a helper.",
    evidence: ["pink hop", "green clap", "gold stomp"],
    options: ["blue", "yellow", "green", "pink"],
    answer: "need help",
    sequence: ["pink", "green", "yellow"],
    note: "You copied the helper dance.",
    difficulty: 1,
    sensitivity: 1,
    success: 100,
    primaryGlyphs: ["💗", "🟢", "⭐"],
    alienLabel: "helper dance",
    warning: "Pink, green, gold means the alien needs a helper.",
  },
  {
    id: "danger-rocks",
    title: "Careful Spin",
    civilization: "Star Path Scout",
    kind: "Dance pattern",
    prompt: "The alien spins gold, blue, green, pink when the path needs care.",
    evidence: ["gold spin", "blue slide", "green clap", "pink stop"],
    options: ["blue", "yellow", "green", "pink"],
    answer: "danger",
    sequence: ["yellow", "blue", "green", "pink"],
    note: "You copied the careful dance.",
    difficulty: 1,
    sensitivity: 1,
    success: 100,
    primaryGlyphs: ["⭐", "💙", "🟢", "💗"],
    alienLabel: "careful dance",
    warning: "Gold, blue, green, pink means slow down and look.",
  },
];

const ALIEN_MEANING_HELPERS = {
  "hello friend": { icon: "👋", kid: "Hello" },
  "need help": { icon: "🛠", kid: "Help" },
  danger: { icon: "⚠", kid: "Danger" },
  "safe greeting": { icon: "👋", kid: "Hello" },
  "storm warning": { icon: "⛈", kid: "Storm" },
  "trade request": { icon: "🎁", kid: "Share" },
  "shared intent": { icon: "🤝", kid: "Together" },
  "territory claim": { icon: "🚩", kid: "Mine" },
  farewell: { icon: "👋", kid: "Bye" },
  "question marker": { icon: "❓", kid: "Question" },
  "danger beacon": { icon: "⚠", kid: "Danger" },
  "gift accepted": { icon: "✅", kid: "Okay" },
  "restricted route": { icon: "⛔", kid: "Stop" },
  "home system": { icon: "🏠", kid: "Home" },
  "celebration path": { icon: "⭐", kid: "Party" },
};

const ALIEN_LANGUAGE_UNLOCKED_KEY = "planets_alien_language_unlocked";
const ALIEN_LANGUAGE_START_MESSAGE =
  "Watch the friendly alien dance, then tap the colors in the same order.";

function readAlienLanguageUnlocked() {
  const saved = readStorageJson(ALIEN_LANGUAGE_UNLOCKED_KEY, []);
  if (!Array.isArray(saved)) return [];
  const validIds = ALIEN_LANGUAGE_CASES.map((item) => item.id);
  return saved.filter((id) => validIds.includes(id));
}

function firstUnsolvedAlienCaseIndex(unlocked) {
  const index = ALIEN_LANGUAGE_CASES.findIndex(
    (item) => !unlocked.includes(item.id),
  );
  return index === -1 ? 0 : index;
}

/*
const ALIEN_LANGUAGE_ARCHIVE_CASES = [
  {
    id: "zeta-glyph",
    title: "Zeta Reticuli Glyph System",
    civilization: "Zeta Reticuli Archive Keepers",
    kind: "Glyph taxonomy",
    prompt: "A three-mark crest appears beside open airlocks.",
    evidence: ["3 pulse marks", "open crescent", "low blue glow"],
    options: ["safe greeting", "storm warning", "trade request"],
    answer: "safe greeting",
    note: "Repeated open shapes usually mark permission, welcome, or safe passage.",
    difficulty: 2,
    sensitivity: 3,
    success: 88,
    primaryGlyphs: ["<>", "O--", "::", "<O>"],
    alienLabel: "AUR-VEK",
    warning: "Do not mirror the crest upside down; inversion means sealed passage.",
  },
  {
    id: "andromeda-gesture",
    title: "Andromeda Gesture Library: Sequence 47",
    civilization: "Andromeda Collective",
    kind: "Gesture sequence",
    prompt: "A visitor touches heart, visor, then points to the horizon.",
    evidence: ["heart tap", "visor lift", "horizon point"],
    options: ["shared intent", "territory claim", "farewell"],
    answer: "shared intent",
    note: "The gesture begins with self, reveals attention, then extends purpose outward.",
    difficulty: 3,
    sensitivity: 5,
    success: 74,
    primaryGlyphs: ["I", "[]", "->", "I[]->"],
    alienLabel: "SEN-TALA",
    warning: "Skipping the visor-lift step reads as suspicion.",
  },
  {
    id: "orion-pulsar",
    title: "Orion Veil Pulsar Resonance",
    civilization: "Orion Veil Signal Choir",
    kind: "Sound-wave pattern",
    prompt: "The same tone repeats twice, pauses, then returns brighter.",
    evidence: ["two short tones", "one long rest", "brighter return"],
    options: ["question marker", "danger beacon", "gift accepted"],
    answer: "question marker",
    note: "A repeated pulse followed by silence leaves space for a response.",
    difficulty: 4,
    sensitivity: 2,
    success: 69,
    primaryGlyphs: ["beep", "beep", "...", "BEEP"],
    alienLabel: "KO-RI?",
    warning: "Answer before the rest completes and the choir treats it as interruption.",
  },
  {
    id: "triangulum-map",
    title: "Triangulum Forbidden Quadrant Map",
    civilization: "Triangulum Navigators",
    kind: "Star-map syntax",
    prompt: "Three bright stars form a gate, but one route line is broken.",
    evidence: ["tri-star gate", "broken route", "dim red marker"],
    options: ["restricted route", "home system", "celebration path"],
    answer: "restricted route",
    note: "Broken paths are not missing data; they are deliberate diplomatic boundaries.",
    difficulty: 5,
    sensitivity: 4,
    success: 61,
    primaryGlyphs: ["*", "*", "*", "-/-"],
    alienLabel: "NOX-LIM",
    warning: "Crossing a broken route without a request can end first-contact talks.",
  },
];
*/

function alienMeaningHelper(option) {
  return ALIEN_MEANING_HELPERS[option] || { icon: "✨", kid: option };
}

function alienDancePad(step) {
  return ALIEN_DANCE_PADS[step] || { icon: "✨", kid: step, color: "#8feaff" };
}

function AlienGlyphSpecimen({ item, active }) {
  return (
    <div className={`alien-specimen ${active ? "active" : ""}`} aria-hidden="true">
      <div className="alien-orbit-ring" />
      <div className="alien-main-glyph">
        {item.primaryGlyphs.map((glyph, index) => (
          <span key={`${item.id}-${glyph}-${index}`}>{glyph}</span>
        ))}
      </div>
      <div className="alien-waveform">
        {[32, 54, 38, 72, 46, 64, 28, 58].map((height, index) => (
          <i key={index} style={{ height: `${height}%` }} />
        ))}
      </div>
    </div>
  );
}

function AlienDanceFriend({ item, activeIndex, copiedCount, solved }) {
  const activeStep = item.sequence[activeIndex];
  return (
    <div
      className={`alien-dance-friend ${activeStep ? "dancing" : ""} ${solved ? "solved" : ""}`}
      aria-hidden="true"
      style={{ "--alien-dance-glow": alienDancePad(activeStep || item.sequence[0]).color }}
    >
      <div className="alien-dance-antenna" />
      <div className="alien-dance-face">
        <span className="alien-dance-eye" />
        <span className="alien-dance-smile" />
        <span className="alien-dance-eye" />
      </div>
      <div className="alien-dance-body">
        {item.sequence.map((step, index) => {
          const pad = alienDancePad(step);
          return (
            <span
              key={`${item.id}-${step}-${index}`}
              className={
                index === activeIndex
                  ? "active"
                  : index < copiedCount || solved
                    ? "copied"
                    : ""
              }
              style={{ "--step-color": pad.color }}
            >
              {pad.icon}
            </span>
          );
        })}
      </div>
    </div>
  );
}

function AlienFieldGuideCard({ item, unlocked, compact }) {
  return (
    <article className={`alien-guide-card ${unlocked ? "unlocked" : "locked"} ${compact ? "compact" : ""}`}>
      <header>
        <span>{unlocked ? "Reward card earned" : "Reward card waiting"}</span>
        <h2>{unlocked ? item.title : "Finish this message"}</h2>
        <small>{unlocked ? item.alienLabel : "?"}</small>
      </header>
      <AlienGlyphSpecimen item={item} active={unlocked} />
      <div className="alien-guide-grid">
        <div>
          <strong>Alien friend</strong>
          <p>
            {unlocked
              ? item.civilization
              : "Copy the dance to reveal this card."}
          </p>
        </div>
        <div>
          <strong>Meaning</strong>
          <p>{unlocked ? alienMeaningHelper(item.answer).kid : "???"}</p>
        </div>
      </div>
      <div className="alien-guide-note">
        <strong>{unlocked ? "Kid clue" : "How to unlock"}</strong>
        <p>
          {unlocked
            ? item.warning
            : "Watch the alien, then tap the color pads in the same order."}
        </p>
      </div>
    </article>
  );
}

function AlienLanguageLevel({ onExit }) {
  const [caseIndex, setCaseIndex] = useState(() =>
    firstUnsolvedAlienCaseIndex(readAlienLanguageUnlocked()),
  );
  const [selected, setSelected] = useState(null);
  const [inputSequence, setInputSequence] = useState([]);
  const [activeDanceIndex, setActiveDanceIndex] = useState(-1);
  const [isShowingDance, setIsShowingDance] = useState(false);
  const [message, setMessage] = useState(ALIEN_LANGUAGE_START_MESSAGE);
  const [unlocked, setUnlocked] = useState(() => readAlienLanguageUnlocked());
  const [selectedCardId, setSelectedCardId] = useState(() => {
    const saved = readAlienLanguageUnlocked();
    return saved[0] || ALIEN_LANGUAGE_CASES[0].id;
  });
  const current = ALIEN_LANGUAGE_CASES[caseIndex];
  const solvedCurrent = unlocked.includes(current.id);
  const complete = unlocked.length === ALIEN_LANGUAGE_CASES.length;
  const selectedCard =
    ALIEN_LANGUAGE_CASES.find((item) => item.id === selectedCardId) ||
    ALIEN_LANGUAGE_CASES[0];

  useEffect(() => {
    let timerId;
    if (isShowingDance) {
      let step = 0;
      setInputSequence([]);
      setSelected(null);
      setMessage("Copy this dance when the lights finish.");
      setActiveDanceIndex(0);
      timerId = setInterval(() => {
        step += 1;
        if (step >= current.sequence.length) {
          clearInterval(timerId);
          setActiveDanceIndex(-1);
          setIsShowingDance(false);
          setMessage("Your turn. Tap the colors in the same order.");
          return;
        }
        setActiveDanceIndex(step);
      }, 720);
    }
    return () => {
      if (timerId) clearInterval(timerId);
    };
  }, [current.id, isShowingDance]);

  useEffect(() => {
    writeStorageValue(ALIEN_LANGUAGE_UNLOCKED_KEY, JSON.stringify(unlocked));
  }, [unlocked]);

  const showDance = () => {
    if (solvedCurrent) return;
    playKidSound("pop");
    setIsShowingDance(true);
  };

  const choose = (option) => {
    if (solvedCurrent) return;
    if (isShowingDance) return;
    const nextIndex = inputSequence.length;
    const expected = current.sequence[nextIndex];
    setSelected(option);
    if (option !== expected) {
      playKidSound("pop");
      setInputSequence([]);
      setMessage(`Good try. Start again with ${alienDancePad(current.sequence[0]).kid}.`);
      return;
    }
    const nextSequence = [...inputSequence, option];
    setInputSequence(nextSequence);
    if (nextSequence.length < current.sequence.length) {
      playKidSound("pop");
      setMessage(`Nice. Now tap ${alienDancePad(current.sequence[nextSequence.length]).kid}.`);
      return;
    }
    const helper = alienMeaningHelper(current.answer);
    playKidSound("chime");
    setUnlocked((items) => (items.includes(current.id) ? items : [...items, current.id]));
    setSelectedCardId(current.id);
    setMessage(`Dance matched. It means ${helper.kid}: ${current.note}`);
  };

  const nextCase = () => {
    const nextIndex = Math.min(caseIndex + 1, ALIEN_LANGUAGE_CASES.length - 1);
    setCaseIndex(nextIndex);
    setSelected(null);
    setInputSequence([]);
    setActiveDanceIndex(-1);
    setIsShowingDance(false);
    setSelectedCardId(ALIEN_LANGUAGE_CASES[nextIndex].id);
    setMessage(ALIEN_LANGUAGE_START_MESSAGE);
  };

  const reset = () => {
    setCaseIndex(0);
    setSelected(null);
    setInputSequence([]);
    setActiveDanceIndex(-1);
    setIsShowingDance(false);
    setUnlocked([]);
    setSelectedCardId(ALIEN_LANGUAGE_CASES[0].id);
    setMessage(ALIEN_LANGUAGE_START_MESSAGE);
  };

  return (
    <section className="alien-language-level" aria-label="Alien Language Explorer">
      <Starfield count={260} />
      <button className="planet-sort-back" onClick={onExit}>
        ← Back to planets
      </button>
      <div className="alien-language-shell">
        <div className="alien-decoder-panel">
          <div className="alien-kicker">Alien Dance</div>
          <h1>{complete ? "Alien dance star!" : "Copy the alien's dance"}</h1>
          <p>
            Watch the friendly alien glow, then tap the color pads in the same order.
          </p>
          <div className="alien-kid-steps" aria-label="How to play">
            <span>1 Watch</span>
            <span>2 Copy</span>
            <span>3 Cheer</span>
          </div>
          <div className="alien-case-prompt">
            <span className="alien-clue-label">Dance to copy</span>
            <strong>{current.prompt}</strong>
            <small>Tap the colors in the same order.</small>
          </div>
          <div className="alien-decoder-stage">
            <AlienDanceFriend
              item={current}
              activeIndex={activeDanceIndex}
              copiedCount={inputSequence.length}
              solved={solvedCurrent}
            />
            <div className="alien-evidence-stack" aria-label="Evidence">
              {current.evidence.map((evidence, index) => (
                <span key={`${current.id}-${evidence}-${index}`}>
                  <b>{`0${index + 1}`}</b>
                  <em>Clue part</em>
                  {evidence}
                </span>
              ))}
            </div>
          </div>
          <div
            className={`alien-decoder-message ${solvedCurrent ? "solved" : selected ? "miss" : ""}`}
            role="status"
            aria-live="polite"
          >
            <strong>{message}</strong>
          </div>
          <div className="alien-options">
            {current.options.map((option) => {
              const helper = alienDancePad(option);
              const isNext = !solvedCurrent && !isShowingDance && option === current.sequence[inputSequence.length];
              return (
                <button
                  key={option}
                  className={
                    selected === option
                      ? option === current.sequence[inputSequence.length - 1]
                        ? "correct"
                        : ""
                      : solvedCurrent && current.sequence.includes(option)
                        ? "correct"
                        : isNext
                          ? "helper"
                          : ""
                  }
                  onClick={() => choose(option)}
                  disabled={solvedCurrent || isShowingDance}
                  style={{ "--step-color": helper.color }}
                >
                  <span className="alien-option-icon" aria-hidden="true">{helper.icon}</span>
                  <strong>{helper.kid}</strong>
                  <small>{isNext ? "Next step" : "Dance pad"}</small>
                </button>
              );
            })}
          </div>
          <div className="alien-decoder-actions">
            <div className="alien-progress" aria-label="Unlocked field guide cards">
              {ALIEN_LANGUAGE_CASES.map((item) => (
                <span key={item.id} className={unlocked.includes(item.id) ? "on" : ""} />
              ))}
            </div>
            {complete ? (
              <>
                <button onClick={reset}>Play again</button>
                <button onClick={onExit}>Done</button>
              </>
            ) : solvedCurrent ? (
              <button onClick={nextCase}>Next message</button>
            ) : (
              <button onClick={showDance} disabled={isShowingDance}>
                {isShowingDance ? "Alien dancing" : "Show dance"}
              </button>
            )}
          </div>
        </div>

        <div className="alien-archive-panel">
          <div className="alien-archive-tabs" aria-label="Alien message stickers">
            {ALIEN_LANGUAGE_CASES.map((item, index) => (
              <button
                key={item.id}
                className={selectedCard.id === item.id ? "on" : ""}
                onClick={() => setSelectedCardId(item.id)}
                aria-label={`Reward card ${index + 1}${unlocked.includes(item.id) ? " earned" : " locked"}`}
              >
                {`0${index + 1}`}
              </button>
            ))}
          </div>
          <AlienFieldGuideCard
            item={selectedCard}
            unlocked={unlocked.includes(selectedCard.id)}
          />
        </div>
      </div>
    </section>
  );
}
