/* ============================================================
   VLF 2026 · ONBOARDING — Welcome · Bạn là ai? · Scan/Permission
   onDone(personaId) khi hoàn tất → vào app.
   ============================================================ */
/* mã vùng — phục vụ cả khách quốc tế */
const VLF_CC = [
{ c: '+84', n: 'Việt Nam' }, { c: '+1', n: 'USA / Canada' }, { c: '+44', n: 'United Kingdom' },
{ c: '+82', n: 'Hàn Quốc' }, { c: '+81', n: 'Nhật Bản' }, { c: '+65', n: 'Singapore' },
{ c: '+66', n: 'Thái Lan' }, { c: '+61', n: 'Úc' }, { c: '+86', n: 'Trung Quốc' },
{ c: '+33', n: 'Pháp' }, { c: '+49', n: 'Đức' }, { c: '+852', n: 'Hong Kong' }];


function Onboard({ onDone, platform }) {
  const t = useT();
  const native = platform === 'ios' || platform === 'android';
  const [step, setStep] = useState('welcome'); // welcome · who · login · scan · perm
  const [pick, setPick] = useState(null);
  const ev = window.VLF.event;

  const personas = [
  { id: 'golfer', icon: 'golfer', name: 'Golfer trong nước', sub: 'Tee time · bảng đấu · vị trí của tôi' },
  { id: 'golfer_intl', icon: 'golfer', name: 'Golfer quốc tế', sub: 'Visa · đón sân bay · tee time · bảng đấu' },
  { id: 'guest', icon: 'gala', name: 'Khách mời', sub: 'Vé mời · lịch trình riêng · Gala' },
  { id: 'spectator', icon: 'ticket', name: 'Khán giả', sub: 'Mua vé · bản đồ · theo dõi golfer' },
  { id: 'vip', icon: 'shield', name: 'VIP & Chính Quyền', sub: 'Lịch riêng · concierge · làn riêng' }];


  function proceed() {
    if (native) {setStep('login');return;} // iOS/Android: đăng nhập SĐT + OTP
    if (pick === 'golfer' || pick === 'golfer_intl') setStep('scan');else
    setStep('perm');
  }

  // golfer / nhân sự: tự nhận diện sau khi "quét" QR
  React.useEffect(() => {
    if (step === 'scan') {
      const tm = setTimeout(() => onDone(pick), 2300);
      return () => clearTimeout(tm);
    }
  }, [step]);

  return (
    <div className="v-onboard">
      <div className="inner">
        {step === 'welcome' &&
        <>
            <div style={{ marginBottom: 30 }}><OrgLogos /></div>
            <div className="kk" style={{ textAlign: 'center', marginTop: 16 }}>{t.lang === 'en' ? 'International Golf Festival' : 'Lễ hội Golf Quốc tế'}</div>
            <h1 style={{ textAlign: 'center', marginTop: 14 }}>Vietnam <em>Legends</em> Festival 2026</h1>
            <p className="lede" style={{ textAlign: 'center', margin: '18px auto 36px', lineHeight: 1.8 }}>{ev.venue}<br />{ev.dates}</p>
            <div style={{ background: 'rgba(255,255,255,.07)', border: '1px solid rgba(255,255,255,.14)', borderRadius: 14, padding: '22px 16px', textAlign: 'center' }}>
              <div style={{ fontWeight: 700, fontSize: 18 }}>{t.lang === 'en' ? '60 world legends · 6-day festival' : '60 huyền thoại · 6 ngày lễ hội'}</div>
              <div style={{ fontSize: 11.5, opacity: .72, marginTop: 7 }}>{t.lang === 'en' ? 'Buy tickets · follow live · explore the Village' : 'Mua vé · theo dõi trực tiếp · khám phá Village'}</div>
            </div>
            <div className="foot">
              <div className="v-spon-kk">{t('sponsors')}</div>
              <div className="v-spon-mask" style={{ margin: '0 -24px 16px', padding: '0 24px' }}>
                <div className="v-spon-track">
                  {window.VLF.sponsors.concat(window.VLF.sponsors).map((s, i) => <span className="v-spon-chip" key={i}>{s.name}</span>)}
                </div>
              </div>
              <button className="v-btn v-btn-gold" onClick={() => setStep('who')}>{t.lang === 'en' ? 'Get started' : 'Bắt đầu'}</button>
            </div>
          </>
        }

        {step === 'who' &&
        <>
            <div className="kk">Cá nhân hoá</div>
            <h1>{t('whoAreYou')}</h1>
            <p className="lede">{t('whoSub')}</p>
            <div className="v-persona">
              {personas.map((p) =>
            <div key={p.id} className={'v-pcard' + (pick === p.id ? ' on' : '')} onClick={() => setPick(p.id)}>
                  <div className="pic"><Icon name={p.icon} size={24} sw={1.7} /></div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div className="pt">{p.name}</div>
                    <div className="ps">{p.sub}</div>
                  </div>
                  {pick === p.id && <Icon name="check" size={22} sw={2.2} style={{ color: 'var(--vlf-purple-700)' }} />}
                </div>
            )}
            </div>
            <div className="foot">
              <button className="v-btn v-btn-gold" disabled={!pick} onClick={proceed}>{t('enter')}</button>
            </div>
          </>
        }

        {step === 'login' && native &&
        <PhoneLogin platform={platform} lang={t.lang}
        onVerified={() => onDone(pick)} onBack={() => setStep('who')} />
        }

        {step === 'scan' &&
        <>
            <div className="kk">Định danh nhanh</div>
            <h1>{pick === 'staff' ? t.lang === 'en' ? 'Scan staff badge' : 'Quét QR thẻ nhân sự' : t.lang === 'en' ? 'Scan golfer QR' : 'Quét QR golfer'}</h1>
            <p className="lede">{pick === 'staff' ? t.lang === 'en' ? 'Scan your staff badge — the app auto-detects your role, subcommittee and zone.' : 'Quét thẻ nhân sự — app tự nhận diện vai trò, tiểu ban và khu vực của bạn.' : t.lang === 'en' ? 'Place the QR on your pass in the frame — the app identifies you and opens your schedule.' : 'Đưa mã QR trên thẻ tham dự vào khung. App tự nhận diện và mở lịch thi đấu của bạn.'}</p>
            <div className="v-scan-box">
              <div className="v-scan-corner" style={{ top: 14, left: 14, borderRight: 'none', borderBottom: 'none' }} />
              <div className="v-scan-corner" style={{ top: 14, right: 14, borderLeft: 'none', borderBottom: 'none' }} />
              <div className="v-scan-corner" style={{ bottom: 14, left: 14, borderRight: 'none', borderTop: 'none' }} />
              <div className="v-scan-corner" style={{ bottom: 14, right: 14, borderLeft: 'none', borderTop: 'none' }} />
              <div className="v-scan-line" />
              <Icon name="qr" size={70} sw={1.2} style={{ color: 'rgba(255,255,255,.3)' }} />
            </div>
            <p className="lede" style={{ textAlign: 'center', marginTop: 22 }}>Đang nhận diện…</p>
          </>
        }
      </div>

      {step === 'perm' &&
      <ZaloPermissionSheet
        appName="VLF 2026"
        appearance="light"
        userName={window.VLF.personas[pick] ? window.VLF.personas[pick].me.name : 'Nguyễn Ngọc Tuấn'}
        logo={<VLFLogo />}
        onDeny={() => onDone(pick)}
        onAllow={() => onDone(pick)} />

      }
    </div>);

}

/* ---- ĐĂNG NHẬP NATIVE: số điện thoại + OTP (có mã vùng) ---- */
function PhoneLogin({ platform, lang, onVerified, onBack }) {
  const T = (vi, en) => lang === 'en' ? en : vi;
  const [sub, setSub] = useState('phone'); // phone | otp
  const [cc, setCc] = useState(VLF_CC[0]);
  const [ccOpen, setCcOpen] = useState(false);
  const [phone, setPhone] = useState('');
  const [otp, setOtp] = useState('');
  const [secs, setSecs] = useState(0);
  React.useEffect(() => {
    if (sub !== 'otp' || secs <= 0) return;
    const id = setTimeout(() => setSecs((s) => s - 1), 1000);
    return () => clearTimeout(id);
  }, [sub, secs]);

  function sendOtp() {if (phone.trim().length < 6) return;setSub('otp');setOtp('');setSecs(30);}

  const ssoLabel = platform === 'ios' ?
  T('Tiếp tục với Apple', 'Continue with Apple') :
  T('Tiếp tục với Google', 'Continue with Google');
  const ssoMark = platform === 'ios' ?
  <svg width="16" height="18" viewBox="0 0 814 1000" fill="currentColor" aria-hidden="true"><path d="M788 340c-6 4-138 78-138 244 0 192 169 260 174 262-1 4-27 92-89 182-55 80-113 159-200 159s-110-51-211-51c-98 0-133 53-213 53S0 1112 0 879c0-199 130-304 257-304 84 0 154 56 207 56 50 0 128-59 224-59 36 0 167 3 253 127zM604 156c40-48 68-114 68-181 0-9-1-18-2-25-65 3-143 44-189 98-37 42-71 109-71 177 0 10 2 20 2 23 4 1 11 2 18 2 58 0 132-39 174-94z" /></svg> :
  <svg width="17" height="17" viewBox="0 0 48 48" aria-hidden="true"><path fill="#4285F4" d="M45 24c0-1.6-.1-3.1-.4-4.6H24v9h11.8c-.5 2.7-2 5-4.3 6.6v5.5h7C42.6 36.4 45 30.7 45 24z" /><path fill="#34A853" d="M24 46c5.9 0 10.8-2 14.4-5.3l-7-5.5c-2 1.3-4.5 2.1-7.4 2.1-5.7 0-10.5-3.8-12.2-9H4.6v5.7C8.2 41.1 15.5 46 24 46z" /><path fill="#FBBC05" d="M11.8 28.3c-.5-1.3-.7-2.8-.7-4.3s.3-3 .7-4.3v-5.7H4.6C3 17.1 2 20.4 2 24s1 6.9 2.6 10l7.2-5.7z" /><path fill="#EA4335" d="M24 10.7c3.2 0 6 1.1 8.3 3.2l6.2-6.2C34.8 4.1 29.9 2 24 2 15.5 2 8.2 6.9 4.6 14l7.2 5.7c1.7-5.2 6.5-9 12.2-9z" /></svg>;

  return (
    <>
      <div className="nl-logo"><VLFLogo /></div>
      {sub === 'phone' ?
      <>
          <div className="kk">{T('Đăng nhập', 'Sign in')}</div>
          <h1>{T('Nhập số điện thoại', 'Your phone number')}</h1>
          <p className="lede">{T('Chúng tôi gửi mã OTP 6 số để xác thực. Khách quốc tế chọn mã vùng phù hợp.', 'We’ll text you a 6-digit code. International guests, pick your country code.')}</p>
          <div className="nl-field">
            <div className="nl-row">
              <button className="nl-cc" onClick={() => setCcOpen((o) => !o)}>
                {cc.c}<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M6 9l6 6 6-6" /></svg>
              </button>
              <input className="nl-input" inputMode="tel" value={phone}
            onChange={(e) => setPhone(e.target.value.replace(/[^\d]/g, ''))}
            placeholder={T('Số điện thoại', 'Phone number')} />
            </div>
            {ccOpen &&
          <div className="nl-cclist">
              {VLF_CC.map((o) =>
            <button key={o.c} className={'nl-ccitem' + (o.c === cc.c ? ' on' : '')} onClick={() => {setCc(o);setCcOpen(false);}}>
                <span className="c">{o.c}</span><span className="n">{o.n}</span>
              </button>
            )}
            </div>
          }
          </div>
          <div className="nl-hint">{T('Bản demo: nhập số bất kỳ rồi gửi mã.', 'Demo: enter any number and send the code.')}</div>
          <button className="v-btn v-btn-gold nl-primary" style={{ marginTop: 18 }} disabled={phone.trim().length < 6} onClick={sendOtp}>{T('Gửi mã OTP', 'Send code')}</button>
          <div className="nl-div"><span>{T('hoặc', 'or')}</span></div>
          <button className="nl-sso" onClick={onVerified} data-plat={platform}>{ssoMark}{ssoLabel}</button>
          <button className="nl-back" onClick={onBack}>{T('‹ Chọn lại vai trò', '‹ Change role')}</button>
        </> :

      <>
          <div className="kk">{T('Xác thực', 'Verify')}</div>
          <h1>{T('Nhập mã OTP', 'Enter the code')}</h1>
          <p className="lede">{T('Đã gửi mã 6 số tới ', 'We sent a 6-digit code to ')}<b style={{ color: '#fff' }}>{cc.c} {phone}</b></p>
          <input className="nl-otp" inputMode="numeric" maxLength={6} value={otp} autoFocus
        onChange={(e) => setOtp(e.target.value.replace(/[^\d]/g, '').slice(0, 6))} placeholder="••••••" />
          <div className="nl-resend">
            {secs > 0 ?
          T('Gửi lại mã sau ', 'Resend in ') + secs + 's' :
          <button onClick={() => setSecs(30)}>{T('Gửi lại mã', 'Resend code')}</button>}
          </div>
          <button className="v-btn v-btn-gold nl-primary" style={{ marginTop: 18 }} disabled={otp.length < 6} onClick={onVerified}>{T('Xác thực & vào app', 'Verify & continue')}</button>
          <button className="nl-back" onClick={() => setSub('phone')}>{T('‹ Đổi số điện thoại', '‹ Change number')}</button>
        </>
      }
    </>);

}

/* logo VLF cho header / popup quyền — khối tím + đỉnh vàng (monogram) */
function VLFLogo() {
  return (
    <svg viewBox="0 0 36 36" aria-hidden="true">
      <rect width="36" height="36" fill="#31153D" />
      <text x="18" y="24" textAnchor="middle" fontFamily="'Be Vietnam Pro', sans-serif" fontWeight="800" fontSize="17" fill="#E8CE8B">V</text>
      <rect x="9" y="27.5" width="18" height="2.2" fill="#C9A24B" />
    </svg>);

}

Object.assign(window, { Onboard, VLFLogo });