// Shared brand components for the portal pages (login, app, lesson, admin)
// and the public site's nav/footer. Loaded with <script type="text/babel">,
// so top-level declarations are globals for the page script that follows.
const { useState, useEffect, useRef, useCallback, useMemo } = React;

// ---------- Icons ----------
// Lucide swaps <i> for <svg>, which React must not own. The icon lives inside
// a span React never re-renders children for.
function Icon({ name, className = 'w-4 h-4' }) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el || !window.lucide) return;
    el.innerHTML = '';
    const i = document.createElement('i');
    i.setAttribute('data-lucide', name);
    i.setAttribute('class', className);
    el.appendChild(i);
    window.lucide.createIcons({ root: el });
  }, [name, className]);
  return <span ref={ref} aria-hidden="true" className="inline-flex shrink-0 items-center justify-center" />;
}

// ---------- Brand artwork (from gemini-svg.svg, as on index.html) ----------
let lanternSeq = 0;
function HangingLantern({ className = '', style = {} }) {
  const id = useMemo(() => 'lantern' + ++lanternSeq, []);
  return (
    <svg viewBox="0 0 90 200" className={className} style={style} fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
      <defs>
        <linearGradient id={id + 'r'} x1="0%" y1="0%" x2="100%" y2="0%">
          <stop offset="0%" stopColor="#DC2626" />
          <stop offset="50%" stopColor="#EF4444" />
          <stop offset="100%" stopColor="#B91C1C" />
        </linearGradient>
        <filter id={id + 'g'} x="-20%" y="-20%" width="140%" height="140%">
          <feDropShadow dx="0" dy="4" stdDeviation="5" floodColor="#B91C1C" floodOpacity="0.4" />
        </filter>
      </defs>
      <line x1="45" y1="0" x2="45" y2="35" stroke="#FDE68A" strokeWidth="3.2" />
      <path d="M 24 35 Q 45 27 66 35 L 61 45 L 29 45 Z" fill="#D97706" stroke="#F59E0B" strokeWidth="1" />
      <ellipse cx="45" cy="85" rx="32" ry="42" fill={`url(#${id}r)`} filter={`url(#${id}g)`} />
      <ellipse cx="45" cy="85" rx="16" ry="42" fill="none" stroke="#FDE68A" strokeWidth="2.2" opacity="0.75" />
      <line x1="13" y1="85" x2="77" y2="85" stroke="#FDE68A" strokeWidth="2.5" opacity="0.85" />
      <path d="M 29 125 L 61 125 L 56 135 L 34 135 Z" fill="#D97706" stroke="#F59E0B" strokeWidth="1" />
      <circle cx="45" cy="140" r="4.5" fill="#FDE68A" stroke="#D97706" strokeWidth="1" />
      <path d="M 45 145 L 39 184 M 45 145 L 45 190 M 45 145 L 51 184" stroke="#DC2626" strokeWidth="2.5" strokeLinecap="round" />
    </svg>
  );
}

function AuspiciousCloud({ className = '', flip = false, opacity = 0.45 }) {
  return (
    <svg viewBox="0 0 140 45" className={`${className} ${flip ? '-scale-x-100' : ''}`} style={{ opacity }} fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
      <path d="M 20 35 C 8 35 0 26 5 16 C 9 7 22 8 28 13 C 34 2 50 1 58 11 C 66 4 80 7 84 17 C 94 13 105 18 106 28 C 107 35 98 35 90 35 Z" fill="#F59E0B" />
      <path d="M 40 35 C 32 35 28 29 32 23 C 35 17 45 17 48 21 C 52 13 64 13 68 20 C 74 15 84 17 86 24 C 92 22 98 25 98 31 C 98 35 92 35 88 35 Z" fill="#FEF08A" opacity="0.6" />
    </svg>
  );
}

function ChineseCorner({ className = '' }) {
  return (
    <svg viewBox="0 0 70 70" className={className} fill="none" stroke="#D97706" strokeWidth="2.5" opacity="0.65" aria-hidden="true">
      <path d="M 5 65 L 5 5 L 65 5 M 5 22 L 32 22 L 32 48 M 22 5 L 22 36" />
    </svg>
  );
}

// ---------- Auth-aware nav ----------
function useAuthState() {
  const [state, setState] = useState({ loading: true, session: null, admin: false });
  useEffect(() => {
    let alive = true;
    const load = async (session) => {
      const admin = session ? await HP.isAdmin(session) : false;
      if (alive) {
        setState((prev) =>
          prev.loading === false && prev.session === session && prev.admin === admin
            ? prev
            : { loading: false, session, admin }
        );
      }
    };
    HP.getSession().then(load);
    const { data } = HP.sb.auth.onAuthStateChange((_e, session) => { setTimeout(() => load(session), 0); });
    return () => { alive = false; data.subscription.unsubscribe(); };
  }, []);
  return state;
}

function NavLink({ href, icon, children, active }) {
  return (
    <a
      href={href}
      className={`inline-flex items-center gap-1.5 px-2.5 sm:px-3 py-1.5 rounded-full text-xs sm:text-sm font-bold transition-colors ${
        active ? 'bg-amber-400 text-red-950' : 'text-amber-200 hover:text-white hover:bg-white/10'
      }`}
    >
      {icon && <Icon name={icon} className="w-3.5 h-3.5 sm:w-4 sm:h-4" />}
      <span>{children}</span>
    </a>
  );
}

function SiteNav({ current = '' }) {
  const { loading, session, admin } = useAuthState();
  return (
    <nav className="bg-[#18181B] border-b-2 border-amber-500/80 relative z-40">
      <div className="max-w-5xl mx-auto px-4 sm:px-6 h-14 flex items-center justify-between gap-2">
        <a href="index.html" className="flex items-center gap-2 min-w-0">
          <HangingLantern className="w-4 h-9 shrink-0 -mt-1" />
          <span className="min-w-0">
            <span className="block font-display font-black tracking-tight text-white text-sm sm:text-base leading-none truncate">HOKEY POKEY CHINESE</span>
            <span className="hidden sm:block font-hanzi text-[11px] text-amber-300 leading-tight mt-0.5">快乐学汉语</span>
          </span>
        </a>
        <div className="flex items-center gap-0.5 sm:gap-1">
          {loading ? (
            <span className="w-20 h-7 rounded-full bg-white/5" />
          ) : session ? (
            <>
              {admin && <NavLink href="admin.html" icon="shield-check" active={current === 'admin'}>Admin</NavLink>}
              {!admin && (
                <NavLink href="app.html" icon="book-open" active={current === 'app' || current === 'lesson'}>
                  <span className="hidden sm:inline">My </span>Classes
                </NavLink>
              )}
              <button
                onClick={HP.signOut}
                className="inline-flex items-center gap-1.5 px-2.5 sm:px-3 py-1.5 rounded-full text-xs sm:text-sm font-bold text-zinc-400 hover:text-white hover:bg-white/10 transition-colors"
              >
                <Icon name="log-out" className="w-3.5 h-3.5 sm:w-4 sm:h-4" />
                <span className="hidden sm:inline">Log out</span>
              </button>
            </>
          ) : (
            <>
              {current !== 'home' && <NavLink href="index.html#register" icon="edit-3">Register</NavLink>}
              <NavLink href="login.html" icon="log-in" active={current === 'login'}>Log in</NavLink>
            </>
          )}
        </div>
      </div>
    </nav>
  );
}

function SiteFooter() {
  return (
    <footer className="bg-[#18181B] text-white pt-10 pb-8 px-6 mt-16 border-t-4 border-amber-500">
      <div className="max-w-5xl mx-auto">
        <div className="flex flex-col md:flex-row justify-between items-center gap-6 pb-6 border-b border-zinc-800 text-center md:text-left">
          <div>
            <h4 className="text-xl font-black font-display tracking-tight text-white">HOKEY POKEY CHINESE</h4>
            <p className="text-xs text-amber-300 font-hanzi mt-0.5">奥克兰趣味中文 • 让汉语好玩好学</p>
            <p className="text-xs text-zinc-400 mt-1 max-w-sm">In-person Mandarin lessons for Kids and Adults at Highbury House, Birkenhead.</p>
          </div>
          <div className="flex flex-wrap items-center justify-center gap-4 text-xs font-semibold text-zinc-300">
            <a href="index.html" className="hover:text-amber-400 transition-colors">Home</a>
            <span>•</span>
            <a href="index.html#register" className="hover:text-amber-400 transition-colors">Enrol</a>
            <span>•</span>
            <a href="mailto:hokeypokeychinese@gmail.com" className="hover:text-amber-400 transition-colors">Email Zoe</a>
          </div>
        </div>
        <p className="pt-6 text-xs text-zinc-500 text-center md:text-left">© 2026 Hokey Pokey Chinese. All rights reserved.</p>
      </div>
    </footer>
  );
}

// ---------- Page header band (compact version of the index hero) ----------
function PageHero({ eyebrow, title, hanzi, children }) {
  return (
    <header className="bg-gradient-to-br from-[#991B1B] via-[#B91C1C] to-[#C2410C] text-white pt-8 pb-12 px-4 sm:px-6 text-center relative overflow-hidden shadow-xl">
      <div className="absolute inset-0 opacity-10 bg-[radial-gradient(#FDE68A_1px,transparent_1px)] [background-size:20px_20px] pointer-events-none" />
      <div className="absolute top-0 left-2 sm:left-8 w-9 sm:w-14 lantern-sway-left drop-shadow-lg pointer-events-none">
        <HangingLantern className="w-full" />
      </div>
      <div className="absolute top-0 right-2 sm:right-8 w-9 sm:w-14 lantern-sway-right drop-shadow-lg pointer-events-none">
        <HangingLantern className="w-full" />
      </div>
      <div className="relative max-w-2xl mx-auto px-8">
        {eyebrow && (
          <div className="inline-flex items-center gap-1.5 bg-gradient-to-r from-amber-400 to-amber-300 text-red-950 font-black px-3 py-1 rounded-full text-[10px] sm:text-xs uppercase tracking-widest mb-3 shadow-sm border border-amber-200">
            {eyebrow}
          </div>
        )}
        <h1 className="text-2xl sm:text-4xl font-black tracking-tight font-display drop-shadow-sm leading-tight">{title}</h1>
        {hanzi && <div className="text-amber-200 text-sm sm:text-lg font-hanzi font-bold tracking-widest mt-1">{hanzi}</div>}
        {children && <div className="text-amber-100 text-sm sm:text-base mt-2">{children}</div>}
      </div>
    </header>
  );
}

// ---------- Small building blocks ----------
const inputClass =
  'w-full px-4 py-2.5 rounded-xl border border-slate-300 focus:outline-none focus:ring-2 focus:ring-red-600 focus:border-transparent text-sm bg-slate-50/50 disabled:opacity-60';
const labelClass = 'block text-xs font-bold uppercase tracking-wider text-slate-700 mb-1';

function Field({ label, required, hint, children, htmlFor }) {
  return (
    <div>
      <label htmlFor={htmlFor} className={labelClass}>
        {label} {required && <span className="text-red-600">*</span>}
        {hint && <span className="text-slate-400 font-normal normal-case tracking-normal"> {hint}</span>}
      </label>
      {children}
    </div>
  );
}

function Button({ variant = 'primary', loading, icon, children, className = '', ...props }) {
  const styles = {
    primary: 'bg-gradient-to-r from-[#991B1B] via-[#B91C1C] to-[#DC2626] hover:from-red-800 hover:to-red-600 text-white shadow-lg shadow-red-900/20',
    gold: 'border-2 border-amber-400 bg-amber-50 hover:bg-amber-100 text-amber-900',
    ghost: 'border border-slate-300 bg-white hover:bg-slate-50 text-slate-700',
    danger: 'border-2 border-red-200 bg-white hover:bg-red-50 text-red-700',
    success: 'bg-emerald-600 hover:bg-emerald-700 text-white shadow-md shadow-emerald-900/20',
  };
  return (
    <button
      {...props}
      disabled={loading || props.disabled}
      className={`inline-flex items-center justify-center gap-2 rounded-2xl font-extrabold font-display transition-all disabled:opacity-60 disabled:cursor-not-allowed ${styles[variant]} ${className}`}
    >
      {loading ? <Icon name="loader-2" className="w-4 h-4 animate-spin" /> : icon && <Icon name={icon} className="w-4 h-4" />}
      <span>{children}</span>
    </button>
  );
}

function Alert({ kind = 'error', title, children }) {
  const k = {
    error: ['bg-red-50 border-red-200 text-red-900', 'alert-circle', 'text-red-600'],
    success: ['bg-emerald-50 border-emerald-200 text-emerald-900', 'check-circle', 'text-emerald-600'],
    info: ['bg-amber-50 border-amber-200 text-amber-950', 'info', 'text-amber-600'],
  }[kind];
  return (
    <div role={kind === 'error' ? 'alert' : 'status'} className={`p-3.5 rounded-2xl border-2 text-sm flex items-start gap-2.5 ${k[0]}`}>
      <span className={`mt-0.5 ${k[2]}`}><Icon name={k[1]} className="w-5 h-5" /></span>
      <div className="min-w-0">
        {title && <p className="font-bold">{title}</p>}
        <div className={title ? 'text-xs sm:text-sm mt-0.5 opacity-90' : ''}>{children}</div>
      </div>
    </div>
  );
}

function Card({ children, className = '', corner = false, ...rest }) {
  return (
    <div {...rest} className={`bg-white rounded-3xl shadow-md border-2 border-amber-200/70 relative ${className}`}>
      {corner && <ChineseCorner className="w-7 h-7 absolute top-3 right-3 -scale-x-100 pointer-events-none opacity-40" />}
      {children}
    </div>
  );
}

const STATUS_STYLE = {
  pending: { label: 'Awaiting approval', cls: 'bg-amber-100 text-amber-900 border-amber-300', icon: 'hourglass' },
  approved: { label: 'Approved', cls: 'bg-emerald-100 text-emerald-900 border-emerald-300', icon: 'check-circle' },
  rejected: { label: 'Please contact Zoe', cls: 'bg-red-100 text-red-900 border-red-300', icon: 'mail' },
};

function StatusBadge({ status, short }) {
  const s = STATUS_STYLE[status] || STATUS_STYLE.pending;
  return (
    <span className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full border text-[11px] font-bold whitespace-nowrap ${s.cls}`}>
      <Icon name={s.icon} className="w-3 h-3" />
      {short ? status.charAt(0).toUpperCase() + status.slice(1) : s.label}
    </span>
  );
}

function LoadingScreen({ label = 'Loading…' }) {
  return (
    <div className="py-24 flex flex-col items-center gap-3 text-amber-800" role="status">
      <Icon name="loader-2" className="w-8 h-8 animate-spin text-[#B91C1C]" />
      <p className="text-sm font-semibold">{label}</p>
    </div>
  );
}

// ---------- Enrolment mode toggle & Student repeater ----------
function EnrolmentModeToggle({ mode, onChange }) {
  const options = [
    { id: 'adult', label: 'Enrolling Myself (Adult)', icon: 'user' },
    { id: 'family', label: 'Enrolling Children / Family', icon: 'users' },
  ];
  return (
    <div
      role="radiogroup"
      aria-label="Enrolment mode"
      className="grid grid-cols-1 sm:grid-cols-2 gap-1.5 p-1.5 rounded-2xl bg-amber-50/90 border-2 border-amber-200/80 mb-5"
    >
      {options.map((opt) => {
        const active = mode === opt.id;
        return (
          <button
            key={opt.id}
            type="button"
            role="radio"
            aria-checked={active}
            data-enrolment-mode={opt.id}
            onClick={() => onChange(opt.id)}
            className={`flex items-center justify-center gap-2 py-2.5 px-3 rounded-xl text-xs sm:text-sm font-extrabold font-display transition-all ${
              active
                ? 'bg-gradient-to-r from-[#991B1B] via-[#B91C1C] to-[#DC2626] text-white shadow-md shadow-red-900/15'
                : 'text-slate-700 hover:text-[#B91C1C] hover:bg-white/70'
            }`}
          >
            <Icon name={opt.icon} className="w-4 h-4" />
            <span>{opt.label}</span>
          </button>
        );
      })}
    </div>
  );
}

let studentSeq = 0;
const CLASS_OPTION_LABEL = { kids: 'Kids · Thu 3:45pm (8+)', adult: 'Adult · Fri 7pm' };
function formatClassOption(cls) {
  if (!cls) return '';
  if (cls.name && cls.schedule) return `${cls.name} · ${cls.schedule}`;
  return CLASS_OPTION_LABEL[cls.id] || cls.name || cls.id;
}
function newStudent(classId = 'kids', isAccountHolder = false) {
  return { key: 's' + ++studentSeq, name: '', age: '', class_id: classId, is_account_holder: isAccountHolder };
}

// Client-side checks that mirror complete_enrolment. Returns an error or ''.
function validateStudents(students) {
  if (!students.length) return 'Please add at least one student.';
  for (const s of students) {
    if (!s.name.trim()) return 'Please enter a name for every student.';
    if (s.age !== '' && s.age !== null && s.age !== undefined && !/^\d{1,3}$/.test(String(s.age).trim())) {
      return `Age for ${s.name.trim()} must be a whole number.`;
    }
  }
  return '';
}

const toRpcStudents = (students) =>
  students.map((s) => ({
    name: s.name.trim(),
    age: s.age === null || s.age === undefined || String(s.age).trim() === '' ? null : String(s.age).trim(),
    class_id: s.class_id,
    is_account_holder: Boolean(s.is_account_holder),
  }));

function StudentRepeater({ students, onChange, classes, onInteract }) {
  const update = (key, patch) => onChange(students.map((s) => (s.key === key ? { ...s, ...patch } : s)));
  const remove = (key) => onChange(students.filter((s) => s.key !== key));
  const openClasses = (classes || []).filter((c) => c.active);
  return (
    <div className="space-y-3">
      {students.map((s, idx) => {
        const young = s.class_id === 'kids' && s.age !== '' && Number(s.age) < 8;
        return (
          <fieldset key={s.key} className="p-4 rounded-2xl bg-amber-50/50 border border-amber-200/80 relative">
            <legend className="sr-only">Student {idx + 1}</legend>
            <div className="flex items-center justify-between mb-3">
              <span className="text-xs font-black uppercase tracking-wider text-amber-800 flex items-center gap-1.5">
                <span className="w-5 h-5 rounded-md bg-[#B91C1C] text-white text-[11px] font-mono flex items-center justify-center">{idx + 1}</span>
                Student
              </span>
              {students.length > 1 && (
                <button type="button" onClick={() => remove(s.key)} aria-label={`Remove student ${idx + 1}`}
                  className="text-xs font-bold text-slate-500 hover:text-red-700 inline-flex items-center gap-1">
                  <Icon name="x" className="w-3.5 h-3.5" /> Remove
                </button>
              )}
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-12 gap-3">
              <div className="sm:col-span-5">
                <Field label="Name" required htmlFor={`${s.key}-name`}>
                  <input id={`${s.key}-name`} type="text" required value={s.name} onFocus={onInteract}
                    onChange={(e) => update(s.key, { name: e.target.value })} placeholder="e.g. Leo Jenkins" className={inputClass} />
                </Field>
              </div>
              <div className="sm:col-span-2">
                <Field label="Age" htmlFor={`${s.key}-age`}>
                  <input id={`${s.key}-age`} type="text" inputMode="numeric" value={s.age} onFocus={onInteract}
                    onChange={(e) => update(s.key, { age: e.target.value.replace(/[^\d]/g, '').slice(0, 3) })}
                    placeholder={s.class_id === 'adult' ? 'Adult' : '9'} className={inputClass} />
                </Field>
              </div>
              <div className="sm:col-span-5">
                <Field label="Class" required htmlFor={`${s.key}-class`}>
                  <select id={`${s.key}-class`} value={s.class_id} onFocus={onInteract}
                    onChange={(e) => update(s.key, { class_id: e.target.value })}
                    className={inputClass + ' bg-white font-medium'}>
                    {openClasses.map((c) => (
                      <option key={c.id} value={c.id}>{formatClassOption(c)}</option>
                    ))}
                  </select>
                </Field>
              </div>
            </div>
            {young && (
              <p className="mt-2 text-xs text-amber-800 flex items-center gap-1">
                <Icon name="info" className="w-3.5 h-3.5" /> The kids class is designed for ages 8 and up. Zoe will be in touch.
              </p>
            )}
          </fieldset>
        );
      })}
      {students.length < 10 && (
        <button type="button" onClick={() => onChange([...students, newStudent(students[students.length - 1]?.class_id || 'kids')])}
          className="w-full py-2.5 rounded-xl border-2 border-dashed border-amber-300 text-amber-800 hover:bg-amber-50 hover:border-amber-400 text-sm font-bold inline-flex items-center justify-center gap-1.5 transition-colors">
          <Icon name="user-plus" className="w-4 h-4" /> Add another student
        </button>
      )}
    </div>
  );
}

// Tells Zoe about new pending enrolments. Never blocks the family on failure.
async function notifyZoe(kind, startedAt, botcheck = '') {
  try {
    return await HP.callApi('/api/enquire', { kind, botcheck, elapsedMs: Date.now() - startedAt });
  } catch (err) {
    console.warn('Enrolment notification failed:', err.message);
    return null;
  }
}

// ---------- Bank Transfer & Payment Instructions Components ----------
function CopyButton({ value, label = 'Copy' }) {
  const [copied, setCopied] = useState(false);
  const copy = async () => {
    try {
      await navigator.clipboard.writeText(String(value || ''));
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch {
      const ta = document.createElement('textarea');
      ta.value = String(value || '');
      document.body.appendChild(ta);
      ta.select();
      document.execCommand('copy');
      document.body.removeChild(ta);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  };
  return (
    <button
      type="button"
      onClick={copy}
      className={`inline-flex items-center gap-1 px-2.5 py-1 rounded-lg border text-xs font-extrabold transition-all shrink-0 ${
        copied
          ? 'bg-emerald-600 border-emerald-600 text-white'
          : 'bg-white border-amber-300 text-amber-900 hover:bg-amber-100'
      }`}
    >
      <Icon name={copied ? 'check' : 'copy'} className="w-3.5 h-3.5" />
      <span>{copied ? 'Copied!' : label}</span>
    </button>
  );
}

async function fetchPaymentInstructions(enrolmentId, fallback = {}) {
  let resolvedEnrolmentId = enrolmentId || fallback.enrolment_id || null;
  let resolvedRef = fallback.payment_ref || null;

  // If no enrolmentId was passed in, look up the caller's most recent enrolment from the database
  if (!resolvedEnrolmentId) {
    try {
      const { data: latestRows } = await HP.sb
        .from('enrolments')
        .select('id,payment_ref,payment_notified_at,paid,class_id,created_at')
        .order('created_at', { ascending: false })
        .limit(1);
      if (latestRows && latestRows[0]) {
        resolvedEnrolmentId = latestRows[0].id;
        resolvedRef = latestRows[0].payment_ref || ('HP-' + String(latestRows[0].id).slice(0, 6).toUpperCase());
      }
    } catch (_) {}
  }

  if (!resolvedRef && resolvedEnrolmentId) {
    resolvedRef = 'HP-' + String(resolvedEnrolmentId).slice(0, 6).toUpperCase();
  }

  const defaultObj = {
    enrolment_id: resolvedEnrolmentId,
    account_name: 'H C Tsai',
    bank_account_number: '03-1394-0462922-000',
    bank_name: 'Westpac',
    instructions: 'Please include your payment reference in the Reference field so we can match your payment quickly.',
    payment_ref: resolvedRef || '',
    amount: fallback.amount || '$200 NZD per term (8 lessons)',
    particulars: 'Mandarin',
    code: fallback.code || '',
    student_name: fallback.student_name || '',
    class_name: fallback.class_name || '',
    paid: Boolean(fallback.paid),
    payment_notified_at: fallback.payment_notified_at || null,
  };

  if (!resolvedEnrolmentId) return defaultObj;

  try {
    const { data, error } = await HP.sb.rpc('get_payment_instructions', { p_enrolment_id: resolvedEnrolmentId });
    if (!error && data) {
      const liveRef = data.payment_ref || resolvedRef || ('HP-' + String(resolvedEnrolmentId).slice(0, 6).toUpperCase());
      return { ...defaultObj, ...data, enrolment_id: data.enrolment_id || resolvedEnrolmentId, payment_ref: liveRef };
    }
    // Fallback: query the enrolment row directly for its live payment_ref
    const { data: row } = await HP.sb
      .from('enrolments')
      .select('id,payment_ref,payment_notified_at,paid')
      .eq('id', resolvedEnrolmentId)
      .maybeSingle();
    if (row) {
      return {
        ...defaultObj,
        enrolment_id: row.id,
        payment_ref: row.payment_ref || resolvedRef || ('HP-' + String(row.id).slice(0, 6).toUpperCase()),
        paid: Boolean(row.paid),
        payment_notified_at: row.payment_notified_at || defaultObj.payment_notified_at,
      };
    }
    return defaultObj;
  } catch {
    return defaultObj;
  }
}

function PaymentInstructionsCard({
  enrolmentId,
  initialDetails = null,
  info = null,
  fallback = {},
  onTransferred,
  onNotified,
  onClose,
  closeLabel = 'Continue to My Student Portal',
  footerActions = null,
  title = 'Bank Transfer Payment Instructions',
}) {
  const seedDetails = initialDetails || info || null;
  const targetEnrolmentId = enrolmentId || seedDetails?.enrolment_id || fallback?.enrolment_id || null;
  const [details, setDetails] = useState(seedDetails);
  const [loading, setLoading] = useState(!seedDetails || !seedDetails.payment_ref);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState('');

  useEffect(() => {
    let alive = true;
    const seed = initialDetails || info || null;
    if (seed && seed.payment_ref) {
      setDetails(seed);
      setLoading(false);
      return;
    }
    setLoading(true);
    fetchPaymentInstructions(targetEnrolmentId, { ...fallback, ...(seed || {}) }).then((d) => {
      if (alive) {
        setDetails(d);
        setLoading(false);
      }
    });
    return () => { alive = false; };
  }, [targetEnrolmentId, initialDetails, info]);

  const markTransferred = async () => {
    const eid = details?.enrolment_id || targetEnrolmentId;
    if (!eid) return;
    setBusy(true);
    setError('');
    try {
      const { data, error } = await HP.sb.rpc('notify_payment_transferred', {
        p_enrolment_id: eid,
      });
      if (error) throw error;
      const ts = (data && data.payment_notified_at) || new Date().toISOString();
      const updated = {
        ...details,
        payment_notified_at: ts,
      };
      setDetails(updated);
      if (onTransferred) onTransferred(updated);
      if (onNotified) onNotified(ts, updated);
    } catch (err) {
      setError(HP.friendlyError(err));
    } finally {
      setBusy(false);
    }
  };

  if (loading || !details) {
    return (
      <div className="p-6 text-center">
        <LoadingScreen label="Generating payment reference & bank transfer details…" />
      </div>
    );
  }

  const notified = Boolean(details.payment_notified_at);
  const liveRef = details.payment_ref || (details.enrolment_id ? 'HP-' + String(details.enrolment_id).slice(0, 6).toUpperCase() : '');

  return (
    <div className="space-y-4" data-payment-instructions={details.payment_ref}>
      <div className="flex items-start gap-3">
        <div className="p-2.5 rounded-2xl bg-red-100 text-[#B91C1C] shrink-0">
          <Icon name="landmark" className="w-6 h-6" />
        </div>
        <div>
          <h3 className="text-lg sm:text-xl font-black font-display text-slate-900">{title}</h3>
          <p className="text-xs sm:text-sm text-slate-600 mt-0.5">{details.instructions}</p>
        </div>
      </div>

      {/* Total Due Banner */}
      <div className="p-4 rounded-2xl bg-gradient-to-r from-[#991B1B] via-[#B91C1C] to-[#DC2626] text-white flex flex-wrap items-center justify-between gap-2 shadow-md">
        <div>
          <p className="text-[11px] font-black uppercase tracking-widest text-amber-200">Total Course Fee Due</p>
          {details.student_name && (
            <p className="text-xs text-amber-100 font-semibold">
              {details.student_name}{details.class_name ? ` · ${details.class_name}` : ''}
            </p>
          )}
        </div>
        <div className="text-xl sm:text-2xl font-black font-display">{details.amount}</div>
      </div>

      {error && <Alert>{error}</Alert>}

      {/* Bank Transfer Fields */}
      <div className="rounded-2xl border-2 border-amber-300/80 bg-amber-50/50 divide-y divide-amber-200/70 text-sm">
        <div className="p-3 sm:p-3.5 flex items-center justify-between gap-3">
          <div>
            <p className="text-[11px] font-bold uppercase tracking-wider text-amber-900">Account Name</p>
            <p className="font-extrabold text-slate-900 text-base">
              {details.account_name}
              {details.bank_name && <span className="ml-2 text-xs font-semibold text-slate-500">({details.bank_name})</span>}
            </p>
          </div>
        </div>

        <div className="p-3 sm:p-3.5 flex items-center justify-between gap-3">
          <div className="min-w-0">
            <p className="text-[11px] font-bold uppercase tracking-wider text-amber-900">Bank Account Number</p>
            <p className="font-mono font-black text-slate-900 text-base sm:text-lg tracking-tight select-all">
              {details.bank_account_number}
            </p>
          </div>
          <CopyButton value={details.bank_account_number} label="Copy Account" />
        </div>

        <div className="grid grid-cols-1 sm:grid-cols-2 divide-y sm:divide-y-0 sm:divide-x divide-amber-200/70">
          <div className="p-3 sm:p-3.5">
            <p className="text-[11px] font-bold uppercase tracking-wider text-amber-900">Particulars</p>
            <p className="font-extrabold text-slate-900">{details.particulars || 'Mandarin'}</p>
          </div>
          <div className="p-3 sm:p-3.5">
            <p className="text-[11px] font-bold uppercase tracking-wider text-amber-900">Code (Account Holder)</p>
            <p className="font-extrabold text-slate-900 truncate">{details.code || 'Your Name'}</p>
          </div>
        </div>

        <div className="p-3 sm:p-3.5 flex items-center justify-between gap-3 bg-amber-100/50">
          <div className="min-w-0">
            <p className="text-[11px] font-bold uppercase tracking-wider text-amber-900">Payment Reference</p>
            {liveRef ? (
              <p className="font-mono font-black text-[#B91C1C] text-base sm:text-lg tracking-wider select-all" data-payment-ref-value={liveRef}>
                {liveRef}
              </p>
            ) : (
              <p className="text-xs font-semibold text-amber-800 italic">Generating reference…</p>
            )}
          </div>
          {liveRef && <CopyButton value={liveRef} label="Copy Ref" />}
        </div>
      </div>

      {/* Transfer Notification State / Button */}
      <div className="pt-1 space-y-2.5">
        {details.paid ? (
          <Alert kind="success" title="Payment confirmed">
            Zoe has confirmed receipt of your course fee payment ({liveRef}).
          </Alert>
        ) : notified ? (
          <div className="p-3.5 rounded-2xl border-2 border-emerald-300 bg-emerald-50 text-emerald-950 flex items-center gap-2.5 text-xs sm:text-sm font-bold">
            <Icon name="check-circle" className="w-5 h-5 text-emerald-600 shrink-0" />
            <span>Payment Pending Verification (Ref: {liveRef}) — Zoe has been notified of your bank transfer.</span>
          </div>
        ) : (
          <Button
            type="button"
            variant="success"
            loading={busy}
            icon="check-circle"
            onClick={markTransferred}
            className="w-full py-3.5 px-5 text-sm sm:text-base"
          >
            I've completed the bank transfer
          </Button>
        )}

        {onClose && !footerActions && (
          <Button
            type="button"
            variant="primary"
            icon="arrow-right"
            onClick={onClose}
            className="w-full py-3 px-5 text-sm"
          >
            {closeLabel}
          </Button>
        )}

        {footerActions}
      </div>
    </div>
  );
}

function PaymentInstructionsModal({ open, onClose, enrolmentId, fallback = {}, onTransferred, onNotified }) {
  if (!open) return null;
  return (
    <div
      className="fixed inset-0 z-50 bg-black/60 backdrop-blur-xs flex items-center justify-center p-4 overflow-y-auto"
      role="dialog"
      aria-modal="true"
      onClick={(e) => e.target === e.currentTarget && onClose()}
    >
      <Card corner className="max-w-lg w-full p-6 sm:p-7 shadow-2xl border-amber-300 my-8">
        <PaymentInstructionsCard
          enrolmentId={enrolmentId}
          fallback={fallback}
          onTransferred={onTransferred}
          onNotified={onNotified}
          footerActions={
            <div className="flex justify-end pt-1">
              <Button type="button" variant="ghost" onClick={onClose} className="w-full sm:w-auto py-2.5 px-5 text-sm">
                Close
              </Button>
            </div>
          }
        />
      </Card>
    </div>
  );
}

// ---------- Mandarin Web Speech API & Lesson Block Helpers ----------
const TONE_META = {
  1: { label: '1st Tone · High Flat', badge: 'bg-red-100 text-red-900 border-red-200' },
  2: { label: '2nd Tone · Rising', badge: 'bg-amber-100 text-amber-900 border-amber-200' },
  3: { label: '3rd Tone · Dipping', badge: 'bg-emerald-100 text-emerald-900 border-emerald-200' },
  4: { label: '4th Tone · Falling', badge: 'bg-sky-100 text-sky-900 border-sky-200' },
  5: { label: '5th Tone · Neutral', badge: 'bg-slate-100 text-slate-700 border-slate-300' },
};

let cachedVoices = [];

// Preload voices and handle asynchronous population in Chrome/Edge/Safari
if (typeof window !== 'undefined' && 'speechSynthesis' in window) {
  cachedVoices = window.speechSynthesis.getVoices();
  window.speechSynthesis.onvoiceschanged = () => {
    cachedVoices = window.speechSynthesis.getVoices();
  };
}

const getBestChineseVoice = () => {
  const voices = (cachedVoices && cachedVoices.length) ? cachedVoices : (typeof window !== 'undefined' && window.speechSynthesis ? window.speechSynthesis.getVoices() : []);
  if (!voices || voices.length === 0) return null;

  const chineseVoices = voices.filter(v => 
    v.lang && (v.lang.startsWith('zh') || v.lang.includes('cmn'))
  );

  if (chineseVoices.length === 0) return null;

  // Normalize voice names before matching: replace non-breaking spaces and multi-spaces with standard spaces
  const normalize = (v) => (v && v.name ? v.name.replace(/\s+/g, ' ').toLowerCase() : '');

  // 1. Tier 1: Target Chrome's Google voices without relying on exact spacing
  const googleVoice = chineseVoices.find(v => {
    const normalizedName = normalize(v);
    return normalizedName.includes('google') && (
      normalizedName.includes('普通话') ||
      normalizedName.includes('国语') ||
      normalizedName.includes('國語') ||
      normalizedName.includes('mandarin')
    );
  });
  if (googleVoice) return googleVoice;

  // 2. Tier 2: Match Edge / System Neural / Natural voices
  const neuralVoice = chineseVoices.find(v => {
    const normalizedName = normalize(v);
    return (
      normalizedName.includes('natural') ||
      normalizedName.includes('xiaoxiao') ||
      normalizedName.includes('yunxi') ||
      normalizedName.includes('ting-ting') ||
      normalizedName.includes('tingting') ||
      normalizedName.includes('online') ||
      normalizedName.includes('premium')
    );
  });
  if (neuralVoice) return neuralVoice;

  // 3. Tier 3: Non-desktop Mainland Mandarin voices (prioritize ahead of legacy Microsoft Desktop voices like huihui, kangkang)
  const isLegacyDesktop = (v) => {
    const normalizedName = normalize(v);
    return (
      normalizedName.includes('desktop') ||
      normalizedName.includes('huihui') ||
      normalizedName.includes('kangkang') ||
      normalizedName.includes('yaoyao') ||
      normalizedName.includes('hanhan')
    );
  };

  const modernMainlandVoice = chineseVoices.find(v => {
    const lang = (v.lang || '').toLowerCase().replace('_', '-');
    return lang === 'zh-cn' && !isLegacyDesktop(v);
  });
  if (modernMainlandVoice) return modernMainlandVoice;

  // 4. Tier 4: Any Mainland Mandarin voice (even if desktop)
  const mainlandVoice = chineseVoices.find(v => (v.lang || '').toLowerCase().replace('_', '-') === 'zh-cn');
  if (mainlandVoice) return mainlandVoice;

  // 5. Fallback: Any available Chinese voice
  return chineseVoices[0];
};

let currentSpeechToken = 0;

function stopMandarinSpeech() {
  currentSpeechToken++;
  if (typeof window !== 'undefined' && 'speechSynthesis' in window) {
    try {
      window.speechSynthesis.cancel();
    } catch (_) {}
  }
}

function playChineseVoice(text, onStateChange) {
  if (!text || !String(text).trim() || typeof window === 'undefined' || !('speechSynthesis' in window)) {
    if (onStateChange) onStateChange(false);
    return;
  }

  const phrase = String(text).replace(/…|\.\.\./g, '').trim();
  if (!phrase) {
    if (onStateChange) onStateChange(false);
    return;
  }

  // Cancel any speech in progress to prevent stutter/queuing on fast taps
  stopMandarinSpeech();
  const sessionToken = currentSpeechToken;

  if (onStateChange) onStateChange(true);

  try {
    const utterance = new SpeechSynthesisUtterance(phrase);
    utterance.lang = 'zh-CN';

    const selectedVoice = getBestChineseVoice();
    if (selectedVoice) {
      utterance.voice = selectedVoice;
    }

    // Force logging to verify voice selection in browser DevTools
    console.log('Selected voice:', utterance.voice?.name);

    // Pacing for language learners: 0.85 rate gives clear tone separation
    utterance.rate = 0.85;
    utterance.pitch = 1.0;

    utterance.onend = () => {
      if (sessionToken === currentSpeechToken && onStateChange) onStateChange(false);
    };
    utterance.onerror = () => {
      if (sessionToken === currentSpeechToken && onStateChange) onStateChange(false);
    };

    window.speechSynthesis.speak(utterance);
  } catch (err) {
    console.error('SpeechSynthesis error:', err);
    if (sessionToken === currentSpeechToken && onStateChange) onStateChange(false);
  }
}

const speakMandarin = playChineseVoice;

if (typeof window !== 'undefined') {
  window.cachedVoices = cachedVoices;
  window.getBestChineseVoice = getBestChineseVoice;
  window.playChineseVoice = playChineseVoice;
  window.speakMandarin = speakMandarin;
  window.stopMandarinSpeech = stopMandarinSpeech;
}

function extractYouTubeId(url) {
  if (!url) return null;
  const m = String(url).match(/(?:youtube\.com\/(?:watch\?v=|embed\/|shorts\/)|youtu\.be\/)([A-Za-z0-9_-]{11})/);
  return m ? m[1] : null;
}


function extractChineseSpeech(text) {
  if (!text) return '';
  const raw = String(text).trim();
  const beforeParen = raw.split(/[（()）]/)[0].trim();
  const candidate = /[\u3400-\u9FFF]/.test(beforeParen) ? beforeParen : raw;
  const match = candidate.match(/[\u3400-\u9FFF\uF900-\uFAFF][\s\S]*[\u3400-\u9FFF\uF900-\uFAFF。！？，、；：”’》）】]/);
  if (match) return match[0].trim();
  const singleMatch = candidate.match(/[\u3400-\u9FFF\uF900-\uFAFF]+/);
  return singleMatch ? singleMatch[0].trim() : candidate;
}

function VocabCardBlock({ block, playingKey, onSpeak, singleColumn = false }) {
  const c = block.content || {};
  const hanzi = c.hanzi || block.title || '';
  const pinyin = c.pinyin || '';
  const english = c.english || c.meaning || '';
  const example = c.example || '';
  const wordKey = `vocab-${block.id}`;
  const exKey = `vocab-ex-${block.id}`;
  const isPlayingWord = playingKey === wordKey;
  const isPlayingEx = playingKey === exKey;

  const hasChineseInExample = /[\u3400-\u9FFF]/.test(example);
  const exampleSpeech = hasChineseInExample ? extractChineseSpeech(example) : example;
  const showExampleAudio = Boolean(example) && hasChineseInExample;

  return (
    <div
      onClick={() => onSpeak(hanzi, wordKey)}
      role="button"
      tabIndex={0}
      style={{ touchAction: 'manipulation' }}
      onKeyDown={(e) => (e.key === 'Enter' || e.key === ' ') && (e.preventDefault(), onSpeak(hanzi, wordKey))}
      className={`cursor-pointer ${singleColumn ? 'p-6 sm:p-7' : 'p-5'} rounded-3xl border-2 transition-all duration-200 bg-white group hover:shadow-lg flex flex-col justify-between ${
        isPlayingWord ? 'border-[#B91C1C] ring-4 ring-red-100 bg-red-50/20 scale-[1.01]' : 'border-amber-200/80 hover:border-amber-400'
      }`}
    >
      <div>
        <div className="flex items-center justify-between gap-2 mb-3">
          <span className="text-[11px] font-bold uppercase tracking-wider text-amber-800 bg-amber-50 px-2.5 py-0.5 rounded-full border border-amber-200">
            {singleColumn ? 'Chengyu · Idiom' : 'Vocabulary'}
          </span>
          <button
            type="button"
            style={{ touchAction: 'manipulation' }}
            onClick={(e) => {
              e.stopPropagation();
              onSpeak(hanzi, wordKey);
            }}
            aria-label={`Listen to ${hanzi}`}
            className={`inline-flex items-center gap-1.5 px-3 py-1.5 min-h-[36px] rounded-full text-xs font-extrabold transition-all ${
              isPlayingWord
                ? 'bg-[#B91C1C] text-white shadow-md animate-pulse'
                : 'bg-red-50 text-[#B91C1C] group-hover:bg-[#B91C1C] group-hover:text-white'
            }`}
          >
            <Icon name="volume-2" className="w-3.5 h-3.5" />
            <span>{isPlayingWord ? 'Playing…' : 'Listen'}</span>
          </button>
        </div>

        <div className={`flex items-baseline gap-3 flex-wrap ${singleColumn ? 'mb-2.5' : 'mb-1.5'}`}>
          <span className={`${singleColumn ? 'text-4xl sm:text-5xl' : 'text-3xl sm:text-4xl'} font-black font-hanzi text-[#991B1B] tracking-wide leading-tight`}>
            {hanzi}
          </span>
          <span className={`${singleColumn ? 'text-xl sm:text-2xl' : 'text-lg sm:text-xl'} font-extrabold font-display text-slate-900`}>
            {pinyin}
          </span>
        </div>

        <p className={`${singleColumn ? 'text-base sm:text-lg' : 'text-sm sm:text-base'} font-bold text-slate-800 leading-relaxed`}>
          {english}
        </p>
      </div>

      {example && (
        <div className="mt-4 pt-3 border-t border-amber-100 flex items-start justify-between gap-2">
          <div className={`${singleColumn ? 'text-sm' : 'text-xs'} text-slate-700 leading-relaxed`}>
            <span className="font-extrabold uppercase tracking-wider text-amber-800 text-[10px] block mb-0.5">
              {singleColumn ? (hasChineseInExample ? 'Example · 例句' : 'Notes') : 'Example'}
            </span>
            {example}
          </div>
          {showExampleAudio && (
            <button
              type="button"
              style={{ touchAction: 'manipulation' }}
              onClick={(e) => {
                e.stopPropagation();
                onSpeak(exampleSpeech, exKey);
              }}
              title="Play example sentence"
              aria-label="Play example sentence"
              className={`shrink-0 inline-flex items-center gap-1 px-2.5 py-1.5 min-h-[36px] min-w-[36px] justify-center rounded-full border text-xs font-extrabold transition-colors ${
                isPlayingEx
                  ? 'bg-amber-500 text-red-950 border-amber-500 animate-pulse'
                  : 'bg-amber-50 text-amber-900 border-amber-200 hover:bg-amber-100'
              }`}
            >
              <Icon name="volume-2" className="w-3.5 h-3.5" />
              {singleColumn && <span>{isPlayingEx ? 'Playing…' : 'Example'}</span>}
            </button>
          )}
        </div>
      )}
    </div>
  );
}

function ResourceLinkBlock({ block }) {
  const c = block.content || {};
  const resourceType = (c.resource_type || 'link').toLowerCase();
  const title = block.title || c.title || 'Lesson Resource';
  const url = c.url || '';
  const description = c.description || '';
  const ytId = resourceType === 'youtube' || extractYouTubeId(url) ? extractYouTubeId(url) : null;

  const meta = {
    youtube: { icon: 'video', badge: 'Video Lesson', btn: 'Watch on YouTube' },
    pdf: { icon: 'file-text', badge: 'PDF Worksheet', btn: 'Download / Open PDF' },
    audio: { icon: 'headphones', badge: 'Audio Practice', btn: 'Open Audio File' },
    link: { icon: 'external-link', badge: 'Resource Link', btn: 'Open Resource' },
  }[resourceType] || { icon: 'external-link', badge: 'Resource', btn: 'Open Link' };

  return (
    <Card className="p-5 sm:p-6 overflow-hidden">
      <div className="flex flex-wrap items-start justify-between gap-3">
        <div className="flex items-start gap-3 min-w-0 flex-1">
          <div className="p-2.5 rounded-2xl bg-red-100 text-[#B91C1C] shrink-0">
            <Icon name={meta.icon} className="w-5 h-5" />
          </div>
          <div className="min-w-0 flex-1">
            <span className="inline-block text-[10px] font-black uppercase tracking-widest text-amber-800 bg-amber-100 border border-amber-200 px-2.5 py-0.5 rounded-full mb-1">
              {meta.badge}
            </span>
            <h3 className="text-lg font-black font-display text-slate-900 leading-snug">{title}</h3>
            {description && <p className="text-sm text-slate-600 mt-1 leading-relaxed whitespace-pre-line">{description}</p>}
          </div>
        </div>
        {url && (
          <a
            href={url}
            target="_blank"
            rel="noopener noreferrer"
            className="inline-flex items-center gap-1.5 px-4 py-2 min-h-[44px] rounded-xl bg-[#B91C1C] hover:bg-red-700 text-white text-xs font-extrabold font-display shadow-sm shrink-0 transition-colors"
          >
            <span>{meta.btn}</span>
            <Icon name="external-link" className="w-3.5 h-3.5" />
          </a>
        )}
      </div>

      {ytId && (
        <div className="mt-4 rounded-2xl overflow-hidden border-2 border-amber-200 shadow-inner aspect-video bg-slate-950">
          <iframe
            src={`https://www.youtube.com/embed/${ytId}`}
            title={title}
            className="w-full h-full border-0"
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
            allowFullScreen
          />
        </div>
      )}

      {resourceType === 'audio' && url && !ytId && (
        <div className="mt-4 pt-3 border-t border-amber-100">
          <audio controls src={url} className="w-full" preload="metadata">
            Your browser does not support the audio element.
          </audio>
        </div>
      )}
    </Card>
  );
}

function TextNoteBlock({ block }) {
  const c = block.content || {};
  const title = block.title || c.title || 'Study Notes';
  const body = c.body || c.text || '';
  return (
    <Card corner className="p-5 sm:p-7">
      <div className="flex items-center gap-2.5 mb-3 pr-8">
        <div className="p-2 rounded-xl bg-amber-100 text-amber-900">
          <Icon name="notebook-pen" className="w-5 h-5" />
        </div>
        <h3 className="text-lg sm:text-xl font-black font-display text-slate-900">{title}</h3>
      </div>
      <div className="text-sm sm:text-base text-slate-700 leading-relaxed whitespace-pre-line bg-amber-50/40 border border-amber-100 rounded-2xl p-4 sm:p-5">
        {body}
      </div>
    </Card>
  );
}

if (typeof window !== 'undefined') {
  window.VocabCardBlock = VocabCardBlock;
  window.ResourceLinkBlock = ResourceLinkBlock;
  window.TextNoteBlock = TextNoteBlock;
  window.HP_UI = {
    VocabCardBlock,
    ResourceLinkBlock,
    TextNoteBlock,
  };
}
