/* global React */
/* E-1 Part 2b §2 (v6) + hotfix9 + Roadmap 7.5 Part A (2026-04-24):
 *   Tweaks 내부 역할 전환 섹션 (4-옵션) + Mock 초기화 버튼.
 *
 * 4-옵션 (Part A 권한 테스트 편의):
 *   - 원장 (배상효 t001, role_id=1)    → branch_admin
 *   - 부원장 (윤민락 t003, role_id=2)  → teacher + override t003
 *   - 선생님 (김채책 t002, role_id=3)  → teacher + override t002 [기본]
 *   - 조교 (김재훈 t007, role_id=4)    → teacher + override t007
 *
 * 선택 시 RoleSim.switchRole(role, teacherIdOverride) 호출 → sessionStorage 저장 + 해당 포털 이동.
 *
 * 격리 원칙 (§11.3 Tweaks = 상태 시뮬레이션):
 *  - 실 UI (사이드바·헤더) 에는 역할 토글 버튼 직접 삽입 금지
 *  - Tweaks 안에만 존재 → Phase 3 이식 시 통째로 제거 가능 */
(function () {
  /* hotfix10 TASK 2: sub 라벨에 호칭 적용 ("배상효 원장 (role_id=1)") */
  const OPTIONS = [
    { key: 'admin',    label: '원장',   sub: '배상효 원장',   role: 'branch_admin', override: null    },
    { key: 'vice',     label: '부원장', sub: '윤민락 부원장', role: 'teacher',      override: 't003'  },
    { key: 'teacher',  label: '선생님', sub: '김채책 선생님', role: 'teacher',      override: 't002'  },
    { key: 'assistant',label: '조교',   sub: '김재훈 조교',   role: 'teacher',      override: 't007'  },
    { key: 'parent',   label: '학부모', sub: '김영숙 (u_p001)',role: 'parent',      override: 'u_p001'},
  ];

  function currentOptionKey() {
    const RS = window.RoleSim;
    if (!RS) return 'admin';
    const role = RS.getRole();
    if (role === 'branch_admin') return 'admin';
    if (role === 'parent') {
      const pid = (typeof RS.getCurrentParentId === 'function') ? RS.getCurrentParentId() : 'u_p001';
      const match = OPTIONS.find(o => o.role === 'parent' && o.override === pid);
      return match ? match.key : 'parent';
    }
    const tid = (typeof RS.getCurrentTeacherId === 'function') ? RS.getCurrentTeacherId() : 't002';
    const match = OPTIONS.find(o => o.role === 'teacher' && o.override === tid);
    return match ? match.key : 'teacher';
  }

  function RoleSwitcher() {
    const curKey = currentOptionKey();

    const onSelect = (opt) => {
      if (opt.key === curKey) return;
      if (!window.RoleSim) return;
      /* Part A 확장: switchRole(role, teacherIdOverride, fromPath) */
      window.RoleSim.switchRole(opt.role, opt.override);
    };

    /* hotfix9 #4: Mock 초기화 — localStorage 의 c200-extra-* 전부 제거 후 새로고침.
     *  Part A: extra-roles / extra-role-permissions 도 포함.
     *  hotfix25.1 H4 (Codex P8 review #1): CORE #4 결제 5키 + sessionStorage
     *   c200.inicis.failMode 도 함께 정리. 결제 잔류 데이터가 invariant 비결정 +
     *   KPI 오류 근본 원인이라 가장 시급한 fix. */
    const onResetMock = () => {
      if (!window.confirm('Mock 데이터를 초기화하시겠습니까?\nlocalStorage 의 등록된 학생·수강반·역할·권한·결제·환불·빌링키 데이터가 전부 삭제됩니다.\n기본 시드 상태로 리셋됩니다.')) return;
      const keysToClear = [
        'c200-extra-students',
        'c200-extra-enrollments',
        'c200-extra-roles',
        'c200-extra-role-permissions',
        'c200-extra-users',
        'c200-extra-user-relations',
        'c200-extra-consent-logs',
        /* CORE #4 결제 영속화 5키 */
        'c200-extra-payments',
        'c200-admin.paymentOverrides',
        'c200-admin.paymentRefunds',
        'c200.inicis.billingKeys',
      ];
      for (const k of keysToClear) {
        localStorage.removeItem(k);
      }
      try { sessionStorage.removeItem('c200.inicis.failMode'); } catch (_) {}
      console.log('[C200] Mock reset: cleared ' + keysToClear.join(', '));
      window.location.reload();
    };

    return (
      <>
        <div className="tweaks-row">
          <label>역할 시뮬레이션</label>
          <div style={{display:'flex', flexDirection:'column', gap:4, marginTop:4}}>
            {OPTIONS.map(opt => (
              <button
                key={opt.key}
                type="button"
                onClick={() => onSelect(opt)}
                style={{
                  display:'flex', alignItems:'center', justifyContent:'flex-start', gap:8,
                  padding:'6px 10px', height:34, borderRadius:6,
                  border: curKey === opt.key ? '1px solid #2BB2A2' : '1px solid var(--border, #E2E8F0)',
                  background: curKey === opt.key ? '#E3F3F3' : '#fff',
                  color: curKey === opt.key ? '#0F4C46' : 'var(--fg-primary, #1F2937)',
                  fontSize:12, fontWeight: curKey === opt.key ? 700 : 500,
                  cursor: curKey === opt.key ? 'default' : 'pointer',
                  textAlign:'left',
                }}
              >
                <span style={{
                  display:'inline-block', width:10, height:10, borderRadius:'50%',
                  border: '2px solid ' + (curKey === opt.key ? '#2BB2A2' : '#CBD5E1'),
                  background: curKey === opt.key ? '#2BB2A2' : 'transparent',
                  flexShrink:0,
                }} />
                <span style={{fontWeight:700}}>{opt.label}</span>
                <span style={{fontSize:11, color:'var(--color-text-muted, #94A3B8)', fontWeight:400}}>
                  · {opt.sub}
                </span>
              </button>
            ))}
          </div>
          <span style={{fontSize:11, color:'var(--color-text-muted)', marginTop:6}}>
            Phase 3 에서는 로그인 기반 자동 분기 — 프로토타입 전용 4-옵션 시뮬레이터
          </span>
        </div>
        <div className="tweaks-row">
          <label>Mock 데이터</label>
          <button
            type="button"
            onClick={onResetMock}
            style={{
              display: 'inline-flex', alignItems: 'center', gap: 6,
              padding: '6px 12px', height: 30, borderRadius: 6,
              border: '1px solid #FCA5A5', background: '#FEF2F2', color: '#991B1B',
              fontSize: 12, fontWeight: 600, cursor: 'pointer', width: 'fit-content',
            }}
          >🗑 Mock 초기화</button>
          <span style={{fontSize:11, color:'var(--color-text-muted)', marginTop:4}}>
            localStorage 의 extras (학생·수강반·역할·권한·결제·환불·빌링키) 전부 삭제 → 기본 시드로 리셋
          </span>
        </div>
      </>
    );
  }
  window.RoleSwitcher = RoleSwitcher;
})();
