/* ============================================================
   VLF 2026 · HOME — Trang chủ (theo persona + phase)
   props: persona, phase ('pre'|'live'), nav(screen,params)
   ============================================================ */
function useCountdown(iso) {
  const [now, setNow] = useState(Date.now());
  React.useEffect(() => {
    const id = setInterval(() => setNow(Date.now()), 1000 * 30);
    return () => clearInterval(id);
  }, []);
  const diff = Math.max(0, new Date(iso).getTime() - now);
  const d = Math.floor(diff / 86400000);
  const h = Math.floor(diff % 86400000 / 3600000);
  const m = Math.floor(diff % 3600000 / 60000);
  return { d, h, m };
}

function Home({ persona, phase, nav, urgent }) {
  const t = useT();const lang = t.lang;const E = (o, k) => window.VLF.L(lang, o, k);
  const ev = window.VLF.event;
  const me = window.VLF.personas[persona].me;
  const cd = useCountdown(ev.countdownTo);
  const live = phase === 'live';
  const post = phase === 'post';
  const [dismissed, setDismissed] = useState(false);
  React.useEffect(() => { setDismissed(false); }, [urgent]);
  const champ = window.VLF.post.champions[0];

  const isGolfer = persona === 'golfer' || persona === 'golfer_intl';
  const greetMap = {
    golfer: lang === 'en' ? 'Hi, golfer' : 'Chào golfer',
    golfer_intl: lang === 'en' ? 'Welcome, legend' : 'Chào golfer',
    guest: lang === 'en' ? 'Welcome, guest' : 'Chào khách mời',
    spectator: lang === 'en' ? 'Hello' : 'Xin chào',
    vip: lang === 'en' ? 'Welcome' : 'Kính chào'
  };

  const QA = {
    golfer: [
    { ic: 'trophy', nm: t('leaderboard'), go: ['compete', { sub: 'leaderboard' }] },
    { ic: 'clock', nm: t('teetime'), go: ['compete', { sub: 'teetime' }] },
    { ic: 'village', nm: t('village'), go: ['village'] },
    { ic: 'bell', nm: t('messages'), go: ['messages'] }],

    golfer_intl: [
    { ic: 'trophy', nm: t('leaderboard'), go: ['compete', { sub: 'leaderboard' }] },
    { ic: 'clock', nm: t('teetime'), go: ['compete', { sub: 'teetime' }] },
    { ic: 'shield', nm: t('prep'), go: ['prep'] },
    { ic: 'village', nm: t('village'), go: ['village'] }],

    guest: [
    { ic: 'ticket', nm: t('myticket'), go: ['ticket'] },
    { ic: 'gala', nm: 'Gala', go: ['rsvp'] },
    { ic: 'map', nm: t('nav_map'), go: ['map'] },
    { ic: 'village', nm: t('village'), go: ['village'] }],

    spectator: [
    { ic: 'ticket', nm: t('buy'), go: ['buy'] },
    { ic: 'village', nm: t('village'), go: ['village'] },
    { ic: 'map', nm: t('nav_map'), go: ['map'] },
    { ic: 'trophy', nm: t('leaderboard'), go: ['compete', { sub: 'leaderboard' }] }],

    vip: [
    { ic: 'shield', nm: t('vipDay'), go: ['viptimeline'] },
    { ic: 'gala', nm: 'Gala', go: ['rsvp'] },
    { ic: 'village', nm: t('village'), go: ['village'] },
    { ic: 'map', nm: t('nav_map'), go: ['map'] }],

    organizer: [
    { ic: 'trophy', nm: t('leaderboard'), go: ['compete', { sub: 'leaderboard' }] },
    { ic: 'clock', nm: t('teetime'), go: ['compete', { sub: 'teetime' }] },
    { ic: 'bell', nm: t('messages'), go: ['messages'] },
    { ic: 'calendar', nm: t('schedule'), go: ['schedule'] }],

    volunteer: [
    { ic: 'map', nm: t('nav_map'), go: ['map'] },
    { ic: 'clock', nm: t('teetime'), go: ['compete', { sub: 'teetime' }] },
    { ic: 'bell', nm: t('messages'), go: ['messages'] },
    { ic: 'calendar', nm: t('schedule'), go: ['schedule'] }]

  }[persona];

  const legends = window.VLF.leaderboard.legends;
  const myTee = window.VLF.teeTimes['25'][0];

  return (
    <div className="v-screen" style={{ paddingBottom: 'calc(60px + var(--zalo-safe-bottom))' }}>
      {/* hero */}
      <div className="v-hero">
        <div className="v-hero-top">
          <div className="v-hero-greet">{post ? t('thanksLine') : greetMap[persona]}<br /><b>{me.name}</b></div>
          {live && <span className="v-live"><i />Live</span>}
        </div>
        <h1>Vietnam <em>Legends</em> Festival</h1>
        <div className="v-hero-rule" />
        <button className="v-hero-sub v-hero-loc" onClick={() => nav('map')}><Icon name="map" size={14} sw={1.8} />{ev.venue} · {ev.dates}<Icon name="chev" size={14} sw={2.2} className="v-hero-loc-chev" /></button>

        {post ?
        <div className="v-count" style={{ alignItems: 'stretch' }}>
            <div className="u" style={{ flex: 2, textAlign: 'left', paddingLeft: 14, alignItems: 'flex-start' }}>
              <span style={{ marginTop: 0, marginBottom: 4 }}>{t('postEnded')} · {t('champion')}</span>
              <b className="v-num" style={{ fontSize: 19, lineHeight: 1.1 }}>{champ.name}</b>
            </div>
            <div className="u"><b className="v-num" style={{ color: 'var(--vlf-gold-300)' }}>{champ.score}</b><span>Legends</span></div>
          </div> :
        !live ?
        <>
            <div className="v-count">
              <div className="u"><b className="v-num">{cd.d}</b><span>{lang === 'en' ? 'days' : 'ngày'}</span></div>
              <div className="u"><b className="v-num">{String(cd.h).padStart(2, '0')}</b><span>{lang === 'en' ? 'hrs' : 'giờ'}</span></div>
              <div className="u"><b className="v-num">{String(cd.m).padStart(2, '0')}</b><span>{lang === 'en' ? 'min' : 'phút'}</span></div>
            </div>
            <div className="v-hero-sub" style={{ marginTop: 10, fontSize: 11.5 }}>{t('countdown')} · {ev.startDate}</div>
          </> :

        <div className="v-count">
            <div className="u" style={{ flex: 2, textAlign: 'left', padding: '11px 14px', display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'flex-start' }}>
              <span style={{ margin: 0 }}>{t('onGoing')}</span>
              <b className="v-num" style={{ fontSize: 17, marginTop: 5, whiteSpace: 'nowrap' }}>Legends 1 · {lang === 'en' ? 'Round 1' : 'Vòng 1'}</b>
            </div>
            <div className="u"><b className="v-num">{window.VLF.divById('legends').count}</b><span>{lang === 'en' ? 'golfers' : 'golfer'}</span></div>
          </div>
        }
      </div>

      <div className="v-pad">
        {/* banner khẩn realtime (live) — biến thể bật từ panel demo */}
        {live && urgent && !dismissed &&
        <div className="v-alert" onClick={() => nav('message', { id: 3 })}>
            <div className="ic"><Icon name="bell" size={18} sw={1.9} /></div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="t">{lang === 'en' ? 'Urgent · tee times delayed 90 min' : 'Khẩn · tee time lùi 90 phút'}</div>
              <div className="s">{lang === 'en' ? 'Storm warning — see updated schedule' : 'Cảnh báo dông — xem lịch cập nhật'}</div>
            </div>
            <button onClick={(e) => {e.stopPropagation();setDismissed(true);}} aria-label="close"><Icon name="x" size={15} sw={2.2} /></button>
          </div>
        }

        {post ?
        <PostHome persona={persona} nav={nav} /> :
        <>
        {/* GOLFER · live: vị trí của tôi */}
        {isGolfer && live &&
          <>
            <div className="v-sect"><h3>{t('myPos')}</h3><a onClick={() => nav('golfer', { name: me.name })}>{t('profile')} ›</a></div>
            <div className="v-card" style={{ padding: 16, display: 'flex', alignItems: 'center', gap: 14 }}>
              <div style={{ textAlign: 'center', flex: '0 0 auto' }}>
                <div style={{ fontSize: 34, fontWeight: 800, color: 'var(--vlf-purple-700)', lineHeight: 1 }} className="v-num">T9</div>
                <div className="v-tag" style={{ marginTop: 6 }}>Legends</div>
              </div>
              <div style={{ width: 1, alignSelf: 'stretch', background: 'var(--vlf-line)' }} />
              <div style={{ flex: 1 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
                  <span className="v-muted" style={{ fontSize: 12 }}>{t('total')}</span><Score n={-1} className="" />
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                  <span className="v-muted" style={{ fontSize: 12 }}>{t('today')} · {t('thru')} F</span><Score n={0} className="" />
                </div>
              </div>
            </div>
          </>
          }

        {/* GOLFER: tee time kế tiếp */}
        {isGolfer &&
          <>
            <div className="v-sect"><h3>{t('nextTee')}</h3><a onClick={() => nav('compete', { sub: 'teetime' })}>{t('viewAll')} ›</a></div>
            <div className="v-card" style={{ padding: '15px 16px', display: 'flex', alignItems: 'center', gap: 14, cursor: 'pointer' }} onClick={() => nav('compete', { sub: 'teetime' })}>
              <div style={{ textAlign: 'center', flex: '0 0 auto' }}>
                <div className="v-tee-time" style={{ fontSize: 24, lineHeight: 1.1 }}>{myTee.time}</div>
                <div className="v-muted" style={{ fontSize: 11, marginTop: 3 }}>T6 · 25/09</div>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 600, fontSize: 14 }}>Legends 1 · {lang === 'en' ? 'Hole' : 'Hố'} {myTee.hole}</div>
                <div className="v-muted" style={{ fontSize: 12, marginTop: 3 }}>{lang === 'en' ? 'With' : 'Cùng'} {myTee.g.slice(0, 2).join(', ')}</div>
              </div>
              <Icon name="chev" size={20} style={{ color: 'var(--vlf-ink-500)' }} />
            </div>
          </>
          }

        {/* VIP: lịch trình riêng + concierge */}
        {persona === 'vip' &&
          <>
            <div className="v-sect"><h3>{t('vipDay')}</h3><a onClick={() => nav('viptimeline')}>{t('viewAll')} ›</a></div>
            <div className="v-card" style={{ cursor: 'pointer' }} onClick={() => nav('viptimeline')}>
              {window.VLF.vipTimeline.slice(0, 3).map((it, i) =>
              <div className="v-row" key={i} style={{ cursor: 'pointer' }}>
                  <div className="v-tee-time v-num" style={{ fontSize: 16, flex: '0 0 46px', textAlign: 'center' }}>{it.time}</div>
                  <div style={{ flex: 1 }}><div className="t" style={{ fontSize: 14 }}>{E(it, 't')}</div><div className="s">{E(it, 's')}</div></div>
                </div>
              )}
            </div>
            <div className="v-card" style={{ padding: 14, display: 'flex', gap: 11, marginTop: 12, cursor: 'pointer' }} onClick={() => nav('viptimeline')}>
              <div className="v-vip-ic" style={{ background: 'rgba(201,162,75,.16)', color: 'var(--vlf-gold-600)' }}><Icon name="bell" size={20} sw={1.7} /></div>
              <div style={{ flex: 1 }}><div className="t" style={{ fontWeight: 700 }}>{t('concierge')} · {t('fastlane')}</div><div className="s">{lang === 'en' ? 'Ms. Hương · +84 94 552 028 · 24/7' : 'Ms. Hương · 094 552 028 · trực 24/7'}</div></div>
              <Icon name="chev" size={18} style={{ color: 'var(--vlf-ink-500)' }} />
            </div>
          </>
          }

        {/* SPECTATOR · pre: CTA mua vé */}
        {persona === 'spectator' && !live &&
          <div className="v-feat" style={{ marginTop: 4, cursor: 'pointer' }} onClick={() => nav('buy')}>
            <div className="ov" />
            <div className="tx">
              <span className="v-pill v-pill-gold" style={{ marginBottom: 8 }}>{lang === 'en' ? 'On sale' : 'Đang mở bán'}</span>
              <h4>{lang === 'en' ? 'VLF 2026 spectator tickets' : 'Vé khán giả VLF 2026'}</h4>
              <p>General · VIP Lounge — {lang === 'en' ? 'from' : 'từ'} 200.000₫</p>
            </div>
          </div>
          }

        {/* GUEST: thư mời */}
        {persona === 'guest' &&
          <div className="v-card v-tk" style={{ marginTop: 4 }}>
            <div className="v-qr-head">
              <div><div className="t">{lang === 'en' ? 'Your invitation' : 'Vé mời của bạn'}</div><div className="s">{lang === 'en' ? 'Full pass · VIP grandstand' : 'Trọn giải · Khán đài VIP'}</div></div>
              <Icon name="ticket" size={26} sw={1.5} style={{ color: 'var(--vlf-gold-300)' }} />
            </div>
            <div style={{ padding: 14, display: 'flex', gap: 12 }}>
              <button className="v-btn v-btn-primary" style={{ height: 46, fontSize: 14 }} onClick={() => nav('ticket')}>{lang === 'en' ? 'Open QR ticket' : 'Mở vé QR'}</button>
            </div>
          </div>
          }

        {/* lối tắt (động theo persona) — đặt trên khối Xem trực tiếp */}
        <div className="v-qa" style={{ marginTop: 16 }}>
          {QA.map((q, i) =>
            <div className="it" key={i} onClick={() => nav(...q.go)}>
              <div className="ic"><Icon name={q.ic} size={24} sw={1.7} /></div>
              <div className="nm">{q.nm}</div>
            </div>
            )}
        </div>

        {/* live: xem trực tiếp */}
        {live &&
          <div className="v-feat" style={{ marginTop: 16, cursor: 'pointer', height: 124 }} onClick={() => nav('live')}>
            <div className="ov" />
            <div className="tx" style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between' }}>
              <div><span className="v-live" style={{ color: '#fff', marginBottom: 6 }}><i />{t('live')}</span><h4>{t('watchLive')} · Legends 1</h4></div>
              <div style={{ width: 44, height: 44, borderRadius: '50%', background: 'rgba(255,255,255,.92)', color: 'var(--vlf-purple-800)', display: 'flex', alignItems: 'center', justifyContent: 'center', flex: '0 0 auto' }}><Icon name="arrowR" size={20} sw={2} style={{ marginLeft: 2 }} /></div>
            </div>
          </div>
          }

        {/* leaderboard snapshot (live) */}
        {live &&
          <>
            <div className="v-sect"><h3>{t('leaderboardSnap')}</h3><a onClick={() => nav('compete', { sub: 'leaderboard' })}>{t('viewAll')} ›</a></div>
            <div className="v-card">
              {legends.slice(0, 3).map((p) =>
              <div key={p.pos} className={'v-lb-row' + (p.pos === 1 ? ' lead' : '')} onClick={() => nav('golfer', { name: p.name })}>
                  <div className="v-lb-pos">{p.pos}</div>
                  <div className="v-lb-name"><div className="nm">{p.name}</div><CountryDot cc={p.cc} /></div>
                  <Score n={p.total} /><span className="v-lb-sub">{p.thru}</span>
                </div>
              )}
            </div>
          </>
          }

        {/* con số trục (pre) */}
        {!live &&
          <>
            <div className="v-sect"><h3>{t('inNumbers')}</h3></div>
            <div className="v-stats">
              {window.VLF.heroStats.map((s, i) =>
              <div className="v-stat" key={i}><b className="v-num">{s.v}</b><div className="k">{E(s, 'k')}</div><div className="s">{E(s, 's')}</div></div>
              )}
            </div>
          </>
          }

        {/* tin tức / hoạt động bên lề */}
        <div className="v-sect"><h3>{t('newsSide')}</h3><a onClick={() => nav('news')}>{t('viewAll')} ›</a></div>
        <div className="v-card">
          {window.VLF.news.map((a) =>
            <div className="v-row" key={a.id} onClick={() => nav('article', { id: a.id })}>
              <div className="ic" style={{ width: 42, height: 42, borderRadius: 12, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--vlf-purple-50)', color: 'var(--vlf-purple-700)', flex: '0 0 auto' }}><Icon name={a.ic} size={20} sw={1.7} /></div>
              <div style={{ flex: 1, minWidth: 0 }}><div className="t">{E(a, 'title')}</div><div className="s">{E(a, 'lede')}</div></div>
              <Icon name="chev" size={18} className="chev" />
            </div>
            )}
        </div>
        </>}
      </div>
    </div>);

}

Object.assign(window, { Home });

/* ---------- POST-EVENT HOME (phase 'post') ---------- */
function PostHome({ persona, nav }) {
  const t = useT();const lang = t.lang;const E = (o, k) => window.VLF.L(lang, o, k);
  const T = (vi, en) => lang === 'en' ? en : vi;
  const P = window.VLF.post;

  const QA = [
  { ic: 'trophy', nm: t('results'), go: ['results'] },
  { ic: 'search', nm: t('gallery'), go: ['gallery'] },
  { ic: 'arrowR', nm: t('highlightsTitle'), go: ['highlights'] },
  { ic: 'survey', nm: t('survey'), go: ['survey'] }];


  return (
    <>
      {/* nhà vô địch → kết quả */}
      <div className="v-feat" style={{ marginTop: 4, height: 132, cursor: 'pointer' }} onClick={() => nav('results')}>
        <div className="ov" />
        <div className="tx" style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between' }}>
          <div>
            <span className="v-pill v-pill-gold" style={{ marginBottom: 6 }}><Icon name="trophy" size={12} sw={2} />{t('results')}</span>
            <h4 style={{ fontSize: 19 }}>{T('Vinh danh nhà vô địch', 'Champions honoured')}</h4>
          </div>
          <Icon name="chev" size={22} style={{ color: '#fff', opacity: .85 }} />
        </div>
      </div>

      {(persona === 'golfer' || persona === 'golfer_intl') && (() => {
        const meName = window.VLF.personas[persona].me.name;
        const lb = window.VLF.leaderboard.legends.find((p) => p.name === meName) || { pos: '—', total: 0 };
        const isChamp = lb.pos === 1;
        return (
          <div className="v-card" style={{ marginTop: 14, padding: 16, display: 'flex', alignItems: 'center', gap: 14, cursor: 'pointer' }} onClick={() => nav('certificate')}>
            <div style={{ textAlign: 'center', flex: '0 0 auto', minWidth: 46 }}>
              <div className="v-num" style={{ fontSize: 30, fontWeight: 800, color: 'var(--vlf-purple-700)', lineHeight: 1 }}>{isChamp ? '1' : 'T' + lb.pos}</div>
              <div className="v-tag" style={{ marginTop: 6 }}>{T('chung cuộc', 'final')}</div>
            </div>
            <div style={{ width: 1, alignSelf: 'stretch', background: 'var(--vlf-line)' }} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="t" style={{ fontWeight: 700 }}>{isChamp ? T('Chúc mừng nhà vô địch!', 'You are the champion!') : T('Kết quả của bạn', 'Your result')}</div>
              <div className="s">Legends · 54 {T('hố', 'holes')} · <Score n={lb.total} className="v-num" /> · {T('xem chứng nhận', 'view certificate')}</div>
            </div>
            <Icon name="chev" size={18} style={{ color: 'var(--vlf-ink-500)' }} />
          </div>);

      })()}

      {/* lối tắt sau giải */}
      <div className="v-sect"><h3>{t('shortcuts')}</h3></div>
      <div className="v-qa">
        {QA.map((q, i) =>
        <div className="it" key={i} onClick={() => nav(...q.go)}>
            <div className="ic"><Icon name={q.ic} size={24} sw={1.7} /></div>
            <div className="nm">{q.nm}</div>
          </div>
        )}
      </div>

      {/* tìm ảnh của tôi */}
      <div className="v-find" style={{ marginTop: 18 }} onClick={() => nav('findphotos')}>
        <div className="ic"><Icon name="user" size={22} sw={1.8} /></div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="t">{t('findMyPhotos')}</div>
          <div className="s">{(P.myPhotos[persona] || P.myPhotos.spectator).count} {t('myPhotosFound')} · {T('quét để xem', 'scan to view')}</div>
        </div>
        <Icon name="chev" size={20} style={{ color: '#fff', opacity: .8 }} />
      </div>

      {/* chứng nhận */}
      <div className="v-card" style={{ padding: 14, display: 'flex', gap: 12, marginTop: 12, cursor: 'pointer', alignItems: 'center' }} onClick={() => nav('certificate')}>
        <div className="v-vip-ic" style={{ background: 'rgba(201,162,75,.16)', color: 'var(--vlf-gold-600)' }}><Icon name="shield" size={20} sw={1.7} /></div>
        <div style={{ flex: 1 }}><div className="t" style={{ fontWeight: 700 }}>{t('certificate')}</div><div className="s">{E(P.cert[persona] || P.cert.spectator, 'badge')}</div></div>
        <Icon name="chev" size={18} style={{ color: 'var(--vlf-ink-500)' }} />
      </div>

      {/* ưu đãi 2027 */}
      <div className="v-next" style={{ marginTop: 18 }} onClick={() => nav('survey')}>
        <span className="v-pill v-pill-gold" style={{ marginBottom: 8 }}>{P.next.perk}</span>
        <div className="h">{E(P.next, 'title')}</div>
        <div className="s">{E(P.next, 'sub')}</div>
        <button className="v-btn v-btn-gold" style={{ height: 46, marginTop: 14 }}>{t('registerInterest')}</button>
      </div>

      {/* tin & hoạt động */}
      <div className="v-sect"><h3>{t('newsSide')}</h3><a onClick={() => nav('news')}>{t('viewAll')} ›</a></div>
      <div className="v-card">
        {window.VLF.news.slice(0, 3).map((a) =>
        <div className="v-row" key={a.id} onClick={() => nav('article', { id: a.id })}>
            <div className="ic" style={{ width: 42, height: 42, borderRadius: 12, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--vlf-purple-50)', color: 'var(--vlf-purple-700)', flex: '0 0 auto' }}><Icon name={a.ic} size={20} sw={1.7} /></div>
            <div style={{ flex: 1, minWidth: 0 }}><div className="t">{E(a, 'title')}</div><div className="s">{E(a, 'lede')}</div></div>
            <Icon name="chev" size={18} className="chev" />
          </div>
        )}
      </div>
    </>);

}

Object.assign(window, { PostHome });