/* app-gl.jsx — 가이드라인 분석 탭 컨텐츠 (Variation C: 분할 패널) */

const GL_MAJORS = [
  { id: 'CV', label: '심혈관질환', enabled: true },
  { id: 'PM', label: '호흡기', enabled: false },
  { id: 'ED', label: '내분비', enabled: false },
];

function AppGl() {
  const { plan } = React.useContext(window.AuthContext || {});
  const s = useGlSession('CV_HF');
  const [major, setMajor] = React.useState('CV');
  const [tocOpen, setTocOpen] = React.useState(true);
  const contentRef = React.useRef(null);

  // plan에 따른 동적 GL_MAJORS 생성
  const currentMajors = React.useMemo(() => {
    const unlocked = window.isUnlocked(plan);
    return [
      { id: 'CV', label: '심혈관질환', enabled: true,     locked: false },
      { id: 'PM', label: '호흡기',     enabled: unlocked, locked: !unlocked },
      { id: 'ED', label: '내분비',     enabled: unlocked, locked: !unlocked },
    ];
  }, [plan]);

  // 안전 복구 로직 1: 권한 없는 사용자가 PM/ED 선택 시 CV로 복구
  React.useEffect(() => {
    const isUnlocked = window.isUnlocked(plan);
    if (!isUnlocked) {
      const currentMajor = GL_MANIFEST[s.diseaseKey]?.major;
      if (currentMajor && currentMajor !== 'CV') {
        s.setDisease('CV_HF');
        setMajor('CV');
      } else if (major !== 'CV') {
        setMajor('CV');
      }
    }
  }, [plan, s.diseaseKey, major]);

  // 안전 복구 로직 2: 비admin이 individual 모드에 있으면 summary로 강제 복구
  React.useEffect(() => {
    if (plan !== 'admin' && s.mode === 'individual') {
      s.setMode('summary');
    }
  }, [plan, s.mode]);

  const handleMajorChange = (m) => {
    if (!currentMajors.find(d => d.id === m)?.enabled) return;
    setMajor(m);
    const first = GL_ORDER.find(k => GL_MANIFEST[k].major === m);
    if (first) s.setDisease(first);
  };

  const filteredItems = GL_ORDER
    .filter(k => GL_MANIFEST[k].major === major)
    .map(k => ({ value: k, label: GL_MANIFEST[k].diseaseLabel }));

  const handleTocSelect = (id) => {
    s.setActiveId(id);
    if (!contentRef.current) return;
    const el = contentRef.current.querySelector('#' + id);
    if (el) contentRef.current.scrollTo({ top: el.offsetTop - 10, behavior: 'smooth' });
  };

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>

      {/* 셀렉터 바 — 처방전 분석과 동일한 구조/스타일 */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8, padding: '11px 12px', background: RX.shell, borderBottom: `1px solid ${RX.line}`, flexShrink: 0 }}>
        {/* 행 1: 내과 + 진료과 세그먼트 */}
        <div style={{ display: 'flex', gap: 7, alignItems: 'center' }}>
          <span style={{ flexShrink: 0, fontSize: 12, fontWeight: 800, color: RX.sub, background: RX.paper, border: `1px solid ${RX.line}`, borderRadius: 8, padding: '8px 11px' }}>내과</span>
          <div style={{ flex: 1, display: 'flex', gap: 3, background: RX.paper, border: `1px solid ${RX.line}`, borderRadius: 9, padding: 3 }}>
            {currentMajors.map(d => {
              const on = d.id === major;
              return (
                <button key={d.id} onClick={() => handleMajorChange(d.id)} disabled={!d.enabled}
                  title={d.enabled ? '' : 'VIP 전용'}
                  style={{
                    flex: 1, padding: '6px 2px', borderRadius: 6, border: 'none', font: 'inherit',
                    fontSize: 12, fontWeight: on ? 800 : 600, cursor: d.enabled ? 'pointer' : 'default',
                    color: on ? '#fff' : d.enabled ? RX.sub : '#c3c8c4',
                    background: on ? RX.teal : 'transparent', position: 'relative',
                  }}>
                  {d.label} {d.locked && '🔒'}
                </button>
              );
            })}
          </div>
        </div>
        {/* 행 2: 질환 드롭다운 + 통합/개별 토글 (개별은 admin만) */}
        <div style={{ display: 'flex', gap: 7 }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <Dropdown value={s.diseaseKey} items={filteredItems} onChange={s.setDisease} />
          </div>
          {plan === 'admin' && (
            <div style={{ display: 'flex', background: RX.paper, border: `1px solid ${RX.line}`, borderRadius: 8, overflow: 'hidden', flexShrink: 0 }}>
              {[{ m: 'summary', label: '통합' }, { m: 'individual', label: '개별' }].map(({ m, label }) => {
                const on = s.mode === m;
                return (
                  <button key={m} onClick={() => s.setMode(m)} style={{
                    padding: '0 14px', border: 'none', font: 'inherit',
                    fontSize: 13, fontWeight: on ? 800 : 700, cursor: 'pointer',
                    background: on ? RX.teal : 'transparent', color: on ? '#fff' : RX.sub,
                    transition: 'all .12s',
                    boxShadow: on ? '0 2px 6px rgba(26,108,91,0.3)' : 'none',
                  }}>{label}</button>
                );
              })}
            </div>
          )}
        </div>
      </div>

      {/* 개별 모드 가이드라인 칩 */}
      {s.mode === 'individual' && (
        <div style={{ background: RX.paper, borderBottom: `1px solid ${RX.line}`, flexShrink: 0 }}>
          <GlGuidelineChips guidelines={s.dis.guidelines} activeId={s.glId} onSelect={s.setGlId} />
        </div>
      )}

      {/* 분할 패널 */}
      <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>

        {/* 좌: TOC 사이드바 */}
        <div style={{
          flexShrink: 0,
          width: tocOpen ? 86 : 18,
          transition: 'width .22s cubic-bezier(.4,0,.2,1)',
          overflow: 'hidden',
          display: 'flex', flexDirection: 'column',
          borderRight: `1px solid ${RX.line}`,
          background: RX.shell,
        }}>
          <button onClick={() => setTocOpen(o => !o)} style={{
            flexShrink: 0, width: '100%', height: 28,
            border: 'none', background: 'transparent',
            cursor: 'pointer', display: 'flex', alignItems: 'center',
            justifyContent: tocOpen ? 'flex-end' : 'center',
            paddingRight: tocOpen ? 7 : 0,
            borderBottom: `1px solid ${RX.line}`,
          }}>
            <svg width="10" height="10" viewBox="0 0 10 10" fill="none"
              style={{ transition: 'transform .22s', transform: tocOpen ? 'rotate(0deg)' : 'rotate(180deg)', flexShrink: 0 }}>
              <path d="M7 5L3 2M7 5L3 8" stroke={RX.faint} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          </button>

          {tocOpen && !s.loading && s.toc.length > 0 && (
            <div style={{ flex: 1, overflowY: 'auto', overflowX: 'hidden', padding: '6px 0', scrollbarWidth: 'none' }}>
              {s.toc.filter(t => t.level === 2).map((t, idx) => {
                const on = t.id === s.activeId;
                return (
                  <button key={t.id} onClick={() => handleTocSelect(t.id)} style={{
                    width: '100%', textAlign: 'left', padding: '8px 10px 8px 12px', border: 'none',
                    background: on ? RX.tealTint : 'transparent', font: 'inherit',
                    cursor: 'pointer', position: 'relative', display: 'flex', alignItems: 'flex-start', gap: 6,
                  }}>
                    {on && <span style={{ position: 'absolute', left: 0, top: 6, bottom: 6, width: 3, background: RX.teal, borderRadius: '0 3px 3px 0' }} />}
                    <span style={{ fontSize: 9.5, fontWeight: 800, color: on ? RX.teal : RX.faint, marginTop: 1, flexShrink: 0 }}>
                      {String(idx + 1).padStart(2, '0')}
                    </span>
                    <span style={{ fontSize: 10.5, fontWeight: on ? 800 : 600, color: on ? RX.teal : RX.sub, lineHeight: 1.4, wordBreak: 'keep-all' }}>
                      {t.text.replace(/^섹션\s*\d+[:\s]*/, '').slice(0, 16)}
                    </span>
                  </button>
                );
              })}
            </div>
          )}

          {!tocOpen && !s.loading && s.toc.length > 0 && (
            <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', paddingBottom: 8 }}>
              <span style={{ fontSize: 8.5, fontWeight: 800, color: RX.faint, writingMode: 'vertical-rl', letterSpacing: '.06em' }}>
                {s.toc.filter(t => t.level === 2).length}섹션
              </span>
            </div>
          )}
        </div>

        {/* 우: 본문 */}
        <div ref={contentRef} style={{ flex: 1, overflowY: 'auto', background: RX.paper, position: 'relative' }}>

          {/* 현재 섹션 sticky 헤더 */}
          {s.activeId && s.toc.length > 0 && (() => {
            const active = s.toc.find(t => t.id === s.activeId);
            return active ? (
              <div style={{ position: 'sticky', top: 0, zIndex: 10, padding: '7px 14px', background: 'rgba(255,255,255,0.92)', backdropFilter: 'blur(8px)', borderBottom: `1px solid ${RX.lineSoft}`, display: 'flex', alignItems: 'center', gap: 6 }}>
                <span style={{ width: 3, height: 14, borderRadius: 3, background: RX.teal, flexShrink: 0 }} />
                <span style={{ fontSize: 11.5, fontWeight: 800, color: RX.teal, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                  {active.text.replace(/^섹션\s*\d+[:\s]*/, '').slice(0, 28)}
                </span>
              </div>
            ) : null;
          })()}

          <GlMdContent
            mdContent={s.mdContent}
            loading={s.loading}
            toc={s.toc}
            activeId={s.activeId}
            setActiveId={s.setActiveId}
            style={{ height: 'auto', overflowY: 'visible', flex: 'none' }}
          />

          {s.mode === 'summary' && !s.loading && (
            <div style={{
              margin: '4px 14px 4px 14px',
              padding: '10px 12px',
              borderRadius: 6,
              background: '#f9f9f9',
              border: '1px solid #e5e5e5',
              fontSize: 11,
              color: '#777777',
              lineHeight: 1.5,
            }}>
              <div style={{ fontWeight: 700, marginBottom: 4, color: '#555555' }}>
                의학 가이드라인 저작권 및 출처 안내
              </div>
              <div style={{ color: '#777777' }}>
                本 정보는 학술 및 정보 공유 목적으로 작성되었으며, 저작권법 제37조에 따라 참조한 원출처를 최하단에 명시하고 있습니다. 보다 상세한 진료·치료 알고리즘 및 지침 전문은 각 학회에서 배포하는 공식 원문 자료를 통해 확인하시기 바랍니다.
              </div>
            </div>
          )}

          {!s.loading && <Disclaimer />}
        </div>
      </div>

      {/* 하단 진행 바 */}
      {!s.loading && s.toc.length > 0 && (() => {
        const h2s = s.toc.filter(t => t.level === 2);
        const idx = h2s.findIndex(t => t.id === s.activeId);
        const pct = idx < 0 ? 0 : Math.round(((idx + 1) / h2s.length) * 100);
        return (
          <div style={{ height: 3, background: RX.line, flexShrink: 0 }}>
            <div style={{ height: '100%', width: pct + '%', background: RX.teal, borderRadius: 99, transition: 'width .3s' }} />
          </div>
        );
      })()}
    </div>
  );
}

window.AppGl = AppGl;
window.AppGlContent = AppGl; // alias
