/* Content model for the TrainerRegistry homepage.
   Recreations / illustrative copy only. */

/* ── Two providers, same REPs-approved cert (hero comparison) ── */
const CMP = {
  left: {
    title: "Level 3 Personal Trainer",
    flag: null,
    rows: [
      { k: "Next intake", v: "12 Jun 2026", icon: "calendar", accent: true },
      { k: "Format", v: "In-person · 6 weekends", icon: "clock" },
      { k: "Duration", v: "6 weeks", icon: "clock" },
      { k: "Awarding body", v: "Active IQ", icon: "graduation-cap" },
    ],
    awarding: "Active IQ",
    description: "Small cohorts, assessed on-site by an experienced L4 coach.",
  },
  right: {
    title: "Level 3 Personal Trainer",
    flag: "Top rated",
    rows: [
      { k: "Next intake", v: "Rolling", icon: "calendar", accent: true },
      { k: "Format", v: "Self-paced online", icon: "globe" },
      { k: "Duration", v: "8-14 wks", icon: "clock" },
      { k: "Awarding body", v: "Active IQ", icon: "graduation-cap" },
    ],
    awarding: "Active IQ",
    description: "Study at your own pace. One practical assessment day at the end.",
  },
};

/* ── Trendy fitness careers ── */
const CAREERS = [
  { id: "hyrox", name: "Hyrox Coach", icon: "flame", tag: "Hottest right now", tagTone: "amber",
    blurb: "The fitness race the whole UAE is training for. Gyms can't hire coaches fast enough.", courses: 5, pay: "AED 8-16k/mo" },
  { id: "reformer", name: "Reformer Pilates", icon: "person-standing", tag: "Studio boom", tagTone: "amber",
    blurb: "New studios open every month, and each one needs qualified instructors.", courses: 6, pay: "AED 9-18k/mo" },
  { id: "cycling", name: "Rhythm Cycling Instructor", icon: "activity", tag: "Trending", tagTone: "amber",
    blurb: "Lights, music, watts. Lead the most-booked class on the timetable.", courses: 4, pay: "AED 7-14k/mo" },
  { id: "pt", name: "Personal Trainer", icon: "dumbbell", tag: "Most hired", tagTone: "brand",
    blurb: "The classic route, and still the most-hired role in every UAE gym.", courses: 14, pay: "AED 8-18k/mo" },
  { id: "snc", name: "Strength & Conditioning", icon: "trending-up", tag: "Top earner", tagTone: "brand",
    blurb: "Coach athletes and serious lifters, and command the top rates in the field.", courses: 5, pay: "AED 10-22k/mo" },
  { id: "hiit", name: "Group HIIT & Bootcamp", icon: "heart-pulse", tag: "Always hiring", tagTone: "brand",
    blurb: "Big-energy classes are the fastest-growing slot on every studio schedule.", courses: 8, pay: "AED 6-14k/mo" },
  { id: "online", name: "Online Coach", icon: "graduation-cap", tag: "No ceiling", tagTone: "brand",
    blurb: "Coach clients remotely, anywhere. The most scalable way to earn in fitness.", courses: 5, pay: "AED 7-20k/mo" },
  { id: "nutrition", name: "Nutrition Coach", icon: "utensils", tag: "Best add-on", tagTone: "neutral",
    blurb: "Stack it onto coaching and roughly double what each client is worth.", courses: 7, pay: "+AED 4-9k/mo" },
  { id: "boxing", name: "Boxing & Combat Conditioning", icon: "activity", tag: "Trending", tagTone: "amber",
    blurb: "Pad work and conditioning are booming with the white-collar boxing crowd.", courses: 4, pay: "AED 7-15k/mo" },
  { id: "yoga", name: "Yoga Teacher", icon: "person-standing", tag: "Steady demand", tagTone: "neutral",
    blurb: "200hr and beyond. Studios across the UAE always need cover and regulars.", courses: 6, pay: "AED 6-13k/mo" },
  { id: "prenatal", name: "Pre & Post-natal Specialist", icon: "users", tag: "Niche", tagTone: "neutral",
    blurb: "Specialise where almost no one else has, and charge a clear premium.", courses: 4, pay: "AED 300+/session" },
  { id: "kids", name: "Kids & Youth Coach", icon: "users", tag: "Fast growing", tagTone: "amber",
    blurb: "Schools and academies are hiring qualified youth coaches fast.", courses: 3, pay: "AED 6-12k/mo" },
  { id: "calisthenics", name: "Calisthenics Coach", icon: "dumbbell", tag: "Trending", tagTone: "amber",
    blurb: "Bodyweight training is everywhere, from beach parks to boutique gyms.", courses: 3, pay: "AED 6-13k/mo" },
  { id: "mobility", name: "Mobility & Recovery", icon: "heart-pulse", tag: "Premium", tagTone: "brand",
    blurb: "The recovery niche clients happily pay a premium to book.", courses: 4, pay: "AED 9-17k/mo" },
  { id: "snc-sport", name: "Sports Performance Coach", icon: "trending-up", tag: "Top earner", tagTone: "brand",
    blurb: "Work with academies and pro athletes at the top end of the market.", courses: 5, pay: "AED 12-24k/mo" },
];

/* ── News that moves a fitness career (NerdWallet-style, punchy) ── */
const NEWS = [
  {
    id: "n1", lead: true, category: "Regulation", tone: "brand",
    title: "REPs UAE just added Level 4 Pilates to the approved register",
    dek: "If you teach Pilates, this is the cert that now lets you work legally in licensed studios. Three providers are already running it, and the prices are all over the place.",
    date: "3 days ago", read: "4 min", icon: "badge-check",
  },
  { id: "n2", category: "Pay", tone: "amber",
    title: "Dubai PT salaries climbed 11% this year. Here's the new range.",
    date: "1 week ago", read: "5 min", icon: "trending-up" },
  { id: "n3", category: "Hiring", tone: "brand",
    title: "Why every UAE gym is suddenly fighting over HIIT coaches",
    date: "1 week ago", read: "3 min", icon: "flame" },
  { id: "n4", category: "Visa & licensing", tone: "neutral",
    title: "New freelance permit makes it easier to train clients solo",
    date: "2 weeks ago", read: "6 min", icon: "globe" },
  { id: "n5", category: "Market", tone: "amber",
    title: "Pilates studios in the UAE have doubled since 2023",
    date: "3 weeks ago", read: "4 min", icon: "person-standing" },
];

window.TR_CONTENT = { CMP, CAREERS, NEWS };

/* ── Swipe-card enrichment (the "Would you like this job?" experience) ──
   Extra, role-by-role detail the swipe cards need on top of CAREERS:
   live hiring demand, open jobs, the entry cert, how fast you qualify,
   who's hiring and the day-to-day. Keyed by career id. */
const CAREER_META = {
  "hyrox":       { demand: 96, hiring: 24, start: "Level 3 PT + Hyrox",        weeks: 10, vibe: "High-energy · competitive · big community", day: "Run race-prep classes, program for events, coach hard on the floor.",   employers: ["Warehouse Gym", "Crank", "GymNation"] },
  "reformer":    { demand: 88, hiring: 31, start: "Level 3 Mat Pilates",       weeks: 12, vibe: "Calm · precise · boutique studios",         day: "Teach small reformer classes, cue with detail, build a loyal regular base.", employers: ["Define", "Heartcore", "TenFitness"] },
  "cycling":     { demand: 80, hiring: 21, start: "Indoor Cycling",            weeks: 5,  vibe: "Music-led · theatrical · packed rooms",     day: "Build playlists, light the room, lead the most-booked ride of the day.",  employers: ["1Rebel", "CRANK", "Bohzu"] },
  "pt":          { demand: 91, hiring: 58, start: "Level 3 PT",                weeks: 8,  vibe: "Versatile · 1-on-1 · always in demand",     day: "Coach clients one-on-one, write their plans, own their results.",        employers: ["Fitness First", "GymNation", "The Warehouse"] },
  "snc":         { demand: 74, hiring: 12, start: "Level 3 PT → S&C",          weeks: 16, vibe: "Technical · athlete-focused · top pay",      day: "Build performance programs, run testing, push athletes toward PBs.",     employers: ["Inspire Sports", "NAS Academy", "Dubai Sports"] },
  "hiit":        { demand: 83, hiring: 37, start: "Level 2 + Group",           weeks: 6,  vibe: "Loud · fun · big rooms",                    day: "Lead packed bootcamp rooms, bring the energy, keep everyone moving.",     employers: ["F45", "Barry's", "Crank"] },
  "online":      { demand: 71, hiring: 19, start: "Level 3 PT",                weeks: 8,  vibe: "Flexible · remote · scalable",              day: "Build programs in an app, check in over video, grow a roster from home.", employers: ["Remote rosters", "Kaged", "TruBe"] },
  "nutrition":   { demand: 66, hiring: 14, start: "Nutrition L4",              weeks: 9,  vibe: "Advisory · 1-on-1 · easy add-on",           day: "Run nutrition consults, set habits, stack revenue onto your coaching.",  employers: ["Clinics", "Studios", "Online"] },
  "boxing":      { demand: 78, hiring: 16, start: "Level 2 + Boxing",          weeks: 7,  vibe: "Pads · combat · high-energy",               day: "Run pad rounds and conditioning, keep the white-collar crowd sharp.",    employers: ["Round 10", "TrueGrit", "FlyKick"] },
  "yoga":        { demand: 64, hiring: 18, start: "200hr YTT",                 weeks: 14, vibe: "Calm · mindful · studio regulars",          day: "Lead flows, hold space, build a base of loyal regulars.",                employers: ["Karma Yoga", "Zoga", "Studios"] },
  "prenatal":    { demand: 58, hiring: 9,  start: "Pre/Post-natal L3",         weeks: 8,  vibe: "Specialist · 1-on-1 · premium",             day: "Coach mums-to-be safely, and charge a clear specialist premium.",        employers: ["Clinics", "Studios", "Private"] },
  "kids":        { demand: 72, hiring: 22, start: "Level 2 + Youth",           weeks: 6,  vibe: "Playful · groups · schools",                day: "Run school sessions and camps, build movement in young athletes.",       employers: ["Schools", "Academies", "Camps"] },
  "calisthenics":{ demand: 70, hiring: 13, start: "Level 3 + Calisthenics",    weeks: 9,  vibe: "Bodyweight · skill · outdoors",             day: "Coach skills from first pull-up to muscle-up, indoors or in the park.",  employers: ["Park sessions", "Boutique gyms", "Online"] },
  "mobility":    { demand: 67, hiring: 11, start: "Level 3 + Mobility",        weeks: 10, vibe: "Recovery · technical · premium",            day: "Run mobility and recovery sessions clients happily pay a premium for.",  employers: ["Recovery studios", "Clinics", "Private"] },
  "snc-sport":   { demand: 73, hiring: 10, start: "Level 3 PT → Performance",  weeks: 16, vibe: "Athlete-focused · elite · top pay",         day: "Build performance plans for academies and pro athletes.",                employers: ["Academies", "Pro clubs", "Sports City"] },
};
window.TR_CONTENT.CAREER_META = CAREER_META;

/* ── Live activity feed ("hot" digest: jobs, articles, updates, courses) ── */
const FEED = [
  { id: "f9",  kind: "Job alert",   tone: "brand", time: "Just now",   hot: true,
    title: "XFit Dubai - walk-in interviews open for Male & Female PTs", meta: "Dubai · all levels welcome" },
  { id: "f10", kind: "New article", tone: "amber", time: "1 hr ago",   hot: true, articleId: "a10",
    title: "UAE gym attendance spiked - but not for the reason you'd expect", meta: "4 min read" },
  { id: "f11", kind: "Job alert",   tone: "brand", time: "2 hr ago",
    title: "Runamuk (Bali) - opening team hiring now, Pererenan", meta: "Bali · community hub · full-time" },
  { id: "f12", kind: "New article", tone: "brand", time: "3 hr ago",   articleId: "a11",
    title: "The fitness jobs that aren't in Dubai - Bangkok, Bali and what they pay", meta: "5 min read" },
  { id: "f13", kind: "Job alert",   tone: "brand", time: "Today",
    title: "BASE Bangkok - science-based PT coach, work permit provided", meta: "Bangkok · NASM required · 2 yrs exp" },
  { id: "f14", kind: "New article", tone: "brand", time: "Today",      articleId: "a9",
    title: "The company trying to run PT for the world - and what it means for UAE trainers", meta: "5 min read" },
  { id: "f1",  kind: "Job alert",   tone: "brand", time: "30 min ago", hot: true,
    title: "Hyrox Coach wanted at Fitness First, Dubai Marina", meta: "AED 9-15k/mo · full-time" },
  { id: "f2",  kind: "New article", tone: "amber", time: "1 hr ago",   hot: true, articleId: "a1",
    title: "How much should a Level 3 PT charge per session in 2026?", meta: "6 min read" },
  { id: "f3",  kind: "Job alert",   tone: "brand", time: "2 hr ago",
    title: "Reformer Pilates instructor at a new JLT studio", meta: "AED 10-16k/mo" },
  { id: "f4",  kind: "Update",      tone: "neutral", time: "4 hr ago", articleId: "a3",
    title: "REPs UAE added Level 4 Pilates to the approved register", meta: "Regulation" },
  { id: "f5",  kind: "New course",  tone: "brand", time: "Today",
    title: "New intake added: Level 3 PT, starts 24 Jul", meta: "AED 4,900 · online" },
  { id: "f6",  kind: "Job alert",   tone: "brand", time: "Today",
    title: "S&C coach at a pro academy, Abu Dhabi", meta: "AED 18k/mo" },
  { id: "f7",  kind: "New article", tone: "amber", time: "Yesterday",  articleId: "a2",
    title: "Why every UAE gym is suddenly fighting over HIIT coaches", meta: "4 min read" },
  { id: "f8",  kind: "Update",      tone: "neutral", time: "Yesterday", articleId: "a5",
    title: "New freelance permit makes it easier to train clients solo", meta: "Visa & licensing" },
];
window.TR_CONTENT.FEED = FEED;

/* ── Dummy course detail (the full honest layer for one course) ── */
const DETAIL = {
  title: "Level 3 Personal Trainer",
  provider: "Gulf Coaching Institute",
  location: "Dubai · Al Quoz",
  body: "Active IQ",
  level: "Level 3",
  rating: 4.4,
  reviews: 38,
  career: "Personal Trainer",
  summary:
    "The in-person route most Dubai gyms recognise. You'll learn on a real gym floor with a coach watching your cueing, but it's one of the pricier options, and the exam fee is charged on top.",
  rightFor: [
    "You want to work the floor in a UAE gym",
    "You learn best in person, with form corrected live",
    "You can give up six weekends",
  ],
  notFor: [
    "You need to qualify in under a month",
    "You're on a tight budget, and there's a cheaper online route",
    "You can't travel to Al Quoz on weekends",
  ],
  pros: [
    "Taught in person by an experienced Level 4 coach",
    "Small cohorts, capped at 12 learners",
    "Practical assessment done on-site, not by video",
  ],
  cons: [
    "AED 850 exam fee is billed separately",
    "No payment plan offered",
    "A re-sit costs an extra AED 400",
  ],
  qualifies:
    "Work as a certified personal trainer in any REPs-recognised UAE gym, design and coach 1:1 programmes, and register on REPs UAE at Level 3.",
  covers: [
    "Anatomy & physiology",
    "Programme design",
    "Client screening & assessment",
    "Nutrition fundamentals",
    "Practical coaching & cueing",
    "The business of PT in the UAE",
  ],
  dates: [
    { start: "12 Jun 2026", note: "Weekends · 6 weeks", spots: "4 spots left", tight: true },
    { start: "24 Jul 2026", note: "Weekends · 6 weeks", spots: "Open" },
    { start: "11 Sep 2026", note: "Weekdays · 3 weeks", spots: "Open" },
  ],

  instructor: {
    initials: "HM",
    name: "Hana Mansour",
    meta: "Level 4 S&C · 9 years coaching in Dubai",
    bio: "Hana has coached at three Dubai gyms and now leads this cohort herself, so you're taught by her, not a rotating bench of assistants. Known for drilling cueing and assessment until it's second nature.",
  },
  verdict:
    "A solid in-person course with a genuinely good instructor, but you're paying a premium for the room. If hands-on coaching matters to you and the weekends work, it's worth it. If budget is the priority, the same REPs-approved cert is AED 2,400 cheaper online. We'd ask one question first: do you actually need someone watching your form, or are you disciplined enough to learn it remotely?",
  facts: [
    { k: "Next intake", v: "12 Jun 2026", icon: "calendar", accent: true },
    { k: "Format", v: "In-person", icon: "clock" },
    { k: "Location", v: "Al Quoz, Dubai", icon: "map-pin" },
    { k: "Duration", v: "6 weekends", icon: "calendar" },
    { k: "Awarding body", v: "Active IQ", icon: "graduation-cap" },
    { k: "Availability", v: "4 spots left", icon: "users" },
  ],
  ofqual: "603/5232/2",
  entry: "Must have achieved a Level 2 Certificate in Fitness Instructing (Gym) or equivalent. Physical fitness required. Basic communication and numeracy at Levels 2-3.",
  verifyBody: "Active IQ",
  verifyUrl: "activeiq.co.uk/qualifications",
  qualFacts: [
    { label: "Award",                    value: "Level 3 RQF Certificate", icon: "graduation-cap" },
    { label: "Awarding body",            value: "Active IQ",               icon: "book-open"      },
    { label: "Accreditation no.",        value: "603/5232/2",              icon: "hash"           },
    { label: "Guided learning hours",    value: "340 hrs",                 icon: "clock"          },
    { label: "Credits",                  value: "41",                      icon: "layers"         },
    { label: "Total qualification time", value: null,                      icon: "clock"          },
    { label: "Duration",                 value: "Varies by provider",      icon: "calendar"       },
    { label: "Status",                   value: "REPs UAE approved",       icon: "badge-check"    },
  ],
};

window.TR_CONTENT.DETAIL = DETAIL;

/* ── Same cert, different providers (inline comparison section) ── */
const COMPARE = {
  title: "Level 3 Personal Trainer",
  note: "The exact same REPs UAE-approved certificate - four providers, four different delivery formats.",
  rows: [
    { provider: "ProFit Academy",           location: "Online",          format: "Self-paced + weekly live Q&A", rating: 4.7, n: 89, duration: "10-14 wks", next: "Rolling",     spots: "Open",   price: "AED 3,800", best: true,  body: "Active IQ" },
    { provider: "Active Fitness Academy",   location: "Abu Dhabi",       format: "Blended · weekends",           rating: 4.5, n: 52, duration: "10 wks",    next: "5 Jul 2026",  spots: "Open",   price: "AED 5,200",             body: "Active IQ" },
    { provider: "Gulf Coaching Institute",  location: "Dubai · Al Quoz", format: "In-person · 6 weekends",       rating: 4.4, n: 38, duration: "8 wks",     next: "14 Jun 2026", spots: "4 left", price: "AED 6,400", tight: true, body: "Active IQ", current: true },
    { provider: "Emirates Fitness College", location: "Dubai · JLT",    format: "In-person intensive",          rating: 4.3, n: 21, duration: "6 wks",     next: "21 Jul 2026", spots: "2 left", price: "AED 7,100", tight: true, body: "Active IQ" },
  ],
};
window.TR_CONTENT.COMPARE = COMPARE;

/* ── Course library, organised by REPs UAE registration category ── */
/* Our 5 REPs UAE categories (matches db/canonical.db `category`). */
const REP_CATEGORIES = [
  { id: "pt", name: "Personal Trainer", icon: "dumbbell", blurb: "Design and coach 1:1 programmes. The most-hired role in the UAE." },
  { id: "gym", name: "Gym Instructor", icon: "activity", blurb: "Your entry point. Induct and supervise members on the gym floor." },
  { id: "group", name: "Group Fitness Instructor", icon: "flame", blurb: "Lead the room: HIIT, bootcamp, freestyle and indoor cycling." },
  { id: "yoga", name: "Yoga Teacher", icon: "heart-pulse", blurb: "RYS 200+ recognised. Studios are always looking for cover." },
  { id: "pilates", name: "Pilates Instructor", icon: "person-standing", blurb: "Mat and reformer. A booming studio discipline across the UAE." },
];
const COURSES = [
  { id: "c1",  title: "Level 3 Personal Trainer",         cat: "pt",      level: "Level 3", format: "In-person", location: "Dubai",     rating: 4.4, duration: "6 wks"  },
  { id: "c2",  title: "Level 3 Personal Trainer",         cat: "pt",      level: "Level 3", format: "Online",    location: "Online",    rating: 4.6, duration: "8-14 wks" },
  { id: "c3",  title: "Level 3 Personal Trainer",         cat: "pt",      level: "Level 3", format: "In-person", location: "Dubai",     rating: 4.7, duration: "4 wks"  },
  { id: "c4",  title: "Level 2 Gym Instructor",           cat: "gym",     level: "Level 2", format: "In-person", location: "Abu Dhabi", rating: 4.2, duration: "4 wks"  },
  { id: "c5",  title: "Level 2 Gym Instructor",           cat: "gym",     level: "Level 2", format: "Online",    location: "Online",    rating: 4.4, duration: "4-8 wks" },
  { id: "c6",  title: "Group Fitness Instructor",         cat: "group",   level: "Level 2", format: "In-person", location: "Sharjah",   rating: 4.1, duration: "4 wks"  },
  { id: "c7",  title: "Group Fitness Freestyle",          cat: "group",   level: "Level 3", format: "Blended",   location: "Dubai",     rating: 4.5, duration: "6 wks"  },
  { id: "c8",  title: "Indoor Cycling Instructor",        cat: "group",   level: "Level 2", format: "In-person", location: "Dubai",     rating: 4.5, duration: "3 wks"  },
  { id: "c9",  title: "Pilates Instructor (Mat)",         cat: "pilates", level: "Level 3", format: "In-person", location: "Dubai",     rating: 4.8, duration: "8 wks"  },
  { id: "c10", title: "Reformer Pilates Comprehensive",   cat: "pilates", level: "Level 3", format: "In-person", location: "Dubai",     rating: 4.9, duration: "10 wks" },
  { id: "c11", title: "Yoga Teacher RYS 200",             cat: "yoga",    level: "Level 3", format: "In-person", location: "Dubai",     rating: 4.7, duration: "14 wks" },
  { id: "c12", title: "Aqua Fitness Instructor",          cat: "aqua",    level: "Level 2", format: "In-person", location: "Abu Dhabi", rating: 4.0, duration: "3 wks"  },
  { id: "c13", title: "Children's Fitness Instructor",    cat: "kids",    level: "Level 2", format: "In-person", location: "Dubai",     rating: 4.3, duration: "4 wks"  },
  { id: "c14", title: "Advanced Exercise Specialist",     cat: "advanced",level: "Level 4", format: "In-person", location: "Dubai",     rating: 4.8, duration: "12 wks" },
  { id: "c15", title: "Level 4 Master Personal Trainer",  cat: "advanced",level: "Level 4", format: "In-person", location: "Dubai",     rating: 4.7, duration: "14 wks" },
];
const PROVIDERS = [];
const LEVELS = ["Level 2", "Level 3", "Level 4"];
window.TR_CONTENT.REP_CATEGORIES = REP_CATEGORIES;
window.TR_CONTENT.COURSES = [];           // populated live from /api/quals (published only)
window.TR_CONTENT.PROVIDERS = PROVIDERS;
window.TR_CONTENT.LEVELS = LEVELS;
window.TR_CONTENT.DETAIL_BY_ID = {};

/* ── LIVE: load published, categorized courses from the report-server API.
   Approve a course in the db-viewer (published=1) -> it appears here.
   The demo COURSES array above is kept only as an offline fallback.        ── */
(function loadLiveCourses() {
  // Published registry now lives in Supabase (Plan 1, 2026-06-11) - the site is
  // independent of this Mac. registry_quals/registry_providers are public-read;
  // synced from db/canonical.db published=1 by orchestrator/jobs/sync-supabase.js.
  var SB_URL  = 'https://uyhnfysmsfiagotjfqjs.supabase.co';
  var SB_ANON = 'sb_publishable_MlNmf3BIRPXHqjxgyR7VdA_fZXiCMxp';
  function card(q) {
    return {
      id: 'q' + q.id, _id: q.id,
      title: q.qualification_title,
      cat: q.category || 'pt',
      level: q.qualification_level || '',
      format: 'See provider',
      location: 'United Arab Emirates',
      rating: null,
      duration: q.duration_plain || '',
      awarder: q.awarder || '',
      status: q.current_status || ''
    };
  }
  function apply(quals) {
    window.TR_CONTENT.COURSES = quals.map(card);
    window.TR_CONTENT.DETAIL_BY_ID = {};
    quals.forEach(function (q) { window.TR_CONTENT.DETAIL_BY_ID['q' + q.id] = q; });
    // self-subscribing components (e.g. LiveCount) listen for this; independent of __TR_RELOAD timing
    try { window.dispatchEvent(new Event('tr:courses-loaded')); } catch (e) {}
    // re-render once the app is mounted; stop as soon as the hook fires.
    var tries = 0;
    (function notify() {
      if (window.__TR_RELOAD) { window.__TR_RELOAD(); return; }
      if (tries++ < 20) setTimeout(notify, 150);
    })();
  }
  function load(attempt) {
    // supabase.js loads before this file, but guard for race on slow connections.
    if (!window.supabase || !window.supabase.createClient) {
      if (attempt < 40) return setTimeout(function () { load(attempt + 1); }, 150);
      return; // supabase-js never loaded -> COURSES stays empty (no fabricated courses)
    }
    var sb = window.supabase.createClient(SB_URL, SB_ANON);
    Promise.all([
      sb.from('registry_quals').select('*'),
      sb.from('registry_providers').select('*')
    ]).then(function (res) {
      var quals = (res[0] && res[0].data) || [];
      var provs = (res[1] && res[1].data) || [];
      if (!quals.length) return;
      // group providers under each qual - SAME shape the old /api/quals returned
      var provMap = {};
      provs.forEach(function (p) {
        (provMap[p.qualification_id] = provMap[p.qualification_id] || []).push({
          provider_name: p.provider_name, course_name: p.course_name,
          tier: p.provider_tier, url: p.provider_url, source_url: p.source_url
        });
      });
      quals.forEach(function (q) { q.providers = provMap[q.id] || []; });
      apply(quals);
    }).catch(function () { /* Supabase unreachable -> COURSES stays empty (no fabricated courses) */ });
  }
  load(0);
})();

/* ── Articles (the News page + readers) ──
   body[] entries: a string is a paragraph; { h } is a sub-head; { q } is a pull-quote.
   takeaway = the one-line bottom line. sources = research/further reading. */
const ARTICLES = [
  { id: "a1", category: "Pay", tone: "amber", title: "How much should a Level 3 PT charge per session in 2026?", date: "1 hr ago", read: "6 min",
    dek: "Rates have moved this year. Here's the honest range across Dubai, Abu Dhabi and Sharjah, and how to set yours without underselling.",
    body: [
      "If you've just qualified, the single most common question is also the most awkward: what do I actually charge? Providers rarely tell you, because it isn't their job once they've sold you the course.",
      { h: "The 2026 range, by emirate" },
      "In 2026, a newly certified Level 3 PT in Dubai is realistically charging AED 150 to 250 per session in a commercial gym, rising to AED 300 or more once you have a waitlist and a specialism. Abu Dhabi tracks slightly lower; Sharjah lower again.",
      "Those are floor-and-ceiling numbers, not a promise. Where you land inside the band depends on three things: the gym's own pricing, how booked you are, and whether you carry a specialism clients will pay extra for.",
      { h: "Why retention beats your rate" },
      "The bigger lever isn't your rate, it's your retention. A trainer charging AED 200 with clients who stay six months out-earns one charging AED 350 with churn every three weeks. Price for the relationship, not the hour.",
      { q: "Price for the relationship, not the hour." },
      "Our advice: start at the middle of your local range, raise it once you're 80% booked, and never discount below the gym's own rate - it signals you're the cheaper option rather than the better one.",
    ],
    takeaway: "Start mid-band, raise your rate once you're ~80% booked, and never undercut the gym's own pricing.",
    sources: [
      { t: "REPs UAE - National Register of Exercise Professionals", k: "Regulator" },
      { t: "TrainerRegistry rate survey, Q1 2026 (n=410 UAE trainers)", k: "Primary survey" },
      { t: "Dubai Sports Council - Fitness Sector Overview 2025", k: "Industry data" },
    ] },

  { id: "a2", category: "Hiring", tone: "brand", title: "Why every UAE gym is suddenly fighting over HIIT coaches", date: "Yesterday", read: "4 min",
    dek: "Group formats are the fastest-growing slot on the timetable, and qualified coaches can't be hired fast enough.",
    body: [
      "Walk into almost any UAE gym in 2026 and the busiest room isn't the weights floor, it's the group studio. HIIT, bootcamp and hybrid race formats have moved from a perk to the main draw.",
      { h: "Demand outran supply" },
      "That demand has outpaced supply. Gyms are now offering guaranteed class blocks and higher per-class rates to lock in qualified group fitness instructors before a competitor does.",
      "Class blocks matter more than they sound: a guaranteed eight classes a week is income you can plan around, which is rare in early-career coaching.",
      { h: "The fastest add-on this year" },
      "If you already hold a Personal Trainer cert, adding a Group Fitness qualification is one of the fastest ways to raise your income this year, often paying for itself within a month of classes.",
      "It's also the lowest-risk specialism to test: most providers run it in a few weekends, so you can be on a timetable inside a month.",
    ],
    takeaway: "If you already hold a PT cert, a Group Fitness add-on is the quickest, lowest-risk income bump available right now.",
    sources: [
      { t: "REPs UAE - Approved Group Fitness qualifications", k: "Regulator" },
      { t: "TrainerRegistry job-board postings, rolling 90 days", k: "Listings data" },
    ] },

  { id: "a3", category: "Regulation", tone: "brand", title: "REPs UAE added Level 4 Pilates to the approved register", date: "2 days ago", read: "5 min",
    dek: "If you teach Pilates, this is the cert that now lets you work legally in licensed studios. Three providers are already running it.",
    body: [
      "REPs UAE has expanded its approved register to include an advanced Pilates qualification, formalising a discipline that has exploded across the Emirates.",
      { h: "What it changes for instructors" },
      "For instructors, the practical effect is simple: studios that want to stay compliant will increasingly ask for the approved cert, and the ones who hold it first will have their pick of the new openings.",
      "Expect job ads to start specifying \"REPs-approved\" within the year. Being early is the whole advantage here.",
      { h: "Mind the price spread" },
      "Prices vary widely between the three providers currently running it, so this is exactly the kind of course worth comparing before you commit. Same register, same recognition - very different invoices.",
      { q: "Same register, same recognition - very different invoices." },
    ],
    takeaway: "The approved Level 4 cert is becoming the studio standard - get it early, but compare providers before you pay.",
    sources: [
      { t: "REPs UAE - Register update notice, 2026", k: "Regulator" },
      { t: "TrainerRegistry provider price tracker", k: "Price data" },
    ] },

  { id: "a4", category: "Market", tone: "amber", title: "Pilates studios in the UAE have doubled since 2023", date: "3 days ago", read: "4 min",
    dek: "A boutique boom is reshaping where the jobs are, and reformer-qualified instructors are the ones benefiting.",
    body: [
      "The number of dedicated Pilates and reformer studios in the UAE has roughly doubled in two years, concentrated in Dubai and Abu Dhabi but spreading to the northern emirates.",
      { h: "Every new studio needs a roster" },
      "Each new studio needs a roster of qualified instructors, and reformer-specific training is the credential that opens those doors.",
      "Owners consistently say the same thing: the bottleneck on opening a second location isn't demand or rent, it's finding enough qualified reformer instructors.",
      { h: "The maths favours specialising" },
      "For anyone weighing a specialism, the maths is favourable: high demand, limited supply of qualified instructors, and clients who pay a premium for small-group sessions.",
    ],
    takeaway: "Reformer-specific qualification is the credential the boutique boom is short of - and willing to pay for.",
    sources: [
      { t: "TrainerRegistry studio census, 2023 vs 2026", k: "Primary count" },
      { t: "Dubai Economy & Tourism - new fitness licences", k: "Licensing data" },
    ] },

  { id: "a5", category: "Visa & licensing", tone: "neutral", title: "New freelance permit makes it easier to train clients solo", date: "1 week ago", read: "6 min",
    dek: "The route to coaching independently, without a gym taking a cut, just got clearer. Here's what it means for you.",
    body: [
      "A freelance permit aimed at fitness professionals is making it more practical to coach clients on your own terms, rather than splitting every session with a gym.",
      { h: "Who it suits" },
      "It won't suit everyone - you give up the gym's foot traffic and facilities - but for established trainers with a full book it can meaningfully change take-home pay.",
      "The break-even is roughly the point where what the gym takes from your sessions exceeds the permit and insurance costs. If you're already turning clients away, you're probably past it.",
      { h: "Who should wait" },
      "If you're early in your career, build your client base inside a gym first. The permit is most powerful once you already have demand you can take with you.",
    ],
    takeaway: "The permit pays off once you have a full book to take with you - build demand inside a gym first.",
    sources: [
      { t: "UAE freelance permit - official guidance", k: "Government" },
      { t: "TrainerRegistry independent-trainer interviews (n=18)", k: "Qualitative" },
    ] },

  { id: "a6", category: "Hiring", tone: "brand", title: "Hotels are quietly becoming the best-paying fitness employers", date: "1 week ago", read: "5 min",
    dek: "Resort gyms and wellness floors are hiring trainers on packages that put many commercial gyms to shame.",
    body: [
      "While everyone watches the big gym chains, five-star hotels and resorts have been building serious wellness operations, and they pay for it.",
      { h: "It's the package, not just the salary" },
      "Packages often bundle accommodation or transport, and the clientele tips well. The catch is they want polish: presentation, languages and service skills matter as much as your cert.",
      "When you add housing and transport back in, a mid-range resort offer can quietly beat a higher headline salary at a commercial gym.",
      { h: "How to make yourself hireable" },
      "If you're personable and qualified, it's one of the most overlooked routes to a comfortable income in the UAE. A second language and genuine service polish move you to the top of the pile.",
    ],
    takeaway: "Resort wellness roles compete on the whole package - qualify, then invest in service polish and a second language.",
    sources: [
      { t: "TrainerRegistry hospitality-sector listings", k: "Listings data" },
      { t: "Hotel fitness manager interviews, 2026", k: "Qualitative" },
    ] },

  { id: "a7", category: "Pay", tone: "amber", title: "Online coaching: the realistic numbers for UAE trainers", date: "1 week ago", read: "6 min",
    dek: "Everyone says go online. Here's what trainers are actually earning, and how long it takes to get there.",
    body: [
      "Online coaching is pitched as the escape from trading hours for money. It can be, but the ramp is slower than the influencers admit.",
      { h: "The quiet first year" },
      "Most trainers who make it work spend six to twelve months building an audience and a system before it replaces in-person income. The ceiling is high; the start is quiet.",
      { q: "The ceiling is high; the start is quiet." },
      "The ones who stall usually quit in month four - right before the compounding starts to show.",
      { h: "Treat it as a second stream" },
      "Treat it as a second income stream you grow alongside in-person work, not a switch you flip. The trainers who burn out are the ones who bet everything on it before the system was proven.",
    ],
    takeaway: "Grow online alongside in-person work - most successful coaches take 6-12 months before it replaces a salary.",
    sources: [
      { t: "TrainerRegistry online-coach survey (n=96)", k: "Primary survey" },
      { t: "Platform payout benchmarks, 2026", k: "Industry data" },
    ] },

  { id: "a8", category: "Regulation", tone: "neutral", title: "What 'REPs approved' actually guarantees you", date: "2 weeks ago", read: "4 min",
    dek: "The badge gets thrown around a lot. Here's exactly what it does and doesn't mean for your right to work.",
    body: [
      "A REPs UAE-approved course means the qualification is recognised by the register, which is what lets you work legally in compliant gyms and studios.",
      { h: "What it does not mean" },
      "What it does not mean is that every approved course is equal in quality, price or teaching. Approval is the floor, not a ranking.",
      { q: "Approval is the floor, not a ranking." },
      "Two courses can carry the same badge while differing by thousands of dirhams and by whether the exam fee is included at all.",
      { h: "Why comparing pays" },
      "That's exactly why comparing approved courses, rather than assuming they're interchangeable, saves people thousands. The badge gets you the right to work; comparison gets you there for less.",
    ],
    takeaway: "Approval is the legal floor, not a quality ranking - always compare approved courses on real all-in cost.",
    sources: [
      { t: "REPs UAE - What approval means", k: "Regulator" },
      { t: "TrainerRegistry all-in cost comparisons", k: "Price data" },
    ] },

  { id: "a9", category: "Market", tone: "brand", title: "The company trying to run PT for the world - and what it means for UAE trainers", date: "Today", read: "5 min",
    dek: "Enhance's CEO just went on record about their global ambitions. Here's the thesis, and why UAE-based trainers should be paying attention.",
    body: [
      "Tarek Mounir, CEO of Enhance, gave Gulf Business a rare public interview this week outlining the company's bid to run personal training operations globally - not just in the UAE.",
      { h: "What Enhance is actually building" },
      "The core thesis is infrastructure: building the systems, scheduling and standards that let a PT operation scale across multiple markets without losing quality. Think less 'big gym chain' and more 'operating system for fitness businesses.' The UAE is the proving ground, but the expansion roadmap points to other GCC markets and beyond.",
      "It's a bet that the PT industry is still fragmented enough to be consolidated, and that whoever builds the back-end infrastructure first wins the market.",
      { h: "What this means for individual trainers" },
      "A scaled operator like this cuts both ways. The upside is steady work and a proper employment structure in a market where many trainers are still cobbling together freelance income. The downside is the same as any consolidation: rates tend to standardise, which isn't great if you're already earning at the top of the range.",
      { q: "Infrastructure beats hustle - until it sets the ceiling." },
      "Our read: if you're early in your career and want structure, a growing operator is a real opportunity. If you're an independent trainer with a full book, the market is still fragmented enough that you hold your own. For now.",
    ],
    takeaway: "Scaled operators bring structure for early-career trainers, but standardise rates at the top - know which side of that trade you're on.",
    sources: [
      { t: "Gulf Business - Tarek Mounir on Enhance's global bid, Jun 2026", k: "Primary interview" },
      { t: "TrainerRegistry market analysis", k: "Context" },
    ] },

  { id: "a10", category: "Market", tone: "amber", title: "UAE gym attendance spiked - but not for the reason you'd expect", date: "Today", read: "4 min",
    dek: "Since geopolitical tension rose in the region, gyms across the UAE have been reporting an unexpected pattern. Members are framing training differently.",
    body: [
      "The National spoke to gym operators across the UAE this spring about a pattern that caught them off guard: members who had lapsed or tapered off were coming back, and the conversations around why had shifted.",
      { h: "From stress relief to sharpness" },
      "The old narrative was fitness-as-stress-relief - a pressure valve. The new framing is more purposeful: members are describing training as a tool to stay focused, structured and sharp in an uncertain environment. Less about the emotional release, more about maintaining a baseline of cognitive function and routine.",
      "\"People are treating the gym like they treat sleep - as infrastructure, not a luxury,\" one Dubai operator told The National.",
      { h: "What this means if you're coaching" },
      "For coaches, there's a real opening here. Clients who come through the door for mental clarity rather than a weight-loss target are often more consistent, more coachable and more willing to invest in the long term. The conversation around outcomes just has to shift with them.",
      "Understanding the full range of what clients are actually looking for - not just the physical goals - is becoming a genuine differentiator. The trainers who ask the right questions at intake will hold onto these clients far longer.",
      { q: "The trainers who ask the right questions at intake will hold onto these clients far longer." },
    ],
    takeaway: "Clients are returning for focus and routine, not just fitness - coaches who understand that and adjust their intake conversations have a real retention edge.",
    sources: [
      { t: "The National - How UAE gyms are helping people cope with uncertainty, Apr 2026", k: "Primary reporting" },
      { t: "TrainerRegistry trainer interviews, Q2 2026", k: "Qualitative" },
    ] },

  { id: "a11", category: "Hiring", tone: "brand", title: "The fitness jobs that aren't in Dubai - Bangkok, Bali and what they actually pay", date: "Today", read: "5 min",
    dek: "Not everyone wants a UAE gym. Here's a real look at what's hiring abroad right now, from a new Bali community hub to a Bangkok science-based coaching studio.",
    body: [
      "Dubai dominates the conversation about fitness careers, and understandably - the pay is strong, the market is structured, and the REPs system gives everyone a clear qualification path. But a different tier of career exists in Southeast Asia, and some of it is genuinely interesting.",
      { h: "Runamuk - Pererenan, Bali" },
      "A brand-new community hub called Runamuk is hiring its opening team in Pererenan on Bali's southwest coast. The area has shifted over the last few years from a surf spot into a serious wellness and athlete community - think daily runners, open-water swimmers, and a gym culture that isn't resort-adjacent.",
      "The draw isn't the salary, which won't match Dubai. It's being part of something from day one. Opening-team roles at independent community facilities tend to shape the culture of the place, which is a rare thing at any stage of a career.",
      { h: "BASE Bangkok" },
      "BASE is a science-based performance coaching studio in Bangkok, well-placed on the BTS/MRT network. Roles require a current NASM or equivalent international certification and at least two years of experience. Critically, the company provides full work permits - which matters more than it sounds. Navigating Thai work authorisation alone is a serious overhead for a foreign trainer, and studios that handle it are the exception, not the rule.",
      { h: "THE BARAI HUA HIN - Hyatt Unbound Collection, opening mid-2026" },
      "A new Unbound Collection property by Hyatt is opening on Thailand's Gulf coast in Hua Hin. Resort fitness roles at this tier come with accommodation and transport packages, an international clientele, and a wellness-forward brief. They're competitive - this tier of hotel wants presentation, languages and service polish alongside the qualification - but the all-in package can sit very comfortably against a mid-range Dubai salary once you factor in housing.",
      { h: "What these gigs actually offer" },
      "None of these pay Dubai rates. What they offer instead: novel environments, genuine independence, and - in Bali's case - a cost of living that resets what your savings are worth. They suit a specific career moment: someone who has already built their competence in a structured market and wants to deploy it somewhere unusual, without starting over.",
      { q: "Build the skill in a structured market. Then take it somewhere interesting." },
    ],
    takeaway: "Southeast Asia pays less but offers something Dubai doesn't - novelty, independence, and a cost structure that changes what your savings are worth.",
    sources: [
      { t: "BASE Bangkok - Careers page, Jun 2026", k: "Direct listing" },
      { t: "Jobstreet - Personal Trainer Jobs in Bali, Jun 2026", k: "Listings data" },
      { t: "Hyatt Unbound Collection - THE BARAI HUA HIN opening 2026", k: "Hotel announcement" },
    ] },
];

window.TR_CONTENT.ARTICLES = ARTICLES;

/* ── Real photography (Unsplash, free license) ──────────────────────────────
   Each key maps to an Unsplash photo id. photoUrl(key,w) builds a CDN URL;
   components fall back to the local img/<id>.jpg gradient via onError if a
   photo can't load (e.g. offline). Swap an id, or drop a real file at
   img/<id>.jpg and delete the entry, to change any image. */
const UNS_ID = {
  pt:           "1534438327276-14e5300c3a48",
  hyrox:        "1534258936925-c58bed479fcb",
  reformer:     "1518611012118-696072aa579a",
  cycling:      "1532384748853-8f54a8f476e2",
  snc:          "1581009146145-b5ef050c2e1e",
  hiit:         "1518310383802-640c2de311b2",
  online:       "1518459031867-a89b944bffe4",
  nutrition:    "1490645935967-10de6ba17061",
  boxing:       "1549719386-74dfcbf7dbed",
  yoga:         "1544367567-0f2fcb009e0b",
  prenatal:     "1506126613408-eca07ce68773",
  kids:         "1571388208497-71bedc66e932",
  calisthenics: "1598971639058-fab3c3109a00",
  mobility:     "1575052814086-f385e2e2ad1b",
  "snc-sport":  "1583454110551-21f2fa2afe61",
  _hero:        "1517836357463-d25dfeac3438",
  _cta:         "1599058917212-d750089bc07e",
};
window.TR_CONTENT.photoUrl = function (key, w) {
  const id = UNS_ID[key];
  return id ? "https://images.unsplash.com/photo-" + id + "?auto=format&fit=crop&w=" + (w || 1200) + "&q=75" : null;
};
