// ────────────────────────────────────────────────────────────────────────────
// app-data.jsx — Unified app shell · routes, helpers, adapters
// Foundation v1 · v1.7.0 · index.html runtime
//
// This module is loaded once by index.html (the unified SPA entry) and
// provides:
//   · APP_ROUTES    — hash-route table for the entire app
//   · APP_I18N      — shell-level strings (page titles, empty states, etc.)
//   · navTo(path)   — programmatic navigation helper
//   · useHashRoute  — React hook subscribed to hashchange
//   · useViewport   — React hook returning { isDesktop } (1024px breakpoint)
//   · adaptUserForTopbar — maps any user shape to DesktopTopbar's expected props
//   · screenForRoute(route, viewport) — returns the component to render
//
// No new CSS tokens. No new visual primitives — only routing + adapters.
// ────────────────────────────────────────────────────────────────────────────

// ─── Route table ────────────────────────────────────────────────────────────
// Each route maps to a slot in the shell. `tabKey` aligns with BottomNav keys.
const APP_ROUTES = {
  home:           { path: '/home',           tabKey: 'home',        title: { fa: 'خانه',         en: 'Home',          ar: 'الرئيسية' } },
  predict:        { path: '/predict',        tabKey: 'predict',     title: { fa: 'پیش‌بینی',     en: 'Predict',       ar: 'التنبؤ' } },
  lineup:         { path: '/lineup',         tabKey: 'lineup',      title: { fa: 'ترکیب',        en: 'Lineup',        ar: 'التشكيلة' } },
  cards:          { path: '/cards',          tabKey: 'cards',       title: { fa: 'کارت‌های من',  en: 'My Cards',      ar: 'بطاقاتي' } },
  leaderboard:    { path: '/leaderboard',    tabKey: 'leaderboard', title: { fa: 'صدر جدول',     en: 'Leaderboard',   ar: 'المتصدرون' } },
  shop:           { path: '/shop',           tabKey: 'shop',        title: { fa: 'فروشگاه',      en: 'Shop',          ar: 'المتجر' } },
  profile:        { path: '/profile',        tabKey: null,          title: { fa: 'پروفایل',      en: 'Profile',       ar: 'الملف الشخصي' } },
  profileEdit:    { path: '/profile/edit',   tabKey: null,          title: { fa: 'ویرایش پروفایل', en: 'Edit Profile',  ar: 'تعديل الملف' } },
  settings:       { path: '/settings',       tabKey: null,          title: { fa: 'تنظیمات',      en: 'Settings',      ar: 'الإعدادات' } },
  notifications:  { path: '/notifications',  tabKey: null,          title: { fa: 'اعلان‌ها',     en: 'Notifications', ar: 'الإشعارات' } },
  about:          { path: '/about',          tabKey: null,          title: { fa: 'درباره ما',    en: 'About',         ar: 'حول' } },
  lineupHistory:  { path: '/lineup-history', tabKey: null,          title: { fa: 'تاریخچه ترکیب‌ها', en: 'Lineup History', ar: 'سجل التشكيلات' } },
  packOpening:    { path: '/pack-opening',   tabKey: null,          title: { fa: 'باز کردن پک',  en: 'Pack Opening',  ar: 'فتح الحزمة' } },
};

// Tab key → route key (for BottomNav clicks)
const APP_TAB_TO_ROUTE = {
  home: 'home',
  predict: 'predict',
  lineup: 'lineup',
  cards: 'cards',
  leaderboard: 'leaderboard',
  shop: 'shop',
};

// Profile menu key → route key (for Profile menu rows)
const APP_MENU_TO_ROUTE = {
  lineupHistory: 'lineupHistory',
  settings: 'settings',
  notifications: 'notifications',
  about: 'about',
};


// ─── Shell-level i18n (Profile menu landing pages, empty states) ────────────
const APP_I18N = {
  fa: {
    comingSoon:      'به‌زودی',
    comingSoonDesc:  'این بخش در دست طراحی و توسعه است. به‌زودی در دسترس قرار می‌گیرد.',
    backToHome:      'بازگشت به خانه',
    backToProfile:   'بازگشت به پروفایل',
    notFoundTitle:   'صفحه پیدا نشد',
    notFoundDesc:    'لینکی که دنبال می‌کنید موجود نیست. می‌توانید به صفحه‌ی خانه برگردید.',
    settingsTitle:   'تنظیمات',
    notifsTitle:     'اعلان‌ها',
    aboutTitle:      'درباره ما',
    lineupHistTitle: 'تاریخچه ترکیب‌ها',
    packOpenTitle:   'باز کردن پک',
  },
  en: {
    comingSoon:      'Coming Soon',
    comingSoonDesc:  'This section is under design and will be available shortly.',
    backToHome:      'Back to Home',
    backToProfile:   'Back to Profile',
    notFoundTitle:   'Page not found',
    notFoundDesc:    'The link you followed does not exist. Return to the home screen.',
    settingsTitle:   'Settings',
    notifsTitle:     'Notifications',
    aboutTitle:      'About',
    lineupHistTitle: 'Lineup History',
    packOpenTitle:   'Pack Opening',
  },
  ar: {
    comingSoon:      'قريبًا',
    comingSoonDesc:  'هذا القسم قيد التصميم والتطوير وسيتاح قريبًا.',
    backToHome:      'العودة إلى الرئيسية',
    backToProfile:   'العودة إلى الملف',
    notFoundTitle:   'الصفحة غير موجودة',
    notFoundDesc:    'الرابط الذي تتبعه غير موجود. ارجع إلى الشاشة الرئيسية.',
    settingsTitle:   'الإعدادات',
    notifsTitle:     'الإشعارات',
    aboutTitle:      'حول',
    lineupHistTitle: 'سجل التشكيلات',
    packOpenTitle:   'فتح الحزمة',
  },
};


// ─── Navigation helpers ─────────────────────────────────────────────────────
// All routes are hash-based: `#/home`, `#/profile/edit`, etc.

function navTo(routeKeyOrPath) {
  if (!routeKeyOrPath) return;
  const r = APP_ROUTES[routeKeyOrPath];
  const path = r ? r.path : (String(routeKeyOrPath).startsWith('/') ? routeKeyOrPath : '/' + routeKeyOrPath);
  if (window.location.hash !== '#' + path) {
    window.location.hash = '#' + path;
  }
}

function currentRouteFromHash() {
  const h = (window.location.hash || '').replace(/^#/, '') || '/home';
  // Find route by exact path
  for (const k in APP_ROUTES) {
    if (APP_ROUTES[k].path === h) return k;
  }
  // Sub-paths: /pack-opening/something → packOpening
  if (h.startsWith('/pack-opening')) return 'packOpening';
  if (h.startsWith('/profile/edit')) return 'profileEdit';
  if (h.startsWith('/profile'))     return 'profile';
  return null;
}


// ─── React hooks ────────────────────────────────────────────────────────────
function useHashRoute(defaultRoute = 'home') {
  const [route, setRoute] = React.useState(() => currentRouteFromHash() || defaultRoute);
  React.useEffect(() => {
    const onHash = () => {
      const next = currentRouteFromHash() || defaultRoute;
      setRoute(next);
      // Scroll to top on route change for crisp navigation feel.
      const scroller = document.querySelector('.app-shell-viewport');
      if (scroller) scroller.scrollTo({ top: 0, behavior: 'instant' });
    };
    window.addEventListener('hashchange', onHash);
    if (!window.location.hash) {
      window.location.hash = '#' + APP_ROUTES[defaultRoute].path;
    }
    return () => window.removeEventListener('hashchange', onHash);
  }, [defaultRoute]);
  return route;
}

function useViewport(breakpoint = 1024) {
  const get = () => (typeof window !== 'undefined' && window.innerWidth >= breakpoint);
  const [isDesktop, setIsDesktop] = React.useState(get);
  React.useEffect(() => {
    const onResize = () => setIsDesktop(get());
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, [breakpoint]);
  return { isDesktop };
}


// ─── Adapters ───────────────────────────────────────────────────────────────
// Different modules use different user shapes. The canonical shape that
// DesktopTopbar and AppBar expect is HH_USER (level, coinBalance, avatarInitial:string).
// PROF_USER (and possibly others) use totalCoins + avatarInitial:object{fa,en,ar}.
function adaptUserForTopbar(user, locale = 'fa') {
  if (!user) return window.HH_USER;
  const base = window.HH_USER || {};
  const ai = user.avatarInitial;
  const avatarInitial = (ai && typeof ai === 'object')
    ? (ai[locale] || ai.fa || ai.en || 'R')
    : (ai || base.avatarInitial || 'R');
  return {
    ...base,
    ...user,
    level: user.level ?? base.level,
    coinBalance: user.coinBalance ?? user.totalCoins ?? base.coinBalance ?? 0,
    avatarInitial,
  };
}


// ─── Export to window ───────────────────────────────────────────────────────
Object.assign(window, {
  APP_ROUTES,
  APP_TAB_TO_ROUTE,
  APP_MENU_TO_ROUTE,
  APP_I18N,
  navTo,
  currentRouteFromHash,
  useHashRoute,
  useViewport,
  adaptUserForTopbar,
});
