// ONOGolf — Swing vs Swing shared data + store
// Shared between the public view and the admin view via localStorage.
// Exported on window for Babel cross-script sharing.

const SVS_STORE_KEY = "ono_svs_v3";

// Brand-consistent avatar palette (matches site)
const SVS_COLORS = ["#5c6b3a", "#bf9a38", "#c4703a", "#286482", "#783c64", "#4a5e8a", "#3a6a5a", "#8a6b3a", "#a03c1e", "#5a7888"];

// Real, embeddable swing clips supplied for the mockup.
const CLIP_A = "P3YksJdejog"; // Rory McIlroy
const CLIP_B = "szCOX4mg2F4"; // Bryson DeChambeau

// Breakdown points are timestamped chapter markers read from the video transcript.
const mkPoints = (a) => a.map(([t, label, note]) => ({ t, label, note }));

// PGA / World-ranking top 10 (OWGR order as of May 2026).
// Each player carries their signature swing clip + transcript breakdown points.
// Real launch numbers come from a launch monitor — these are realistic demo
// values, editable in Admin. PGA TOUR season averages shown as benchmarks.
const SVS_DEFAULT_PLAYERS = [
  { id: "p1",  rank: 1,  name: "Scottie Scheffler", country: "USA", initials: "SS", color: SVS_COLORS[0], photo: "assets/players/scottie-scheffler.jpg",
    clip: CLIP_A, videoTitle: "Full swing — down the line",
    points: mkPoints([["0:02","Setup","Wide base, signature footwork"],["0:06","Backswing","Deliberate, unhurried takeaway"],["0:10","Transition","Famous lateral foot slide"],["0:14","Impact","Hands incredibly quiet"],["0:17","Finish","Controlled, repeatable"]]),
    stats: { clubSpeed: 116.5, ballSpeed: 174.2, smash: 1.49, driverCarry: 296, ironCarry: 178, apex: 102 } },
  { id: "p2",  rank: 2,  name: "Rory McIlroy",      country: "NIR", initials: "RM", color: SVS_COLORS[1], photo: "assets/players/rory-mcilroy.jpg",
    clip: CLIP_A, videoTitle: "Driver — face on",
    points: mkPoints([["0:03","Setup","Slight tilt away, ball forward"],["0:06","Backswing","Effortless width, parallel at top"],["0:10","Downswing","Ground force — left heel re-plants"],["0:14","Impact","Late release, speed signature"],["0:18","Finish","Tall, balanced, full extension"]]),
    stats: { clubSpeed: 122.3, ballSpeed: 183.1, smash: 1.50, driverCarry: 318, ironCarry: 182, apex: 109 } },
  { id: "p3",  rank: 3,  name: "Xander Schauffele", country: "USA", initials: "XS", color: SVS_COLORS[2], photo: "assets/players/xander-schauffele.jpg",
    clip: CLIP_B, videoTitle: "7-iron — face on",
    points: mkPoints([["0:03","Setup","Athletic, weight centered"],["0:07","Backswing","Smooth tempo, full turn"],["0:11","Transition","Sequenced hips → torso → arms"],["0:15","Impact","Compression, hands lead"],["0:18","Finish","Balanced hold"]]),
    stats: { clubSpeed: 118.1, ballSpeed: 176.9, smash: 1.49, driverCarry: 302, ironCarry: 179, apex: 105 } },
  { id: "p4",  rank: 4,  name: "Ludvig Åberg",      country: "SWE", initials: "LÅ", color: SVS_COLORS[3], photo: "assets/players/ludvig-aberg.jpg",
    clip: CLIP_B, videoTitle: "Driver — down the line",
    points: mkPoints([["0:02","Setup","Tall, modern posture"],["0:06","Backswing","Textbook width"],["0:10","Transition","Smooth pressure shift"],["0:14","Impact","Pure speed, low spin"],["0:17","Finish","Effortless balance"]]),
    stats: { clubSpeed: 120.4, ballSpeed: 180.0, smash: 1.50, driverCarry: 311, ironCarry: 181, apex: 107 } },
  { id: "p5",  rank: 5,  name: "Collin Morikawa",   country: "USA", initials: "CM", color: SVS_COLORS[4], photo: "assets/players/collin-morikawa.jpg",
    clip: CLIP_A, videoTitle: "7-iron — down the line",
    points: mkPoints([["0:02","Address","Neutral grip, hands ahead"],["0:06","Halfway back","Shaft splits the forearms"],["0:10","Top","Compact, no overswing"],["0:13","Impact","Ball-first, shallow divot"],["0:16","Release","Held-off — the fade signature"]]),
    stats: { clubSpeed: 114.8, ballSpeed: 170.6, smash: 1.49, driverCarry: 289, ironCarry: 176, apex: 99 } },
  { id: "p6",  rank: 6,  name: "Bryson DeChambeau", country: "USA", initials: "BD", color: SVS_COLORS[5], photo: "assets/players/bryson-dechambeau.jpg",
    clip: CLIP_B, videoTitle: "Driver — power swing",
    points: mkPoints([["0:02","Wide setup","Feet well outside shoulders to brace speed"],["0:05","Takeaway","One-piece, club outside the hands"],["0:09","Top","Huge turn, lead arm above plane"],["0:13","Transition","Aggressive lower-body shift"],["0:17","Impact","Shaft lean, hips fully cleared"]]),
    stats: { clubSpeed: 133.2, ballSpeed: 197.4, smash: 1.48, driverCarry: 332, ironCarry: 190, apex: 112 } },
  { id: "p7",  rank: 7,  name: "Justin Thomas",     country: "USA", initials: "JT", color: SVS_COLORS[6], photo: "assets/players/justin-thomas.jpg",
    clip: CLIP_A, videoTitle: "Driver — face on",
    points: mkPoints([["0:03","Setup","Narrow, dynamic"],["0:07","Backswing","Deep turn, big extension"],["0:11","Transition","Explosive lower body"],["0:15","Impact","Jump through the ball"],["0:18","Finish","Recoil finish"]]),
    stats: { clubSpeed: 119.6, ballSpeed: 178.2, smash: 1.49, driverCarry: 305, ironCarry: 180, apex: 106 } },
  { id: "p8",  rank: 8,  name: "Hideki Matsuyama",  country: "JPN", initials: "HM", color: SVS_COLORS[7], photo: "assets/players/hideki-matsuyama.jpg",
    clip: CLIP_B, videoTitle: "Full swing — the pause",
    points: mkPoints([["0:03","Setup","Quiet address"],["0:07","Top","Trademark pause at the top"],["0:11","Transition","Stored lag released late"],["0:15","Impact","Crisp strike"],["0:18","Finish","Full wrap-around"]]),
    stats: { clubSpeed: 115.9, ballSpeed: 172.8, smash: 1.49, driverCarry: 293, ironCarry: 177, apex: 101 } },
  { id: "p9",  rank: 9,  name: "Russell Henley",    country: "USA", initials: "RH", color: SVS_COLORS[8], photo: "assets/players/russell-henley.jpg",
    clip: CLIP_B, videoTitle: "Wedge — short game",
    points: mkPoints([["0:03","Setup","Open stance, weight forward"],["0:06","Backswing","Quiet lower body"],["0:10","Impact","Crisp, descending"],["0:13","Finish","Held finish"]]),
    stats: { clubSpeed: 112.4, ballSpeed: 167.9, smash: 1.49, driverCarry: 284, ironCarry: 174, apex: 97 } },
  { id: "p10", rank: 10, name: "Tommy Fleetwood",   country: "ENG", initials: "TF", color: SVS_COLORS[9], photo: "assets/players/tommy-fleetwood.jpg",
    clip: CLIP_B, videoTitle: "Long iron — classic",
    points: mkPoints([["0:02","Setup","Classic, flowing posture"],["0:06","Backswing","Rounded, rhythmic"],["0:10","Transition","Smooth, no rush"],["0:14","Impact","Sweeping strike"],["0:17","Finish","Elegant balance"]]),
    stats: { clubSpeed: 117.3, ballSpeed: 175.5, smash: 1.50, driverCarry: 299, ironCarry: 179, apex: 104 } },
];

// PGA TOUR season-average benchmarks (pgatour.com/stats) — drawn as a marker on bars.
const SVS_TOUR_AVG = { clubSpeed: 115.5, ballSpeed: 171.4, smash: 1.49, driverCarry: 290, ironCarry: 176, apex: 100 };

const SVS_STAT_DEFS = [
  { key: "clubSpeed",   label: "Club Head Speed", unit: "mph",  max: 140, dec: 1 },
  { key: "ballSpeed",   label: "Ball Speed",      unit: "mph",  max: 205, dec: 1 },
  { key: "smash",       label: "Smash Factor",    unit: "",     max: 1.52, min: 1.40, dec: 2 },
  { key: "driverCarry", label: "Driver Carry",    unit: "yds",  max: 345, dec: 0 },
  { key: "ironCarry",   label: "7-Iron Carry",    unit: "yds",  max: 200, dec: 0 },
  { key: "apex",        label: "Apex Height",     unit: "ft",   max: 120, dec: 0 },
];

// Featured matchups — shortcuts that set both positions at once.
const SVS_DEFAULT_CHALLENGES = [
  { id: "c1", title: "The Power Driver",  category: "Driver", leftId: "p6", rightId: "p2" },
  { id: "c2", title: "Iron Precision",    category: "Iron",   leftId: "p5", rightId: "p3" },
  { id: "c3", title: "Tempo Masters",     category: "Tempo",  leftId: "p1", rightId: "p8" },
  { id: "c4", title: "Rising Stars",      category: "Driver", leftId: "p4", rightId: "p7" },
  { id: "c5", title: "Short-Game Touch",  category: "Wedge",  leftId: "p1", rightId: "p9" },
  { id: "c6", title: "Classic vs Modern", category: "Iron",   leftId: "p10", rightId: "p2" },
];

const SVS_DEFAULTS = { players: SVS_DEFAULT_PLAYERS, challenges: SVS_DEFAULT_CHALLENGES };

// ---- Store: localStorage-backed, falls back to defaults ----
function svsLoad() {
  try {
    const raw = localStorage.getItem(SVS_STORE_KEY);
    if (!raw) return structuredClone(SVS_DEFAULTS);
    const data = JSON.parse(raw);
    if (!data.players || !data.challenges) return structuredClone(SVS_DEFAULTS);
    // Heal stores persisted before the headshot assets existed: backfill the
    // photo from the matching default player whenever the stored photo is
    // missing, null, or empty. Admin-uploaded photos (truthy) win; custom
    // players with no matching default keep whatever they have.
    const defPhoto = {};
    SVS_DEFAULT_PLAYERS.forEach(d => {
      if (d.photo) { defPhoto["id:" + d.id] = d.photo; defPhoto["name:" + d.name] = d.photo; }
    });
    data.players = data.players.map(p => {
      if (p.photo) return p;
      const photo = defPhoto["id:" + p.id] || defPhoto["name:" + p.name];
      return photo ? { ...p, photo } : p;
    });
    return data;
  } catch (e) {
    return structuredClone(SVS_DEFAULTS);
  }
}
function svsSave(data) {
  try { localStorage.setItem(SVS_STORE_KEY, JSON.stringify(data)); } catch (e) {}
}
function svsReset() {
  try { localStorage.removeItem(SVS_STORE_KEY); } catch (e) {}
  return structuredClone(SVS_DEFAULTS);
}

// Parse a YouTube URL or raw id → 11-char id
function svsParseYt(input) {
  if (!input) return "";
  const s = input.trim();
  if (/^[\w-]{11}$/.test(s)) return s;
  const m = s.match(/(?:youtu\.be\/|v=|embed\/|shorts\/)([\w-]{11})/);
  return m ? m[1] : "";
}
// "1:23" or seconds → seconds
function svsToSeconds(t) {
  if (typeof t === "number") return t;
  if (!t) return 0;
  const parts = String(t).split(":").map(Number);
  if (parts.some(isNaN)) return 0;
  return parts.reduce((acc, p) => acc * 60 + p, 0);
}

Object.assign(window, {
  SVS_STORE_KEY, SVS_COLORS, SVS_DEFAULTS, SVS_DEFAULT_PLAYERS, SVS_DEFAULT_CHALLENGES,
  SVS_TOUR_AVG, SVS_STAT_DEFS, svsLoad, svsSave, svsReset, svsParseYt, svsToSeconds,
});
