/* rx-blocks.jsx — Section-B 콘텐츠 블록
   requires: window.RX (rx-core.jsx), window.rxHelpers (rx-core.jsx),
             window.SectionCard (rx-ui.jsx)
   exports:  DxBlock, DifferentialDxBlock, IntentBlock, GroupsOverview, CautionBlock, GuidelineBlock, Disclaimer */

function DxBlock({ pattern }) {
  return (
    <SectionCard kicker="① 질병 예측" title="이 처방의 환자는?">
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 11 }}>
        {pattern.diseases.map(dz => (
          <span key={dz} style={{ fontSize: 13, fontWeight: 800, color: '#fff', background: RX.teal, borderRadius: 99, padding: '5px 13px' }}>{dz}</span>
        ))}
      </div>
      <div style={{ fontSize: 13, color: RX.ink, lineHeight: 1.66 }}>{rxHelpers.fmt(pattern.context)}</div>
    </SectionCard>
  );
}

function IntentBlock({ pattern }) {
  return (
    <SectionCard kicker="③ 의사 처방 의도" title="왜 이렇게 처방했나">
      <div style={{ fontSize: 13, color: RX.ink, lineHeight: 1.68 }}>{rxHelpers.fmt(pattern.aiInterpretation)}</div>
    </SectionCard>
  );
}

function DifferentialDxBlock({ pattern }) {
  const items = rxHelpers.differentialDxForPattern(pattern);
  const [openSet, setOpenSet] = React.useState(new Set());
  if (!items || items.length === 0) return null;

  const toggle = (disease) => {
    setOpenSet(prev => {
      const next = new Set(prev);
      next.has(disease) ? next.delete(disease) : next.add(disease);
      return next;
    });
  };

  return (
    <SectionCard kicker="② 감별 포인트" title="다른 질환 가능성">
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 9 }}>
        {items.map(item => {
          const open = openSet.has(item.disease);
          return (
            <button key={item.disease} onClick={() => toggle(item.disease)} style={{
              padding: '4px 10px', borderRadius: 20, fontSize: 12.5, fontWeight: 700,
              border: `1px solid ${open ? RX.teal : RX.line}`, background: open ? RX.tealTint : RX.paper,
              color: open ? RX.teal : RX.sub, cursor: 'pointer', font: 'inherit',
            }}>
              {item.label || item.disease}
            </button>
          );
        })}
      </div>
      {items.filter(item => openSet.has(item.disease)).map(item => (
        <div key={item.disease} style={{
          marginBottom: 10, padding: '10px 12px', background: RX.tealTint,
          borderRadius: 8, borderLeft: `3px solid ${RX.teal}`,
        }}>
          <div style={{ fontWeight: 800, fontSize: 13, color: RX.teal, marginBottom: 5 }}>
            {item.label || item.disease}
          </div>
          {item.drugs.map((drug, i) => (
            <div key={`${drug.generic}-${drug.role}-${i}`} style={{ fontSize: 12.5, color: RX.ink, marginBottom: 2 }}>
              <span style={{ fontWeight: 700 }}>{drug.generic || drug.brand}</span>
              {drug.role && <span style={{ color: RX.sub }}> — {drug.role}</span>}
            </div>
          ))}
          {item.summary && (
            <div style={{ fontSize: 12, color: RX.sub, marginTop: 6, lineHeight: 1.55 }}>
              {rxHelpers.fmt(item.summary)}
            </div>
          )}
        </div>
      ))}
      <div style={{ fontSize: 11.5, color: RX.faint, marginTop: 4, lineHeight: 1.5 }}>
        ※ 이 처방만으로 다른 질환을 확정하지 않습니다.
      </div>
    </SectionCard>
  );
}

function GroupsOverview({ pattern, onDrugClick }) {
  const groups = pattern.drugGroups || [];
  return (
    <SectionCard kicker="처방 구성" title="약물 조합 그룹">
      <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
        {groups.map(g => {
          const members = pattern.drugs.map((d, i) => ({ d, i })).filter(x => x.d.groupId === g.id);
          return (
            <div key={g.id} style={{ background: RX.shell, borderRadius: 10, padding: '11px 12px' }}>
              <div style={{ fontSize: 12.5, fontWeight: 800, color: RX.ink, marginBottom: 7 }}>{g.label}</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5 }}>
                {members.map(({ d, i }) => (
                  <button key={i} onClick={() => onDrugClick && onDrugClick(i)} style={{
                    cursor: 'pointer', border: `1px solid ${RX.tealLine}`, background: RX.paper,
                    color: RX.teal, borderRadius: 7, padding: '4px 9px', font: 'inherit',
                    fontSize: 11.5, fontWeight: 700,
                  }}>{d.brand.split(' ')[0]}</button>
                ))}
              </div>
            </div>
          );
        })}
      </div>
    </SectionCard>
  );
}

function AdjunctContextBlock({ pattern }) {
  const notes = rxHelpers.contextNotesForPattern(pattern);
  if (!notes.length) return null;

  return (
    <SectionCard kicker="⑤ 동반 보조요법" title="같이 나온 약의 의미">
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {notes.map(note => {
          const low = note.confidence === 'low';
          return (
            <div key={note.contextId} style={{
              border: `1px solid ${low ? RX.lineSoft : RX.tealLine}`,
              background: low ? RX.shell : RX.tealTint,
              borderRadius: 10,
              padding: '10px 12px',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 7, flexWrap: 'wrap', marginBottom: 6 }}>
                <span style={{ fontSize: 12.5, fontWeight: 800, color: RX.ink, lineHeight: 1.35 }}>
                  {note.clinicalContext}
                </span>
                {low && (
                  <span style={{
                    fontSize: 10, fontWeight: 800, color: RX.faint,
                    border: `1px solid ${RX.line}`, background: RX.paper,
                    borderRadius: 99, padding: '2px 7px', whiteSpace: 'nowrap',
                  }}>낮은 확신도</span>
                )}
              </div>
              <div style={{ fontSize: 12.5, color: RX.sub, lineHeight: 1.65, wordBreak: 'keep-all' }}>
                {rxHelpers.fmt(note.interpretation)}
              </div>
            </div>
          );
        })}
      </div>
    </SectionCard>
  );
}

function CautionBlock({ pattern }) {
  const items = rxHelpers.cautionItems(pattern.cautions);
  return (
    <SectionCard kicker="④ 복약지도 포인트" title="주의사항 · 상담" accent={RX.rose}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
        {items.map((it, i) => (
          <div key={i} style={{ display: 'flex', gap: 9, alignItems: 'flex-start' }}>
            <span style={{ flexShrink: 0, marginTop: 1, width: 19, height: 19, borderRadius: '50%', background: RX.roseBg, color: RX.rose, fontSize: 11, fontWeight: 800, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{it.marker}</span>
            <span style={{ fontSize: 12.5, color: RX.ink, lineHeight: 1.58 }}>{rxHelpers.fmt(it.text)}</span>
          </div>
        ))}
      </div>
    </SectionCard>
  );
}

function GuidelineBlock({ pattern }) {
  if (!pattern.guidelineRefs || pattern.guidelineRefs.length === 0) return null;
  return (
    <SectionCard kicker="근거" title="가이드라인">
      <div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
        {pattern.guidelineRefs.map(ref => {
          const parts = ref.split('_');
          const country = parts[2], year = parts[3], org = parts[4], title = parts.slice(5).join('_');
          return (
            <div key={ref} style={{ display: 'flex', gap: 9, alignItems: 'center', background: RX.shell, borderRadius: 9, padding: '9px 11px' }}>
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none" style={{ flexShrink: 0 }}><rect x="2.5" y="1.5" width="11" height="13" rx="1.5" stroke={RX.teal} strokeWidth="1.3" /><path d="M5 5h6M5 7.5h6M5 10h4" stroke={RX.teal} strokeWidth="1.1" strokeLinecap="round" /></svg>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: 12, fontWeight: 700, color: RX.ink, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{title}</div>
                <div style={{ fontSize: 10, color: RX.faint, fontWeight: 600, marginTop: 1 }}>{org} · {country} · {year}</div>
              </div>
            </div>
          );
        })}
      </div>
    </SectionCard>
  );
}

function Disclaimer() {
  return (
    <div style={{ padding: '14px 16px 6px', fontSize: 10, color: RX.faint, lineHeight: 1.5, textAlign: 'center' }}>
      이 서비스는 임상 약사의 학습 및 참고 목적으로 제공되며, 실제 임상 판단을 대체하지 않습니다.
    </div>
  );
}

Object.assign(window, { DxBlock, IntentBlock, DifferentialDxBlock, GroupsOverview, AdjunctContextBlock, CautionBlock, GuidelineBlock, Disclaimer });
