// mycards-data.jsx — Inventory items wrapping COLLECTION + FAN_CARDS + COACH_CARDS
// from lineup-data with the metadata My Cards needs: instance_id, acquired_at,
// source (which pack/mission), last_used (linked deck submission), status, and a
// "isNew" flag for the freshness ribbon. Plus i18n for screen-only strings.

// ─── screen-only i18n strings ───────────────────────────────────────────────
const MC_I18N = {
  fa: {
    title: 'رختکن',
    subtitle: (n) => `${n} کارت فعال`,
    back: 'بازگشت',
    coin: 'سکه',
    notif: 'اعلان',

    // tabs
    tabAll:    'همه',
    tabPlayer: 'بازیکن',
    tabNull:   'وایلدکارد',
    tabFan:    'هواداری',
    tabCoach:  'مربی',

    // counts strip
    countCards: (n) => `${n} کارت`,
    countTotal: 'مجموع',

    // filters
    filterTier:     'سطح',
    filterPosition: 'پست',
    filterStatus:   'وضعیت',
    filterTeam:     'تیم',
    statusAvailable: 'فعال',
    statusReserved:  'در ترکیب',
    statusExpired:   'منقضی',

    // search
    search: 'جستجو در کارت‌ها…',
    searchHint: 'نام بازیکن، تیم، مربی یا شرط',

    // sort
    sortLabel: 'مرتب‌سازی',
    sortOverall: 'بالاترین امتیاز',
    sortRecent:  'جدیدترین',
    sortTier:    'بالاترین سطح',
    sortName:    'الفبایی',
    sortTeam:    'تیم/کشور',
    sortPosition:'پست',

    // view
    viewGrid: 'شبکه',
    viewList: 'لیست',

    // labels on cards
    badgeNew:      'جدید',
    badgeMission:  'برای ماموریت طلایی',
    overlayInDeck: 'در ترکیب',
    overlayExpired:'منقضی',

    // modal · player
    posScoresTitle: 'امتیاز در پست‌ها',
    posScoresHint:  'بازیکن در پست اصلی بیشترین کارایی را دارد',
    mainPos:        'پست اصلی',

    // modal · coach
    multiplierLabel: 'ضریب امتیاز پایه',
    coachUseTimes:   'استفاده',
    coachAvgScore:   'میانگین امتیاز',
    coachBestScore:  'بهترین امتیاز',
    coachUnlockedAt: 'چطور آزاد شد',

    // modal · fan
    fanBonusLabel:   'بنوس امتیاز',
    fanUseTimes:     'استفاده',
    fanTotalBonus:   'مجموع بنوس داده‌شده',
    fanRelatedCount: 'بازیکن مرتبط',
    fanSource:       'منبع',

    // modal · meta
    metaAcquired:  'تاریخ دریافت',
    metaSource:    'منبع',
    metaLastUsed:  'آخرین استفاده',
    metaInstance:  'شناسه',
    metaStatus:    'وضعیت',
    metaNeverUsed: 'استفاده نشده',

    // modal actions
    actAddToLineup:  'استفاده در ترکیب',
    actViewHistory:  'تاریخچه استفاده',
    actShare:        'اشتراک‌گذاری',
    actClose:        'بستن',

    // empty
    emptyTitle: 'هنوز کارتی نداری',
    emptySub:   'اولین پک رو باز کن و کلکسیون رو شروع کن',
    emptyCta:   'باز کردن اولین پک',

    // sponsor
    sponsorEyebrow: 'با حمایت',
    sponsorCta:     'بیشتر بدانید',
  },
  en: {
    title: 'Locker',
    subtitle: (n) => `${n} active cards`,
    back: 'Back',
    coin: 'Coin',
    notif: 'Notifications',

    tabAll: 'All', tabPlayer: 'Players', tabNull: 'Wildcard', tabFan: 'Fan', tabCoach: 'Coach',

    countCards: (n) => `${n} cards`,
    countTotal: 'Total',

    filterTier: 'Tier', filterPosition: 'Position', filterStatus: 'Status', filterTeam: 'Team',
    statusAvailable: 'Available', statusReserved: 'In lineup', statusExpired: 'Expired',

    search: 'Search cards…',
    searchHint: 'Player, team, coach, or condition',

    sortLabel: 'Sort',
    sortOverall: 'Highest overall',
    sortRecent:  'Most recent',
    sortTier:    'Highest tier',
    sortName:    'Alphabetical',
    sortTeam:    'Team / Country',
    sortPosition:'Position',

    viewGrid: 'Grid', viewList: 'List',

    badgeNew: 'NEW',
    badgeMission: 'Golden Mission',
    overlayInDeck: 'In Lineup',
    overlayExpired:'Expired',

    posScoresTitle: 'Position scores',
    posScoresHint: 'Player performs best at their main position',
    mainPos: 'Main',

    multiplierLabel: 'Base score multiplier',
    coachUseTimes: 'Uses',
    coachAvgScore: 'Avg score',
    coachBestScore: 'Best score',
    coachUnlockedAt: 'How unlocked',

    fanBonusLabel: 'Score bonus',
    fanUseTimes: 'Uses',
    fanTotalBonus: 'Total bonus given',
    fanRelatedCount: 'Related players',
    fanSource: 'Source',

    metaAcquired: 'Acquired',
    metaSource:  'From',
    metaLastUsed:'Last used',
    metaInstance:'Instance',
    metaStatus:  'Status',
    metaNeverUsed: 'Never used',

    actAddToLineup: 'Add to Lineup',
    actViewHistory: 'Deck history',
    actShare:       'Share',
    actClose:       'Close',

    emptyTitle: 'No cards yet',
    emptySub:   'Open your first pack to start a collection',
    emptyCta:   'Open first pack',

    sponsorEyebrow: 'Sponsored by',
    sponsorCta:     'Learn more',
  },
  ar: {
    title: 'خزانة',
    subtitle: (n) => `${n} بطاقة نشطة`,
    back: 'رجوع',
    coin: 'عملة',
    notif: 'إشعارات',

    tabAll: 'الكل', tabPlayer: 'لاعب', tabNull: 'وايلدكارد', tabFan: 'مشجع', tabCoach: 'مدرب',

    countCards: (n) => `${n} بطاقة`,
    countTotal: 'المجموع',

    filterTier: 'المستوى', filterPosition: 'المركز', filterStatus: 'الحالة', filterTeam: 'الفريق',
    statusAvailable: 'متاح', statusReserved: 'في التشكيلة', statusExpired: 'منتهي',

    search: 'ابحث في البطاقات…',
    searchHint: 'لاعب، فريق، مدرب أو شرط',

    sortLabel: 'الترتيب',
    sortOverall: 'الأعلى تقييماً',
    sortRecent:  'الأحدث',
    sortTier:    'الأعلى مستوى',
    sortName:    'أبجدي',
    sortTeam:    'الفريق/البلد',
    sortPosition:'المركز',

    viewGrid: 'شبكة', viewList: 'قائمة',

    badgeNew: 'جديد',
    badgeMission: 'المهمة الذهبية',
    overlayInDeck: 'في التشكيلة',
    overlayExpired:'منتهي',

    posScoresTitle: 'النقاط حسب المركز',
    posScoresHint: 'اللاعب يقدم أداءً أفضل في مركزه الأصلي',
    mainPos: 'المركز الأصلي',

    multiplierLabel: 'مضاعف النقاط الأساسية',
    coachUseTimes: 'استخدام',
    coachAvgScore: 'متوسط النقاط',
    coachBestScore: 'الأفضل',
    coachUnlockedAt: 'كيف تم الفتح',

    fanBonusLabel: 'مكافأة النقاط',
    fanUseTimes: 'استخدام',
    fanTotalBonus: 'إجمالي المكافآت',
    fanRelatedCount: 'لاعبون مرتبطون',
    fanSource: 'المصدر',

    metaAcquired: 'تاريخ الاستلام',
    metaSource: 'من',
    metaLastUsed: 'آخر استخدام',
    metaInstance: 'المعرف',
    metaStatus: 'الحالة',
    metaNeverUsed: 'لم تُستخدم',

    actAddToLineup: 'استخدم في التشكيلة',
    actViewHistory: 'سجل التشكيلات',
    actShare:       'مشاركة',
    actClose:       'إغلاق',

    emptyTitle: 'لا توجد بطاقات بعد',
    emptySub:   'افتح أول حزمة وابدأ المجموعة',
    emptyCta:   'افتح أول حزمة',

    sponsorEyebrow: 'برعاية',
    sponsorCta:     'اعرف المزيد',
  },
};

// ─── Source labels (where a card came from) ─────────────────────────────────
const SOURCES = {
  pack_starter:   { fa: 'پک شروع',         en: 'Starter Pack',     ar: 'حزمة البداية' },
  pack_weekly:    { fa: 'پک هفتگی',         en: 'Weekly Pack',      ar: 'الحزمة الأسبوعية' },
  pack_legend:    { fa: 'پک افسانه‌ای',       en: 'Legendary Pack',   ar: 'الحزمة الأسطورية' },
  pack_iran:      { fa: 'پک ویژه ایران',     en: 'Iran Special Pack', ar: 'حزمة إيران الخاصة' },
  mission_daily:  { fa: 'ماموریت روزانه',    en: 'Daily Mission',    ar: 'المهمة اليومية' },
  mission_camp:   { fa: 'کمپین برزیل',       en: 'Brazil Campaign',  ar: 'حملة البرازيل' },
  sponsor_mci:    { fa: 'کمپین همراه اول',   en: 'MCI Sponsor',      ar: 'رعاية MCI' },
  sponsor_blu:    { fa: 'کمپین بلوبانک',     en: 'blu Sponsor',      ar: 'رعاية blu' },
  coach_unlock:   { fa: 'آزادسازی از Submit', en: 'Submit unlock',   ar: 'فتح من Submit' },
};

// ─── Persian relative date helper (for "اکنون" / "۲ روز پیش") ─────────────
function relativeDate(daysAgo, locale = 'fa') {
  if (daysAgo === 0) return locale === 'fa' ? 'امروز' : locale === 'ar' ? 'اليوم' : 'Today';
  if (daysAgo === 1) return locale === 'fa' ? 'دیروز' : locale === 'ar' ? 'أمس' : 'Yesterday';
  if (daysAgo < 7) {
    const n = toLocaleDigits(daysAgo, locale);
    return locale === 'fa' ? `${n} روز پیش` : locale === 'ar' ? `قبل ${n} يوم` : `${daysAgo} days ago`;
  }
  if (daysAgo < 30) {
    const w = Math.round(daysAgo / 7);
    const n = toLocaleDigits(w, locale);
    return locale === 'fa' ? `${n} هفته پیش` : locale === 'ar' ? `قبل ${n} أسبوع` : `${w}w ago`;
  }
  const m = Math.round(daysAgo / 30);
  const n = toLocaleDigits(m, locale);
  return locale === 'fa' ? `${n} ماه پیش` : locale === 'ar' ? `قبل ${n} شهر` : `${m}mo ago`;
}

// ─── Build inventory: combine COLLECTION + special cards with metadata ─────
// Each entry is a CardInstance with: instance_id, type, status, acquired_days_ago,
// source_key, last_used_days_ago (or null), isNew, isPinned (for golden mission),
// and a `card` ref to the original record so Picker can reuse PlayerCard /
// NullCard / FanCard / CoachCard for rendering.

function mkInstance(idx, type, ref, opts = {}) {
  return {
    instance_id: `inv_${type}_${idx}`,
    type, // 'player' | 'null' | 'fan' | 'coach'
    card: ref,
    status: opts.status || 'available',          // 'available' | 'reserved' | 'expired'
    acquired_days_ago: opts.acquired_days_ago ?? Math.floor(idx * 1.7) + 1,
    source_key: opts.source_key || 'pack_weekly',
    last_used_days_ago: opts.last_used_days_ago ?? null,
    use_count: opts.use_count ?? 0,
    avg_score: opts.avg_score ?? null,
    best_score: opts.best_score ?? null,
    total_bonus: opts.total_bonus ?? null,
    related_count: opts.related_count ?? null,
    isNew: opts.isNew ?? (idx < 2),
    isPinned: opts.isPinned ?? false,
  };
}

// Null card stubs — each is an instance with its own tier.
const NULL_INVENTORY_REFS = [
  { id: 'null1', tier: 'gold',     overall: 85 },
  { id: 'null2', tier: 'platinum', overall: 91 },
];

// Build the inventory list.
function buildInventory() {
  const out = [];

  // Players — every entry in COLLECTION becomes an instance.
  COLLECTION.forEach((p, i) => {
    const tierBoost = { bronze: 0, silver: 1, gold: 2, platinum: 3 }[p.tier];
    const isPinned = (p.id === 'mf1' || p.id === 'df3');
    const status = (p.status === 'locked')
      ? 'reserved'
      : (i === 9 ? 'expired' : 'available');
    out.push(mkInstance(i, 'player', p, {
      status,
      acquired_days_ago: 1 + i * 2,
      source_key: ['pack_starter','pack_weekly','pack_iran','pack_legend','pack_weekly'][i % 5],
      last_used_days_ago: i % 3 === 0 ? (3 + i) : null,
      use_count: tierBoost + (i % 4),
      isNew: i < 3,
      isPinned,
    }));
  });

  // Null cards — wildcards.
  NULL_INVENTORY_REFS.forEach((n, i) => {
    out.push(mkInstance(100 + i, 'null', n, {
      status: 'available',
      acquired_days_ago: 5 + i * 3,
      source_key: 'pack_legend',
      isNew: i === 0,
    }));
  });

  // Fan cards — bonus.
  FAN_CARDS.forEach((f, i) => {
    out.push(mkInstance(200 + i, 'fan', f, {
      status: 'available',
      acquired_days_ago: 4 + i * 4,
      source_key: ['mission_camp', 'sponsor_mci', 'sponsor_blu'][i % 3],
      last_used_days_ago: 6 + i * 3,
      use_count: 18 - i * 4,
      total_bonus: f.bonus * (18 - i * 4),
      related_count: 5 + i,
      isPinned: i === 0,
    }));
  });

  // Coach cards — multiplier.
  COACH_CARDS.forEach((c, i) => {
    out.push(mkInstance(300 + i, 'coach', c, {
      status: i === 2 ? 'reserved' : 'available',
      acquired_days_ago: 10 + i * 5,
      source_key: 'coach_unlock',
      last_used_days_ago: 12 + i * 6,
      use_count: 12 - i * 3,
      avg_score: 2150 - i * 200,
      best_score: 2850 - i * 250,
    }));
  });

  return out;
}

const INVENTORY = buildInventory();

// ─── Counts helper ──────────────────────────────────────────────────────────
function inventoryCounts(items) {
  const c = { all: items.length, player: 0, null: 0, fan: 0, coach: 0,
              bronze: 0, silver: 0, gold: 0, platinum: 0,
              available: 0, reserved: 0, expired: 0,
              new: 0, pinned: 0 };
  items.forEach((it) => {
    c[it.type] += 1;
    if (it.type === 'player') c[it.card.tier] += 1;
    if (it.type === 'null')   c[it.card.tier] += 1;
    c[it.status] += 1;
    if (it.isNew) c.new += 1;
    if (it.isPinned) c.pinned += 1;
  });
  return c;
}

// ─── Player position-score helper ──────────────────────────────────────────
// Generates plausible per-position scores given a player's main position and
// stat value. Used in modal · Player tab. (Mocked — final values come from
// API in production.)
function playerPositionScores(player) {
  const main = player.position;
  const ovr = player.overall;
  const base = player.statValue || ovr;
  const drop = { GK: 0.30, DEF: 0.55, MID: 0.85, FWD: 0.95 };
  const scoreFor = (pos) => {
    if (pos === main) return base;
    // For non-GK→GK/DEF→FWD long jumps, big penalty. For adjacent positions
    // milder. Just illustrative.
    const order = ['GK','DEF','MID','FWD'];
    const dist  = Math.abs(order.indexOf(pos) - order.indexOf(main));
    const penalty = [0, 12, 28, 50][dist];
    return Math.max(20, base - penalty);
  };
  return { GK: scoreFor('GK'), DEF: scoreFor('DEF'), MID: scoreFor('MID'), FWD: scoreFor('FWD'), main };
}

// ─── Inventory item adapter ──────────────────────────────────────────────
// Wraps a raw card object (Player / Null / Fan / Coach) into the inventory
// "item" shape that MyCardsDetailModal expects. Used by Lineup picker and
// standalone PlayerCard preview screens where real inventory metadata doesn't
// exist — we synthesize plausible defaults so the modal renders cleanly.
//
// In those screens, the caller should typically also pass `hideMeta: true` to
// the modal so the (mocked) Acquired/Source/Last-used row doesn't show.
function toInventoryItem(card, type, opts = {}) {
  const defaultSource =
    type === 'coach' ? 'coach_unlock' :
    type === 'fan'   ? 'mission_camp' :
                       'pack_weekly';
  return {
    instance_id: opts.instance_id || `vp_${type}_${card?.id || Math.random().toString(36).slice(2, 8)}`,
    type,
    card,
    status:            opts.status            || 'available',
    acquired_days_ago: opts.acquired_days_ago ?? 7,
    source_key:        opts.source_key        || defaultSource,
    last_used_days_ago:opts.last_used_days_ago ?? null,
    use_count:         opts.use_count         ?? 0,
    avg_score:         opts.avg_score         ?? null,
    best_score:        opts.best_score        ?? null,
    total_bonus:       opts.total_bonus       ?? null,
    related_count:     opts.related_count     ?? null,
    isNew:             opts.isNew             ?? false,
    isPinned:          opts.isPinned          ?? false,
  };
}

// Build a card-shaped object from props that arrive as plain strings (the
// PlayerCard / NullCard / FanCard / CoachCard components in card-v2.jsx and
// card-special.jsx take `playerName`, `teamName`, etc. as strings — already
// localized for the current locale). We rewrap them as `{ fa, en, ar }`
// objects so the modal's locale-switcher still has something to read.
function _mono(s) { return { fa: s, en: s, ar: s }; }

function playerCardPropsToCard({ tier, position, overall, statKey, statValue,
                                  playerName, teamName, playerImage }) {
  return {
    id:        `sp_${(playerName || '').slice(0, 12)}`,
    tier, position, overall, statKey, statValue,
    name:  _mono(playerName),
    team:  _mono(teamName),
    image: playerImage,
  };
}
function nullCardPropsToCard({ tier, overall, image }) {
  return { id: 'sp_null', tier, overall, image };
}
function fanCardPropsToCard({ bonusValue, team, image }) {
  return { id: 'sp_fan', bonus: bonusValue, team: _mono(team), image };
}
function coachCardPropsToCard({ multiplier, coachName, condition, image }) {
  return {
    id:        `sp_co_${(coachName || '').slice(0, 12)}`,
    multiplier,
    name:      _mono(coachName),
    condition: _mono(condition),
    image,
  };
}

Object.assign(window, {
  MC_I18N, SOURCES, INVENTORY,
  buildInventory, inventoryCounts, playerPositionScores, relativeDate, mkInstance,
  toInventoryItem,
  playerCardPropsToCard, nullCardPropsToCard, fanCardPropsToCard, coachCardPropsToCard,
});
