// AKC Registration Tracker — live status tracking page
// Served at /booking/track/{registration_id}

const { useState: useStateK, useEffect: useEffectK } = React;

// ── Status stages ─────────────────────────────────────────────────────────────

const STAGES = [
  {
    key: 'submitted',
    label: 'Registration Received',
    desc: 'Your registration has been received and is being processed. Our customer service team will be in touch with you shortly.',
  },
  {
    key: 'pending_eligibility',
    label: 'Pending Eligibility Check',
    desc: 'We are verifying your eligibility for course subsidies and grants. This typically takes 1 to 2 business days.',
  },
  {
    key: 'pending_payment',
    label: 'Pending Payment',
    desc: 'Your eligibility has been confirmed. An invoice has been sent to your registered email. Please proceed with payment to secure your spot.',
  },
  {
    key: 'enrolled',
    label: 'Enrolled',
    desc: 'Congratulations! Your enrollment is confirmed. We look forward to seeing you at the course.',
  },
];

const STATUS_ORDER = STAGES.map(s => s.key);

function stageIdx(status) {
  const i = STATUS_ORDER.indexOf(status);
  return i === -1 ? 0 : i;
}

// ── Helpers ───────────────────────────────────────────────────────────────────

function fmtDate(iso) {
  if (!iso) return '';
  const d = new Date(iso.includes('T') ? iso : iso + 'T00:00:00');
  if (isNaN(d)) return iso;
  return d.toLocaleDateString('en-SG', { day: 'numeric', month: 'short', year: 'numeric' });
}

function fmtDateTime(iso) {
  if (!iso) return '';
  const d = new Date(iso);
  if (isNaN(d)) return '';
  return d.toLocaleString('en-SG', { day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' });
}

function lessonCountdownLabel(iso) {
  if (!iso) return '';
  const lesson = new Date(iso.includes('T') ? iso : iso + 'T00:00:00');
  if (isNaN(lesson)) return '';

  const today = new Date();
  today.setHours(0, 0, 0, 0);
  lesson.setHours(0, 0, 0, 0);

  const days = Math.ceil((lesson - today) / 86400000);
  if (days > 1) return `${days} days to lesson`;
  if (days === 1) return '1 day to lesson';
  if (days === 0) return 'Lesson starts today';
  return 'Lesson date has passed';
}

function apiBase() {
  return (
    (window.AKCBookingConfig && window.AKCBookingConfig.restBase) ||
    window.AKC_API_BASE ||
    'http://127.0.0.1:4176/wp-json/akc/v1'
  ).replace(/\/$/, '');
}

// ── Icons ─────────────────────────────────────────────────────────────────────

function CheckIcon() {
  return (
    <svg width="13" height="13" viewBox="0 0 13 13" fill="none">
      <path d="M2 6.5L5 9.5L11 3.5" stroke="white" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

// ── TrackingScreen ────────────────────────────────────────────────────────────

function TrackingScreen({ registrationId }) {
  const [reg, setReg]         = useStateK(null);
  const [loading, setLoading] = useStateK(true);
  const [error, setError]     = useStateK('');

  function load() {
    fetch(`${apiBase()}/registrations/${encodeURIComponent(registrationId)}`)
      .then(r => (r.ok ? r.json() : Promise.reject(r.status)))
      .then(data => {
        if (data && data.registration_id) { setReg(data); setLoading(false); }
        else { setError('Registration not found.'); setLoading(false); }
      })
      .catch(() => {
        setError('Unable to load registration details. Please check your link and try again.');
        setLoading(false);
      });
  }

  useEffectK(() => {
    load();
    const t = setInterval(load, 30000);
    return () => clearInterval(t);
  }, [registrationId]);

  // ── Loading ──────────────────────────────────────────────────────────────

  if (loading) return (
    <div style={{
      minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center',
      background: 'var(--bg)', fontFamily: "'Inter', sans-serif",
    }}>
      <div style={{ textAlign: 'center' }}>
        <div style={{
          width: 40, height: 40, borderRadius: '50%',
          border: '3px solid var(--primary-100, #dce8fd)',
          borderTopColor: 'var(--primary)',
          animation: 'akc-spin 0.8s linear infinite',
          margin: '0 auto',
        }} />
        <p style={{ marginTop: 16, color: 'var(--muted)', fontSize: 14 }}>
          Loading your registration...
        </p>
      </div>
    </div>
  );

  // ── Error / Not found ────────────────────────────────────────────────────

  if (error || !reg) return (
    <div style={{
      minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center',
      background: 'var(--bg)', padding: 24, fontFamily: "'Inter', sans-serif",
    }}>
      <div style={{
        maxWidth: 440, width: '100%', background: 'var(--surface)',
        border: '1px solid var(--line)', borderRadius: 16,
        padding: '36px 28px', textAlign: 'center',
      }}>
        <div style={{ fontSize: 42, marginBottom: 16 }}>🔍</div>
        <h2 style={{
          fontFamily: "'General Sans','Inter',sans-serif",
          fontSize: 20, fontWeight: 700, margin: '0 0 8px', color: 'var(--ink)',
        }}>
          Registration not found
        </h2>
        <p style={{ color: 'var(--muted)', fontSize: 14, margin: '0 0 24px', lineHeight: 1.6 }}>
          {error || 'This tracking link may be invalid or expired.'}
        </p>
        <a href="/booking/" style={{
          display: 'inline-block', padding: '10px 22px',
          background: 'var(--primary)', color: 'white',
          borderRadius: 8, textDecoration: 'none',
          fontWeight: 600, fontSize: 14,
        }}>
          Back to course booking
        </a>
      </div>
    </div>
  );

  // ── Cancelled state ──────────────────────────────────────────────────────

  if (reg.status === 'cancelled') return (
    <PageShell registrationId={registrationId}>
      <div style={{
        background: '#fff5f5', border: '1px solid #fecaca',
        borderRadius: 14, padding: '28px 24px', textAlign: 'center',
        marginBottom: 24,
      }}>
        <div style={{ fontSize: 40, marginBottom: 12 }}>❌</div>
        <h2 style={{
          fontFamily: "'General Sans','Inter',sans-serif",
          fontSize: 20, fontWeight: 700, color: '#b91c1c', margin: '0 0 8px',
        }}>Registration Cancelled</h2>
        <p style={{ color: '#6b7280', fontSize: 14, margin: 0, lineHeight: 1.6 }}>
          This registration has been cancelled. If you believe this is an error,
          please contact us at the email below.
        </p>
      </div>
      <ContactCard />
    </PageShell>
  );

  // ── Main tracking view ───────────────────────────────────────────────────

  const currentIdx = stageIdx(reg.status);
  const isEnrolled = reg.status === 'enrolled';
  const countdownLabel = isEnrolled ? lessonCountdownLabel(reg.start_date) : '';

  return (
    <PageShell registrationId={registrationId}>

      {/* Status badge + title */}
      <div style={{ textAlign: 'center', marginBottom: 32 }}>
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 7,
          background: isEnrolled ? '#f0fdf4' : 'var(--primary-050, #f0f5ff)',
          color: isEnrolled ? '#15803d' : 'var(--primary)',
          border: `1px solid ${isEnrolled ? '#86efac' : 'var(--primary-200, #bfd0f5)'}`,
          borderRadius: 99, padding: '5px 14px 5px 10px',
          fontSize: 12, fontWeight: 700, letterSpacing: '0.04em',
          textTransform: 'uppercase', marginBottom: 18,
        }}>
          <span style={{
            width: 8, height: 8, borderRadius: '50%',
            background: isEnrolled ? '#22c55e' : 'var(--primary)',
            animation: isEnrolled ? 'none' : 'akc-track-dot 1.6s ease-in-out infinite',
            flexShrink: 0,
          }} />
          {STAGES[currentIdx]?.label}
        </div>

        <h1 style={{
          fontFamily: "'General Sans','Inter',sans-serif",
          fontSize: 26, fontWeight: 700, color: 'var(--ink)',
          letterSpacing: '-0.02em', margin: '0 0 6px',
        }}>
          Registration Tracker
        </h1>
        <p style={{ margin: 0, fontSize: 13, color: 'var(--muted)' }}>
          Ref:{' '}
          <span style={{
            fontFamily: "'JetBrains Mono', ui-monospace, monospace",
            fontWeight: 600, color: 'var(--ink-2)', letterSpacing: '0.03em',
          }}>
            {registrationId}
          </span>
        </p>
      </div>

      {/* Course details card */}
      <div style={{
        background: 'var(--surface)', border: '1px solid var(--line)',
        borderRadius: 14, padding: '20px 24px', marginBottom: 20,
      }}>
        <div style={{
          fontSize: 10, fontWeight: 700, letterSpacing: '0.07em',
          textTransform: 'uppercase', color: 'var(--primary)',
          marginBottom: 10, fontFamily: "'General Sans','Inter',sans-serif",
        }}>
          Course Details
        </div>
        <h2 style={{
          fontFamily: "'General Sans','Inter',sans-serif",
          fontSize: 16, fontWeight: 700, color: 'var(--ink)',
          margin: '0 0 12px', lineHeight: 1.35,
        }}>
          {reg.course_name}
        </h2>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: '6px 20px', fontSize: 13, color: 'var(--ink-2)' }}>
          {reg.start_date && (
            <span>
              📅 {fmtDate(reg.start_date)}
              {reg.end_date && reg.end_date !== reg.start_date ? ` — ${fmtDate(reg.end_date)}` : ''}
            </span>
          )}
          {reg.venue    && <span>📍 {reg.venue}</span>}
          {reg.language && <span>🌐 {reg.language}</span>}
        </div>
        {reg.primary_name && (
          <div style={{
            marginTop: 12, paddingTop: 12,
            borderTop: '1px solid var(--line)',
            fontSize: 13, color: 'var(--ink-2)',
          }}>
            Registrant: <strong style={{ color: 'var(--ink)' }}>{reg.primary_name}</strong>
          </div>
        )}
      </div>

      {countdownLabel && (
        <div style={{
          background: '#f0fdf4',
          border: '1px solid #bbf7d0',
          borderRadius: 14,
          padding: '16px 20px',
          marginBottom: 20,
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          gap: 16,
        }}>
          <div>
            <div style={{
              fontSize: 10,
              fontWeight: 700,
              letterSpacing: '0.07em',
              textTransform: 'uppercase',
              color: '#15803d',
              marginBottom: 4,
              fontFamily: "'General Sans','Inter',sans-serif",
            }}>
              Lesson Countdown
            </div>
            <div style={{
              fontFamily: "'General Sans','Inter',sans-serif",
              fontSize: 18,
              fontWeight: 700,
              color: '#166534',
            }}>
              {countdownLabel}
            </div>
          </div>
          <div style={{
            fontSize: 12,
            color: '#166534',
            fontWeight: 600,
            textAlign: 'right',
            whiteSpace: 'nowrap',
          }}>
            Starts {fmtDate(reg.start_date)}
          </div>
        </div>
      )}

      {/* Progress timeline */}
      <div style={{
        background: 'var(--surface)', border: '1px solid var(--line)',
        borderRadius: 14, padding: '24px 24px 8px', marginBottom: 20,
      }}>
        <div style={{
          fontSize: 10, fontWeight: 700, letterSpacing: '0.07em',
          textTransform: 'uppercase', color: 'var(--primary)',
          marginBottom: 24, fontFamily: "'General Sans','Inter',sans-serif",
        }}>
          Registration Progress
        </div>

        {STAGES.map((stage, i) => {
          const isDone    = i < currentIdx;
          const isCurrent = i === currentIdx;
          const isLast    = i === STAGES.length - 1;
          const progressBlue = '#1a5fbf';

          return (
            <div key={stage.key} style={{ display: 'flex', gap: 16 }}>

              {/* Circle + connector */}
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', width: 28, flexShrink: 0 }}>
                {/* Dot */}
                <div style={{ position: 'relative', width: 28, height: 28, flexShrink: 0 }}>
                  {isCurrent && (
                    <span style={{
                      position: 'absolute', inset: -12, borderRadius: '50%',
                      background: 'rgba(26, 95, 191, 0.24)',
                      boxShadow: '0 0 0 1px rgba(26, 95, 191, 0.28), 0 0 18px rgba(26, 95, 191, 0.28)',
                      animation: 'akc-track-pulse 1.5s ease-in-out infinite',
                      pointerEvents: 'none',
                    }} />
                  )}
                  <div style={{
                    width: 28, height: 28, borderRadius: '50%',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    background: isDone || isCurrent ? progressBlue : '#f8fafc',
                    border: isDone || isCurrent ? 'none' : '2px solid var(--line-strong, #d1d5db)',
                    position: 'relative', zIndex: 1,
                    boxShadow: isCurrent ? '0 0 0 5px rgba(26, 95, 191, 0.16), 0 0 18px rgba(26, 95, 191, 0.22)' : 'none',
                    transition: 'background 0.3s ease, box-shadow 0.3s ease',
                  }}>
                    {isDone ? (
                      null
                    ) : isCurrent ? (
                      <div style={{ width: 9, height: 9, borderRadius: '50%', background: 'white' }} />
                    ) : (
                      <div style={{ width: 7, height: 7, borderRadius: '50%', background: '#d1d5db' }} />
                    )}
                  </div>
                </div>

                {/* Vertical line */}
                {!isLast && (
                  <div style={{
                    width: 3, flex: 1, minHeight: 34, margin: '6px 0 -2px',
                    borderRadius: 99,
                    background: isDone ? progressBlue : '#cbd5e1',
                    transition: 'background 0.3s ease',
                  }} />
                )}
              </div>

              {/* Content */}
              <div style={{ paddingBottom: isLast ? 16 : 24, flex: 1, paddingTop: 3 }}>
                <div style={{
                  display: 'flex', alignItems: 'center', gap: 8,
                  flexWrap: 'wrap', marginBottom: (isDone || isCurrent) ? 5 : 0,
                }}>
                  <span style={{
                    fontFamily: "'General Sans','Inter',sans-serif",
                    fontWeight: isCurrent ? 700 : isDone ? 600 : 400,
                    fontSize: 14,
                    color: isDone ? progressBlue : isCurrent ? 'var(--ink)' : 'var(--muted)',
                  }}>
                    {stage.label}
                  </span>

                  {isCurrent && (
                    <span style={{
                      fontSize: 10, fontWeight: 700, letterSpacing: '0.05em',
                      textTransform: 'uppercase', padding: '2px 8px',
                      background: 'var(--primary-100, #dce8fd)',
                      color: 'var(--primary)', borderRadius: 99,
                    }}>
                      Current
                    </span>
                  )}

                  {isDone && i === 0 && reg.submitted_at && (
                    <span style={{ fontSize: 11, color: 'var(--muted)', fontFamily: "'Inter',sans-serif" }}>
                      {fmtDateTime(reg.submitted_at)}
                    </span>
                  )}
                </div>

                {(isCurrent || isDone) && (
                  <p style={{
                    margin: 0, fontSize: 13, lineHeight: 1.6,
                    color: isCurrent ? 'var(--ink-2)' : '#6b7280',
                  }}>
                    {stage.desc}
                  </p>
                )}
              </div>
            </div>
          );
        })}
      </div>

      {/* Contact card */}
      <ContactCard />

      <p style={{ textAlign: 'center', fontSize: 11, color: 'var(--muted)', marginTop: 20 }}>
        This page refreshes automatically every 30 seconds.
      </p>
    </PageShell>
  );
}

// ── Sub-components ────────────────────────────────────────────────────────────

function PageShell({ registrationId, children }) {
  return (
    <div className="akc-app" style={{ minHeight: '100vh', background: 'var(--bg)', fontFamily: "'Inter', sans-serif" }}>
      {/* Nav */}
      <div style={{
        background: 'var(--surface)', borderBottom: '1px solid var(--line)',
        padding: '13px 24px', display: 'flex', alignItems: 'center',
      }}>
        <a href="/booking/" style={{ display: 'flex', alignItems: 'center', textDecoration: 'none' }}>
          <img src="akc-logo.png" alt="AKC" style={{ height: 34, width: 'auto', display: 'block' }} />
        </a>
        <a href="tel:+6566905555" style={{
          marginLeft: 'auto', fontSize: 12, color: 'var(--muted)',
          fontWeight: 600, textDecoration: 'none', whiteSpace: 'nowrap',
        }}>
          📞 6690 5555
        </a>
      </div>

      {/* Content */}
      <div style={{ maxWidth: 680, margin: '0 auto', padding: '40px 20px 72px' }}>
        {children}
      </div>
    </div>
  );
}

function ContactCard() {
  return (
    <div style={{
      background: 'var(--surface)', border: '1px solid var(--line)',
      borderRadius: 14, padding: '20px 24px',
      display: 'flex', gap: 16, alignItems: 'flex-start',
    }}>
      <div style={{
        width: 42, height: 42, borderRadius: 11,
        background: 'var(--primary-100, #dce8fd)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 20, flexShrink: 0,
      }}>
        💬
      </div>
      <div>
        <div style={{
          fontFamily: "'General Sans','Inter',sans-serif",
          fontWeight: 700, fontSize: 15, color: 'var(--ink)', marginBottom: 4,
        }}>
          Need help?
        </div>
        <p style={{ margin: '0 0 10px', fontSize: 13, color: 'var(--muted)', lineHeight: 1.6 }}>
          Our team is happy to assist you with any questions about your registration.
        </p>
        <a
          href="https://wa.me/6566905566"
          target="_blank"
          rel="noopener noreferrer"
          style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            color: 'var(--primary)', fontSize: 13, fontWeight: 600, textDecoration: 'none',
            marginRight: 16, marginBottom: 8,
          }}
        >
          📱 WhatsApp 6690 5566
        </a>
        <a
          href="mailto:enquiry@sg-akc.com"
          style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            color: 'var(--primary)', fontSize: 13, fontWeight: 600, textDecoration: 'none',
          }}
        >
          ✉ enquiry@sg-akc.com
        </a>
      </div>
    </div>
  );
}

Object.assign(window, { TrackingScreen });
