/* rx-form.jsx — faithful Korean prescription form + drug popup
   Exports: RxForm, DrugPopup, seededPatient  */

// deterministic patient meta from patternId
function seededPatient(patternId) {
  let h = 0;
  for (let i = 0; i < patternId.length; i++) h = (h * 31 + patternId.charCodeAt(i)) >>> 0;
  const sur = ['김', '이', '박', '최', '정', '강', '조', '윤', '장', '한'][h % 10];
  const sex = (h >> 3) % 2 === 0 ? '남' : '여';
  const age = 48 + ((h >> 5) % 35); // 48–82, 심혈관 환자 연령대
  const rrnFront = String(26 - Math.floor(age / 10)).padStart(2, '0') + String(((h >> 7) % 12) + 1).padStart(2, '0') + String(((h >> 9) % 28) + 1).padStart(2, '0');
  const issue = String(((h >> 11) % 28) + 1).padStart(2, '0');
  const giveNo = String(10000 + (h % 89999));
  return {
    name: sur + '○○', sex, age,
    rrn: rrnFront + '-' + (sex === '남' ? (age < 76 ? '1' : '3') : (age < 76 ? '2' : '4')) + '******',
    issueDate: `2026-05-${issue}`,
    giveNo: giveNo.slice(0, 5) + '-' + String(h % 9 + 1),
  };
}

function RxForm({ pattern, onDrugClick, revealedDx = null, activeDrug = null }) {
  const p = seededPatient(pattern.patternId);
  const deptMap = { CV: '순환기내과', PM: '호흡기내과', ED: '내분비내과' };
  const dept = deptMap[pattern.major] || '내과';
  const cell = { padding: '0 4px', display: 'flex', flexDirection: 'column', justifyContent: 'center' };
  const lbl = { fontSize: 9.5, color: RX.faint, fontWeight: 600, letterSpacing: '.01em' };
  const val = { fontSize: 12.5, color: RX.ink, fontWeight: 600, fontVariantNumeric: 'tabular-nums' };

  return (
    <div style={{
      background: RX.paper, border: `1px solid ${RX.ink}`,
      fontFamily: '"Pretendard Variable", Pretendard, system-ui, sans-serif',
    }}>
      {/* title band */}
      <div style={{ textAlign: 'center', padding: '11px 0 8px', borderBottom: `1.5px solid ${RX.ink}`, position: 'relative' }}>
        <div style={{ position: 'absolute', left: 10, top: 9, fontSize: 8.5, color: RX.faint }}>[별지 제2호서식]</div>
        <div style={{ fontSize: 19, fontWeight: 800, letterSpacing: '.42em', color: RX.ink, paddingLeft: '.42em' }}>처 방 전</div>
        <div style={{ fontSize: 10, color: RX.sub, marginTop: 3, letterSpacing: '.02em' }}>
          [<span style={{ color: RX.teal, fontWeight: 800 }}>✓</span> 건강보험]&nbsp; [ 의료급여 ]&nbsp; [ 자동차보험 ]
        </div>
      </div>

      {/* meta grid */}
      <div style={{ borderBottom: `1px solid ${RX.line}` }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', borderBottom: `1px solid ${RX.lineSoft}` }}>
          <div style={{ ...cell, padding: '6px 8px', borderRight: `1px solid ${RX.lineSoft}` }}>
            <span style={lbl}>교부번호</span><span style={val}>제 {p.giveNo} 호</span>
          </div>
          <div style={{ ...cell, padding: '6px 8px' }}>
            <span style={lbl}>발행 연월일</span><span style={val}>{p.issueDate}</span>
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', borderBottom: `1px solid ${RX.lineSoft}` }}>
          <div style={{ ...cell, padding: '6px 8px', borderRight: `1px solid ${RX.lineSoft}` }}>
            <span style={lbl}>환자 성명</span><span style={val}>{p.name}</span>
          </div>
          <div style={{ ...cell, padding: '6px 8px' }}>
            <span style={lbl}>성별 / 나이</span><span style={val}>{p.sex} / 만 {p.age}세</span>
          </div>
        </div>
        {/* the quiz target — masked KCD code */}
        <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr' }}>
          <div style={{ ...cell, padding: '6px 8px', borderRight: `1px solid ${RX.lineSoft}` }}>
            <span style={lbl}>의료기관 명칭</span><span style={{ ...val, fontSize: 11.5 }}>○○대학교병원 {dept}</span>
          </div>
          <div style={{ ...cell, padding: '6px 8px', background: revealedDx ? RX.tealTint : '#f4f5f3' }}>
            <span style={lbl}>질병분류기호</span>
            {revealedDx
              ? <span style={{ ...val, color: RX.teal, fontWeight: 800 }}>{revealedDx.join(' · ')}</span>
              : <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, marginTop: 1 }}>
                  <span style={{ display: 'inline-block', width: 52, height: 13, borderRadius: 2, background: `repeating-linear-gradient(115deg, ${RX.mask}, ${RX.mask} 5px, #d6dad6 5px, #d6dad6 10px)` }} />
                  <span style={{ fontSize: 9, color: RX.faint, fontWeight: 700 }}>가림</span>
                </span>}
          </div>
        </div>
      </div>

      {/* table header */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 42px 38px 40px', background: '#f6f7f5', borderBottom: `1.5px solid ${RX.ink}`, fontSize: 9.5, color: RX.sub, fontWeight: 700 }}>
        <div style={{ padding: '6px 8px' }}>처방 의약품의 명칭</div>
        <div style={{ padding: '6px 2px', textAlign: 'center', borderLeft: `1px solid ${RX.lineSoft}` }}>1회<br />투약량</div>
        <div style={{ padding: '6px 2px', textAlign: 'center', borderLeft: `1px solid ${RX.lineSoft}` }}>1일<br />횟수</div>
        <div style={{ padding: '6px 2px', textAlign: 'center', borderLeft: `1px solid ${RX.lineSoft}` }}>총<br />일수</div>
      </div>

      {/* drug rows */}
      {pattern.drugs.map((d, i) => {
        const active = activeDrug === i;
        return (
          <button key={i} onClick={() => onDrugClick && onDrugClick(i)} style={{
            display: 'block', width: '100%', textAlign: 'left', cursor: 'pointer',
            background: active ? RX.tealTint : RX.paper, font: 'inherit',
            border: 'none', borderBottom: `1px solid ${RX.lineSoft}`,
            borderLeft: `3px solid ${active ? RX.teal : 'transparent'}`,
            padding: 0, transition: 'background .12s',
          }}
            onMouseEnter={e => { if (!active) e.currentTarget.style.background = '#fafbfa'; }}
            onMouseLeave={e => { if (!active) e.currentTarget.style.background = RX.paper; }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 42px 38px 40px', alignItems: 'center' }}>
              <div style={{ padding: '8px 8px 8px 7px', minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 5 }}>
                  <span style={{ fontSize: 10, color: RX.faint, fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>{String(i + 1).padStart(2, '0')}</span>
                  <span style={{ fontSize: 13, fontWeight: 700, color: RX.ink, lineHeight: 1.25 }}>{d.brand}</span>
                  <svg width="13" height="13" viewBox="0 0 16 16" style={{ flexShrink: 0, marginLeft: 'auto', opacity: .55 }}>
                    <circle cx="8" cy="8" r="7" fill="none" stroke={RX.teal} strokeWidth="1.3" />
                    <path d="M8 7v4M8 4.6v.6" stroke={RX.teal} strokeWidth="1.5" strokeLinecap="round" />
                  </svg>
                </div>
                <div style={{ fontSize: 10.5, color: RX.sub, marginTop: 2, lineHeight: 1.3 }}>{d.ingredient}</div>
                <div style={{ fontSize: 10, color: RX.teal, marginTop: 3, fontWeight: 600 }}>용법 · {d.timing}</div>
              </div>
              <div style={{ textAlign: 'center', fontSize: 12, fontWeight: 700, color: RX.ink, fontVariantNumeric: 'tabular-nums', borderLeft: `1px solid ${RX.lineSoft}`, alignSelf: 'stretch', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{d.dose}</div>
              <div style={{ textAlign: 'center', fontSize: 12, fontWeight: 700, color: RX.ink, fontVariantNumeric: 'tabular-nums', borderLeft: `1px solid ${RX.lineSoft}`, alignSelf: 'stretch', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{(d.frequency.match(/(\d+)\s*회/) || [null, '1'])[1]}회</div>
              <div style={{ textAlign: 'center', fontSize: 12, fontWeight: 700, color: RX.ink, fontVariantNumeric: 'tabular-nums', borderLeft: `1px solid ${RX.lineSoft}`, alignSelf: 'stretch', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{d.days}일</div>
            </div>
          </button>
        );
      })}

      {/* footer */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8, padding: '7px 9px', fontSize: 9.5, color: RX.faint, borderTop: `1px solid ${RX.line}`, whiteSpace: 'nowrap' }}>
        <span>주사제 처방내역 — 해당 없음</span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
          의사 서명
          <span style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 17, height: 17, borderRadius: '50%', border: `1.2px solid ${RX.rose}`, color: RX.rose, fontSize: 8, fontWeight: 800 }}>印</span>
        </span>
      </div>
    </div>
  );
}

// ── translucent drug detail popup (Section C) ────────────────
function DrugPopup({ pattern, drugIndex, onClose }) {
  if (drugIndex == null) return null;
  const d = pattern.drugs[drugIndex];
  const g = rxHelpers.groupOf(pattern, d);
  const [enter, setEnter] = React.useState(false);
  React.useEffect(() => {
    let r1, r2;
    const t = setTimeout(() => setEnter(true), 24);
    r1 = requestAnimationFrame(() => { r2 = requestAnimationFrame(() => setEnter(true)); });
    return () => { clearTimeout(t); cancelAnimationFrame(r1); cancelAnimationFrame(r2); };
  }, []);
  const close = () => { setEnter(false); setTimeout(onClose, 180); };

  return (
    <div onClick={close} style={{
      position: 'absolute', inset: 0, zIndex: 200, display: 'flex', alignItems: 'flex-end',
      background: enter ? 'rgba(18,40,34,0.34)' : 'rgba(18,40,34,0)',
      backdropFilter: enter ? 'blur(3px)' : 'none', WebkitBackdropFilter: enter ? 'blur(3px)' : 'none',
      transition: 'background .2s, backdrop-filter .2s',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: '100%', maxHeight: '82%', overflowY: 'auto',
        background: 'rgba(255,255,255,0.97)', borderRadius: '20px 20px 0 0',
        boxShadow: '0 -16px 48px rgba(18,40,34,0.28)',
        transform: enter ? 'translateY(0)' : 'translateY(100%)', transition: 'transform .26s cubic-bezier(.32,.72,.31,1)',
        padding: '10px 0 calc(20px + env(safe-area-inset-bottom))',
        fontFamily: '"Pretendard Variable", Pretendard, system-ui, sans-serif',
      }}>
        <div style={{ width: 38, height: 4, borderRadius: 99, background: RX.line, margin: '4px auto 12px' }} />
        <div style={{ padding: '0 18px' }}>
          <div style={{ fontSize: 10.5, fontWeight: 700, color: RX.teal, letterSpacing: '.04em' }}>개별 약제 처방 설명</div>
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8, marginTop: 6 }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 19, fontWeight: 800, color: RX.ink, lineHeight: 1.2 }}>{d.brand}</div>
              <div style={{ fontSize: 12.5, color: RX.sub, marginTop: 3 }}>{d.ingredient}</div>
            </div>
            <SelectionBadge basis={d.selectionBasis} />
          </div>

          {/* dose chips */}
          <div style={{ display: 'flex', gap: 7, marginTop: 13 }}>
            {[['1회', d.dose], ['1일', d.frequency.replace('1일 ', '')], ['총', d.days + '일'], ['용법', d.timing]].map(([k, v]) => (
              <div key={k} style={{ flex: 1, background: RX.tealTint, border: `1px solid ${RX.tealLine}`, borderRadius: 9, padding: '8px 6px', textAlign: 'center' }}>
                <div style={{ fontSize: 9.5, color: RX.teal, fontWeight: 700 }}>{k}</div>
                <div style={{ fontSize: 11.5, color: RX.ink, fontWeight: 700, marginTop: 2, lineHeight: 1.2 }}>{v}</div>
              </div>
            ))}
          </div>

          <Field label="이 약의 역할" body={d.diseaseRole} />
          <Field label={<span>성분 선택 근거 <SelectionBadge basis={d.selectionBasis} small /></span>} body={rxHelpers.fmt(d.selectionNote)} />

          {g && (
            <div style={{ marginTop: 16, background: RX.shell, border: `1px solid ${RX.lineSoft}`, borderRadius: 12, padding: '13px 14px' }}>
              <div style={{ fontSize: 10.5, fontWeight: 700, color: RX.sub, letterSpacing: '.03em' }}>소속 약물 조합 그룹</div>
              <div style={{ fontSize: 14, fontWeight: 800, color: RX.ink, marginTop: 4 }}>{g.label}</div>
              <div style={{ fontSize: 12.5, color: RX.sub, marginTop: 7, lineHeight: 1.62 }}>{rxHelpers.fmt(g.analysis)}</div>
            </div>
          )}
        </div>
        <button onClick={close} style={{
          margin: '18px 18px 0', width: 'calc(100% - 36px)', padding: '13px',
          background: RX.teal, color: '#fff', border: 'none', borderRadius: 12,
          font: 'inherit', fontSize: 15, fontWeight: 700, cursor: 'pointer',
        }}>닫기</button>
      </div>
    </div>
  );
}

function Field({ label, body }) {
  return (
    <div style={{ marginTop: 16 }}>
      <div style={{ fontSize: 11, fontWeight: 700, color: RX.teal, letterSpacing: '.03em', marginBottom: 5 }}>{label}</div>
      <div style={{ fontSize: 13, color: RX.ink, lineHeight: 1.66 }}>{body}</div>
    </div>
  );
}

window.RxForm = RxForm;
window.DrugPopup = DrugPopup;
window.seededPatient = seededPatient;
