/* global React */
/* CORE #4 P5: 미납 학생 차단 안내 배너.
 *  spec §3.4.2 — parent/student 페이지 진입 시 isBlockedForToday(studentId) 가
 *    true 면 빨간 배너 노출 + 결제하기 링크. 다중 자녀(parent home)는 N명 표기.
 *  Phase 3: parent/Payments.html 신설 후 redirect 하드 차단으로 강화. 현재는 inline 배너만.
 *
 *  사용 예:
 *    <PaymentBlockBanner studentIds={[childId]} payHref="./mypage-payments.html" />
 *    <PaymentBlockBanner studentIds={children.map(c => c.student.id)} payHref="./Payments.html" />
 */
(function () {
  const { useEffect, useMemo, useState } = React;

  function _monthLabel(cycleYyyymm) {
    if (!cycleYyyymm) return '';
    const m = String(cycleYyyymm).split('-')[1];
    return m ? Number(m) + '월' : '';
  }

  function _resolveBlocked(ids) {
    if (!ids || !ids.length) return [];
    if (typeof window.isBlockedForToday !== 'function') return [];
    const out = [];
    ids.forEach(function (sid) {
      if (!sid) return;
      if (!window.isBlockedForToday(sid)) return;
      const stu = (window.studentsMock || []).find(function (s) { return s.id === sid; });
      const lastBill = window.lastBillingDate && window.lastBillingDate();
      const cycle = lastBill && window.getCycleForBilling
        ? window.getCycleForBilling(lastBill)
        : '';
      out.push({
        id: sid,
        name: stu ? stu.name : sid,
        cycle: cycle,
        monthLabel: _monthLabel(cycle),
      });
    });
    return out;
  }

  function PaymentBlockBanner(props) {
    const ids = props.studentIds || [];
    const payHref = props.payHref || null;
    /* Phase 5 (2026-05-06): props.blocked 가 사전 계산된 배열이면
     *   _resolveBlocked (paymentsMock + isBlockedForToday) 를 우회하고 그대로 사용.
     *   supabase 모드에서 caller 가 RLS 통한 결제 row 로 차단 산출 후 주입.
     *   undefined / null 이면 기존 mock 흐름. */
    const precomputedBlocked = Array.isArray(props.blocked) ? props.blocked : null;

    /* hotfix24.3 (Codex review #4): admin/teacher role 차단 제외 정책 enforce.
       spec §3.4.2 — admin/teacher 는 결제 등록/환불/면제 처리해야 하므로
       parent/* URL 직접 진입 시에도 배너 안 보이게 component 자체에서 guard. */
    const role = (window.RoleSim && typeof window.RoleSim.getRole === 'function')
      ? window.RoleSim.getRole()
      : null;
    const isAdminOrTeacher = role === 'branch_admin' || role === 'teacher';

    /* hotfix25.4 M8: paymentsMock 변경 시 banner 재계산 — c200:payments-updated /
     *   storage / pageshow 이벤트 catch 후 tick 증가. back-navigation cache 에서
     *   banner 잔존하던 문제 해결. */
    const [tick, setTick] = useState(0);
    useEffect(function () {
      const onUpdate = function () { setTick(function (t) { return t + 1; }); };
      const onStorage = function (e) {
        if (!e || !e.key) return;
        if (e.key === 'c200-extra-payments'
          || e.key === 'c200-admin.paymentOverrides'
          || e.key === 'c200-admin.paymentRefunds') {
          setTick(function (t) { return t + 1; });
        }
      };
      const onPageShow = function (e) { if (e.persisted) setTick(function (t) { return t + 1; }); };
      window.addEventListener('c200:payments-updated', onUpdate);
      window.addEventListener('storage', onStorage);
      window.addEventListener('pageshow', onPageShow);
      return function () {
        window.removeEventListener('c200:payments-updated', onUpdate);
        window.removeEventListener('storage', onStorage);
        window.removeEventListener('pageshow', onPageShow);
      };
    }, []);

    const blocked = useMemo(function () {
      if (isAdminOrTeacher) return [];
      if (precomputedBlocked) return precomputedBlocked;
      return _resolveBlocked(ids);
    }, [ids.join(','), isAdminOrTeacher, tick, precomputedBlocked]);

    useEffect(function () { if (window.lucide) window.lucide.createIcons(); }, [blocked.length]);

    if (!blocked.length) return null;

    /* hotfix24.3 (Codex review #6): multi-child 포맷 — "자녀 N명 (이름1, 이름2)"
       단일 자녀는 기존 그대로 "[학생명] 학생의 …". */
    const isMulti = blocked.length > 1;
    const headMonth = blocked[0].monthLabel || '';
    const namesJoin = blocked.map(function (b) { return b.name; }).join(', ');

    const message = isMulti
      ? '자녀 ' + blocked.length + '명 (' + namesJoin + ')의 ' + headMonth + ' 수강료가 미납되어 일부 서비스 이용이 제한됩니다.'
      : blocked[0].name + ' 학생의 ' + headMonth + ' 수강료가 미납되어 일부 서비스 이용이 제한됩니다.';

    return (
      <div
        className="payment-block-banner"
        role="alert"
        aria-live="polite"
        style={{
          display: 'flex',
          alignItems: 'center',
          gap: 12,
          padding: '14px 18px',
          margin: '0 0 16px',
          background: '#FEE2E2',
          border: '1px solid #DC2626',
          borderRadius: 8,
          color: '#991B1B',
          fontSize: 13,
          fontWeight: 500,
        }}
      >
        <i data-lucide="alert-triangle" style={{ width: 18, height: 18, flexShrink: 0 }}></i>
        <div style={{ flex: 1, lineHeight: 1.5 }}>
          <b style={{ display: 'block', fontWeight: 700, marginBottom: 2 }}>
            {message}
          </b>
          <span style={{ color: '#7F1D1D', fontWeight: 400 }}>
            결제 후 이용 가능합니다.
          </span>
        </div>
        {payHref && (
          <a
            href={payHref}
            style={{
              padding: '8px 14px',
              background: '#DC2626',
              color: '#fff',
              borderRadius: 6,
              fontSize: 12,
              fontWeight: 600,
              textDecoration: 'none',
              flexShrink: 0,
              display: 'inline-flex',
              alignItems: 'center',
              gap: 6,
            }}
          >
            <i data-lucide="credit-card" style={{ width: 14, height: 14 }}></i>
            결제하기
          </a>
        )}
      </div>
    );
  }

  window.PaymentBlockBanner = PaymentBlockBanner;
})();
