// QR code generator — produces a member check-in QR from MEMBER data.
// Uses the `qrcode-generator` UMD lib (window.qrcode) loaded via CDN.
// Payload rotates every 30s so the QR visibly "regenerates" and the
// signature embedded in the URL invalidates after a short window —
// the experience the user describes as "AI-generated from customer data".

const QR_REFRESH_SEC = 30;

// Tiny FNV-1a — cosmetic signature only, not a security primitive.
function _fnv1a(str) {
  let h = 0x811c9dc5;
  for (let i = 0; i < str.length; i++) {
    h ^= str.charCodeAt(i);
    h = (h + ((h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24))) >>> 0;
  }
  return h.toString(36).padStart(7, '0').slice(0, 7);
}

function buildCheckinPayload(member, context, bucketSec) {
  const bucket = Math.floor(Date.now() / 1000 / QR_REFRESH_SEC) * QR_REFRESH_SEC;
  const ts = bucketSec ?? bucket;
  const tierLetter = (member.tier || '').slice(0, 1).toUpperCase();
  const sig = _fnv1a(`${member.id}:${ts}:${context}:${tierLetter}:clover`);
  return `https://app.clover-clinic.com/c/${context}?m=${member.id}&t=${ts}&s=${sig}`;
}

function useDynamicCheckinPayload(member, context = 'checkin') {
  const [bucket, setBucket] = React.useState(
    () => Math.floor(Date.now() / 1000 / QR_REFRESH_SEC) * QR_REFRESH_SEC
  );
  React.useEffect(() => {
    const id = setInterval(() => {
      setBucket(Math.floor(Date.now() / 1000 / QR_REFRESH_SEC) * QR_REFRESH_SEC);
    }, 1000);
    return () => clearInterval(id);
  }, []);
  return React.useMemo(
    () => buildCheckinPayload(member, context, bucket),
    [member.id, context, bucket]
  );
}

function useSecondsToNextRefresh() {
  const [s, setS] = React.useState(() => QR_REFRESH_SEC - (Math.floor(Date.now() / 1000) % QR_REFRESH_SEC));
  React.useEffect(() => {
    const id = setInterval(() => {
      setS(QR_REFRESH_SEC - (Math.floor(Date.now() / 1000) % QR_REFRESH_SEC));
    }, 250);
    return () => clearInterval(id);
  }, []);
  return s;
}

function QRCodeSVG({ value, size = 220, color = '#14140F', bg = '#fff', margin = 2 }) {
  const qr = React.useMemo(() => {
    if (typeof window === 'undefined' || !window.qrcode) return null;
    // typeNumber 0 = auto-pick smallest fitting; level M (~15% error correction).
    for (const type of [0, 6, 8, 12, 16, 20]) {
      try {
        const q = window.qrcode(type, 'M');
        q.addData(value);
        q.make();
        return q;
      } catch (_) { /* try next */ }
    }
    return null;
  }, [value]);

  if (!qr) {
    return (
      <div style={{
        width: size, height: size, background: bg, color: '#7A7A72',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
      }}>QR generating…</div>
    );
  }

  const count = qr.getModuleCount();
  const total = count + margin * 2;
  const cell = size / total;
  const rects = [];
  for (let r = 0; r < count; r++) {
    for (let c = 0; c < count; c++) {
      if (qr.isDark(r, c)) {
        rects.push(
          <rect
            key={r + '-' + c}
            x={(c + margin) * cell}
            y={(r + margin) * cell}
            width={cell + 0.4}
            height={cell + 0.4}
            fill={color}
          />
        );
      }
    }
  }

  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ display: 'block' }}>
      <rect width={size} height={size} fill={bg} />
      <g>{rects}</g>
    </svg>
  );
}

function MemberQRModal({ open, onClose, context = 'checkin' }) {
  const { t, tierName } = useTranslation();
  const payload = useDynamicCheckinPayload(MEMBER, context);
  const secondsLeft = useSecondsToNextRefresh();

  if (!open) return null;

  const C2 = {
    clover: '#1F4435', gold: '#C9A66B', goldDeep: '#A8854A',
    ink: '#14140F', mute: '#7A7A72', line: '#E6E2D7',
    bone: '#F6F3EC', paper: '#FAF8F2', cloverMid: '#2E5A47',
  };

  return (
    <div
      onClick={onClose}
      className="fade-in"
      style={{
        position: 'absolute', inset: 0, zIndex: 100,
        background: 'rgba(18, 42, 32, 0.55)',
        backdropFilter: 'blur(8px)', WebkitBackdropFilter: 'blur(8px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 20,
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        className="slide-up"
        style={{
          width: '100%', maxWidth: 320,
          background: '#fff', borderRadius: 22, padding: '22px 22px 20px',
          boxShadow: '0 30px 80px rgba(0,0,0,0.35)',
          position: 'relative', textAlign: 'center',
        }}
      >
        {/* tier badge */}
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 6,
          padding: '4px 10px', borderRadius: 999,
          background: 'rgba(201,166,107,0.16)', color: C2.goldDeep,
          fontSize: 10.5, letterSpacing: 1.6, textTransform: 'uppercase', fontWeight: 700,
        }}>
          <IconStar size={10} color={C2.goldDeep} />
          {tierName(MEMBER.tier)} {t('common.member')}
        </div>

        <div className="serif" style={{ fontSize: 22, color: C2.clover, marginTop: 10, letterSpacing: -0.2 }}>
          {t('qr.title')}
        </div>
        <div style={{ fontSize: 12, color: C2.mute, marginTop: 4, lineHeight: 1.5 }}>
          {t('qr.subtitle')}
        </div>

        {/* QR */}
        <div style={{
          marginTop: 18, padding: 14,
          background: C2.paper, border: '1px solid ' + C2.line,
          borderRadius: 18,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <QRCodeSVG value={payload} size={220} color={C2.clover} bg="#fff" />
        </div>

        {/* member */}
        <div style={{ marginTop: 14, fontSize: 13, color: C2.ink, fontWeight: 600 }}>
          {MEMBER.name}
        </div>
        <div className="mono" style={{ fontSize: 11, color: C2.mute, marginTop: 2, letterSpacing: 0.5 }}>
          {MEMBER.id}
        </div>

        {/* refresh ring */}
        <div style={{
          marginTop: 14, display: 'flex', alignItems: 'center',
          justifyContent: 'center', gap: 10,
        }}>
          <div style={{ position: 'relative', width: 22, height: 22 }}>
            <svg width={22} height={22} viewBox="0 0 22 22" style={{ transform: 'rotate(-90deg)' }}>
              <circle cx={11} cy={11} r={9} stroke={C2.line} strokeWidth={2} fill="none" />
              <circle
                cx={11} cy={11} r={9}
                stroke={C2.clover} strokeWidth={2} fill="none"
                strokeDasharray={`${(secondsLeft / QR_REFRESH_SEC) * 56.5} 56.5`}
                strokeLinecap="round"
                style={{ transition: 'stroke-dasharray 250ms linear' }}
              />
            </svg>
          </div>
          <div style={{ fontSize: 11.5, color: C2.cloverMid, fontWeight: 600 }}>
            {t('qr.refresh_in', { s: secondsLeft })}
          </div>
        </div>

        <div style={{ marginTop: 10, fontSize: 10.5, color: C2.mute, fontStyle: 'italic', lineHeight: 1.5 }}>
          {t('qr.scan_note')}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  QRCodeSVG, MemberQRModal,
  useDynamicCheckinPayload, useSecondsToNextRefresh,
  buildCheckinPayload, QR_REFRESH_SEC,
});
