// Shared app state + data used by both directions.
// Both direction components consume useQM() and render screens from the same data model.

const FOCUS_CATEGORIES = [
  { value: 'anxiety', label: 'Anxiety Relief', emoji: '🌿' },
  { value: 'sleep',   label: 'Better Sleep',   emoji: '🌙' },
  { value: 'confidence', label: 'Confidence',  emoji: '✨' },
  { value: 'trauma',  label: 'Release',        emoji: '🕊' },
  { value: 'focus',   label: 'Deep Focus',     emoji: '◎' },
  { value: 'habits',  label: 'Habit Change',   emoji: '↻' },
];

const MUSIC_TRACKS = [
  { id: 'rain',   name: 'Rainfall on Cedar',    tags:['rain','nature','calming'] },
  { id: 'ocean',  name: 'Tidepool',             tags:['ocean','ambient','sleep'] },
  { id: 'drone',  name: 'Soft Drone 432Hz',     tags:['ambient','deep','grounding'] },
  { id: 'piano',  name: 'Moonlit Piano',        tags:['piano','gentle','melodic'] },
  { id: 'forest', name: 'Forest at Dusk',       tags:['nature','warm'] },
  { id: 'wind',   name: 'Wind Through Grass',   tags:['nature','minimal'] },
  { id: 'bowls',  name: 'Tibetan Bowls',        tags:['resonant','meditation'] },
  { id: 'space',  name: 'Interstellar Hush',    tags:['ambient','deep'] },
  { id: 'fire',   name: 'Crackling Hearth',     tags:['cozy','grounding'] },
  { id: 'stream', name: 'Mountain Stream',      tags:['water','nature'] },
  { id: 'hum',    name: 'Evening Hum',          tags:['drone','sleep'] },
  { id: 'none',   name: 'Pure Voice',           tags:['no music'] },
];

const SAMPLE_SESSIONS = [
  { id: 's1', title: 'Releasing evening anxiety', focus: 'anxiety', status: 'audio_ready', date: '2d ago', duration: 22 },
  { id: 's2', title: 'Deep restorative sleep',    focus: 'sleep',   status: 'audio_ready', date: '5d ago', duration: 38 },
  { id: 's3', title: 'Confidence before a hard conversation', focus: 'confidence', status: 'script_ready', date: 'today', duration: 15 },
];

const SAMPLE_SCRIPT = `Find a position that feels supportive. Eyes softly closed, or gaze low and still.
Let your breath settle — not forced, not held. Just an easy rhythm arriving on its own.

[Induction — descending staircase metaphor]
And as you notice the weight of your body settling into the surface below, imagine a wide staircase appearing in front of you — warm stone, lit by something you can't quite see. With each step down, ten … nine … eight … you feel the day loosening its grip. Seven … six … a softening behind the eyes. Five … four … the shoulders release what they've been carrying. Three … two … one …

[Resource activation — your anchoring memory]
You mentioned a place where you felt completely at ease — standing on the cliffs near your grandparents' house, salt in the air. Let that memory come forward now. Not as a picture, but as a feeling in the body. The exact temperature of the light. The exact give of the ground beneath you.

[Core change work]
The part of you that has been working so hard to keep you safe — the one who tightens the chest before bed, who rehearses tomorrow in the middle of the night — that part has been doing its best. Thank it. And then, gently, let it know: tonight you are safe enough to rest.`;

const QMContext = React.createContext(null);

function QMProvider({ children }) {
  // Global app state — screen, selected session, audio player state, intake step
  const [screen, setScreen] = React.useState('home');
  const [sessionId, setSessionId] = React.useState('s1');
  const [intakeStep, setIntakeStep] = React.useState(0);
  const [audioState, setAudioState] = React.useState('ready'); // setup | generating | ready
  const [isPlaying, setIsPlaying] = React.useState(false);
  const [progress, setProgress] = React.useState(0.34);
  const [selectedTrack, setSelectedTrack] = React.useState('rain');
  const [moodBefore, setMoodBefore] = React.useState(4);
  const [moodAfter, setMoodAfter] = React.useState(null);
  const [focusCategory, setFocusCategory] = React.useState('anxiety');
  const [intakeAnswers, setIntakeAnswers] = React.useState({
    mainIssue: '',
    desiredShift: '',
    successVision: '',
    duration: 25,
    postState: 'awake',
  });

  // drive the progress when playing
  React.useEffect(() => {
    if (!isPlaying) return;
    const id = setInterval(() => {
      setProgress(p => {
        const next = p + 0.003;
        if (next >= 1) { setIsPlaying(false); return 1; }
        return next;
      });
    }, 80);
    return () => clearInterval(id);
  }, [isPlaying]);

  const current = SAMPLE_SESSIONS.find(s => s.id === sessionId) || SAMPLE_SESSIONS[0];

  const value = {
    screen, setScreen,
    sessionId, setSessionId,
    intakeStep, setIntakeStep,
    audioState, setAudioState,
    isPlaying, setIsPlaying,
    progress, setProgress,
    selectedTrack, setSelectedTrack,
    moodBefore, setMoodBefore,
    moodAfter, setMoodAfter,
    focusCategory, setFocusCategory,
    intakeAnswers, setIntakeAnswers,
    sessions: SAMPLE_SESSIONS,
    tracks: MUSIC_TRACKS,
    current,
    script: SAMPLE_SCRIPT,
    focusCats: FOCUS_CATEGORIES,
  };

  return <QMContext.Provider value={value}>{children}</QMContext.Provider>;
}

function useQM() { return React.useContext(QMContext); }

// Breathing gradient — a canvas that slowly morphs color + scale, synced to isPlaying.
function BreathingGradient({ palette, size = 260, playing = true }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const c = ref.current; if (!c) return;
    const ctx = c.getContext('2d');
    const dpr = window.devicePixelRatio || 1;
    c.width = size * dpr; c.height = size * dpr;
    ctx.scale(dpr, dpr);
    let raf; let t0 = performance.now();
    const draw = (now) => {
      const t = (now - t0) / 1000;
      const breath = 0.5 + 0.5 * Math.sin(t * (playing ? 0.6 : 0.25));
      ctx.clearRect(0, 0, size, size);
      // base wash
      const base = ctx.createRadialGradient(size/2, size/2, 0, size/2, size/2, size*0.55);
      base.addColorStop(0, palette[0]);
      base.addColorStop(1, palette[1]);
      ctx.fillStyle = base;
      ctx.fillRect(0,0,size,size);
      // two breathing orbs
      for (let i=0;i<3;i++) {
        const ang = t*0.3 + i*2.094;
        const r = size*0.28 + breath*size*0.08;
        const cx = size/2 + Math.cos(ang)*size*0.12;
        const cy = size/2 + Math.sin(ang)*size*0.12;
        const g = ctx.createRadialGradient(cx, cy, 0, cx, cy, r);
        g.addColorStop(0, palette[2+i] || palette[2]);
        g.addColorStop(1, 'rgba(0,0,0,0)');
        ctx.globalCompositeOperation = 'lighter';
        ctx.fillStyle = g;
        ctx.beginPath(); ctx.arc(cx, cy, r, 0, Math.PI*2); ctx.fill();
      }
      ctx.globalCompositeOperation = 'source-over';
      raf = requestAnimationFrame(draw);
    };
    raf = requestAnimationFrame(draw);
    return () => cancelAnimationFrame(raf);
  }, [palette.join('|'), size, playing]);
  return <canvas ref={ref} style={{ width: size, height: size, borderRadius: 9999, display: 'block' }} />;
}

// Tiny "live" waveform
function MiniWave({ color = '#00D4FF', playing = true, width = 160, height = 32 }) {
  const [t, setT] = React.useState(0);
  React.useEffect(() => {
    if (!playing) return;
    let raf; const loop = () => { setT(x => x + 0.06); raf = requestAnimationFrame(loop); };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, [playing]);
  const bars = 28;
  return (
    <svg width={width} height={height} viewBox={`0 0 ${bars} 10`}>
      {Array.from({length: bars}).map((_, i) => {
        const h = 2 + Math.abs(Math.sin(t*1.1 + i*0.5)) * 6 * (0.3 + 0.7*Math.sin(i*0.2 + t*0.4)**2);
        return <rect key={i} x={i+0.1} y={5 - h/2} width={0.8} height={h} rx={0.3} fill={color} opacity={0.5 + 0.5*Math.sin(i*0.3+t)} />;
      })}
    </svg>
  );
}

Object.assign(window, { QMProvider, useQM, BreathingGradient, MiniWave, QM_FOCUS: FOCUS_CATEGORIES, QM_TRACKS: MUSIC_TRACKS });
