const { useState, useMemo, useRef, useEffect } = React;

const NOTES = ["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];

const SCALES = [
  { id: "chromatic", name: "Chromatic", set: 1, pos: 2, intervals: [0,1,2,3,4,5,6,7,8,9,10,11], mood: "Tense, anxious, atonal", desc: "All 12 semitones. Dense, uneasy, cinematic tension." },
  { id: "major-pent", name: "Major Pentatonic", set: 1, pos: 4, intervals: [0,2,4,7,9], mood: "Bright, joyful, open", desc: "The happiest scale. No wrong notes." },
  { id: "minor-pent", name: "Minor Pentatonic", set: 1, pos: 5, intervals: [0,3,5,7,10], mood: "Soulful, bluesy, warm", desc: "Foundation of blues. Warm sadness without despair." },
  { id: "blues", name: "Blues", set: 1, pos: 6, intervals: [0,3,5,6,7,10], mood: "Gritty, expressive, raw", desc: "Minor pentatonic + blue note. Dirty and human." },
  { id: "arabic", name: "Arabic", set: 1, pos: 7, intervals: [0,1,4,5,7,8,11], mood: "Exotic, mystical, dramatic", desc: "Double harmonic major. Intense Middle Eastern drama." },
  { id: "pelog", name: "Pelog", set: 1, pos: 8, intervals: [0,1,3,7,8], mood: "Otherworldly, ancient", desc: "Indonesian gamelan. Alien, ceremonial atmospheres." },
  { id: "hirajoshi", name: "Hiraj\u014Dshi", set: 1, pos: 9, intervals: [0,2,3,7,8], mood: "Haunting, elegant, lonely", desc: "Japanese scale. An ache that never resolves." },
  { id: "chinese", name: "Chinese", set: 1, pos: 10, intervals: [0,4,6,7,11], mood: "Bright, crystalline, suspended", desc: "Pentatonic with lydian flavor. Otherworldly brightness." },
  { id: "ionian", name: "Ionian (Major)", set: 2, pos: 1, intervals: [0,2,4,5,7,9,11], mood: "Happy, resolved, complete", desc: "Standard major scale. Bright, familiar." },
  { id: "dorian", name: "Dorian", set: 2, pos: 2, intervals: [0,2,3,5,7,9,10], mood: "Cool, sophisticated, bittersweet", desc: "Minor with raised 6th. Incredibly versatile." },
  { id: "phrygian", name: "Phrygian", set: 2, pos: 3, intervals: [0,1,3,5,7,8,10], mood: "Dark, Spanish, ominous", desc: "The \u266D2 creates instant tension and gravity." },
  { id: "lydian", name: "Lydian", set: 2, pos: 4, intervals: [0,2,4,6,7,9,11], mood: "Dreamy, floating, wonder", desc: "Raised 4th \u2014 weightlessness and awe." },
  { id: "mixolydian", name: "Mixolydian", set: 2, pos: 5, intervals: [0,2,4,5,7,9,10], mood: "Warm, earthy, bluesy major", desc: "Major with \u266D7. Lived-in and honest." },
  { id: "aeolian", name: "Aeolian (Nat. Minor)", set: 2, pos: 6, intervals: [0,2,3,5,7,8,10], mood: "Sad, introspective, autumnal", desc: "Classic minor. Deep sadness without drama." },
  { id: "locrian", name: "Locrian", set: 2, pos: 7, intervals: [0,1,3,5,6,8,10], mood: "Unstable, anxious, desolate", desc: "Darkest mode. Even the root chord is diminished." },
  { id: "mel-minor", name: "Melodic Minor", set: 3, pos: 1, intervals: [0,2,3,5,7,9,11], mood: "Yearning, sophisticated", desc: "Tension between minor 3rd and major 7th." },
  { id: "dorian-b2", name: "Dorian \u266D2", set: 3, pos: 2, intervals: [0,1,3,5,7,9,10], mood: "Tense beauty, Middle Eastern", desc: "Dorian + Phrygian \u266D2. Deeply evocative." },
  { id: "lydian-aug", name: "Lydian Augmented", set: 3, pos: 3, intervals: [0,2,4,6,8,9,11], mood: "Cosmic, expansive, shimmering", desc: "Maximum brightness and lift." },
  { id: "lydian-dom", name: "Lydian Dominant", set: 3, pos: 4, intervals: [0,2,4,6,7,9,10], mood: "Triumphant, tension, push-pull", desc: "Lydian dreaminess meets Mixolydian earth." },
  { id: "mixo-b6", name: "Mixolydian \u266D6", set: 3, pos: 5, intervals: [0,2,4,5,7,8,10], mood: "Bittersweet, devotional", desc: "Bright on top, dark underneath." },
  { id: "locrian-2", name: "Locrian \u266F2", set: 3, pos: 6, intervals: [0,2,3,5,6,8,10], mood: "Dark but grounded", desc: "Locrian made usable. Still deeply dark." },
  { id: "super-locrian", name: "Super Locrian", set: 3, pos: 7, intervals: [0,1,3,4,6,8,10], mood: "Maximum tension, dissolution", desc: "Every note altered. Reality dissolving." },
];

const S = Object.fromEntries(SCALES.map(s => [s.id, s]));
const SET_COL = { 1: "#E8C547", 2: "#6BA0D6", 3: "#C77DBA" };
const mono = "'JetBrains Mono','SF Mono','Fira Code',monospace";

const MOODS = {
  bright:     { label: "Bright / Hopeful",           color: "#FFD166", bg: "rgba(255,200,60,0.10)",  scales: ["major-pent","chinese","ionian"] },
  warm:       { label: "Warm / Grounded",             color: "#EF824B", bg: "rgba(239,130,75,0.10)",  scales: ["minor-pent","blues","dorian","mixolydian","mixo-b6"] },
  open:       { label: "Open / Floating",             color: "#78D2C8", bg: "rgba(120,210,200,0.10)", scales: ["lydian","lydian-aug","lydian-dom"] },
  melancholic:{ label: "Melancholic / Introspective",  color: "#82A0DC", bg: "rgba(130,160,220,0.10)", scales: ["hirajoshi","aeolian","mel-minor"] },
  dark:       { label: "Dark / Intense",              color: "#8C64AA", bg: "rgba(140,100,170,0.10)", scales: ["phrygian","locrian","dorian-b2","locrian-2","arabic"] },
  eerie:      { label: "Eerie / Unstable",            color: "#B45064", bg: "rgba(180,80,100,0.10)",  scales: ["pelog","chromatic","super-locrian"] },
};
const MOOD_ORDER = ["bright","warm","open","melancholic","dark","eerie"];

const REL_TYPES = {
  superset: { label: "Your scale fits inside these", desc: "Every note you play appears in the complement, plus more" },
  subset:   { label: "These fit inside your scale", desc: "Everything they play, you already play" },
  relative: { label: "Modal relatives", desc: "Same parent scale, different expression" },
  borrowed: { label: "Borrowed tension", desc: "Mostly shared notes with a few colorful differences" },
  polymodal:{ label: "Polymodal contrast", desc: "Different enough to create tension and movement" },
};
const REL_ORDER = ["superset","subset","relative","borrowed","polymodal"];

const GRID_COL = { shared: "#E8E8E8", "a-only": "#6BA0D6", "b-only": "#EF824B", empty: "#1e1e1e" };

/* ── Utilities ── */

function canonicalForm(intervals) {
  if (!intervals || intervals.length === 0) return "";
  const ps = new Set(intervals);
  let best = null;
  for (let r = 0; r < 12; r++) {
    const rotated = [...ps].map(p => ((p - r) + 12) % 12).sort((a, b) => a - b).join(",");
    if (best === null || rotated < best) best = rotated;
  }
  return best;
}

function classifyRelationship(aInt, bInt) {
  if (!aInt || !bInt) return null;
  const a = new Set(aInt), b = new Set(bInt);
  const shared = [...a].filter(n => b.has(n));
  const aOnly = [...a].filter(n => !b.has(n));
  const bOnly = [...b].filter(n => !a.has(n));
  if (aOnly.length === 0 && bOnly.length === 0) return null;
  if (aOnly.length === 0) return { type: "subset", shared: shared.length };
  if (bOnly.length === 0) return { type: "superset", shared: shared.length };
  if (canonicalForm(aInt) === canonicalForm(bInt)) return { type: "relative", shared: shared.length };
  const union = new Set([...a, ...b]);
  if (shared.length / union.size >= 0.55 && aOnly.length <= 3 && bOnly.length <= 3) return { type: "borrowed", shared: shared.length };
  return { type: "polymodal", shared: shared.length };
}

function getComplementaryCandidates(primaryId) {
  const primary = S[primaryId];
  if (!primary?.intervals) return {};
  const results = {};
  REL_ORDER.forEach(t => { results[t] = []; });
  SCALES.forEach(s => {
    if (s.id === primaryId || !s.intervals || s.intervals.length <= 1) return;
    const rel = classifyRelationship(primary.intervals, s.intervals);
    if (rel) results[rel.type].push({ ...s, shared: rel.shared });
  });
  Object.keys(results).forEach(t => results[t].sort((a, b) => b.shared - a.shared));
  return results;
}

function computeGrid(aInt, bInt) {
  if (!aInt || !bInt) return new Array(12).fill("empty");
  const a = new Set(aInt), b = new Set(bInt);
  return Array.from({ length: 12 }, (_, i) => {
    const inA = a.has(i), inB = b.has(i);
    if (inA && inB) return "shared";
    if (inA) return "a-only";
    if (inB) return "b-only";
    return "empty";
  });
}

function midiToNote(midi) {
  return NOTES[midi % 12] + (Math.floor(midi / 12) - 1);
}

/* ── Components ── */

function PianoRoll({ intervals, rootIdx }) {
  if (!intervals) return null;
  const black = [1,3,6,8,10];
  return (
    <div style={{ display: "flex", alignItems: "flex-end", height: 28, marginTop: 4 }}>
      {Array.from({ length: 12 }, (_, i) => {
        const isB = black.includes(i);
        const on = intervals.includes(i);
        const isRoot = i === 0;
        return (
          <div key={i} style={{
            width: isB ? 11 : 15, height: isB ? 18 : 28, borderRadius: 2,
            background: on ? (isRoot ? "#FFD166" : "#ddd") : (isB ? "#1a1a1a" : "#2a2a2a"),
            border: `1px solid ${on ? (isRoot ? "#FFD16688" : "#88888866") : "#333"}`,
            marginRight: 1, marginLeft: isB ? -5 : 0,
            zIndex: isB ? 2 : 1, alignSelf: isB ? "flex-start" : "flex-end",
            display: "flex", alignItems: "flex-end", justifyContent: "center", paddingBottom: 1,
            fontSize: 6, color: on ? "#111" : "transparent", fontWeight: isRoot ? 700 : 400,
          }}>{on ? NOTES[(i + rootIdx) % 12] : ""}</div>
        );
      })}
    </div>
  );
}

function ChromaticStrip({ grid, rootIdx, currentStep, mini }) {
  return (
    <div style={{ display: "flex", gap: mini ? 1 : 2, height: mini ? 14 : 48 }}>
      {grid.map((type, i) => {
        const isActive = currentStep === i;
        return (
          <div key={i} style={{
            flex: 1, borderRadius: mini ? 2 : 3,
            background: isActive ? "#FFD166" : GRID_COL[type],
            border: isActive ? "2px solid #FFD166" : `1px solid ${type === "empty" ? "#2a2a2a" : GRID_COL[type] + "66"}`,
            display: "flex", alignItems: "center", justifyContent: "center",
            fontSize: mini ? 0 : 9, fontFamily: mono, fontWeight: 500,
            color: isActive ? "#111" : (type === "shared" ? "#111" : (type === "empty" ? "transparent" : "#fff")),
            transition: "background 0.05s",
          }}>{!mini ? NOTES[(rootIdx + i) % 12] : ""}</div>
        );
      })}
    </div>
  );
}

function AuditionPanel({ grid, rootIdx, primaryName, candidateName }) {
  const [isPlaying, setIsPlaying] = useState(false);
  const [currentStep, setCurrentStep] = useState(-1);
  const audioRef = useRef(null);
  const loopRef = useRef(null);
  const gridRef = useRef(grid);
  const rootRef = useRef(rootIdx);
  const stepRef = useRef(0);

  useEffect(() => { gridRef.current = grid; }, [grid]);
  useEffect(() => { rootRef.current = rootIdx; }, [rootIdx]);

  const stop = () => {
    if (loopRef.current) { loopRef.current.stop(); loopRef.current.dispose(); loopRef.current = null; }
    if (typeof Tone !== "undefined") { Tone.Transport.stop(); Tone.Transport.position = 0; }
    stepRef.current = 0;
    setCurrentStep(-1);
    setIsPlaying(false);
  };

  useEffect(() => { return () => stop(); }, []);

  const play = async () => {
    if (typeof Tone === "undefined") return;
    await Tone.start();

    if (!audioRef.current) {
      const panA = new Tone.Panner(-0.4).toDestination();
      const panB = new Tone.Panner(0.4).toDestination();
      const env = { attack: 0.01, decay: 0.12, sustain: 0.15, release: 0.25 };
      audioRef.current = {
        synthA: new Tone.Synth({ oscillator: { type: "sine" }, envelope: env, volume: -8 }).connect(panA),
        synthB: new Tone.Synth({ oscillator: { type: "triangle" }, envelope: env, volume: -8 }).connect(panB),
      };
    }

    stepRef.current = 0;
    Tone.Transport.bpm.value = 150;

    loopRef.current = new Tone.Loop((time) => {
      const g = gridRef.current;
      const step = stepRef.current;
      const type = g[step];
      const note = midiToNote(48 + rootRef.current + step);
      const { synthA, synthB } = audioRef.current;

      if (type === "shared") {
        synthA.triggerAttackRelease(note, "16n", time, 0.4);
        synthB.triggerAttackRelease(note, "16n", time, 0.4);
      } else if (type === "a-only") {
        synthA.triggerAttackRelease(note, "16n", time, 0.7);
      } else if (type === "b-only") {
        synthB.triggerAttackRelease(note, "16n", time, 0.7);
      }

      Tone.Draw.schedule(() => setCurrentStep(step), time);
      stepRef.current = (step + 1) % 12;
    }, "8n");

    loopRef.current.start(0);
    Tone.Transport.start();
    setIsPlaying(true);
  };

  return (
    <div style={{ marginTop: 16, padding: 16, background: "rgba(255,255,255,0.03)", border: "1px solid #2a2a2a", borderRadius: 10 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
        <div style={{ fontSize: 12, fontFamily: mono, color: "#999" }}>
          <span style={{ color: "#6BA0D6" }}>{primaryName}</span>
          <span style={{ color: "#555", margin: "0 8px" }}>{"\u2194"}</span>
          <span style={{ color: "#EF824B" }}>{candidateName}</span>
        </div>
        <div style={{ display: "flex", gap: 4, fontSize: 10, fontFamily: mono }}>
          <span style={{ color: "#6BA0D6" }}>{"\u25A0"} primary</span>
          <span style={{ color: "#E8E8E8" }}>{"\u25A0"} shared</span>
          <span style={{ color: "#EF824B" }}>{"\u25A0"} complement</span>
        </div>
      </div>
      <ChromaticStrip grid={grid} rootIdx={rootIdx} currentStep={currentStep} />
      <div style={{ marginTop: 12, display: "flex", justifyContent: "center" }}>
        <button onClick={isPlaying ? stop : play} style={{
          background: isPlaying ? "rgba(255,255,255,0.06)" : "#FFD166",
          color: isPlaying ? "#888" : "#111",
          border: `1px solid ${isPlaying ? "#333" : "#FFD166"}`,
          borderRadius: 6, padding: "8px 24px", fontSize: 13, fontWeight: 600,
          fontFamily: mono, transition: "all 0.15s ease",
        }}>{isPlaying ? "\u25A0 Stop" : "\u25B6 Play"}</button>
      </div>
    </div>
  );
}

function App() {
  const [rootIdx, setRootIdx] = useState(0);
  const [selectedMood, setSelectedMood] = useState(null);
  const [primaryId, setPrimaryId] = useState(null);
  const [candidateId, setCandidateId] = useState(null);

  const changeMood = (m) => { setSelectedMood(selectedMood === m ? null : m); setPrimaryId(null); setCandidateId(null); };
  const changePrimary = (id) => { setPrimaryId(primaryId === id ? null : id); setCandidateId(null); };

  const candidates = useMemo(() => primaryId ? getComplementaryCandidates(primaryId) : {}, [primaryId]);
  const primary = primaryId ? S[primaryId] : null;
  const candidate = candidateId ? S[candidateId] : null;
  const grid = useMemo(() => {
    if (!primary?.intervals || !candidate?.intervals) return null;
    return computeGrid(primary.intervals, candidate.intervals);
  }, [primary, candidate]);

  const moodColor = selectedMood ? MOODS[selectedMood].color : "#666";

  return (
    <div style={{ minHeight: "100vh", background: "#111", color: "#E8E8E8", fontFamily: "'Inter',-apple-system,sans-serif", padding: "24px 20px", maxWidth: 680, margin: "0 auto" }}>

      {/* Header */}
      <div style={{ marginBottom: 28, display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
        <div>
          <div style={{ fontSize: 10, letterSpacing: 3, color: "#555", textTransform: "uppercase", fontFamily: mono, marginBottom: 4 }}>CLANK CHAOS</div>
          <h1 style={{ fontSize: 24, fontWeight: 700, margin: 0, letterSpacing: -0.5 }}>Scale Explorer</h1>
          <p style={{ fontSize: 12, color: "#666", margin: "3px 0 0" }}>Explore how two scales sound together</p>
        </div>
        <a href="https://www.clank.eu/chaos" target="_blank" rel="noopener noreferrer" style={{
          fontSize: 10, color: "#555", fontFamily: mono, marginTop: 4, borderBottom: "1px solid #333", paddingBottom: 1,
        }}>clank.eu/chaos {"\u2192"}</a>
      </div>

      {/* Root */}
      <div style={{ marginBottom: 20 }}>
        <div style={{ fontSize: 10, color: "#666", fontFamily: mono, letterSpacing: 2, marginBottom: 6 }}>ROOT NOTE</div>
        <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
          {NOTES.map((n, i) => (
            <button key={n} onClick={() => setRootIdx(i)} style={{
              background: rootIdx === i ? "#FFD166" : "rgba(255,255,255,0.04)",
              color: rootIdx === i ? "#111" : "#777",
              border: `1px solid ${rootIdx === i ? "#FFD166" : "#333"}`,
              borderRadius: 5, padding: "6px 12px", fontSize: 13, fontWeight: rootIdx === i ? 700 : 400,
              fontFamily: mono, transition: "all 0.15s ease", minWidth: 36, textAlign: "center",
            }}>{n}</button>
          ))}
        </div>
      </div>

      {/* Mood */}
      <div style={{ marginBottom: 20 }}>
        <div style={{ fontSize: 10, color: "#666", fontFamily: mono, letterSpacing: 2, marginBottom: 6 }}>MOOD</div>
        <div style={{ display: "flex", gap: 5, flexWrap: "wrap" }}>
          {MOOD_ORDER.map(m => {
            const mood = MOODS[m];
            const isSel = selectedMood === m;
            return (
              <button key={m} onClick={() => changeMood(m)} style={{
                background: isSel ? mood.bg : "rgba(255,255,255,0.03)",
                color: isSel ? mood.color : "#666",
                border: `1px solid ${isSel ? mood.color : "#333"}`,
                borderRadius: 5, padding: "6px 12px", fontSize: 11, fontWeight: isSel ? 600 : 400,
                fontFamily: mono, transition: "all 0.15s ease",
              }}>{mood.label}</button>
            );
          })}
        </div>
      </div>

      {/* Primary Scale Selection */}
      {selectedMood && (
        <div style={{ marginBottom: 20 }}>
          <div style={{ fontSize: 10, color: moodColor, fontFamily: mono, letterSpacing: 2, marginBottom: 6 }}>YOUR SCALE</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
            {MOODS[selectedMood].scales.map(id => {
              const s = S[id];
              if (!s) return null;
              const isSel = primaryId === id;
              return (
                <div key={id} onClick={() => changePrimary(id)} style={{
                  background: isSel ? MOODS[selectedMood].bg : "rgba(255,255,255,0.02)",
                  border: `1px solid ${isSel ? moodColor + "66" : "#2a2a2a"}`,
                  borderRadius: 8, padding: "10px 14px", cursor: "pointer",
                  transition: "all 0.15s ease",
                }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <span style={{ color: SET_COL[s.set], fontSize: 11, fontFamily: mono, fontWeight: 700 }}>{s.set}-{s.pos}</span>
                    <span style={{ color: "#E8E8E8", fontSize: 14, fontWeight: 600, fontFamily: mono }}>{s.name}</span>
                  </div>
                  <div style={{ fontSize: 11, color: moodColor, marginTop: 3, fontStyle: "italic" }}>{s.mood}</div>
                  <div style={{ fontSize: 11, color: "#777", marginTop: 2, lineHeight: 1.4 }}>{s.desc}</div>
                  <PianoRoll intervals={s.intervals} rootIdx={rootIdx} />
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Complementary Candidates */}
      {primaryId && (
        <div style={{ marginBottom: 20 }}>
          <div style={{ fontSize: 10, color: "#666", fontFamily: mono, letterSpacing: 2, marginBottom: 6 }}>COMPLEMENTS</div>
          {REL_ORDER.map(type => {
            const items = candidates[type];
            if (!items || items.length === 0) return null;
            const rt = REL_TYPES[type];
            return (
              <div key={type} style={{ marginBottom: 12 }}>
                <div style={{ marginBottom: 4 }}>
                  <div style={{ fontSize: 12, color: "#ccc", fontFamily: mono, fontWeight: 600 }}>{rt.label}</div>
                  <div style={{ fontSize: 10, color: "#555", fontStyle: "italic" }}>{rt.desc}</div>
                </div>
                <div style={{ display: "flex", flexDirection: "column", gap: 3 }}>
                  {items.map(s => {
                    const isSel = candidateId === s.id;
                    const g = computeGrid(primary.intervals, s.intervals);
                    return (
                      <div key={s.id} onClick={() => setCandidateId(isSel ? null : s.id)} style={{
                        display: "flex", alignItems: "center", gap: 8, padding: "6px 10px",
                        background: isSel ? "rgba(239,130,75,0.08)" : "rgba(255,255,255,0.02)",
                        border: `1px solid ${isSel ? "#EF824B44" : "#2a2a2a"}`,
                        borderRadius: 6, cursor: "pointer", transition: "all 0.15s ease",
                        flexWrap: "wrap",
                      }}>
                        <span style={{ color: SET_COL[s.set], fontSize: 10, fontFamily: mono, fontWeight: 700 }}>{s.set}-{s.pos}</span>
                        <span style={{ color: "#ccc", fontSize: 12, fontFamily: mono, fontWeight: 500 }}>{s.name}</span>
                        <span style={{ color: "#555", fontSize: 10, fontFamily: mono }}>{s.mood.split(",")[0]}</span>
                        <span style={{ color: "#666", fontSize: 10, fontFamily: mono, marginLeft: "auto" }}>{s.shared} shared</span>
                        <div style={{ width: 96, flexShrink: 0 }}>
                          <ChromaticStrip grid={g} rootIdx={rootIdx} currentStep={-1} mini />
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* Audition */}
      {grid && candidate && (
        <AuditionPanel key={candidateId} grid={grid} rootIdx={rootIdx} primaryName={primary.name} candidateName={candidate.name} />
      )}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
