/* rx-ui.jsx — 앱 탭 + 진료과 선택기
   requires: window.RX (rx-core.jsx), window.AuthContext (rx-auth.jsx),
             window.getVisibleDepts (rx-auth.jsx), window.rxHelpers (rx-core.jsx),
             window.Dropdown (rx-core.jsx)
   exports:  AppTabs, SelectorBar, SectionCard */

const TABS = [
  { id: 'rx', label: '처방전 분석' },
  { id: 'gl', label: '가이드라인 분석' },
  { id: 'drug', label: '의약품 정보' },
];

const ADMIN_TAB = { id: 'admin-ocr', label: 'OCR 개선센터', adminOnly: true };

function AppTabs({ active, onChange, onMenu, onOcr }) {
  const { plan } = React.useContext(window.AuthContext || {});
  const visibleTabs = plan === 'admin' ? [...TABS, ADMIN_TAB] : TABS;

  return (
    <div style={{ display: 'flex', alignItems: 'stretch', background: RX.paper, borderBottom: `1px solid ${RX.line}` }}>
      <div style={{ flex: 1, display: 'flex', padding: '0 0 0 6px', minWidth: 0 }}>
        {visibleTabs.map(t => {
          const on = t.id === active;
          return (
            <button key={t.id} onClick={() => onChange(t.id)} style={{
              position: 'relative', flex: 1,
              padding: '12px 3px 11px', cursor: 'pointer',
              background: 'transparent', border: 'none', font: 'inherit',
              fontSize: 12.5, fontWeight: on ? 800 : 600, color: on ? RX.teal : RX.faint,
              letterSpacing: '-.01em', whiteSpace: 'nowrap', minWidth: 0,
            }}>
              {t.label}
              <span style={{ position: 'absolute', left: 4, right: 4, bottom: -1, height: 2.5, borderRadius: 3, background: on ? RX.teal : 'transparent' }} />
            </button>
          );
        })}
      </div>
      {plan === 'admin' && onOcr && (
        <React.Fragment>
          <input
            id="ocr-file-input"
            type="file"
            accept="image/*"
            style={{ display: 'none' }}
            onChange={onOcr}
          />
          <button
            onClick={() => document.getElementById('ocr-file-input').click()}
            style={{
              flexShrink: 0, width: 44, padding: 0,
              background: 'transparent', border: 'none', cursor: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}
            title="처방전 사진 분석 (관리자)"
          >
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
              <path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z" stroke={RX.sub} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
              <circle cx="12" cy="13" r="4" stroke={RX.sub} strokeWidth="1.8" />
            </svg>
          </button>
        </React.Fragment>
      )}
      {onMenu && (
        <button onClick={onMenu} style={{
          flexShrink: 0, width: 44, padding: 0,
          background: 'transparent', border: 'none', cursor: 'pointer',
          display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 4.5,
        }}>
          <span style={{ display: 'block', width: 16, height: 1.8, background: RX.sub, borderRadius: 99 }} />
          <span style={{ display: 'block', width: 16, height: 1.8, background: RX.sub, borderRadius: 99 }} />
          <span style={{ display: 'block', width: 16, height: 1.8, background: RX.sub, borderRadius: 99 }} />
        </button>
      )}
    </div>
  );
}

function SelectorBar({ subspec, onSubspec, diseaseKey, caseIdx, onDisease, onCase, onRandom }) {
  const { plan } = React.useContext(window.AuthContext || {});
  const visibleDepts = window.getVisibleDepts(plan);
  const deptLabel = { all: '전체', CV: '순환기', PM: '호흡기', ED: '내분비' };
  const diseases = rxHelpers.diseaseList(subspec, plan);
  const scoped = rxHelpers.scopedPatterns(subspec, diseaseKey, plan);
  const isMix = diseaseKey === '__all';
  const allLabel = `통합 · ${deptLabel[subspec] || ''} 전체 (복합처방 섞기)`;
  const diseaseItems = [
    { value: '__all', label: allLabel, hint: scoped.length + '건' },
    ...diseases.map(d => ({ value: d.key, label: (subspec === 'all' ? deptLabel[d.major] + ' · ' : '') + d.label, hint: '비중 ' + d.weight + '%' })),
  ];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8, padding: '11px 12px', background: RX.shell, borderBottom: `1px solid ${RX.line}` }}>
      <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 }}>
          {visibleDepts.map(d => {
            const on = d.id === subspec;
            return (
              <button key={d.id} onClick={() => d.enabled && onSubspec(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>
      <Dropdown value={diseaseKey} onChange={onDisease} width="100%" items={diseaseItems} />
      {isMix && (
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 5, fontSize: 10.5, color: RX.teal, fontWeight: 600, marginTop: -2, lineHeight: 1.4 }}>
          <svg width="12" height="12" viewBox="0 0 16 16" fill="none" style={{ flexShrink: 0, marginTop: 1 }}><path d="M2 4h3.2l5.6 8H14M2 12h3.2l1.6-2.3M9.2 6.3L10.8 4H14" stroke={RX.teal} strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" /></svg>
          통합 모드 · 단일·복합 처방이 섞여 출제됩니다 (실제 환자는 여러 질환 동반이 흔함)
        </div>
      )}
      <div style={{ display: 'flex', gap: 7 }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <Dropdown value={caseIdx} onChange={onCase}
            items={scoped.map((x, i) => {
              const pctStr = x.pattern.match_pct_str ? `${x.pattern.match_pct_str} ` : '';
              return {
                value: i,
                label: (isMix ? rxHelpers.labelOf(x.key) + ' · ' : `Case ${i + 1} · `) + x.pattern.title.split(' — ')[0],
                hint: pctStr + '#' + (x.pattern.dynamic_rank || x.pattern.frequency_rank),
              };
            })} />
        </div>
        <button onClick={onRandom} style={{
          flexShrink: 0, display: 'inline-flex', alignItems: 'center', gap: 6,
          background: RX.teal, color: '#fff', border: 'none', borderRadius: 8,
          padding: '0 14px', font: 'inherit', fontSize: 13, fontWeight: 700, cursor: 'pointer',
          boxShadow: '0 2px 6px rgba(26,108,91,0.3)',
        }}>
          <svg width="14" height="14" viewBox="0 0 16 16" fill="none"><path d="M2 4h3.2l5.6 8H14M2 12h3.2l1.6-2.3M9.2 6.3L10.8 4H14" stroke="#fff" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" /><path d="M12 2.5L14 4l-2 1.5M12 10.5L14 12l-2 1.5" stroke="#fff" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" /></svg>
          랜덤
        </button>
      </div>
    </div>
  );
}

function SectionCard({ kicker, title, accent = RX.teal, children, style }) {
  return (
    <div style={{ background: RX.paper, border: `1px solid ${RX.line}`, borderRadius: 13, overflow: 'hidden', ...style }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '11px 14px', borderBottom: `1px solid ${RX.lineSoft}` }}>
        <span style={{ width: 4, height: 16, borderRadius: 3, background: accent }} />
        <div>
          {kicker && <div style={{ fontSize: 9.5, fontWeight: 700, color: RX.faint, letterSpacing: '.06em' }}>{kicker}</div>}
          <div style={{ fontSize: 14, fontWeight: 800, color: RX.ink }}>{title}</div>
        </div>
      </div>
      <div style={{ padding: '13px 14px' }}>{children}</div>
    </div>
  );
}

Object.assign(window, { AppTabs, SelectorBar, SectionCard });
