// Komonichi — Learn page: meditation & grounding practices (Japanese tradition)
const { useKomonichi } = window.KomonichiState;

const PRACTICES = [
  {
    id: 'zazen',
    kanji: '坐禅',
    name: 'Zazen',
    romaji: 'za-zen',
    gloss: 'seated meditation',
    tradition: 'Zen Buddhism · Sōtō & Rinzai',
    duration: '20–40 min',
    posture: 'cross-legged on a cushion, spine upright, half-closed eyes',
    summary: 'The heart of Zen. To sit without aim — neither chasing thought nor pushing it away. Just this.',
    steps: [
      'Sit on a zafu, legs crossed (half or full lotus, or burmese). The cushion tilts the pelvis forward, the spine stacks.',
      'Place the left hand inside the right, thumbs lightly touching — the cosmic mudra (hokkaijoin). Rest at the navel.',
      'Lower the eyelids to about a third open. Soften the gaze toward the floor a meter ahead. Do not close fully.',
      'Breathe through the nose, into the lower belly. Count exhalations from one to ten, then begin again.',
      'When thoughts arise, do not follow them, do not push them away. Return to the breath. This is the whole practice.',
    ],
    note: 'Shikantaza — "just sitting" — drops even the counting. The bell ends the period.',
  },
  {
    id: 'kinhin',
    kanji: '経行',
    name: 'Kinhin',
    romaji: 'kin-hin',
    gloss: 'walking meditation',
    tradition: 'Zen monastic tradition',
    duration: '10–15 min, between zazen periods',
    posture: 'standing, hands in shashu mudra at the sternum',
    summary: 'Walking that is not going anywhere. One half-step on each full breath cycle. The threshold between sitting and the world.',
    steps: [
      'Stand from zazen slowly. Place the right hand, thumb folded into the palm, against the chest — left hand wraps over it (shashu).',
      'Eyes lowered, gaze a meter ahead.',
      'Inhale: shift weight, prepare. Exhale: step forward half the length of the foot. One breath = one step.',
      'Walk a single line of the room, then turn ninety degrees right at the wall and continue.',
      'There is no destination. The walking is the practice.',
    ],
    note: 'Kinhin keeps the legs from numbness during long sesshin retreats — but the form was never merely practical.',
  },
  {
    id: 'shinrin',
    kanji: '森林浴',
    name: 'Shinrin-yoku',
    romaji: 'shin-rin-yoh-ku',
    gloss: 'forest bathing',
    tradition: 'Coined 1982, Forestry Agency of Japan',
    duration: '2 hours, slowly',
    posture: 'walking, sitting, standing — whatever the forest invites',
    summary: 'To enter a forest with the senses open, not the legs hurrying. Bathe in the atmosphere of trees.',
    steps: [
      'Choose a forest, a copse, or a single old tree in a park. Leave the phone in the bag.',
      'Walk slowly, half your normal pace. There is no trail to finish.',
      'Stop often. Look up into the canopy. Notice the light filtering through leaves (komorebi).',
      'Touch the bark of a tree. Smell the soil after rain. Listen for the layered sounds — wind, bird, leaf.',
      'If you sit, sit for at least twenty minutes before deciding the visit is over.',
    ],
    note: 'Research has found measurable drops in cortisol and blood pressure after two hours among trees. The forest does the work.',
  },
  {
    id: 'hara',
    kanji: '丹田呼吸',
    name: 'Tanden breathing',
    romaji: 'tan-den ko-kyū',
    gloss: 'breath into the lower belly',
    tradition: 'Budō, Zen, traditional medicine',
    duration: '5–15 min',
    posture: 'seiza, cross-legged, or standing',
    summary: 'A practice for finding the center of gravity — the tanden — three fingers below the navel. The seat of life-energy in Japanese tradition.',
    steps: [
      'Sit upright. Place one palm three fingers below the navel — this is the tanden, the lower elixir field.',
      'Inhale through the nose, slowly, four counts. The hand should rise as the lower belly expands. The chest stays still.',
      'Hold for one count.',
      'Exhale through the mouth, slowly, six to eight counts. The hand sinks. Empty fully.',
      'Repeat. Twelve cycles is one set. Three sets is a practice.',
    ],
    note: 'In kendō, archery, calligraphy — the strike, the release, the brushstroke all begin from the tanden, not the arm.',
  },
  {
    id: 'misogi',
    kanji: '禊',
    name: 'Misogi',
    romaji: 'mi-so-gi',
    gloss: 'purification by cold water',
    tradition: 'Shintō',
    duration: '5–20 min, before dawn ideally',
    posture: 'standing under cold water — waterfall, river, or shower',
    summary: 'To wash away the dust of self. A practice older than Buddhism in Japan — the body as the place where purification happens.',
    steps: [
      'Begin with intention. Stand quietly. Acknowledge what you wish to release.',
      'Step under the cold water. Do not flinch outwardly — receive it.',
      'Breathe deeply through the nose. Long exhales. Count the breaths.',
      'Remain for as long as is right — one minute is enough at first. Build slowly.',
      'Step out. Dry. Notice the body — vivid, present, no longer in yesterday.',
    ],
    note: 'A home shower set to cold is a legitimate beginning. Misogi at a waterfall is the deeper form, but practice is practice.',
  },
  {
    id: 'naikan',
    kanji: '内観',
    name: 'Naikan',
    romaji: 'nai-kan',
    gloss: 'looking inward',
    tradition: 'Yoshimoto Ishin, 1940s',
    duration: '30 min, evening',
    posture: 'seated quietly, writing if desired',
    summary: 'A structured reflection on one person at a time — usually beginning with one\'s mother. Three questions, no more.',
    steps: [
      'Choose one person who has been in your life. For the first practice: a parent.',
      'Sit. Bring them to mind clearly. Pick a recent period — last week, last month, last year.',
      'Ask: What did this person give me? List specifics — meals, rides, words, silences. Take time.',
      'Ask: What did I give this person? Again, specifics. Often the list is shorter.',
      'Ask: What troubles or difficulties did I cause this person? Sit with the answer.',
    ],
    note: 'Naikan is not self-flagellation. It is accounting — to see clearly what has actually flowed between two people.',
  },
];

function PracticeCard({ p, open, onToggle }) {
  const S = window.KomonichiState;
  const [state] = S.useKomonichi();
  const progress = S.sel.learnStatusFor(p.id);
  const mark = async (status) => { try { await S.actions.markLearn(p.id, status); } catch {} };
  return (
    <div className="card practice-card" style={{ padding: 0, overflow: 'hidden' }}>
      <button onClick={onToggle} className="practice-card-toggle" style={{
        all: 'unset', cursor: 'pointer', width: '100%', display: 'block',
        padding: '24px 28px',
      }}>
        <div className="practice-card-row">
          <div className="practice-kanji">
            <div className="display" style={{ fontSize: 48, lineHeight: 1, color: 'var(--ink)' }}>
              <span style={{ fontFamily: 'serif' }}>{p.kanji}</span>
            </div>
            <div className="label" style={{ marginTop: 6, fontSize: 8, whiteSpace: 'nowrap' }}>{p.romaji}</div>
          </div>
          <div className="practice-body">
            <div className="label" style={{ color: 'var(--persimmon)' }}>{p.gloss}</div>
            <h3 className="display" style={{ fontSize: 28, margin: '4px 0 6px' }}>{p.name}</h3>
            <div style={{ fontSize: 13, color: 'var(--ink-soft)' }}>{p.summary}</div>
            <div className="practice-duration">{p.duration}</div>
          </div>
          <div className="practice-toggle" style={{ transform: open ? 'rotate(45deg)' : 'none' }}>+</div>
        </div>
      </button>
      {open && (
        <div className="fade-in practice-card-detail" style={{ padding: '4px 28px 28px', borderTop: '1px dashed var(--paper-line)' }}>
          <div className="practice-detail-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 28, marginTop: 18 }}>
            <div>
              <div className="label">tradition</div>
              <div style={{ fontSize: 13, color: 'var(--ink-soft)', marginTop: 4 }}>{p.tradition}</div>
              <div className="label" style={{ marginTop: 16 }}>posture</div>
              <div style={{ fontSize: 13, color: 'var(--ink-soft)', marginTop: 4, fontStyle: 'italic' }}>{p.posture}</div>
            </div>
            <div>
              <div className="label">the form</div>
              <ol style={{ paddingLeft: 18, margin: '8px 0 0', color: 'var(--ink-soft)' }}>
                {p.steps.map((s, i) => (
                  <li key={i} style={{ fontSize: 13, marginBottom: 8, lineHeight: 1.55 }}>{s}</li>
                ))}
              </ol>
            </div>
          </div>
          <div style={{ marginTop: 22, paddingTop: 14, borderTop: '1px dashed var(--paper-line)' }}>
            <div className="haiku" style={{ fontSize: 14 }}>
              <span className="line">— {p.note}</span>
            </div>
          </div>
          <div style={{ marginTop: 14, display: 'flex', gap: 8, alignItems: 'center' }}>
            {progress ? (
              <span className={'chip ' + (progress === 'completed' ? 'moss' : 'warm')}>{progress}</span>
            ) : (
              <span className="chip locked">not started</span>
            )}
            <span style={{ flex: 1 }} />
            <button className="btn ghost tiny" onClick={() => mark('started')}>mark started</button>
            <button className="btn warm tiny" onClick={() => mark('completed')}>mark completed</button>
          </div>
        </div>
      )}
    </div>
  );
}

function GroundingFive() {
  // 5-4-3-2-1 grounding, framed in Japanese sensory terms
  const senses = [
    { n: 5, jp: '見る', en: 'miru — to see',    prompt: 'five things you can see — the grain of the wood, a corner of light, the shape of your own hand' },
    { n: 4, jp: '聞く', en: 'kiku — to hear',   prompt: 'four sounds — near and far, the hum of a fridge, the wind under a door' },
    { n: 3, jp: '触る', en: 'sawaru — to touch', prompt: 'three textures — the chair, the fabric of your sleeve, your own face' },
    { n: 2, jp: '匂う', en: 'niou — to smell',  prompt: 'two scents — paper, tea, soap, the room itself' },
    { n: 1, jp: '味わう', en: 'ajiwau — to taste', prompt: 'one taste — water, the taste of the mouth at rest' },
  ];
  return (
    <div className="card">
      <div className="cap">
        <div>
          <div className="label">when the day is much</div>
          <h3 className="title"><span className="em">grounding</span> — five senses</h3>
        </div>
        <span className="chip moss">5 min</span>
      </div>
      <div className="haiku" style={{ marginBottom: 18 }}>
        <span className="line">Anxiety is the mind in tomorrow.</span>
        <span className="line">The senses live only in this moment —</span>
        <span className="line">so we return through them.</span>
      </div>
      <div style={{ display: 'grid', gap: 14 }}>
        {senses.map(s => (
          <div key={s.n} style={{
            display: 'grid', gridTemplateColumns: '60px 110px 1fr', gap: 18,
            alignItems: 'center', padding: '12px 0',
            borderBottom: '1px dashed var(--paper-line)',
          }}>
            <div className="display" style={{ fontSize: 36, color: 'var(--persimmon)', textAlign: 'center', lineHeight: 1 }}>{s.n}</div>
            <div>
              <div className="display" style={{ fontSize: 22, color: 'var(--ink)' }}>{s.jp}</div>
              <div className="label" style={{ marginTop: 2 }}>{s.en}</div>
            </div>
            <div style={{ fontSize: 13, color: 'var(--ink-soft)' }}>{s.prompt}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function BreathBox() {
  // box breathing (4-4-4-4) with a moving dot around a square
  const [phase, setPhase] = React.useState(0); // 0=in 1=hold 2=out 3=hold
  const [count, setCount] = React.useState(4);
  const [running, setRunning] = React.useState(false);
  React.useEffect(() => {
    if (!running) return;
    const id = setInterval(() => {
      setCount(c => {
        if (c > 1) return c - 1;
        setPhase(p => (p + 1) % 4);
        return 4;
      });
    }, 1000);
    return () => clearInterval(id);
  }, [running]);

  const labels = ['breathe in', 'hold', 'breathe out', 'hold'];
  const SIZE = 220;
  // dot position around square perimeter — progress within current phase
  const progress = (4 - count) / 4; // 0 → 1 within phase
  const sidePoints = [
    [0, SIZE], [0, 0],     // left side, bottom→top (inhale)
    [0, 0], [SIZE, 0],     // top, left→right (hold)
    [SIZE, 0], [SIZE, SIZE], // right, top→bottom (exhale)
    [SIZE, SIZE], [0, SIZE], // bottom, right→left (hold)
  ];
  const a = sidePoints[phase * 2], b = sidePoints[phase * 2 + 1];
  const dx = a[0] + (b[0] - a[0]) * progress;
  const dy = a[1] + (b[1] - a[1]) * progress;

  return (
    <div className="card" style={{ textAlign: 'center' }}>
      <div className="cap" style={{ justifyContent: 'center', border: 0, paddingBottom: 4 }}>
        <div>
          <div className="label">samurai breath</div>
          <h3 className="title" style={{ marginTop: 4 }}><span className="em">box</span> breathing · 四</h3>
        </div>
      </div>
      <div style={{ position: 'relative', width: SIZE + 40, height: SIZE + 40, margin: '14px auto 8px' }}>
        <svg width={SIZE + 40} height={SIZE + 40}>
          <g transform="translate(20,20)">
            <rect x="0" y="0" width={SIZE} height={SIZE}
              fill="none" stroke="var(--paper-line)" strokeWidth="1" strokeDasharray="3 5" />
            <circle cx={dx} cy={dy} r="9" fill="var(--persimmon)" opacity="0.85">
              <animate attributeName="r" values="9;11;9" dur="2s" repeatCount="indefinite" />
            </circle>
          </g>
        </svg>
        <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', pointerEvents: 'none' }}>
          <div className="label" style={{ color: 'var(--ink-faint)' }}>{labels[phase]}</div>
          <div className="display" style={{ fontSize: 56, lineHeight: 1, marginTop: 4 }}>{count}</div>
        </div>
      </div>
      <button className="btn warm" onClick={() => {
        if (running) {
          // releasing the breath — return the dot to its starting point
          setRunning(false);
          setPhase(0);
          setCount(4);
        } else {
          setRunning(true);
        }
      }}>
        {running ? 'release' : 'begin'}
      </button>
      <div className="label" style={{ marginTop: 14, fontStyle: 'italic', opacity: 0.8 }}>
        four counts in · four hold · four out · four hold
      </div>
    </div>
  );
}

function Glossary() {
  const terms = [
    { jp: '間', romaji: 'ma',       en: 'the pause; the meaningful space between things — between notes, between words, between breaths' },
    { jp: '間合い', romaji: 'maai',  en: 'the right distance; the negotiated space in combat, conversation, music' },
    { jp: '無心', romaji: 'mushin',  en: 'no-mind; the state of action without self-conscious thought — the calligrapher\'s stroke' },
    { jp: '初心', romaji: 'shoshin', en: 'beginner\'s mind; to meet the practice as if for the first time, again' },
    { jp: '一期一会', romaji: 'ichigo ichie', en: 'one time, one meeting; this moment will not return — meet it accordingly' },
    { jp: '木漏れ日', romaji: 'komorebi', en: 'the sunlight filtered through leaves; a word for what most languages cannot name' },
    { jp: '物の哀れ', romaji: 'mono no aware', en: 'the gentle sadness of things passing; the awareness of impermanence as sweetness, not grief' },
    { jp: '幽玄', romaji: 'yūgen',   en: 'the profound suggestion of what cannot be seen; the deep mystery beneath surfaces' },
  ];
  return (
    <div className="card">
      <div className="cap">
        <div>
          <div className="label">a small dictionary</div>
          <h3 className="title">words for the <span className="em">inner weather</span></h3>
        </div>
      </div>
      <div style={{ display: 'grid', gap: 0 }}>
        {terms.map((t, i) => (
          <div key={i} style={{
            display: 'grid', gridTemplateColumns: '160px 1fr', gap: 22,
            padding: '13px 0', borderBottom: '1px dashed var(--paper-line)', alignItems: 'baseline',
          }}>
            <div>
              <div className="display" style={{ fontSize: 24, color: 'var(--ink)' }}>{t.jp}</div>
              <div className="label" style={{ marginTop: 2 }}>{t.romaji}</div>
            </div>
            <div style={{ fontSize: 13, color: 'var(--ink-soft)', fontStyle: 'italic' }}>{t.en}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function LearnPage() {
  const [open, setOpen] = React.useState('zazen');
  return (
    <div className="fade-in">
      <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', alignItems: 'end', marginBottom: 22, gap: 18 }}>
        <div>
          <div className="label">a way of being</div>
          <h2 className="display" style={{ fontSize: 48, lineHeight: 1, margin: '8px 0 0' }}>
            learn the <span style={{ color: 'var(--persimmon)' }}>quiet arts</span>
          </h2>
        </div>
        <div className="haiku" style={{ textAlign: 'right', fontSize: 14, maxWidth: 320 }}>
          <span className="line">Practice does not improve you.</span>
          <span className="line">It reveals what was already here.</span>
        </div>
      </div>

      <div className="grid g-12">
        <div className="c-8" style={{ display: 'grid', gap: 18 }}>
          {PRACTICES.map(p => (
            <PracticeCard key={p.id} p={p} open={open === p.id}
              onToggle={() => setOpen(o => o === p.id ? null : p.id)} />
          ))}
        </div>
        <div className="c-4" style={{ display: 'grid', gap: 22, alignContent: 'start' }}>
          <BreathBox />
          <GroundingFive />
          <Glossary />
        </div>
      </div>
    </div>
  );
}

window.LearnPage = LearnPage;
