/* global React */
/* Phase 6.2 옵션 C-2 (2026-05-07): 자동결제 등록 권유 banner.
 *
 * parent/home + parent/Payments 의 미등록 자녀 대상 — 자동결제 가입 CTA + 가치 제안.
 *
 * props:
 *   - children: parent 자녀 리스트 (mockQueries.getChildrenByParent 또는 supabase 응답).
 *               각 항목: { child: {id, name}, student: {id (legacy), name}, can_view_payments?, valid_until? }
 *   - source: 'mock' | 'supabase'
 *   - payHref: 자동결제 등록 페이지 href (default './Payments.html')
 *
 * 로직:
 *   - source='mock': window.inicisMock localStorage `c200.inicis.billingKeys` 의 studentId
 *     매핑 → 자녀 student.id (legacy 'st128') 와 비교해서 미등록 자녀 산출
 *   - source='supabase': c200BillingKeysQueries.getByStudentIdsFromSupabase
 *     ({activeOnly: true}) → 활성 빌링키 있는 자녀 제외
 *
 * 미등록 자녀 0명 시 banner 미렌더 (null).
 *
 * 컨벤션: string concat. 파일명 _v1_0507.
 */
const { useState: useABS, useEffect: useABE, useMemo: useABM } = React;

function AutoBillingPromoteBanner({ children, source, payHref }) {
  const [billingMap, setBillingMap] = useABS(null); /* null = loading, {} = 검사 완료 */

  useABE(function () {
    let cancelled = false;
    (async function () {
      try {
        if (source === 'supabase') {
          if (!window.c200BillingKeysQueries || !window.c200BillingKeysQueries.getByStudentIdsFromSupabase) {
            if (!cancelled) setBillingMap({});
            return;
          }
          const childIds = (children || [])
            .map(function (c) { return c.child && c.child.id; })
            .filter(Boolean);
          if (childIds.length === 0) { if (!cancelled) setBillingMap({}); return; }
          const rows = await window.c200BillingKeysQueries.getByStudentIdsFromSupabase(childIds, { activeOnly: true });
          const map = {};
          (rows || []).forEach(function (r) { map[r.student_id] = r; });
          if (!cancelled) setBillingMap(map);
        } else {
          /* mock — inicisMock localStorage. studentId 는 'st128' (legacy stripped). */
          let map = {};
          try {
            const raw = JSON.parse(localStorage.getItem('c200.inicis.billingKeys') || '{}');
            Object.keys(raw).forEach(function (bk) {
              const meta = raw[bk] || {};
              if (meta.studentId) map[meta.studentId] = bk;
            });
          } catch (_) {}
          if (!cancelled) setBillingMap(map);
        }
      } catch (e) {
        console.warn('[C200 auto-billing] map build failed', e);
        if (!cancelled) setBillingMap({});
      }
    })();
    return function () { cancelled = true; };
  }, [children, source]);

  /* sync — 다른 탭에서 등록/해지 시 갱신. */
  useABE(function () {
    const onUpd = function () { setBillingMap(null); };
    window.addEventListener('c200:billing-keys-updated', onUpd);
    const onStorage = function (e) {
      if (e && e.key === 'c200.inicis.billingKeys') setBillingMap(null);
    };
    window.addEventListener('storage', onStorage);
    return function () {
      window.removeEventListener('c200:billing-keys-updated', onUpd);
      window.removeEventListener('storage', onStorage);
    };
  }, []);

  /* trigger reload when billingMap was reset to null. */
  useABE(function () {
    if (billingMap === null && children && children.length > 0) {
      /* useABS dispatch 를 다시 발화시키기 위해 setBillingMap({}) 후 첫 effect 가 다시 fetch.
       *  effect 의존성에 billingMap 안 넣어서 무한 루프 X — 그냥 deps re-run trigger 만. */
      const t = setTimeout(function () { setBillingMap(function (cur) { return cur === null ? {} : cur; }); }, 0);
      return function () { clearTimeout(t); };
    }
  }, [billingMap, children]);

  const unregistered = useABM(function () {
    if (!Array.isArray(children) || children.length === 0) return [];
    if (billingMap === null) return [];
    return children.filter(function (c) {
      if (!c.child || !c.child.id) return false;
      /* can_view_payments=FALSE 보호자 관계는 자동결제 권유 대상 X. */
      if (c.can_view_payments === false) return false;
      if (source === 'supabase') {
        return !billingMap[c.child.id];
      }
      /* mock — inicisMock map 의 studentId 는 legacy ('st128'). c.student.id 와 비교. */
      const sid = c.student && c.student.id;
      return sid ? !billingMap[sid] : false;
    });
  }, [children, billingMap, source]);

  useABE(function () { if (window.lucide) window.lucide.createIcons(); });

  if (billingMap === null) return null;
  if (unregistered.length === 0) return null;

  const names = unregistered
    .map(function (c) { return (c.student && c.student.name) || (c.child && c.child.name) || '자녀'; })
    .join(', ');

  return (
    <div className="auto-billing-promote-banner" style={{
      display: 'flex',
      alignItems: 'center',
      gap: 14,
      padding: '14px 18px',
      margin: '0 0 16px',
      background: 'linear-gradient(135deg, #E0F2F1 0%, #B2DFDB 100%)',
      border: '1px solid #0E9594',
      borderRadius: 10,
      color: '#0A7B7A',
    }}>
      <div style={{
        flexShrink: 0,
        width: 40,
        height: 40,
        borderRadius: '50%',
        background: '#0E9594',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        color: '#fff',
      }}>
        <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
          <path d="m17 2 4 4-4 4"/><path d="M3 11v-1a4 4 0 0 1 4-4h14"/>
          <path d="m7 22-4-4 4-4"/><path d="M21 13v1a4 4 0 0 1-4 4H3"/>
        </svg>
      </div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 15, fontWeight: 700, marginBottom: 4 }}>
          매달 25일 자동결제로 결제 누락 위험 0
        </div>
        <div style={{ fontSize: 13, color: '#0F766E' }}>
          {names + ' '}
          {unregistered.length === 1 ? '자녀의 ' : '자녀들의 '}
          자동결제가 아직 등록되지 않았습니다. 한 번 등록하면 매월 25일에 자동 청구되어 미납 차단을 예방합니다.
        </div>
      </div>
      <a
        href={payHref || './Payments.html'}
        className="auto-billing-promote-cta"
        style={{
          flexShrink: 0,
          padding: '10px 18px',
          background: '#0E9594',
          color: '#fff',
          borderRadius: 8,
          fontSize: 14,
          fontWeight: 600,
          textDecoration: 'none',
          whiteSpace: 'nowrap',
        }}
      >
        자동결제 등록하기 →
      </a>
    </div>
  );
}

window.AutoBillingPromoteBanner = AutoBillingPromoteBanner;
