/* ============================================================
   VLF 2026 · ZALO OA — THẺ ZNS + dựng luồng tin nhắn
   - ZNSRender({zt,d,lang})  : vẽ 1 thẻ ZNS theo loại
   - seedOAThread(persona)   : hội thoại nền (lịch sử)
   - buildOAMessages(type,payload,ctx) : sinh tin khi có trigger
   - window.VLF.oaTriggers   : danh mục trigger OA chủ động (panel)
   Chrome chat = Zalo (xanh); nội dung thẻ = brand VLF (tím).
   ============================================================ */

const OA_EV = (window.VLF && window.VLF.event) || {};
const OA_VENUE = 'Montgomerie Links, Đà Nẵng';
const OA_DATES = '22–27/09/2026';
function oaMoney(n) {
  if (typeof n !== 'number') return n || '—';
  try { return window.VLF.money(n); } catch (e) { return n.toLocaleString('vi-VN') + '₫'; }
}
function oaName(persona) {
  const p = (window.VLF.personas || {})[persona];
  return (p && p.me && p.me.name) || 'Quý khách';
}

/* small inline glyphs */
function VTick({ cls }) {
  return <svg className={cls} viewBox="0 0 24 24" fill="currentColor"><path d="M12 2l2.6 1.5 3 .2 1.2 2.7 2.2 2-.6 3 .6 3-2.2 2-1.2 2.7-3 .2L12 22l-2.6-1.5-3-.2-1.2-2.7-2.2-2 .6-3-.6-3 2.2-2L6.4 3.7l3-.2L12 2z"/><path d="M8.5 12.2l2.3 2.3 4.5-4.7" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>;
}

/* ---------- ZNS primitives ---------- */
function ZnsLogo() {
  return (
    <div className="zns-logobar">
      <div className="lg"><VLFLogo /></div>
      <div className="nm"><span>Vietnam Legends Festival</span><VTick cls="v" /></div>
    </div>
  );
}
function ZnsBanner({ label, a, b, fg, ring, ringIc, ringBg, badge }) {
  const st = { '--bnA': a, '--bnB': b, '--bnFg': fg };
  return (
    <div className="zns-banner" style={st}>
      {ring ? <div className="ring" style={{ background: ringBg }}><Icon name={ringIc} size={32} sw={2.2} /></div>
        : <span className="cap">{label}</span>}
      {badge && <span className="badge">{badge}</span>}
    </div>
  );
}
function ZnsTable({ rows }) {
  return (
    <div className="zns-table">
      {rows.filter(Boolean).map((r, i) => (
        <div className="zns-trow" key={i}>
          <div className="k">{r.k}</div>
          <div className={'v' + (r.hl ? ' hl' : '')}>
            {r.dot && <span className="dot" style={{ background: r.dot }} />}{r.v}
          </div>
        </div>
      ))}
    </div>
  );
}
function ZnsCode({ label, value, bg, bd, fg, hint }) {
  return (
    <div className="zns-code" style={{ '--cdBg': bg, '--cdBd': bd, '--cdFg': fg }}>
      <div className="lbl">{label}</div>
      <div className="val">{value}</div>
      {hint && <div className="hint"><Icon name="info" size={12} sw={2} />{hint}</div>}
    </div>
  );
}
function ZnsBtns({ btns }) {
  return (
    <div className="zns-btns">
      {btns.map((b, i) => (
        <div className={'zns-btn ' + (b.kind || 'primary')} key={i}>
          {b.ic && <Icon name={b.ic} size={15} sw={2} />}{b.t}
        </div>
      ))}
    </div>
  );
}
function ZnsFoot({ tag, tagBg, tagFg }) {
  return (
    <div className="zns-foot">
      <div className="by"><VTick cls="v" />Được gửi từ VLF 2026 OA</div>
      <div className="tag" style={{ '--tgBg': tagBg, '--tgFg': tagFg }}>{tag}</div>
    </div>
  );
}
const ZNS_TAG = {
  t1: { t: 'Giao dịch · Tag 1', bg: '#EAF1FB', fg: '#2C63B5' },
  t2: { t: 'Chăm sóc · Tag 2', bg: '#E8F5EE', fg: '#1F8A5B' },
  t3: { t: 'Khuyến mãi · Tag 3', bg: '#FBEEF4', fg: '#B0467B' },
};

/* ============================================================
   ZNSRender — vẽ thẻ theo loại
   ============================================================ */
function ZNSRender({ zt, d, lang }) {
  const T = (vi, en) => (lang === 'en' ? en : vi);
  d = d || {};
  const ev = T('Vietnam Legends Festival 2026', 'Vietnam Legends Festival 2026');

  switch (zt) {

    case 'order_ticket':
      return (
        <div className="zns">
          <ZnsLogo />
          <ZnsBanner ring ringIc="check" ringBg="#1F8A5B" a="#E3F2E9" b="#D6ECDF" />
          <div className="zns-body">
            <div className="zns-title">{T('Vé điện tử đã sẵn sàng', 'Your e-ticket is ready')}</div>
            <div className="zns-content">{T('Thanh toán thành công. Vé QR đã được gửi đến bạn và lưu vào Apple/Google Wallet.', 'Payment successful. Your QR ticket has been delivered and saved to Apple/Google Wallet.')}</div>
            <ZnsTable rows={[
              { k: T('Sự kiện', 'Event'), v: ev },
              { k: T('Loại vé', 'Ticket'), v: d.ticket || T('Vé VLF 2026', 'VLF 2026 ticket') },
              { k: T('Ngày', 'Dates'), v: OA_DATES },
              { k: T('Địa điểm', 'Venue'), v: OA_VENUE },
              { k: T('Mã đơn', 'Order'), v: d.ref || '—' },
              { k: T('Tổng tiền', 'Total'), v: oaMoney(d.total), hl: true },
            ]} />
            <div className="zns-qr">
              <div className="frame"><QR seed={'VLF-' + (d.code || d.ref || '0000')} size={120} /></div>
              <div className="cap"><Icon name="qr" size={12} sw={2} />{T('Quét mã tại cổng vào', 'Scan at the gate')}</div>
            </div>
            <ZnsBtns btns={[
              { t: T('Xem vé điện tử', 'View e-ticket'), ic: 'ticket' },
              { t: T('Chỉ đường đến sân', 'Directions to venue'), kind: 'ghost', ic: 'pin' },
            ]} />
          </div>
          <ZnsFoot tag={ZNS_TAG.t1.t} tagBg={ZNS_TAG.t1.bg} tagFg={ZNS_TAG.t1.fg} />
        </div>
      );

    case 'order_shop':
      return (
        <div className="zns">
          <ZnsLogo />
          <ZnsBanner label={T('ẢNH ĐƠN HÀNG · QUÀ LƯU NIỆM', 'ORDER IMAGE · MERCHANDISE')} />
          <div className="zns-body">
            <div className="zns-title">{T('Đặt hàng thành công!', 'Order confirmed!')}</div>
            <div className="zns-content">{T('Cảm ơn bạn đã mua sắm tại cửa hàng VLF. Đơn hàng đang được xử lý.', 'Thanks for shopping at the VLF store. Your order is being processed.')}</div>
            <ZnsTable rows={[
              { k: T('Mã đơn', 'Order'), v: d.ref || '—' },
              { k: T('Sản phẩm', 'Items'), v: d.itemLine || '—' },
              { k: T('Nhận hàng', 'Fulfilment'), v: d.deliv === 'ship' ? T('Giao tận nơi', 'Shipping') : T('Nhận tại VLF Village', 'Pickup · VLF Village') },
              { k: T('Tổng tiền', 'Total'), v: oaMoney(d.total), hl: true },
              { k: T('Trạng thái', 'Status'), v: T('Đang xử lý', 'Processing'), dot: '#E1A33A' },
            ]} />
            <ZnsBtns btns={[
              { t: T('Theo dõi đơn hàng', 'Track order'), ic: 'village' },
              { t: T('Liên hệ cửa hàng', 'Contact store'), kind: 'ghost', ic: 'bell' },
            ]} />
          </div>
          <ZnsFoot tag={ZNS_TAG.t1.t} tagBg={ZNS_TAG.t1.bg} tagFg={ZNS_TAG.t1.fg} />
        </div>
      );

    case 'invite_activated':
      return (
        <div className="zns">
          <ZnsLogo />
          <ZnsBanner ring ringIc="ticket" ringBg="#522367" a="#EFE7F4" b="#E6DBEE" badge={d.code ? T('Mã vé · ', 'Ticket · ') + d.code : null} />
          <div className="zns-body">
            <div className="zns-title">{T('Vé mời đã kích hoạt', 'Invite activated')}</div>
            <div className="zns-content">{T('Vé mời QR của bạn đã sẵn sàng. Xuất trình tại cổng để vào sự kiện.', 'Your invite QR is ready. Show it at the gate to enter.')}</div>
            <ZnsTable rows={[
              { k: T('Sự kiện', 'Event'), v: ev },
              { k: T('Loại vé', 'Ticket type'), v: d.ticket || T('Vé mời', 'Invite') },
              { k: T('Người tham dự', 'Attendee'), v: d.attendee || oaName(d.persona) },
              { k: T('Mã vé', 'Ticket code'), v: d.code || '—' },
              { k: T('Trạng thái', 'Status'), v: T('Đã kích hoạt', 'Activated'), dot: '#1F8A5B' },
            ]} />
            <div className="zns-qr">
              <div className="frame"><QR seed={'INV-' + (d.code || '0000')} size={120} /></div>
              <div className="cap"><Icon name="qr" size={12} sw={2} />{T('Quét mã tại cổng vào', 'Scan at the gate')}</div>
            </div>
            <ZnsBtns btns={[
              { t: T('Xem vé QR', 'View QR ticket'), ic: 'ticket' },
              { t: T('Thêm vào Wallet', 'Add to Wallet'), kind: 'ghost', ic: 'qr' },
            ]} />
          </div>
          <ZnsFoot tag={ZNS_TAG.t1.t} tagBg={ZNS_TAG.t1.bg} tagFg={ZNS_TAG.t1.fg} />
        </div>
      );

    case 'invite_code':
      return (
        <div className="zns">
          <ZnsLogo />
          <ZnsBanner label={T('THIỆP MỜI · VLF 2026', 'INVITATION · VLF 2026')} a="#EDE6F3" b="#E2D7EC" />
          <div className="zns-body">
            <div className="zns-title">{T('Bạn nhận được vé mời', 'You have an invitation')}</div>
            <div className="zns-content">{T('Bạn được mời tham dự VLF 2026. Dùng mã bên dưới để kích hoạt vé điện tử ngay trong Mini App.', 'You are invited to VLF 2026. Use the code below to activate your e-ticket in the Mini App.')}</div>
            <ZnsCode label={T('MÃ VÉ MỜI', 'INVITE CODE')} value={d.code || 'A7K9X'} bg="#F3ECF7" bd="#C7AED6" fg="#522367" hint={T('Nhấn nút bên dưới để kích hoạt', 'Tap below to activate')} />
            <ZnsTable rows={[
              { k: T('Sự kiện', 'Event'), v: ev },
              { k: T('Thời gian', 'When'), v: OA_DATES },
              { k: T('Địa điểm', 'Venue'), v: OA_VENUE },
              { k: T('Loại vé', 'Type'), v: T('Vé mời (1 người)', 'Invite (1 guest)') },
              { k: T('Hạn kích hoạt', 'Activate by'), v: d.deadline || '16/08/2026 23:59' },
            ]} />
            <ZnsBtns btns={[
              { t: T('Kích hoạt vé ngay', 'Activate now'), ic: 'ticket' },
              { t: T('Hướng dẫn sử dụng', 'How it works'), kind: 'ghost', ic: 'info' },
            ]} />
          </div>
          <ZnsFoot tag={ZNS_TAG.t1.t} tagBg={ZNS_TAG.t1.bg} tagFg={ZNS_TAG.t1.fg} />
        </div>
      );

    case 'invite_reminder':
      return (
        <div className="zns">
          <ZnsLogo />
          <ZnsBanner ring ringIc="clock" ringBg="#E1882B" a="#FBEFE0" b="#F6E6D2" />
          <div className="zns-body">
            <div className="zns-title">{T('Đừng quên kích hoạt vé mời!', "Don't forget to activate!")}</div>
            <div className="zns-content">{T('Mã vé mời của bạn sắp hết hạn. Hãy kích hoạt ngay để giữ chỗ tham dự.', 'Your invite code is about to expire. Activate now to keep your spot.')}</div>
            <div className="zns-warn"><Icon name="bell" size={15} sw={2} />{T('Còn 1 ngày để kích hoạt · Hết hạn ', '1 day left · expires ') + (d.deadline || '16/08/2026 23:59')}</div>
            <div className="zns-coderow"><span className="k">{T('Mã vé mời', 'Invite code')}</span><span className="v">{d.code || 'A7K9X'}</span></div>
            <ZnsTable rows={[
              { k: T('Sự kiện', 'Event'), v: ev },
              { k: T('Thời gian', 'When'), v: OA_DATES },
              { k: T('Trạng thái', 'Status'), v: T('Chưa kích hoạt', 'Not activated'), dot: '#E1882B' },
            ]} />
            <ZnsBtns btns={[
              { t: T('Kích hoạt ngay', 'Activate now'), ic: 'ticket' },
              { t: T('Cần hỗ trợ?', 'Need help?'), kind: 'ghost', ic: 'bell' },
            ]} />
          </div>
          <ZnsFoot tag={ZNS_TAG.t2.t} tagBg={ZNS_TAG.t2.bg} tagFg={ZNS_TAG.t2.fg} />
        </div>
      );

    case 'schedule':
      return (
        <div className="zns">
          <ZnsLogo />
          <ZnsBanner label={T('SÂN MONTGOMERIE LINKS', 'MONTGOMERIE LINKS')} a="#E7EFE9" b="#DCE8DF" fg="rgba(40,90,60,.6)" />
          <div className="zns-body">
            <div className="zns-title">{T('Lịch sắp tới của bạn', 'Your upcoming schedule')}</div>
            <div className="zns-spot">
              <div className="top">{d.div || T('Pro-Am · Shotgun', 'Pro-Am · Shotgun')}</div>
              <div className="big">{d.tee || '07:00'} · {d.date || '23/09'}</div>
              <div className="meta"><Icon name="pin" size={13} sw={2} />{d.where || T('Tee hố 1 & 10', 'Tee 1 & 10')}<span className="sep">·</span>{OA_VENUE}</div>
            </div>
            <ZnsTable rows={[
              { k: T('Nội dung', 'Session'), v: d.div || T('Pro-Am · Shotgun', 'Pro-Am · Shotgun') },
              { k: T('Giờ', 'Time'), v: (d.tee || '07:00'), hl: true },
              { k: T('Ngày', 'Date'), v: d.date || '23/09/2026' },
              { k: T('Trực tiếp', 'Live on'), v: 'VLF Live · YouTube' },
            ]} />
            <ZnsBtns btns={[
              { t: T('Xem lịch của tôi', 'View my schedule'), ic: 'calendar' },
              { t: T('Thêm vào lịch', 'Add to calendar'), kind: 'ghost', ic: 'clock' },
            ]} />
          </div>
          <ZnsFoot tag={ZNS_TAG.t2.t} tagBg={ZNS_TAG.t2.bg} tagFg={ZNS_TAG.t2.fg} />
        </div>
      );

    case 'result':
      return (
        <div className="zns">
          <ZnsLogo />
          <ZnsBanner ring ringIc="trophy" ringBg="#C9A24B" a="#F5EEDC" b="#EFE6CC" />
          <div className="zns-body">
            <div className="zns-title">{T('Kết quả vòng đấu', 'Round results')}</div>
            <div className="zns-content">{T('Bảng Legends · Legends — cập nhật sau vòng 3 (gross to-par).', 'Legends · Legends — updated after round 3 (gross to-par).')}</div>
            <div className="zns-lb">
              {[['1', 'Bernhard Langer', '−14'], ['2', 'Mark Ellison', '−12'], ['3', 'Trần Quốc Bảo', '−9']].map((r, i) => (
                <div className="zns-lbrow" key={i}><span className="ps">{r[0]}</span><span className="nm">{r[1]}</span><span className="sc neg">{r[2]}</span></div>
              ))}
            </div>
            <ZnsTable rows={[
              { k: T('Vòng', 'Round'), v: T('Vòng 3 · Chung kết', 'Round 3 · Final') },
              { k: T('Cập nhật', 'Updated'), v: '27/09/2026 16:40' },
            ]} />
            <ZnsBtns btns={[
              { t: T('Xem bảng xếp hạng', 'View leaderboard'), ic: 'trophy' },
              { t: T('Xem highlights', 'Watch highlights'), kind: 'ghost', ic: 'star' },
            ]} />
          </div>
          <ZnsFoot tag={ZNS_TAG.t2.t} tagBg={ZNS_TAG.t2.bg} tagFg={ZNS_TAG.t2.fg} />
        </div>
      );

    case 'miniapp_invite':
      return (
        <div className="zns">
          <ZnsLogo />
          <ZnsBanner label={T('GIAO DIỆN MINI APP VLF 2026', 'VLF 2026 MINI APP UI')} a="#EAE2F1" b="#E0D4EB" />
          <div className="zns-body">
            <div className="zns-title">{T('Trải nghiệm Mini App VLF 2026', 'Try the VLF 2026 Mini App')}</div>
            <div className="zns-content">{T('Mua vé, theo dõi bảng đấu và nhận ưu đãi — ngay trong Mini App, không cần tải app.', 'Buy tickets, follow the leaderboard and get offers — right in the Mini App, no download.')}</div>
            <div className="zns-feats">
              {[['ticket', T('Mua vé nhanh chỉ 30 giây', 'Buy a ticket in 30 seconds')],
                ['trophy', T('Theo dõi bảng đấu trực tiếp', 'Follow the live leaderboard')],
                ['bell', T('Nhắc lịch & ưu đãi riêng', 'Schedule reminders & offers')]].map((f, i) => (
                  <div className="zns-feat" key={i}><div className="ic"><Icon name={f[0]} size={16} sw={2} /></div><div className="tx">{f[1]}</div></div>
                ))}
            </div>
            <ZnsBtns btns={[
              { t: T('Mở Mini App ngay', 'Open Mini App'), ic: 'star' },
              { t: T('Tìm hiểu thêm', 'Learn more'), kind: 'ghost', ic: 'info' },
            ]} />
          </div>
          <ZnsFoot tag={ZNS_TAG.t3.t} tagBg={ZNS_TAG.t3.bg} tagFg={ZNS_TAG.t3.fg} />
        </div>
      );

    case 'checkin':
      return (
        <div className="zns">
          <ZnsLogo />
          <ZnsBanner ring ringIc="check" ringBg="#1F8A5B" a="#E3F2E9" b="#D6ECDF" badge={d.code ? T('Mã check-in · ', 'Check-in · ') + d.code : null} />
          <div className="zns-body">
            <div className="zns-title">{T('Check-in thành công!', 'Checked in!')}</div>
            <div className="zns-content">{T('Cảm ơn bạn đã có mặt tại VLF 2026. Chúc bạn có trải nghiệm tuyệt vời!', 'Thanks for joining VLF 2026. Enjoy the experience!')}</div>
            <ZnsTable rows={[
              { k: T('Sự kiện', 'Event'), v: ev },
              { k: T('Người tham dự', 'Attendee'), v: d.attendee || oaName(d.persona) },
              { k: T('Thời gian', 'Time'), v: d.time || '25/09/2026 08:42' },
              { k: T('Cổng vào', 'Gate'), v: d.gate || T('Cổng A', 'Gate A') },
              { k: T('Trạng thái', 'Status'), v: T('Đã check-in', 'Checked in'), dot: '#1F8A5B' },
            ]} />
            <ZnsBtns btns={[
              { t: T('Xem lịch trình hôm nay', "Today's schedule"), ic: 'calendar' },
              { t: T('Bản đồ khu vực', 'Site map'), kind: 'ghost', ic: 'map' },
            ]} />
          </div>
          <ZnsFoot tag={ZNS_TAG.t2.t} tagBg={ZNS_TAG.t2.bg} tagFg={ZNS_TAG.t2.fg} />
        </div>
      );

    case 'lucky':
      return (
        <div className="zns">
          <ZnsLogo />
          <ZnsBanner label={T('QUAY SỐ TRÚNG THƯỞNG', 'LUCKY DRAW')} a="#FBF0D8" b="#F6E6C0" fg="rgba(160,110,20,.7)" />
          <div className="zns-body">
            <div className="zns-title">{T('Mã số may mắn của bạn', 'Your lucky number')}</div>
            <div className="zns-content">{T('Chúc mừng! Bạn đã nhận mã tham gia quay thưởng. Giữ mã này để dò kết quả nhé!', 'Congrats! Here is your draw code. Keep it to check the results!')}</div>
            <ZnsCode label={T('MÃ SỐ DỰ THƯỞNG', 'DRAW NUMBER')} value={d.code || '88-5271-04'} bg="#FFF6E0" bd="#E8C778" fg="#C77E10" />
            <ZnsTable rows={[
              { k: T('Chương trình', 'Program'), v: T('Quay số quà tặng VLF', 'VLF gift draw') },
              { k: T('Ngày quay số', 'Draw date'), v: '27/09/2026 20:00' },
              { k: T('Hình thức', 'Format'), v: T('Livestream trên OA', 'Livestream on OA') },
            ]} />
            <ZnsBtns btns={[
              { t: T('Xem thể lệ & giải thưởng', 'Rules & prizes'), ic: 'info' },
              { t: T('Dò kết quả quay số', 'Check results'), kind: 'ghost', ic: 'star' },
            ]} />
          </div>
          <ZnsFoot tag={ZNS_TAG.t3.t} tagBg={ZNS_TAG.t3.bg} tagFg={ZNS_TAG.t3.fg} />
        </div>
      );

    case 'news':
      return (
        <div className="zns">
          <ZnsLogo />
          <ZnsBanner label={T('ẢNH BÌA BẢN TIN 16:9', 'NEWSLETTER COVER 16:9')} a="#E7E2EE" b="#DDD5E7" />
          <div className="zns-body">
            <div className="zns-title">{T('Bản tin tuần · VLF 2026', 'Weekly digest · VLF 2026')}</div>
            <div className="zns-content">{T('Tổng hợp tin tức nổi bật của giải dành cho bạn.', 'This week’s highlights from the festival.')}</div>
            <div className="zns-news">
              {[[T('60 huyền thoại xác nhận góp mặt', '60 legends confirmed'), T('2 giờ trước · Tin giải', '2h ago · News')],
                [T('Lịch thi đấu vòng chung kết', 'Final round schedule'), T('5 giờ trước · Lịch đấu', '5h ago · Schedule')],
                [T('Top khoảnh khắc đẹp nhất tuần', 'Best moments of the week'), T('1 ngày trước · Video', '1d ago · Video')]].map((n, i) => (
                  <div className="zns-newsrow" key={i}><div className="zns-newsthumb" /><div><div className="tt">{n[0]}</div><div className="mt">{n[1]}</div></div></div>
                ))}
            </div>
            <ZnsBtns btns={[{ t: T('Đọc tất cả bản tin', 'Read all news'), ic: 'star' }]} />
          </div>
          <ZnsFoot tag={ZNS_TAG.t3.t} tagBg={ZNS_TAG.t3.bg} tagFg={ZNS_TAG.t3.fg} />
        </div>
      );

    default:
      return null;
  }
}

/* ============================================================
   Dựng hội thoại nền + sinh tin theo trigger
   ============================================================ */
const OA_NOW = { vi: 'Vừa xong', en: 'Just now' };
let _oaSeed = 0;

function seedOAThread(persona, lang) {
  _oaSeed = 0;
  const nm = oaName(persona);
  const id = () => 'seed_' + (_oaSeed++);
  return [
    { id: id(), view: 'day', text: { vi: 'Hôm qua', en: 'Yesterday' } },
    { id: id(), from: 'oa', view: 'text', text: { vi: 'Xin chào ' + nm + ' 👋 VLF 2026 OA luôn sẵn sàng hỗ trợ bạn về vé, lịch thi đấu và sự kiện.', en: 'Hi ' + nm + ' 👋 VLF 2026 OA is here to help with tickets, schedule and the event.' }, time: { vi: 'Hôm qua 18:30', en: 'Yesterday 18:30' } },
    { id: id(), from: 'oa', view: 'zns', zt: 'miniapp_invite', d: { persona }, time: { vi: 'Hôm qua 18:30', en: 'Yesterday 18:30' } },
    { id: id(), view: 'day', text: { vi: 'Hôm nay', en: 'Today' } },
    { id: id(), from: 'me', view: 'text', text: { vi: 'Cảm ơn OA, mình muốn xem vé và lịch thi đấu.', en: 'Thanks OA, I’d like to see tickets and schedule.' }, time: { vi: '09:10', en: '09:10' }, seen: true },
    { id: id(), from: 'oa', view: 'text', text: { vi: 'Dạ, bạn có thể thao tác trực tiếp trong Mini App bên trái — mọi cập nhật vé, đơn hàng & nhắc lịch sẽ được gửi về đây.', en: 'Sure — do everything in the Mini App on the left; ticket, order & schedule updates land right here.' }, time: { vi: '09:11', en: '09:11' } },
    { id: id(), from: 'oa', view: 'chips', items: [{ vi: 'Mua vé', en: 'Buy ticket' }, { vi: 'Lịch thi đấu', en: 'Schedule' }, { vi: 'Hỗ trợ', en: 'Support' }] },
  ];
}

/* mỗi trigger → 1..2 tin (text dẫn + thẻ ZNS) */
function buildOAMessages(type, payload, ctx) {
  ctx = ctx || {};
  const seq = ctx.seq || Date.now();
  const persona = ctx.persona;
  const id = (k) => 'oa_' + seq + '_' + k;
  const out = [];
  const push = (m) => out.push(Object.assign({ id: id(out.length), from: 'oa', time: OA_NOW }, m));

  if (type === 'order_ticket') {
    const o = (payload && payload.order) || {};
    const tk = (payload && payload.ticket) || {};
    push({ view: 'text', text: { vi: 'Thanh toán thành công ✓ Vé điện tử của bạn đã được phát hành.', en: 'Payment successful ✓ Your e-ticket has been issued.' } });
    push({ view: 'zns', zt: 'order_ticket', d: { ref: o.ref, total: o.total, ticket: tk.name, code: tk.code } });
  } else if (type === 'order_shop') {
    const o = payload || {};
    const first = (o.items && o.items[0]) || {};
    const more = (o.items && o.items.length > 1) ? ' +' + (o.items.length - 1) : '';
    push({ view: 'text', text: { vi: 'Đơn hàng quà lưu niệm của bạn đã được xác nhận.', en: 'Your merchandise order is confirmed.' } });
    push({ view: 'zns', zt: 'order_shop', d: { ref: o.ref, total: o.total, deliv: o.deliv, itemLine: (first.name || '—') + (first.qty ? ' ×' + first.qty : '') + more } });
  } else if (type === 'invite_activated') {
    const tk = payload || {};
    push({ view: 'text', text: { vi: 'Vé mời đã kích hoạt thành công 🎫', en: 'Your invite has been activated 🎫' } });
    push({ view: 'zns', zt: 'invite_activated', d: { ticket: tk.name, code: tk.code, attendee: tk.attendee, persona } });
  } else if (type === 'invite_code') {
    push({ view: 'text', text: { vi: 'Bạn vừa được nhà tài trợ gửi một vé mời VLF 2026.', en: 'A sponsor just sent you a VLF 2026 invitation.' } });
    push({ view: 'zns', zt: 'invite_code', d: { code: 'A7K9X' } });
  } else if (type === 'invite_reminder') {
    push({ view: 'zns', zt: 'invite_reminder', d: { code: 'A7K9X' } });
  } else if (type === 'schedule') {
    push({ view: 'text', text: { vi: 'Nhắc bạn lịch sắp tới tại VLF 2026.', en: 'A reminder of your upcoming VLF 2026 schedule.' } });
    push({ view: 'zns', zt: 'schedule', d: {} });
  } else if (type === 'result') {
    push({ view: 'zns', zt: 'result', d: {} });
  } else if (type === 'checkin') {
    push({ view: 'zns', zt: 'checkin', d: { persona, code: 'CK-728193' } });
  } else if (type === 'lucky') {
    push({ view: 'zns', zt: 'lucky', d: {} });
  } else if (type === 'miniapp_invite') {
    push({ view: 'zns', zt: 'miniapp_invite', d: { persona } });
  } else if (type === 'news') {
    push({ view: 'text', text: { vi: 'Tin truyền thông · Bản tin tuần đã đến!', en: 'Broadcast · this week’s digest is here!' } });
    push({ view: 'zns', zt: 'news', d: {} });
  }
  return out;
}

/* danh mục trigger OA chủ động (cho panel demo) */
if (window.VLF) window.VLF.oaTriggers = [
  { id: 'invite_code', vi: 'Gửi mã vé mời', en: 'Send invite code', note: { vi: 'BTC gửi mã 5 ký tự → kích hoạt trong Mini App', en: 'Sponsor sends a 5-char code → activate in Mini App' } },
  { id: 'invite_reminder', vi: 'Nhắc kích hoạt mã', en: 'Activation reminder', note: { vi: 'Đếm ngược · sắp hết hạn mã mời', en: 'Countdown · invite code expiring' } },
  { id: 'schedule', vi: 'Nhắc lịch thi đấu', en: 'Schedule reminder', note: { vi: 'Tee time / nội dung sắp diễn ra', en: 'Upcoming tee time / session' } },
  { id: 'checkin', vi: 'Cảm ơn check-in', en: 'Check-in thanks', note: { vi: 'Khi quét vé tại cổng', en: 'When ticket is scanned at gate' } },
  { id: 'result', vi: 'Kết quả vòng đấu', en: 'Round results', note: { vi: 'BXH cập nhật sau vòng', en: 'Leaderboard after a round' } },
  { id: 'lucky', vi: 'Mã số may mắn', en: 'Lucky number', note: { vi: 'Mã dự thưởng quay số', en: 'Lucky-draw code' } },
  { id: 'news', vi: 'Bản tin tuần', en: 'Weekly digest', note: { vi: 'Broadcast vào hộp thư chính', en: 'Broadcast to the main inbox' } },
];

Object.assign(window, { ZNSRender, seedOAThread, buildOAMessages });
