/* =========================================================
   三藏閣 — 탐구 (Exploration)
   그래프 · 연표 · 지도 · 계보 · 비교
   ========================================================= */

const { Icon: XIcon } = window;

const TABS = [
  { id:'graph',     name:'그래프', desc:'개념·인물·문헌의 연결망' },
  { id:'timeline',  name:'연표',   desc:'붓다부터 근현대까지의 시간축' },
  { id:'map',       name:'지도',   desc:'불교가 머문 자리들의 지리' },
  { id:'lineage',   name:'계보',   desc:'스승–제자로 이어진 전법의 줄기' },
  { id:'compare',   name:'비교',   desc:'한 구절의 다섯 언어 본문' },
];

window.Explore = (props) => <window.ExploreScreen onOpenEntry={props.onOpenEncy || props.onOpenEntry || (() => {})}/>;

window.ExploreScreen = ({ onOpenEntry }) => {
  const [tab, setTab] = React.useState('graph');

  return (
    <div className="explore" data-screen-label="04 탐구">

      <header className="explore__hero">
        <div className="explore__hero-inner">
          <div className="explore__hero-eyebrow">색인 · EXPLORATION</div>
          <h1 className="explore__hero-title">한 개념에서<br/>다른 생각으로 건너가기</h1>
          <p className="explore__hero-sub">읽다가 떠오른 물음을 따라 그래프로, 연표로, 지도로 건너간다. 각 노드는 백과 항목으로 다시 이어진다.</p>
        </div>
      </header>

      <div className="explore__inner">
        <nav className="explore__tabs">
          {TABS.map(t => (
            <button key={t.id}
              className={'explore__tab' + (tab===t.id ? ' is-active' : '')}
              onClick={() => setTab(t.id)}>
              <span className="explore__tab-name">{t.name}</span>
              <span className="explore__tab-desc">{t.desc}</span>
            </button>
          ))}
        </nav>

        <div className="explore__stage">
          {tab === 'graph'    && <window.ExploreGraph onOpenEntry={onOpenEntry}/>}
          {tab === 'timeline' && <window.ExploreTimeline/>}
          {tab === 'map'      && <window.ExploreMap/>}
          {tab === 'lineage'  && <window.ExploreLineage/>}
          {tab === 'compare'  && <window.ExploreCompare/>}
        </div>
      </div>
    </div>
  );
};

/* ---------- 그래프 ---------- */
window.ExploreGraph = ({ onOpenEntry }) => {
  const [hover, setHover] = React.useState(null);
  const [focus, setFocus] = React.useState('sunyata');
  const seed = window.GRAPH_SEED;
  const W = 1100, H = 620;
  const proj = (x, y) => ({ cx: x * W, cy: y * H });

  const nodeColor = (k) => k==='concept' ? '#5a3820' : k==='person' ? '#2a3f5f' : k==='school' ? '#2e5c4a' : '#6b2c5a';

  const focused = seed.edges
    .filter(([a,b]) => a===focus || b===focus)
    .map(([a,b]) => a===focus ? b : a);

  return (
    <div className="xgraph">
      <div className="xgraph__legend">
        <span><i style={{background:'#5a3820'}}/>개념</span>
        <span><i style={{background:'#2a3f5f'}}/>인물</span>
        <span><i style={{background:'#2e5c4a'}}/>종파</span>
        <span><i style={{background:'#6b2c5a'}}/>문헌</span>
      </div>
      <svg viewBox={`0 0 ${W} ${H}`} className="xgraph__svg" preserveAspectRatio="xMidYMid meet">
        {seed.edges.map(([a,b], i) => {
          const A = seed.nodes.find(n => n.id===a);
          const B = seed.nodes.find(n => n.id===b);
          const pa = proj(A.x, A.y), pb = proj(B.x, B.y);
          const isFocus = a===focus || b===focus;
          return <line key={i} x1={pa.cx} y1={pa.cy} x2={pb.cx} y2={pb.cy}
            stroke={isFocus ? 'rgba(60,40,20,.55)' : 'rgba(60,40,20,.13)'}
            strokeWidth={isFocus ? 1.4 : 0.8}/>;
        })}
        {seed.nodes.map(n => {
          const p = proj(n.x, n.y);
          const c = nodeColor(n.kind);
          const isFocus = n.id===focus;
          const isLinked = focused.includes(n.id);
          const r = (n.w/2.2) * (isFocus ? 1.15 : 1);
          return (
            <g key={n.id} className="xgraph__node"
               onMouseEnter={() => setHover(n.id)}
               onMouseLeave={() => setHover(h => h===n.id ? null : h)}
               onClick={() => setFocus(n.id)}
               onDoubleClick={() => onOpenEntry(n.id)}>
              <circle cx={p.cx} cy={p.cy} r={r}
                fill={isFocus ? c : 'rgba(250,246,236,0.95)'}
                stroke={c} strokeWidth={isFocus ? 2 : isLinked ? 1.4 : 1}
                opacity={focus && !isFocus && !isLinked ? 0.45 : 1}/>
              <text x={p.cx} y={p.cy+5} textAnchor="middle" fontSize="15"
                fill={isFocus ? '#faf6ec' : c} fontWeight="500"
                opacity={focus && !isFocus && !isLinked ? 0.5 : 1}>{n.label}</text>
            </g>
          );
        })}
      </svg>
      <div className="xgraph__hint">노드를 클릭해 초점을 옮기고, 더블클릭으로 백과 항목을 엽니다.</div>
      {focus && (
        <aside className="xgraph__detail">
          <div className="xgraph__detail-eyebrow">초점</div>
          <h3>{seed.nodes.find(n => n.id===focus)?.label}</h3>
          <button className="xgraph__detail-btn" onClick={() => onOpenEntry(focus)}>
            백과 항목 열기 <XIcon name="arrow-right" size={14}/>
          </button>
        </aside>
      )}
    </div>
  );
};

/* ---------- 연표 ---------- */
window.ExploreTimeline = () => {
  return (
    <div className="xtimeline">
      <div className="xtimeline__line"/>
      {window.TIMELINE_SEED.map((t, i) => (
        <div key={i} className={'xtimeline__row xtimeline__row--' + t.kind}>
          <div className="xtimeline__era">{t.era}</div>
          <div className="xtimeline__dot"><span/></div>
          <div className="xtimeline__card">
            <div className="xtimeline__card-label">{t.label}</div>
            <div className="xtimeline__card-kind">
              {t.kind==='event' ? '사건' : t.kind==='figure' ? '인물' : '결집'}
            </div>
          </div>
        </div>
      ))}
    </div>
  );
};

/* ---------- 지도 ---------- */
window.ExploreMap = () => {
  /* 단순화한 SVG 지도 — 실제 지도 대신 도식 */
  const places = [
    { id:'lumbini', name:'룸비니',       han:'藍毘尼',  x:0.36, y:0.66, kind:'birth' },
    { id:'bodhgaya',name:'보드가야',     han:'菩提伽耶',x:0.40, y:0.72, kind:'birth' },
    { id:'sarnath', name:'사르나트',     han:'鹿野苑',  x:0.42, y:0.68, kind:'birth' },
    { id:'rajagaha',name:'라자가하',     han:'王舍城',  x:0.44, y:0.74, kind:'birth' },
    { id:'nalanda', name:'날란다',       han:'那爛陀',  x:0.46, y:0.72, kind:'birth' },
    { id:'kushinag',name:'쿠시나가라',   han:'拘尸那',  x:0.40, y:0.62, kind:'birth' },
    { id:'dunhuang',name:'돈황',         han:'敦煌',    x:0.62, y:0.45, kind:'transmit' },
    { id:'changan', name:'장안',         han:'長安',    x:0.70, y:0.50, kind:'east' },
    { id:'gyeongju',name:'경주',         han:'慶州',    x:0.82, y:0.52, kind:'east' },
    { id:'haeinsa', name:'해인사',       han:'海印寺',  x:0.81, y:0.55, kind:'east' },
    { id:'kyoto',   name:'교토',         han:'京都',    x:0.90, y:0.54, kind:'east' },
    { id:'lhasa',   name:'라싸',         han:'拉薩',    x:0.55, y:0.58, kind:'tibet' },
    { id:'anuradha',name:'아누라다푸라', han:'阿耨樓陀',x:0.44, y:0.92, kind:'south' },
  ];
  const W = 1100, H = 540;
  const proj = (x,y) => ({cx: x*W, cy: y*H});

  /* 전파 경로 (간단한 곡선들) */
  const routes = [
    { from:'rajagaha', to:'dunhuang', label:'서역 북도' },
    { from:'dunhuang', to:'changan',  label:'' },
    { from:'changan',  to:'gyeongju', label:'동아시아' },
    { from:'gyeongju', to:'kyoto',    label:'' },
    { from:'rajagaha', to:'lhasa',    label:'후기 인도→티벳' },
    { from:'rajagaha', to:'anuradha', label:'남전' },
  ];
  const placeMap = Object.fromEntries(places.map(p => [p.id, p]));

  const kindColor = k => k==='birth' ? '#5a1a1a' : k==='transmit' ? '#8b6914' : k==='east' ? '#1f3a3a' : k==='tibet' ? '#a85020' : '#2e5c4a';

  return (
    <div className="xmap">
      <svg viewBox={`0 0 ${W} ${H}`} className="xmap__svg" preserveAspectRatio="xMidYMid meet">
        {/* 대륙 윤곽 (도식) */}
        <path d="M180,360 Q220,260 320,220 Q420,180 520,200 Q640,170 760,200 Q900,210 1020,260 L1020,420 Q900,460 760,440 Q640,460 520,440 Q420,460 320,440 Q220,460 180,400 Z"
              fill="rgba(180,160,120,0.08)" stroke="rgba(60,40,20,0.18)" strokeWidth="0.8"/>
        <path d="M380,440 Q440,490 500,510 Q540,520 540,500 Q500,470 440,460 Z"
              fill="rgba(180,160,120,0.06)" stroke="rgba(60,40,20,0.15)" strokeWidth="0.6"/>

        {/* 경로 */}
        {routes.map((r, i) => {
          const a = placeMap[r.from], b = placeMap[r.to];
          if (!a || !b) return null;
          const pa = proj(a.x, a.y), pb = proj(b.x, b.y);
          const mx = (pa.cx + pb.cx)/2;
          const my = (pa.cy + pb.cy)/2 - 30;
          return (
            <g key={i}>
              <path d={`M${pa.cx},${pa.cy} Q${mx},${my} ${pb.cx},${pb.cy}`}
                    fill="none" stroke="rgba(120,70,30,0.45)" strokeWidth="1.2" strokeDasharray="3 3"/>
              {r.label && <text x={mx} y={my-4} textAnchor="middle" fontSize="11"
                fill="rgba(60,40,20,0.55)" fontStyle="italic">{r.label}</text>}
            </g>
          );
        })}

        {/* 장소 */}
        {places.map(p => {
          const pp = proj(p.x, p.y);
          return (
            <g key={p.id} className="xmap__node">
              <circle cx={pp.cx} cy={pp.cy} r="6" fill={kindColor(p.kind)} stroke="#faf6ec" strokeWidth="2"/>
              <text x={pp.cx+10} y={pp.cy+4} fontSize="13" fill="#3d2818" fontWeight="500">{p.name}</text>
              <text x={pp.cx+10} y={pp.cy+19} fontSize="10" fill="rgba(60,40,20,0.55)" className="han">{p.han}</text>
            </g>
          );
        })}
      </svg>
      <div className="xmap__legend">
        <span><i style={{background:'#5a1a1a'}}/>붓다의 생애</span>
        <span><i style={{background:'#8b6914'}}/>실크로드</span>
        <span><i style={{background:'#1f3a3a'}}/>동아시아</span>
        <span><i style={{background:'#a85020'}}/>티벳</span>
        <span><i style={{background:'#2e5c4a'}}/>남전</span>
      </div>
    </div>
  );
};

/* ---------- 계보 ---------- */
window.ExploreLineage = () => {
  const trees = [
    { id:'madhyamaka', title:'중관 계보', han:'中觀', root:'용수',
      nodes:[
        { name:'용수', sub:'2–3C 인도', children:[
          { name:'제바', sub:'3C', children:[
            { name:'청변', sub:'6C', children:[ { name:'관음 길조', sub:'8C', children:[] } ] },
            { name:'불호', sub:'6C', children:[ { name:'월칭', sub:'7C', children:[ { name:'적호', sub:'8C, 티벳 전법', children:[] } ] } ] },
          ]},
        ]},
      ]},
    { id:'seon', title:'동아시아 선종 초조 계보', han:'禪宗', root:'달마',
      nodes:[
        { name:'달마', sub:'5–6C 중국', children:[
          { name:'혜가', sub:'6C', children:[
            { name:'승찬', sub:'6–7C', children:[
              { name:'도신', sub:'7C', children:[
                { name:'홍인', sub:'7C', children:[
                  { name:'혜능', sub:'7–8C 남종', children:[] },
                  { name:'신수', sub:'7–8C 북종', children:[] },
                ]},
              ]},
            ]},
          ]},
        ]},
      ]},
  ];

  const renderNode = (n, depth=0) => (
    <div className="xlin__node" key={n.name + depth}>
      <div className="xlin__node-card" style={{'--depth': depth}}>
        <span className="xlin__node-name">{n.name}</span>
        <span className="xlin__node-sub">{n.sub}</span>
      </div>
      {n.children && n.children.length > 0 && (
        <div className="xlin__children">
          {n.children.map(c => renderNode(c, depth+1))}
        </div>
      )}
    </div>
  );

  return (
    <div className="xlin">
      {trees.map(t => (
        <section key={t.id} className="xlin__tree">
          <header className="xlin__tree-head">
            <h3>{t.title}</h3>
            <span className="xlin__tree-han">{t.han}</span>
          </header>
          {t.nodes.map(n => renderNode(n))}
        </section>
      ))}
    </div>
  );
};

/* ---------- 비교(다국어 본문 정렬) ---------- */
window.ExploreCompare = () => {
  const samples = [
    {
      id:'evam',
      title:'경전의 첫머리 — “이와 같이 나는 들었다”',
      sub:'결집에서 아난이 송출한 정형구. 전승의 신뢰를 보장하는 표지.',
      lines: [
        { lang:'한문 (구마라집)',    text:'如是我聞。一時佛在……',          klass:'han'},
        { lang:'한문 (현장)',        text:'如是我聞。一時薄伽梵住……',      klass:'han'},
        { lang:'산스크리트',         text:'evaṃ mayā śrutam ekasmin samaye bhagavān ...', klass:'skt'},
        { lang:'빨리어',             text:'evaṃ me sutaṃ ekaṃ samayaṃ bhagavā ...',       klass:'pi'},
        { lang:'티벳어',             text:'འདི་སྐད་བདག་གིས་ཐོས་པའི་དུས་གཅིག་ན། བཅོམ་ལྡན་འདས་...', klass:'tib'},
        { lang:'한국어',             text:'이와 같이 나는 들었다. 한때 세존께서 …',          klass:'kr'},
        { lang:'영어',               text:'Thus have I heard. At one time the Blessed One ...', klass:'en'},
      ]
    },
    {
      id:'gate',
      title:'반야심경 종결 진언',
      sub:'한국어 의례에서도 산스크리트 음역을 그대로 송경한다.',
      lines: [
        { lang:'한문 (현장)',  text:'揭諦揭諦 波羅揭諦 波羅僧揭諦 菩提薩婆訶', klass:'han'},
        { lang:'산스크리트', text:'gate gate pāragate pārasaṃgate bodhi svāhā', klass:'skt'},
        { lang:'한국어 음역', text:'아제아제 바라아제 바라승아제 모지사바하',      klass:'kr'},
        { lang:'한국어 풀이', text:'가신 이여, 가신 이여, 저 언덕에 가신 이여, 모두 함께 가신 이여, 깨달음이여 — 평안하소서.', klass:'kr'},
      ]
    },
  ];
  return (
    <div className="xcompare">
      {samples.map(s => (
        <section key={s.id} className="xcompare__block">
          <header className="xcompare__head">
            <h3>{s.title}</h3>
            <p>{s.sub}</p>
          </header>
          <div className="xcompare__rows">
            {s.lines.map((l, i) => (
              <div key={i} className="xcompare__row">
                <div className="xcompare__lang">{l.lang}</div>
                <div className={'xcompare__text ' + l.klass}>{l.text}</div>
              </div>
            ))}
          </div>
        </section>
      ))}
    </div>
  );
};
