// learn.jsx — the Learn hub: written method teachings from Goenka & Dipa Ma,
// their quotes, and a launcher for the interactive "Watch a master" simulation.

const MT_METHODS = {
  goenka: {
    id: 'goenka', teacher: 'S. N. Goenka', accent: '#36E8D2', initials: 'G',
    title: 'Vipassanā — the body sweep',
    tagline: 'Observe sensation. Stay equanimous. Everything changes.',
    duration: '6 min read · then sit',
    intro: 'Vipassanā, as taught by S. N. Goenka in the tradition of U Ba Khin, is the systematic observation of sensation throughout the body. You are not visualising, not repeating a word, not trying to relax. You are training the mind to observe reality directly — and to stop reacting to it.',
    principle: 'Every experience — every thought, emotion, craving, aversion — registers as a sensation on the body. If you can observe those sensations without reacting, you weaken the deep habit of reaction at its very root. The whole method rests on one law you will verify for yourself: anicca — everything that arises, passes away.',
    steps: [
      { h: 'Settle with the breath (Anapana)', b: 'Sit upright and still, eyes closed. Rest attention on the natural breath where it enters and leaves the nostrils. Do not control it — only observe. When the mind wanders, gently bring it back. A few minutes of this sharpens the mind into the instrument you need.' },
      { h: 'Begin at the crown', b: 'Move attention to the top of the head. Pause there. Notice whatever sensation is present — warmth, tingling, pulsing, itching, or even a blank, dull absence. You are not looking for anything in particular. You are only observing what is already there.' },
      { h: 'Sweep, part by part', b: 'Move attention slowly downward — face, neck, shoulders, each arm, the torso, the legs, to the tips of the toes. Give each part a moment. Then sweep back up. Keep the movement orderly and unhurried.' },
      { h: 'Observe — do not react', b: 'Pleasant sensations will tempt craving; unpleasant ones, aversion. Meet both exactly the same way: just observe. The instant you cling or push away, you feed the habit you came here to dissolve. Equanimity is the entire practice.' },
      { h: 'Know impermanence directly', b: 'Watch how each sensation shifts and passes. Nothing stays. This is not a belief to accept — it is a fact you witness, again and again, on your own body. With time, gross solid sensations dissolve into a subtle, flowing field.' },
    ],
    wander: 'The mind will wander a thousand times. That is not failure — noticing it and returning IS the practice. No frustration, no self-judgement. Patiently, persistently, begin again.',
    oneSentence: 'Settle the mind on the breath, then move attention through the body part by part, meeting every sensation — pleasant or unpleasant — with the understanding that it will change.',
    principles: {
      title: 'His practical principles',
      items: [
        'Keep s\u012bla — moral conduct is the soil the practice grows in.',
        'Sit every day, morning and evening, without fail.',
        'Observe sensation, not the story around it.',
        'Remain equanimous — neither craving the pleasant nor resisting the unpleasant.',
        'Remember anicca: whatever arises, passes.',
        'Do not mix techniques — give one method a full, honest chance.',
        'Learn from the source: sit a ten-day course at least once.',
      ],
    },
    resource: { label: 'Learn the real method — free 10-day courses worldwide', org: 'Dhamma.org', url: 'https://www.dhamma.org', note: 'Goenka\u2019s Vipassanā is traditionally learned on a silent residential course, taught entirely free of charge.' },
  },
  dipama: {
    id: 'dipama', teacher: 'Dipa Ma', accent: '#B49CFF', initials: 'DM',
    title: 'The householder’s path',
    tagline: 'No separation between practice and life.',
    duration: '6 min read · then live it',
    intro: 'Dipa Ma proved that awakening is not reserved for monks on mountaintops. A widow raising a child, running a household, she reached the deepest stages of insight — by making mindfulness continuous through ordinary life. Her path is for people with jobs, families, and full days.',
    principle: 'There is no separation between practice and life. Any moment of awareness counts. “If you can be mindful for one moment,” she taught, “you can be mindful for the next.” These single moments, strung together through a day, become the whole path. Consistency matters more than duration.',
    steps: [
      { h: 'Give the mind a home', b: 'Choose one simple anchor — the breath at the belly, or the rising and falling of each footstep. This is where attention returns whenever it is lost. You will return countless times; that returning is the work.' },
      { h: 'Note what arises, gently', b: 'As thoughts, feelings, and sensations appear, note them softly — “planning,” “hearing,” “wanting,” “worrying” — and let them pass. Naming loosens their grip. There is no need to analyse or follow the story.' },
      { h: 'Bring practice into one daily act', b: 'Pick a single ordinary activity — washing dishes, walking to the train, feeding a child — and do it with complete attention. Feel the warm water, the pressing foot, the weight in your hands. Let that one island of mindfulness slowly widen into the rest of your day.' },
      { h: 'Keep the heart soft (mettā)', b: 'Dipa Ma taught lovingkindness alongside insight. Silently wish yourself and others well. A soft heart steadies a clear mind, and turns practice from a grim duty into something you want to return to.' },
      { h: 'Be patient and consistent', b: 'Short, daily, unbroken practice outperforms rare long retreats. Sit a little each day, and carry awareness into your acts. And be a little kinder to yourself than you think you need to be.' },
    ],
    wander: 'When you forget to be aware — and you will, all day long — simply remember, and return. The forgetting was never the problem. The remembering is the practice.',
    oneSentence: 'Watch the breath, notice whatever arises, label it gently, let it pass, and return to simple awareness — both on the cushion and throughout daily life.',
    principles: {
      title: 'Her ten practical principles',
      items: [
        'Stay with one meditation method.',
        'Practice every day.',
        'Any situation can be used for practice.',
        'Develop patience.',
        'Don\u2019t believe every story the mind tells.',
        'Cool anger and emotional reactivity.',
        'Have fun along the way.',
        'Live simply.',
        'Bless others.',
        'Let meditation become part of your whole life.',
      ],
    },
    resource: { label: 'Find a teacher in Dipa Ma\u2019s noting lineage', org: 'Insight Meditation Society', url: 'https://www.dharma.org', note: 'Dipa Ma\u2019s Mahasi-style noting is carried on at IMS (Barre, MA) and centres worldwide. Vipassana fellowship lists sitting groups near you.' },
  },
};
const MT_METHOD_ORDER = ['goenka', 'dipama'];

function LearnScreen({ vp, onStartSim, onBrowseTeachings }) {
  const C = MT_COLORS;
  const wide = vp && vp.isWide;
  const [open, setOpen] = React.useState(null); // null = hub | 'goenka' | 'dipama'

  if (open) return <LearnGuide method={MT_METHODS[open]} onBack={() => setOpen(null)} vp={vp} />;

  return (
    <div style={{ padding: '8px 20px 120px' }}>
      <h1 style={{ font: '300 32px/1.1 var(--serif)', color: C.ink, margin: '12px 0 6px' }}>Learn meditation</h1>
      <div style={{ fontSize: 14, color: C.inkFaint, marginBottom: 22 }}>Two living methods — read the way, watch a master, then practice.</div>

      {/* interactive sim launcher */}
      <div onClick={onStartSim} style={{ position: 'relative', borderRadius: 24, overflow: 'hidden', cursor: 'pointer', marginBottom: 26,
        border: `1px solid ${hexA('#B49CFF', 0.4)}`, background: 'radial-gradient(130% 120% at 0% 0%, rgba(34,26,58,0.85), rgba(10,18,28,0.6))', padding: '22px 20px' }}>
        <ParticleField count={20} />
        <div style={{ position: 'relative' }}>
          <MTEyebrow color="#B49CFF">Interactive · watch a master</MTEyebrow>
          <div style={{ font: '300 24px/1.25 var(--serif)', color: C.ink, margin: '10px 0 8px', maxWidth: 360 }}>
            See how Dipa Ma &amp; Goenka meet what arises
          </div>
          <div style={{ fontSize: 14, color: C.inkFaint, lineHeight: 1.5, maxWidth: 380, marginBottom: 18 }}>
            An x-ray of a mind in practice — sitting, walking, cooking, working. Thoughts and sensations arise; watch each one met, and released.
          </div>
          <MTButton size="md" onClick={(e) => { e.stopPropagation(); onStartSim(); }} style={{ background: 'linear-gradient(180deg, #B49CFF, #8A6FE0)' }}>
            <MTIcon name="eye" size={18} color="#1a1030" /> Begin watching
          </MTButton>
        </div>
      </div>

      {/* written method guides */}
      <div style={{ margin: '0 4px 12px' }}><MTEyebrow>The two paths · written guides</MTEyebrow></div>
      <div style={{ display: 'grid', gap: 14, gridTemplateColumns: wide ? '1fr 1fr' : '1fr', marginBottom: 26 }}>
        {MT_METHOD_ORDER.map(id => {
          const m = MT_METHODS[id];
          return (
            <MTPanel key={id} pressable onClick={() => setOpen(id)} style={{ padding: 20, cursor: 'pointer' }}>
              <div style={{ display: 'flex', gap: 13, alignItems: 'center', marginBottom: 14 }}>
                <span style={{ width: 48, height: 48, borderRadius: '50%', display: 'grid', placeItems: 'center', flexShrink: 0,
                  background: `radial-gradient(60% 60% at 50% 38%, ${hexA(m.accent, 0.34)}, ${hexA(m.accent, 0.05)})`, border: `1px solid ${hexA(m.accent, 0.5)}`,
                  fontFamily: 'var(--serif)', fontSize: 17, color: C.ink }}>{m.initials}</span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 17, fontWeight: 600, color: C.ink }}>{m.title}</div>
                  <div style={{ fontSize: 12.5, color: C.inkFaint, marginTop: 2 }}>{m.teacher}</div>
                </div>
                <MTIcon name="chevR" size={18} color={C.inkFaint} />
              </div>
              <div style={{ font: 'italic 300 15px/1.5 var(--serif)', color: C.inkDim, marginBottom: 14, textWrap: 'pretty' }}>{m.tagline}</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, color: m.accent, fontFamily: 'var(--mono)' }}>
                <MTIcon name="book" size={14} color={m.accent} /> {m.duration}
              </div>
            </MTPanel>
          );
        })}
      </div>

      {/* quotes from both */}
      <div style={{ margin: '0 4px 14px' }}><MTEyebrow>In their words · tap for another</MTEyebrow></div>
      <div style={{ display: 'grid', gap: 12, gridTemplateColumns: wide ? '1fr 1fr' : '1fr' }}>
        {['Dipa Ma', 'S. N. Goenka'].map(name => {
          const m = MT_METHODS[name === 'Dipa Ma' ? 'dipama' : 'goenka'];
          return (
            <MTPanel key={name} style={{ padding: '18px 18px', borderLeft: `2px solid ${hexA(m.accent, 0.6)}` }}>
              <LearnQuote name={name} accent={m.accent} />
            </MTPanel>
          );
        })}
      </div>

      <div style={{ display: 'flex', justifyContent: 'center', marginTop: 24 }}>
        <button onClick={onBrowseTeachings} style={{ appearance: 'none', cursor: 'pointer', background: 'rgba(255,255,255,0.03)', border: `1px solid ${C.inkGhost}`, borderRadius: 999, padding: '10px 18px', color: C.inkDim, fontSize: 13.5, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 8, fontFamily: 'var(--sans)' }}>
          <MTIcon name="quotes" size={15} color={C.teal} /> Browse all teachers
        </button>
      </div>
    </div>
  );
}

// quotes for the Learn hub draw from a teacher's own set; reshuffle within that teacher
function LearnQuote({ name, accent }) {
  const C = MT_COLORS;
  const pool = mtQuotesFor(name);
  const [i, setI] = React.useState(0);
  const q = pool[i % pool.length];
  return (
    <div onClick={() => setI(x => x + 1)} style={{ cursor: 'pointer' }}>
      <div key={i} style={{ font: 'italic 300 16px/1.5 var(--serif)', color: C.inkDim, textWrap: 'pretty', animation: 'mtRise .5s ease-out' }}>“{q.t}”</div>
      <div style={{ marginTop: 10, fontSize: 12.5, color: C.ink, fontWeight: 600 }}>{q.a} <span style={{ color: C.inkFaint, fontWeight: 400 }}>· {q.r}</span></div>
    </div>
  );
}

// full written guide
function LearnGuide({ method: m, onBack, vp }) {
  const C = MT_COLORS;
  const quotes = mtQuotesFor(m.teacher);
  return (
    <div style={{ padding: '4px 20px 120px', maxWidth: 680, margin: '0 auto' }}>
      <button onClick={onBack} style={{ appearance: 'none', background: 'none', border: 'none', color: C.inkDim, display: 'flex', alignItems: 'center', gap: 5, cursor: 'pointer', margin: '8px 0 18px', padding: 0, fontSize: 15, fontFamily: 'var(--sans)' }}>
        <MTIcon name="chevL" size={20} /> Learn
      </button>

      <div style={{ display: 'flex', gap: 15, alignItems: 'center', marginBottom: 18 }}>
        <span style={{ width: 56, height: 56, borderRadius: '50%', display: 'grid', placeItems: 'center', flexShrink: 0,
          background: `radial-gradient(60% 60% at 50% 38%, ${hexA(m.accent, 0.34)}, ${hexA(m.accent, 0.05)})`, border: `1px solid ${hexA(m.accent, 0.5)}`,
          fontFamily: 'var(--serif)', fontSize: 20, color: C.ink }}>{m.initials}</span>
        <div>
          <h1 style={{ font: '300 26px/1.15 var(--serif)', color: C.ink, margin: 0 }}>{m.title}</h1>
          <div style={{ fontSize: 13, color: C.inkFaint, marginTop: 3 }}>{m.teacher}</div>
        </div>
      </div>

      <p style={{ fontSize: 16, lineHeight: 1.65, color: C.inkDim, margin: '0 0 22px', textWrap: 'pretty' }}>{m.intro}</p>

      <MTPanel hi style={{ padding: 18, marginBottom: 26, borderLeft: `2px solid ${m.accent}` }}>
        <MTEyebrow color={m.accent}>The principle</MTEyebrow>
        <p style={{ fontSize: 15.5, lineHeight: 1.6, color: C.ink, margin: '10px 0 0', textWrap: 'pretty' }}>{m.principle}</p>
      </MTPanel>

      <div style={{ margin: '0 0 14px' }}><MTEyebrow>How to practice</MTEyebrow></div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginBottom: 26 }}>
        {m.steps.map((s, i) => (
          <div key={i} style={{ display: 'flex', gap: 14 }}>
            <span style={{ flexShrink: 0, width: 30, height: 30, borderRadius: '50%', display: 'grid', placeItems: 'center',
              border: `1px solid ${hexA(m.accent, 0.5)}`, background: hexA(m.accent, 0.08), color: m.accent, fontFamily: 'var(--mono)', fontSize: 14 }}>{i + 1}</span>
            <div style={{ flex: 1, paddingTop: 2 }}>
              <div style={{ fontSize: 16.5, fontWeight: 600, color: C.ink, marginBottom: 5 }}>{s.h}</div>
              <div style={{ fontSize: 14.5, lineHeight: 1.6, color: C.inkDim, textWrap: 'pretty' }}>{s.b}</div>
            </div>
          </div>
        ))}
      </div>

      <MTPanel style={{ padding: 18, marginBottom: 18 }}>
        <MTEyebrow color="#FF9E6B">When the mind wanders</MTEyebrow>
        <p style={{ fontSize: 15, lineHeight: 1.6, color: C.inkDim, margin: '10px 0 0', textWrap: 'pretty' }}>{m.wander}</p>
      </MTPanel>

      {/* optional: the teacher's distilled rules for living the practice */}
      {m.principles && (
        <MTPanel style={{ padding: 18, marginBottom: 18 }}>
          <MTEyebrow color={m.accent}>{m.principles.title}</MTEyebrow>
          <ol style={{ margin: '12px 0 0', padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 9 }}>
            {m.principles.items.map((it, i) => (
              <li key={i} style={{ display: 'flex', gap: 12, alignItems: 'baseline' }}>
                <span style={{ flexShrink: 0, width: 22, textAlign: 'right', color: hexA(m.accent, 0.8), fontFamily: 'var(--mono)', fontSize: 12.5 }}>{i + 1}</span>
                <span style={{ fontSize: 15, lineHeight: 1.55, color: C.ink }}>{it}</span>
              </li>
            ))}
          </ol>
        </MTPanel>
      )}

      {/* optional: the whole method, one sentence */}
      {m.oneSentence && (
        <MTPanel hi style={{ padding: 18, marginBottom: 18, borderLeft: `2px solid ${m.accent}` }}>
          <MTEyebrow color={m.accent}>The method in one sentence</MTEyebrow>
          <p style={{ font: 'italic 300 17px/1.6 var(--serif)', color: C.ink, margin: '10px 0 0', textWrap: 'pretty' }}>{m.oneSentence}</p>
        </MTPanel>
      )}

      {/* go deeper — point to a real teacher / course */}
      {m.resource && (
        <a href={m.resource.url} target="_blank" rel="noopener noreferrer" style={{ textDecoration: 'none', display: 'block', marginBottom: 26 }}>
          <MTPanel hi style={{ padding: 18, borderLeft: `2px solid ${m.accent}` }}>
            <MTEyebrow color={m.accent}>Go deeper — with a real teacher</MTEyebrow>
            <div style={{ fontSize: 15.5, fontWeight: 600, color: C.ink, margin: '10px 0 4px' }}>{m.resource.label}</div>
            <p style={{ fontSize: 13.5, lineHeight: 1.55, color: C.inkDim, margin: '0 0 12px', textWrap: 'pretty' }}>{m.resource.note}</p>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontSize: 13, fontWeight: 600, color: m.accent, fontFamily: 'var(--mono)' }}>
              {m.resource.org} <MTIcon name="chevR" size={15} color={m.accent} />
            </span>
          </MTPanel>
        </a>
      )}
      <p style={{ fontSize: 12, color: C.inkFaint, lineHeight: 1.6, margin: '0 0 22px', textWrap: 'pretty' }}>
        Anicca is a companion for practice, not a substitute for a living teacher. Both traditions are best learned directly — from a guide and a community.
      </p>

      <div style={{ margin: '0 0 12px' }}><MTEyebrow>In {m.teacher.split(' ').slice(-1)[0]}’s words</MTEyebrow></div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {quotes.map((q, i) => (
          <MTPanel key={i} style={{ padding: '15px 17px', borderLeft: `2px solid ${hexA(m.accent, 0.5)}` }}>
            <div style={{ font: 'italic 300 16px/1.55 var(--serif)', color: C.ink, textWrap: 'pretty' }}>“{q.t}”</div>
            <div style={{ marginTop: 7, fontSize: 11.5, color: C.inkFaint, fontFamily: 'var(--mono)', letterSpacing: 0.5 }}>{q.r}</div>
          </MTPanel>
        ))}
      </div>

      <button onClick={onBack} style={{ appearance: 'none', background: 'none', border: `1px solid ${C.inkGhost}`, borderRadius: 999, color: C.inkDim, display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer', margin: '26px auto 0', padding: '11px 20px', fontSize: 14, fontFamily: 'var(--sans)' }}>
        <MTIcon name="chevL" size={18} /> Back to Learn
      </button>
    </div>
  );
}

Object.assign(window, { MT_METHODS, MT_METHOD_ORDER, LearnScreen, LearnGuide });
