/* Sentence breakdown view — multi-granularity decomposition
   昨日友達と渋谷で美味しいラーメンを食べました
   The most domain-specific surface in the batch. Sentence as a path
   through the knowledge graph; each granularity exposes a layer of that path. */

const SentenceBreakdown = () => {
  const [granularity, setGranularity] = React.useState("morpheme");
  const [selectedTok, setSelectedTok] = React.useState(7);

  // Granularity layers, top-to-bottom:
  //  1) bunsetsu  — phrase chunks
  //  2) morpheme  — MeCab/Sudachi tokens
  //  3) kanji     — kanji components
  //
  // Each token carries indices into all three layers.
  const tokens = [
    { i:0,  jp:"昨日",       kana:"きのう",      roma:"kinō",        pos:"N · time",      gloss:"yesterday",        kanji:["昨","日"], bunsetsu:0, lemma:"昨日", freq: 312, jlpt:"N5", state:"mastered" },
    { i:1,  jp:"友達",       kana:"ともだち",    roma:"tomodachi",   pos:"N",             gloss:"friend",            kanji:["友","達"], bunsetsu:1, lemma:"友達", freq: 540, jlpt:"N5", state:"mastered" },
    { i:2,  jp:"と",         kana:"と",          roma:"to",          pos:"PRT · with",    gloss:"with",              kanji:[],          bunsetsu:1, lemma:"と",   freq:  18, jlpt:"N5", state:"mastered" },
    { i:3,  jp:"渋谷",       kana:"しぶや",      roma:"Shibuya",     pos:"N · place",     gloss:"Shibuya",           kanji:["渋","谷"], bunsetsu:2, lemma:"渋谷", freq:8420, jlpt:"—",  state:"learning" },
    { i:4,  jp:"で",         kana:"で",          roma:"de",          pos:"PRT · loc.",    gloss:"at, in",            kanji:[],          bunsetsu:2, lemma:"で",   freq:   5, jlpt:"N5", state:"mastered" },
    { i:5,  jp:"美味しい",   kana:"おいしい",    roma:"oishii",      pos:"i-adj",         gloss:"delicious",         kanji:["美","味"], bunsetsu:3, lemma:"美味しい", freq:2104, jlpt:"N5", state:"mastered" },
    { i:6,  jp:"ラーメン",   kana:"らーめん",    roma:"rāmen",       pos:"N · loanword",  gloss:"ramen",             kanji:[],          bunsetsu:3, lemma:"ラーメン", freq:1840, jlpt:"—",  state:"mastered" },
    { i:7,  jp:"を",         kana:"を",          roma:"o",           pos:"PRT · obj.",    gloss:"(direct object)",   kanji:[],          bunsetsu:3, lemma:"を",   freq:   3, jlpt:"N5", state:"frontier" },  // currently selected
    { i:8,  jp:"食べました", kana:"たべました", roma:"tabemashita", pos:"V · past·polite", gloss:"ate",              kanji:["食"],     bunsetsu:4, lemma:"食べる", freq:  87, jlpt:"N5", state:"mastered" },
  ];

  // Bunsetsu groupings
  const bunsetsuGroups = [
    { id:0, label:"adverbial", role:"when?",   tokens:[0],     gloss:"yesterday" },
    { id:1, label:"subject(-ish)", role:"who-with?", tokens:[1,2], gloss:"with my friend" },
    { id:2, label:"locative",  role:"where?",  tokens:[3,4],   gloss:"in Shibuya" },
    { id:3, label:"object",    role:"what?",   tokens:[5,6,7], gloss:"delicious ramen (obj.)" },
    { id:4, label:"predicate", role:"verb",    tokens:[8],     gloss:"ate (past polite)" },
  ];

  // Kanji components for each token's kanji
  const kanjiInfo = {
    "昨":{r:"日 day",      strokes:9, jlpt:"N4"},
    "日":{r:"日 day",      strokes:4, jlpt:"N5"},
    "友":{r:"又 again",    strokes:4, jlpt:"N4"},
    "達":{r:"⻌ road",     strokes:12, jlpt:"N3"},
    "渋":{r:"氵water",     strokes:11, jlpt:"—"},
    "谷":{r:"谷 valley",   strokes:7, jlpt:"N3"},
    "美":{r:"羊 sheep",    strokes:9, jlpt:"N3"},
    "味":{r:"口 mouth",    strokes:8, jlpt:"N4"},
    "食":{r:"食 eat",      strokes:9, jlpt:"N5"},
  };

  const sel = tokens[selectedTok];

  return (
    <div className="sb">
      <header className="vp__top">
        <div className="vp__top-l">
          <span className="t-mono" style={{color:"var(--ink-4)"}}>§ JP · SENTENCE</span>
          <span className="cp__bc-sep">/</span>
          <a className="cp__bc-link" href="#">日本語 · Sentence corpus</a>
          <span className="cp__bc-sep">/</span>
          <span className="cp__bc-cur">sent.jp.0832</span>
          <span className="cp__bc-sep">·</span>
          <span className="t-meta">N4 · 9 morphemes · 9 kanji</span>
        </div>
        <div className="vp__top-r">
          <span className="t-meta">Granularity</span>
          <div className="pg__viewseg">
            {["bunsetsu","morpheme","kanji"].map(g => (
              <button key={g} className={"pg__viewseg-btn " + (granularity===g?"is-on":"")} onClick={()=>setGranularity(g)}>{g}</button>
            ))}
          </div>
          <span className="cp__top-divider" />
          <button className="btn btn--ghost cp__top-btn">Audio</button>
          <button className="btn cp__top-btn">Add to deck →</button>
        </div>
      </header>
      <hr className="rule" />

      <div className="sb__hero">
        <div className="t-meta">Sentence</div>
        <div className="sb__sent">
          {tokens.map(t => (
            <span key={t.i}
                  className={"sb__tok " + (selectedTok===t.i?"is-sel ":"") + (t.kanji.length?"sb__tok--has-kanji ":"")}
                  onClick={()=>setSelectedTok(t.i)}>
              <ruby>{t.jp}<rt className="sb__furi">{t.kana}</rt></ruby>
            </span>
          ))}
        </div>
        <div className="sb__gloss">
          <span className="t-meta">Translation</span>
          <span className="t-body">Yesterday I ate delicious ramen with my friend in Shibuya.</span>
        </div>
      </div>

      <hr className="rule-2" />

      {/* Three-layer decomposition stack — only the active layer is fully rendered;
          the other layers show as collapsed strips above/below */}
      <div className="sb__stack">
        {/* BUNSETSU LAYER */}
        <section className={"sb__layer sb__layer--bunsetsu " + (granularity==="bunsetsu"?"is-active":"is-collapsed")}>
          <div className="sb__layer-head">
            <span className="t-meta">Layer · bunsetsu</span>
            <span className="t-mono sb__layer-meta">phrase chunks · 5</span>
          </div>
          <div className="sb__bunsetsu">
            {bunsetsuGroups.map(b => (
              <div key={b.id} className="sb__bun">
                <div className="sb__bun-tokens">
                  {b.tokens.map(ti => <span key={ti} className="sb__bun-tok">{tokens[ti].jp}</span>)}
                </div>
                <div className="sb__bun-bracket">└─</div>
                <div className="sb__bun-meta">
                  <span className="t-meta">{b.label}</span>
                  <span className="t-mono sb__bun-role">{b.role}</span>
                </div>
                <div className="sb__bun-gloss">{b.gloss}</div>
              </div>
            ))}
          </div>
        </section>

        {/* MORPHEME LAYER (default active) */}
        <section className={"sb__layer sb__layer--morph " + (granularity==="morpheme"?"is-active":"is-collapsed")}>
          <div className="sb__layer-head">
            <span className="t-meta">Layer · morpheme</span>
            <span className="t-mono sb__layer-meta">SudachiPy · {tokens.length} tokens</span>
          </div>
          <div className="sb__morph-grid">
            <div className="sb__mh">i</div>
            <div className="sb__mh">surface</div>
            <div className="sb__mh">reading</div>
            <div className="sb__mh">lemma</div>
            <div className="sb__mh">POS</div>
            <div className="sb__mh">gloss</div>
            <div className="sb__mh">freq</div>
            <div className="sb__mh">state</div>
            {tokens.map(t => (
              <React.Fragment key={t.i}>
                <div className={"sb__mc t-mono " + (selectedTok===t.i?"is-sel":"")} onClick={()=>setSelectedTok(t.i)}>{t.i.toString().padStart(2,"0")}</div>
                <div className={"sb__mc sb__mc-jp " + (selectedTok===t.i?"is-sel":"")} onClick={()=>setSelectedTok(t.i)}>{t.jp}</div>
                <div className="sb__mc">{t.kana}</div>
                <div className="sb__mc t-mono">{t.lemma}</div>
                <div className="sb__mc t-mono sb__mc-pos">{t.pos}</div>
                <div className="sb__mc">{t.gloss}</div>
                <div className="sb__mc t-mono">#{t.freq}</div>
                <div className="sb__mc"><span className={"mastery-dot mastery-dot--" + t.state}/></div>
              </React.Fragment>
            ))}
          </div>
        </section>

        {/* KANJI LAYER */}
        <section className={"sb__layer sb__layer--kanji " + (granularity==="kanji"?"is-active":"is-collapsed")}>
          <div className="sb__layer-head">
            <span className="t-meta">Layer · kanji components</span>
            <span className="t-mono sb__layer-meta">{Object.keys(kanjiInfo).length} unique · radical decomposition</span>
          </div>
          <div className="sb__kanji-row">
            {Object.entries(kanjiInfo).map(([k, info]) => (
              <div key={k} className="sb__kanji-card">
                <div className="sb__kanji-glyph">{k}</div>
                <div className="t-mono sb__kanji-r">{info.r}</div>
                <div className="t-meta sb__kanji-meta">{info.strokes} st · {info.jlpt}</div>
              </div>
            ))}
          </div>
        </section>
      </div>

      <hr className="rule-2" />

      <div className="sb__split">
        {/* Selected token detail */}
        <section className="sb__detail">
          <div className="t-meta">Selected · token {sel.i.toString().padStart(2,"0")}</div>
          <hr className="rule-3" />
          <div className="sb__detail-head">
            <span className="sb__detail-jp">{sel.jp}</span>
            <span className="sb__detail-kana">{sel.kana}</span>
            <span className="t-mono sb__detail-roma">{sel.roma}</span>
          </div>
          <div className="sb__detail-grid">
            <div><span className="t-meta">POS</span><span className="t-mono">{sel.pos}</span></div>
            <div><span className="t-meta">Gloss</span><span className="t-body">{sel.gloss}</span></div>
            <div><span className="t-meta">Lemma</span><span className="t-mono">{sel.lemma}</span></div>
            <div><span className="t-meta">Freq</span><span className="t-mono">#{sel.freq}</span></div>
            <div><span className="t-meta">JLPT</span><span className="t-mono">{sel.jlpt}</span></div>
            <div><span className="t-meta">Bunsetsu</span><span className="t-mono">{bunsetsuGroups[sel.bunsetsu].label}</span></div>
          </div>
          {sel.jp === "を" && (
            <>
              <hr className="rule-3" />
              <div className="sb__particle">
                <div className="t-meta">Particle role</div>
                <div className="t-body sb__particle-body">
                  <span className="t-mono">を</span> marks the <strong>direct object</strong> of <span className="t-mono">食べました</span>. The full object phrase is <span className="t-mono">美味しいラーメン</span> (delicious ramen). Without <span className="t-mono">を</span>, the sentence is ungrammatical.
                </div>
              </div>
            </>
          )}
        </section>

        {/* Path through the knowledge graph */}
        <section className="sb__path">
          <div className="t-meta">Path · this sentence traverses</div>
          <hr className="rule-3" />
          <ul className="sb__path-list">
            <li className="sb__path-item">
              <span className="mastery-dot mastery-dot--mastered"/>
              <span className="t-ui">grammar.jp.particle.を</span>
              <span className="t-mono sb__path-d">N5</span>
            </li>
            <li className="sb__path-item">
              <span className="mastery-dot mastery-dot--mastered"/>
              <span className="t-ui">grammar.jp.particle.で</span>
              <span className="t-mono sb__path-d">N5</span>
            </li>
            <li className="sb__path-item">
              <span className="mastery-dot mastery-dot--mastered"/>
              <span className="t-ui">grammar.jp.i_adj.attributive</span>
              <span className="t-mono sb__path-d">N5</span>
            </li>
            <li className="sb__path-item">
              <span className="mastery-dot mastery-dot--mastered"/>
              <span className="t-ui">grammar.jp.verb.masu_past</span>
              <span className="t-mono sb__path-d">N5</span>
            </li>
            <li className="sb__path-item is-frontier">
              <span className="mastery-dot mastery-dot--frontier"/>
              <span className="t-ui">grammar.jp.particle_chain.を_de</span>
              <span className="t-mono sb__path-d">N4 · frontier</span>
            </li>
            <li className="sb__path-item">
              <span className="mastery-dot mastery-dot--learning"/>
              <span className="t-ui">vocab.jp.proper.shibuya</span>
              <span className="t-mono sb__path-d">place</span>
            </li>
          </ul>
          <div className="t-meta sb__path-foot">9 graph nodes touched · 1 frontier · 0 locked</div>
        </section>
      </div>

      <hr className="rule" />
      <footer className="vp__foot">
        <span className="t-meta">sent.jp.0832 · N4 · BCCWJ corpus · 9 morphemes</span>
        <span className="t-mono" style={{color:"var(--ink-4)"}}>parsed by SudachiPy v0.6 · split mode B</span>
      </footer>
    </div>
  );
};

window.SentenceBreakdown = SentenceBreakdown;
