/* ===== DATA ===== */
const DISCOUNT = 0.30;
function disc(p) { return Math.round(p * (1 - DISCOUNT)); }

const products = {
  'Instant 51010': [
    { size: '$5,000',   price: 55,   profitTarget: '10%', dailyLoss: '5% ($250)',    maxLoss: '10% ($500)',    buyingPower: '$500,000',    fixedSpread: true,  riskConsistency: 'removed' },
    { size: '$10,000',  price: 95,   profitTarget: '10%', dailyLoss: '5% ($500)',    maxLoss: '10% ($1,000)',  buyingPower: '$1,000,000',  fixedSpread: true,  riskConsistency: 'removed' },
    { size: '$25,000',  price: 245,  profitTarget: '10%', dailyLoss: '5% ($1,250)',  maxLoss: '10% ($2,500)',  buyingPower: '$2,500,000',  fixedSpread: true,  riskConsistency: 'removed' },
    { size: '$50,000',  price: 360,  profitTarget: '10%', dailyLoss: '5% ($2,500)',  maxLoss: '10% ($5,000)',  buyingPower: '$5,000,000',  fixedSpread: false, riskConsistency: 'removed', featured: true },
    { size: '$100,000', price: 690,  profitTarget: '10%', dailyLoss: '5% ($5,000)',  maxLoss: '10% ($10,000)', buyingPower: '$10,000,000', fixedSpread: false, riskConsistency: '2%' },
    { size: '$200,000', price: 1340, profitTarget: '10%', dailyLoss: '5% ($10,000)', maxLoss: '10% ($20,000)', buyingPower: '$20,000,000', fixedSpread: false, riskConsistency: '2%' },
  ],
  'Instant 510Zero': [
    { size: '$5,000',   price: 65,   profitTarget: 'N/A', dailyLoss: '5% ($250)',    maxLoss: '10% ($500)',    buyingPower: '$500,000',    fixedSpread: true,  riskConsistency: 'removed' },
    { size: '$10,000',  price: 105,  profitTarget: 'N/A', dailyLoss: '5% ($500)',    maxLoss: '10% ($1,000)',  buyingPower: '$1,000,000',  fixedSpread: true,  riskConsistency: 'removed' },
    { size: '$25,000',  price: 275,  profitTarget: 'N/A', dailyLoss: '5% ($1,250)',  maxLoss: '10% ($2,500)',  buyingPower: '$2,500,000',  fixedSpread: true,  riskConsistency: 'removed' },
    { size: '$50,000',  price: 410,  profitTarget: 'N/A', dailyLoss: '5% ($2,500)',  maxLoss: '10% ($5,000)',  buyingPower: '$5,000,000',  fixedSpread: false, riskConsistency: 'removed', featured: true },
    { size: '$100,000', price: 800,  profitTarget: 'N/A', dailyLoss: '5% ($5,000)',  maxLoss: '10% ($10,000)', buyingPower: '$10,000,000', fixedSpread: false, riskConsistency: '2%' },
    { size: '$200,000', price: 1560, profitTarget: 'N/A', dailyLoss: '5% ($10,000)', maxLoss: '10% ($20,000)', buyingPower: '$20,000,000', fixedSpread: false, riskConsistency: '2%' },
  ],
};

const challengeData = {
  '$10,000':  { price: 45,  daily: '$500',   overall: '$1,000',  profit1: '$800',   profit2: '$600' },
  '$25,000':  { price: 100, daily: '$1,250',  overall: '$2,500',  profit1: '$2,000', profit2: '$1,500' },
  '$50,000':  { price: 175, daily: '$2,500',  overall: '$5,000',  profit1: '$4,000', profit2: '$3,000', featured: true },
  '$100,000': { price: 320, daily: '$5,000',  overall: '$10,000', profit1: '$8,000', profit2: '$6,000' },
};

const traders = [
  { country: 'Thailand',     code: 'th', name: 'Teerapong', payout: 7864.52,  img: './public/Thailand_Trader_Payout.png' },
  { country: 'Malaysia',     code: 'my', name: 'Safarrizal', payout: 7599.66, img: './public/Malaysia Trader Payout.png' },
  { country: 'Canada',       code: 'ca', name: 'Michael',   payout: 12133.08, img: './public/Canada Trader Payout.png' },
  { country: 'Egypt',        code: 'eg', name: 'Eslam',     payout: 9356.77,  img: './public/Egypt Trader Payout.png' },
  { country: 'Saudi Arabia', code: 'sa', name: 'Amed',      payout: 5443.79,  img: './public/Saudi Arabia Trader Payout.png' },
  { country: 'Malaysia',     code: 'my', name: 'Jonathan',  payout: 2071.84,  img: './public/Malaysia Trader Payout.png' },
];

const wmtTraders = [
  { id: 'Yk7c2Lfkndc', title: 'How an Iraq female trader turned one year of learning into a $5,011.25 payout?' },
  { id: '4_L_YXizBCM', title: 'Malaysia Trader Shares His First Payout Experience With WeMasterTrade' },
  { id: 'oOJjqlc6nm0', title: 'Successful Payout Story From A Young Trader In Uzbekistan' },
  { id: 'uYcP-Mi1uOo', title: 'Simple Trading Strategy Success Story From An Indonesian Female Trader' },
  { id: 'b_gD0fnIUjY', title: 'From Uzbekistan: A Trader Who Chose Discipline Over Emotion With WeMasterTrade' },
  { id: 'ZRYJPNDlrIY', title: 'A Thai trader secures a $13,834.00 payout with WeMasterTrade by following strict risk management' },
  { id: '364y1bNK4JM', title: 'Consistency in action as a Thailand trader secures his second $15,425.20 payout with WeMasterTrade' },
  { id: 'J01Ex546EIo', title: '$2,817.67 Payout From WeMasterTrade! After Multiple Attempts A Singapore Trader Succeeds' },
  { id: 'hDrRV5CESXc', title: 'Indonesia Trader Achieves A Successful Payout At WeMasterTrade After A 16 Year Trading Journey' },
  { id: 'LLKkxlq59Bk', title: 'A Real Trading Interview | A $32,714.28 payout achieved by a female trader with WeMasterTrade' },
  { id: 'zaYeu-tRN4c', title: 'How a trader from Canada maintains discipline and earns his second payout with WeMasterTrade' },
  { id: 'SI58W75uHKE', title: 'A Saudi Veteran Returns for His Second WeMasterTrade Interview' },
];

/* ===== COUPON COPY ===== */
function initCoupon() {
  const btn = document.getElementById('coupon-btn');
  if (!btn) return;
  btn.addEventListener('click', () => {
    navigator.clipboard.writeText('NEWUSER30').then(() => {
      btn.textContent = t('coupon_copied');
      setTimeout(() => { btn.textContent = t('coupon_copy'); }, 2000);
    });
  });
}

/* ===== SCROLL TO PRODUCTS ===== */
function initScrollBtn() {
  const btn = document.getElementById('see-packages-btn');
  if (!btn) return;
  btn.addEventListener('click', () => {
    document.getElementById('products')?.scrollIntoView({ behavior: 'smooth' });
  });
}

/* ===== HERO TRADER ===== */
window.traderIndex = 0;
let animFrame = null;

function formatPayout(val) {
  return '$' + val.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

function easeOutQuart(t) { return 1 - Math.pow(1 - t, 4); }

function animateNumber(targetEl, target) {
  if (animFrame) cancelAnimationFrame(animFrame);
  const duration = 2000;
  let start = null;
  function step(ts) {
    if (!start) start = ts;
    const pct = Math.min((ts - start) / duration, 1);
    targetEl.textContent = formatPayout(target * easeOutQuart(pct));
    if (pct < 1) animFrame = requestAnimationFrame(step);
  }
  animFrame = requestAnimationFrame(step);
}

function renderTrader(idx) {
  const tr = traders[idx];
  const card = document.getElementById('hero-trader-card');
  if (!card) return;
  card.querySelector('.trader-payout-label').textContent = `${t('recent_payout_to')} [${tr.name}]`;
  card.querySelector('.trader-img').src = tr.img;
  card.querySelector('.trader-flag-img').src = `https://flagcdn.com/w40/${tr.code}.png`;
  card.querySelector('.trader-name-text').textContent = tr.name;
  animateNumber(card.querySelector('.trader-payout-amount'), tr.payout);
}

function initHeroTrader() {
  if (!document.getElementById('hero-trader-card')) return;
  renderTrader(0);
  setInterval(() => {
    window.traderIndex = (window.traderIndex + 1) % traders.length;
    renderTrader(window.traderIndex);
  }, 6000);
}

/* ===== MARQUEE ===== */
function initMarquee() {
  const track = document.getElementById('marquee-track');
  if (!track) return;
  const items = wmtTraders.map(wt => `
    <a href="https://www.youtube.com/watch?v=${wt.id}" target="_blank" rel="noopener noreferrer" class="trader-card-item">
      <div class="trader-thumb">
        <img src="https://i.ytimg.com/vi/${wt.id}/hqdefault.jpg" alt="${wt.title}" loading="lazy" referrerpolicy="no-referrer">
        <div class="trader-thumb-overlay">
          <div class="play-btn">
            <svg width="28" height="28" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>
          </div>
        </div>
      </div>
      <div class="trader-card-meta">
        <div class="wmt-badge">WMT</div>
        <div class="trader-card-title">${wt.title}</div>
      </div>
    </a>`).join('');
  track.innerHTML = items + items; // duplicate for infinite scroll
}

/* ===== PRODUCT SELECTOR ===== */
let activeTab = 'Instant 51010';

function productCardHTML(p) {
  return `
    <div class="product-card${p.featured ? ' featured' : ''}">
      ${p.featured ? `<div class="best-value-badge">${t('best_value')}</div>` : ''}
      <div class="card-size">${p.size}</div>
      <div class="card-size-label">${t('card_account')}</div>
      <a href="https://my.wemastertrade.com/en/register/" target="_blank" rel="noopener noreferrer" class="card-cta">${t('card_cta_instant')}</a>
      <div class="card-price-area">
        <span class="card-orig">$${p.price}</span>
        <span class="card-disc">$${disc(p.price)}</span>
      </div>
      <div class="card-price-label">${t('card_fee')}</div>
      <div class="card-divider"></div>
      <div class="card-features">
        <div class="card-feat-row">
          <span class="card-feat-label">${t('feat_profit_target')}</span>
          <span class="card-feat-val${p.profitTarget === 'N/A' ? ' tag-none' : ''}">${p.profitTarget}</span>
        </div>
        <div class="card-feat-row">
          <span class="card-feat-label">${t('feat_daily_loss')}</span>
          <span class="card-feat-val">${p.dailyLoss}</span>
        </div>
        <div class="card-feat-row">
          <span class="card-feat-label">${t('feat_max_loss')}</span>
          <span class="card-feat-val">${p.maxLoss}</span>
        </div>
        <div class="card-feat-row">
          <span class="card-feat-label">${t('feat_buying_power')}</span>
          <span class="card-feat-val">${p.buyingPower}</span>
        </div>
        <div class="card-feat-row">
          <span class="card-feat-label">${t('feat_swap_fee')}</span>
          <span class="card-feat-val">${t('feat_free_swap')}</span>
        </div>
        <div class="card-feat-row">
          <span class="card-feat-label">${t('feat_profit_split')}</span>
          <span class="card-feat-val">90%</span>
        </div>
      </div>
    </div>`;
}

function challengeCardsHTML() {
  return Object.entries(challengeData).map(([size, d]) => `
    <div class="product-card${d.featured ? ' featured' : ''}">
      ${d.featured ? `<div class="best-value-badge">${t('best_value')}</div>` : ''}
      <div class="card-size">${size}</div>
      <div class="card-size-label">${t('card_account')}</div>
      <a href="https://my.wemastertrade.com/en/register/" target="_blank" rel="noopener noreferrer" class="card-cta">${t('card_cta_challenge')}</a>
      <div class="card-price-area">
        <span class="card-orig">$${d.price}</span>
        <span class="card-disc">$${disc(d.price)}</span>
      </div>
      <div class="card-price-label">${t('card_fee_challenge')}</div>
      <div class="card-divider"></div>
      <div class="card-features">
        <div class="card-feat-row">
          <span class="card-feat-label">${t('feat_profit_target')}</span>
          <span class="card-feat-val card-feat-val-stack">
            <span>Phase 1: 8%</span>
            <span>Phase 2: 6%</span>
          </span>
        </div>
        <div class="card-feat-row">
          <span class="card-feat-label">${t('feat_daily_loss')}</span>
          <span class="card-feat-val">5% (${d.daily})</span>
        </div>
        <div class="card-feat-row">
          <span class="card-feat-label">${t('feat_max_loss')}</span>
          <span class="card-feat-val">10% (${d.overall})</span>
        </div>
        <div class="card-feat-row">
          <span class="card-feat-label">${t('feat_swap_fee')}</span>
          <span class="card-feat-val">${t('feat_free_swap')}</span>
        </div>
        <div class="card-feat-row">
          <span class="card-feat-label">${t('feat_profit_share')}</span>
          <span class="card-feat-val card-feat-val-stack">
            <span>Phase 2: 30%</span>
            <span>Funded: 90%</span>
          </span>
        </div>
        <div class="card-feat-row">
          <span class="card-feat-label">${t('feat_leverage')}</span>
          <span class="card-feat-val">1:100</span>
        </div>
        <div class="card-feat-row">
          <span class="card-feat-label">${t('feat_reset_disc')}</span>
          <span class="card-feat-val">30%</span>
        </div>
      </div>
    </div>`).join('');
}

function positionSubSlider(animate, startX, startW) {
  const inner = document.getElementById('instant-toggle');
  if (!inner) return;
  const active = inner.querySelector('.tab-sub-btn.active');
  if (!active) return;

  let slider = inner.querySelector('.tab-sub-slider');
  if (!slider) {
    slider = document.createElement('div');
    slider.className = 'tab-sub-slider';
    inner.appendChild(slider);
  }

  const tx = active.offsetLeft;
  const w  = active.offsetWidth;
  const h  = active.offsetHeight;
  const ty = active.offsetTop;

  if (animate && startX !== undefined) {
    slider.style.transition = 'none';
    slider.style.top = ty + 'px';
    slider.style.height = h + 'px';
    slider.style.width = startW + 'px';
    slider.style.transform = `translateX(${startX}px)`;
    slider.getBoundingClientRect();
    slider.style.transition = 'transform 0.28s cubic-bezier(0.4,0,0.2,1), width 0.28s cubic-bezier(0.4,0,0.2,1)';
    slider.style.width = w + 'px';
    slider.style.transform = `translateX(${tx}px)`;
  } else {
    slider.style.transition = 'none';
    slider.style.top = ty + 'px';
    slider.style.height = h + 'px';
    slider.style.width = w + 'px';
    slider.style.transform = `translateX(${tx}px)`;
  }
}

function renderTabBar(animate = false) {
  const inner = document.getElementById('tab-bar-inner');
  if (!inner) return;

  const isInstant = activeTab === 'Instant 51010' || activeTab === 'Instant 510Zero';
  const isChallenge = activeTab === 'Challenge';

  let startX, startW;
  if (animate && isInstant) {
    const oldActive = inner.querySelector('.tab-sub-btn.active');
    if (oldActive) { startX = oldActive.offsetLeft; startW = oldActive.offsetWidth; }
  }

  const ICON_BOLT    = `<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="m3.75 13.5 10.5-11.25L12 10.5h8.25L9.75 21.75 12 13.5H3.75Z"/></svg>`;
  const ICON_TROPHY  = `<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M6 2v9a6 6 0 0012 0V2H6zM4 5H2v1a4 4 0 004 4V5zm16 0v5a4 4 0 004-4V5h-2zM10 17v1H8v2h8v-2h-2v-1z"/></svg>`;

  inner.innerHTML = `
    <div class="tab-group${isInstant ? ' instant-active' : ''}">
      <span class="tab-group-label"><span class="tab-icon">${ICON_BOLT}</span>${t('tab_instant') || 'Instant'}</span>
      <div class="tab-group-inner" id="instant-toggle">
        <button class="tab-sub-btn${activeTab === 'Instant 51010' ? ' active' : ''}" data-tab="Instant 51010">51010</button>
        <button class="tab-sub-btn${activeTab === 'Instant 510Zero' ? ' active' : ''}" data-tab="Instant 510Zero">510Zero</button>
      </div>
    </div>
    <button class="tab-challenge-btn${isChallenge ? ' active' : ''}" data-tab="Challenge"><span class="tab-icon">${ICON_TROPHY}</span>${t('tab_challenge') || 'Challenge'}</button>
  `;

  inner.querySelectorAll('[data-tab]').forEach(btn => {
    btn.addEventListener('click', () => {
      if (btn.dataset.tab === activeTab) return;
      activeTab = btn.dataset.tab;
      renderTabBar(true);
      renderProducts();
    });
  });

  positionSubSlider(animate, startX, startW);
}

function renderProducts() {
  const grid = document.getElementById('products-grid');
  if (!grid) return;
  grid.className = activeTab === 'Challenge' ? 'cards-scroll cards-center' : 'cards-scroll';
  grid.innerHTML = activeTab === 'Challenge'
    ? challengeCardsHTML()
    : products[activeTab].map(productCardHTML).join('');
}

function initProductSelector() {
  renderTabBar();
  renderProducts();
}

/* ===== REVIEWS ===== */
const reviews = [
  { name: 'Nikito',              time: '11 hours ago', title: 'Good experience',                          text: 'Good experience',                                                                                           rating: 5 },
  { name: 'Josef',               time: '18 hours ago', title: 'Dashboard',                                text: 'I like how the overview is laid out in the Dashboard.',                                                   rating: 5 },
  { name: 'Dieudonne Chrameh',   time: '21 hours ago', title: 'A thumbs up to WeMasterTrade.',            text: 'A thumbs up to WeMasterTrade. I received my 1st payout yesterday in 10.3 seconds. I was surprised, no prop firm does that.', rating: 5 },
  { name: 'Nikola',              time: '1 day ago',    title: 'Best',                                     text: 'Best prop company',                                                                                         rating: 5 },
  { name: 'TomÃ¡Å¡',     time: '3 days ago',   title: 'Absolutely top prop firm in the world :)', text: 'Absolutely top prop firm in the world :)',                                                                  rating: 5 },
  { name: 'customer',            time: '4 days ago',   title: 'I think this WMT is realy good...',        text: 'I think WeMasterTrade is a really good option for beginners because it fights your greed by strict risk management.', rating: 4 },
  { name: 'Kazuhumi',            time: '4 days ago',   title: 'Understandable',                           text: 'Very easy to understand the goals and rules for the challenge.',                                            rating: 5 },
  { name: 'Piotr',               time: '5 days ago',   title: 'Super Å›wietne',                       text: 'Super Å›wietne',                                                                                        rating: 5 },
];

function starHTML(rating) {
  return Array.from({ length: 5 }, (_, i) =>
    `<div class="r-star${i >= rating ? ' empty' : ''}"><svg width="12" height="12" viewBox="0 0 24 24" fill="white"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg></div>`
  ).join('');
}

function renderReviews() {
  const grid = document.getElementById('reviews-grid');
  if (!grid) return;
  grid.innerHTML = reviews.map(r => `
    <div class="review-card">
      <div class="review-stars-row">
        <div class="review-stars">${starHTML(r.rating)}</div>
        <div class="verified-badge">
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
          ${t('tp_verified')}
        </div>
      </div>
      <div class="review-meta">
        <span class="name">${r.name}</span><span>,</span><span>${r.time}</span>
      </div>
      <h4 class="review-title">${r.title}</h4>
      <p class="review-text">${r.text}</p>
    </div>`).join('');
}

/* ===== DISCOUNT POPUP ===== */
function initPopup() {
  const overlay = document.getElementById('discount-popup');
  const closeBtn = document.getElementById('popup-close');
  if (!overlay) return;
  let shown = false;

  function show() {
    if (shown) return;
    shown = true;
    overlay.classList.remove('hidden');
    requestAnimationFrame(() => overlay.classList.add('visible'));
  }
  function hide() {
    overlay.classList.remove('visible');
    setTimeout(() => overlay.classList.add('hidden'), 300);
  }

  window.addEventListener('scroll', () => {
    if (shown) return;
    const el = document.getElementById('trading-platforms');
    if (el && el.getBoundingClientRect().top < window.innerHeight * 0.75) show();
  }, { passive: true });

  closeBtn?.addEventListener('click', hide);
  overlay.addEventListener('click', e => { if (e.target === overlay) hide(); });
}

/* ===== INIT ===== */
document.addEventListener('DOMContentLoaded', () => {
  initCoupon();
  initScrollBtn();
  initHeroTrader();
  initMarquee();
  initProductSelector();
  renderReviews();
  initPopup();
});
