// Club picker cards, formation board, league table, trophy cabinet, register, final CTA

/* ===== CLUB PICKER — real clubs without a manager ===== */
const ClubPicker = () => {
  const d = (window.PM_DATA || {});
  const T = d.t || {};
  const QSCALE = T.qualityScale || ["Awful","Very Bad","Bad","Weak","Reasonable","Good","Very Good","Excellent","Formidable","World Class"];
  const open = Array.isArray(d.openClubs) ? d.openClubs : [];
  const demo = [
    { id: 0, n: "FC Odivelas", div: "A-2", flag: "PT", form: ["W","W","D","L","W"], rep: 78, skill: 72, c1: "#2a6a3a", c2: "#f4c040", init: "FCO" },
    { id: 0, n: "Pelouros FC", div: "A-2", flag: "PT", form: ["L","W","W","D","W"], rep: 72, skill: 64, c1: "#b53a3a", c2: "#ffffff", init: "PEL" },
    { id: 0, n: "Bitcoin FC",  div: "B-1", flag: "BR", form: ["W","W","W","W","W"], rep: 91, skill: 85, c1: "#f4a020", c2: "#1a1a1a", init: "BTC" },
    { id: 0, n: "Saraiva",     div: "A-1", flag: "BR", form: ["D","L","W","D","W"], rep: 68, skill: 58, c1: "#2f5fb5", c2: "#ffd44e", init: "SAR" },
    { id: 0, n: "Frozen Penguin", div: "C-2", flag: "FR", form: ["W","D","D","W","L"], rep: 54, skill: 46, c1: "#4aa8c8", c2: "#ffffff", init: "FRO" },
    { id: 0, n: "Giants FC",   div: "B-4", flag: "US", form: ["W","W","L","W","W"], rep: 82, skill: 74, c1: "#5a2a8a", c2: "#f4c040", init: "GIA" },
  ];

  // clubes.form is "0=W 1=L 2=D"; take the last 5 digits for the card dots.
  const parseForm = (s) => {
    const map = { "0": "W", "1": "L", "2": "D" };
    const str = (s || "").toString();
    const out = [];
    for (let i = Math.max(0, str.length - 5); i < str.length; i++) {
      const ch = map[str[i]]; if (ch) out.push(ch);
    }
    while (out.length < 5) out.push("D");
    return out;
  };
  const divName = (div, serie) => {
    const letter = (div >= 1 && div <= 7) ? "ABCDEFG"[div - 1] : ("D" + div);
    return div === 1 ? letter : (letter + "-" + serie);
  };
  const qualityLabel = (n) => {
    const v = Math.max(0, Math.min(100, Math.round(n || 0)));
    let idx;
    if (v <= 10) idx = 0;
    else if (v <= 20) idx = 1;
    else if (v <= 30) idx = 2;
    else if (v <= 40) idx = 3;
    else if (v <= 50) idx = 4;
    else if (v <= 60) idx = 5;
    else if (v <= 70) idx = 6;
    else if (v <= 80) idx = 7;
    else if (v <= 90) idx = 8;
    else idx = 9;
    return QSCALE[idx] || "";
  };
  const initials = (name) => {
    const clean = (name || "").toUpperCase().replace(/[^A-Z]/g, "");
    return (clean || "???").slice(0, 3);
  };
  const fmtMoney = (n) => {
    if (n >= 1000000) return "€" + (n / 1000000).toFixed(1) + "M";
    if (n >= 1000)    return "€" + Math.round(n / 1000).toLocaleString() + "k";
    return "€" + (n || 0).toLocaleString();
  };
  // Deterministic palette fallback when cor_shirt is empty (body parses to
  // the neutral grey fallback). Seeded by clube_id so each club always picks
  // the same pair, but different clubs look distinct.
  const PALETTE = [
    ["#b53a3a","#ffffff"], ["#2f5fb5","#ffd44e"], ["#2a6a3a","#f4c040"],
    ["#5a2a8a","#f4c040"], ["#d97a4a","#1a1a1a"], ["#f4a020","#1a1a1a"],
    ["#4aa8c8","#ffffff"], ["#1e5e30","#c0e4c8"], ["#8a4a24","#e8c29a"],
    ["#3a7fc0","#ffffff"], ["#8e2a4b","#f4c040"], ["#0e7c66","#ffffff"],
  ];
  const pickPalette = (id) => PALETTE[Math.abs(((id || 0) * 7) + 3) % PALETTE.length];
  const isGrey = (hex) => !hex || hex.toLowerCase() === "#888888";

  const clubs = open.length > 0
    ? open.map(c => {
        const [fb, fc] = pickPalette(c.id);
        return {
          id:     c.id,
          n:      c.name,
          div:    divName(c.divisao, c.serie),
          paisId: c.paisId,
          sigla:  c.sigla,
          form:   parseForm(c.form),
          rep:    c.rep,
          skill:  c.skill,
          budget: fmtMoney(c.dinheiro),
          fans:   (c.socios || 0).toLocaleString(),
          c1:     isGrey(c.body)   ? fb : c.body,
          c2:     (c.collar && c.collar.toLowerCase() !== "#222222") ? c.collar : fc,
          init:   initials(c.name),
        };
      })
    : demo.map(c => ({ ...c, budget: "€" + (c.rep * 42).toLocaleString() + "k", fans: (c.rep * 137).toLocaleString() }));

  const onClaim = (clubeId) => (e) => {
    e.preventDefault();
    if (clubeId) {
      try { localStorage.setItem("pm_claim_club_id", String(clubeId)); } catch (err) {}
      try { window.dispatchEvent(new CustomEvent("pm:claim-changed", { detail: { clubeId } })); } catch (err) {}
    }
    const el = document.getElementById("register");
    if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
  };

  return (
    <section className="clubs" id="pick">
      <div className="sec-head">
        <div className="sec-eye">▸ 01. CHOOSE YOUR CLUB</div>
        <h2 className="sec-h2">Open clubs in your region. <span>Pick one, claim it.</span></h2>
        <p className="sec-lede">Real clubs in the game, currently without a manager. Take over — inherit the squad, the budget, the fans.</p>
      </div>
      <div className="clubs__grid">
        {clubs.map((c, i) => (
          <article key={c.id || i} className="card">
            <div className="card__top">
              <div className="card__div">DIV {c.div}</div>
              <div className="card__rarity">{qualityLabel(c.skill).toUpperCase()}</div>
            </div>
            <div className="card__crest-wrap"><Crest primary={c.c1} secondary={c.c2} initials={c.init}/></div>
            <div className="card__name">
              {c.paisId
                ? <img src={"/img/bandeiras-small/" + c.paisId + ".gif"} alt={c.sigla || ""} style={{height: 11, borderRadius: 1}}/>
                : <Flag code={c.flag}/>}
              <span>{c.n}</span>
            </div>
            <div className="card__form">
              {c.form.map((r, ri) => <span key={ri} className={"formdot formdot--" + r}>{r}</span>)}
            </div>
            <div className="card__stats">
              <div><span>REP</span><b>{c.rep}/100</b></div>
              <div><span>BUDGET</span><b>{c.budget}</b></div>
              <div><span>FANS</span><b>{c.fans}</b></div>
            </div>
            <a className="gbtn gbtn--cta gbtn--full" href="#register" onClick={onClaim(c.id)} style={{marginTop: 12}}>▶ {T.getTeam || "GET A TEAM"}</a>
          </article>
        ))}
      </div>
    </section>
  );
};

/* ===== FORMATION / TACTICS BOARD ===== */
const FORMATIONS = {
  "4-3-3": [[50,92],[15,72],[38,78],[62,78],[85,72],[25,52],[50,52],[75,52],[20,22],[50,15],[80,22]],
  "4-4-2": [[50,92],[15,72],[38,78],[62,78],[85,72],[15,48],[40,52],[60,52],[85,48],[38,20],[62,20]],
  "3-5-2": [[50,92],[25,78],[50,82],[75,78],[10,55],[32,50],[50,55],[68,50],[90,55],[38,22],[62,22]],
};
const POSNAMES = {
  "4-3-3": ["GK","LB","CB","CB","RB","CM","CM","CM","LW","ST","RW"],
  "4-4-2": ["GK","LB","CB","CB","RB","LM","CM","CM","RM","ST","ST"],
  "3-5-2": ["GK","CB","CB","CB","LWB","CM","CM","CM","RWB","ST","ST"],
};
const TacticsBoard = () => {
  // Options map to real clubes columns (see titulares.asp / titulares_v3.asp):
  //   atitude          → 0 Play it cool / 1 Normal / 2 Match of the Season
  //   tipo_pressao     → 0 None / 1 Low / 2 High
  //   contra_ataque    → 0/1  (counter attack)
  //   defesa_linha     → 0/1  (offside trap)
  //   high_balls       → 0/1
  //   long_shots       → 0/1
  //   desarme          → 0 Soft / 1 Normal / 2 Hard  (tackling)
  //   men_marking      → 0 Zonal / 1 Mixed / 2 Man
  const [f, setF] = React.useState("4-3-3");
  const [atitude, setAtitude] = React.useState(1);
  const [pressao, setPressao] = React.useState(2);
  const [counter, setCounter] = React.useState(true);
  const [offside, setOffside] = React.useState(false);
  const [highBalls, setHighBalls] = React.useState(false);
  const [longShots, setLongShots] = React.useState(true);
  const [desarme, setDesarme] = React.useState(1);
  const [marking, setMarking] = React.useState(0);
  const pos = FORMATIONS[f];
  const names = POSNAMES[f];
  const ATITUDE = [[0,"Play it cool"], [1,"Normal"], [2,"Match of the season"]];
  const PRESSAO = [[0,"None"], [1,"Low"], [2,"High"]];
  const DESARME = [[0,"Soft"], [1,"Normal"], [2,"Hard"]];
  const MARKING = [[0,"Zonal"], [1,"Mixed"], [2,"Man"]];
  return (
    <section className="tactics" id="tactics">
      <div className="sec-head">
        <div className="sec-eye">▸ 02. SET YOUR TACTICS</div>
        <h2 className="sec-h2">11 players. Dozens of formations. <span>One manager brain.</span></h2>
        <p className="sec-lede">A full tactical engine — positions, attitude, pressing, counter-attack, offside trap, tackling style. The match sim reads every decision.</p>
      </div>

      <div className="tactics__wrap">
        <div className="tactics__pitch">
          <div className="pitch">
            <div className="pitch__stripes"/>
            <div className="pitch__mid"/>
            <div className="pitch__circle"/>
            <div className="pitch__box pitch__box--top"/>
            <div className="pitch__box pitch__box--bot"/>
            <div className="pitch__spot pitch__spot--top"/>
            <div className="pitch__spot pitch__spot--bot"/>
            {pos.map((p, i) => (
              <div key={i} className={"player" + (i === 0 ? " player--gk" : "")} style={{left: p[0] + "%", top: p[1] + "%"}}>
                <PlayerIllus num={i + 1} isGk={i === 0}/>
                <div className="player__pos">{names[i]}</div>
              </div>
            ))}
            <div className="pitch__corner pitch__corner--tl"/>
            <div className="pitch__corner pitch__corner--tr"/>
            <div className="pitch__corner pitch__corner--bl"/>
            <div className="pitch__corner pitch__corner--br"/>
          </div>
        </div>

        <div className="tactics__panel">
          <div className="panel">
            <div className="panel__h">FORMATION</div>
            <div className="panel__row">
              {Object.keys(FORMATIONS).map(k => (
                <button key={k} className={"pbtn" + (f === k ? " is-on" : "")} onClick={() => setF(k)}>{k}</button>
              ))}
            </div>
          </div>
          <div className="panel">
            <div className="panel__h">ATTITUDE</div>
            <div className="panel__slider">
              {ATITUDE.map(([v, l]) => (
                <button key={v} className={"pbtn pbtn--sm" + (atitude === v ? " is-on" : "")} onClick={() => setAtitude(v)}>{l}</button>
              ))}
            </div>
          </div>
          <div className="panel">
            <div className="panel__h">PRESSING</div>
            <div className="panel__slider">
              {PRESSAO.map(([v, l]) => (
                <button key={v} className={"pbtn pbtn--sm" + (pressao === v ? " is-on" : "")} onClick={() => setPressao(v)}>{l}</button>
              ))}
            </div>
          </div>
          <div className="panel">
            <div className="panel__h">TACKLING</div>
            <div className="panel__slider">
              {DESARME.map(([v, l]) => (
                <button key={v} className={"pbtn pbtn--sm" + (desarme === v ? " is-on" : "")} onClick={() => setDesarme(v)}>{l}</button>
              ))}
            </div>
          </div>
          <div className="panel">
            <div className="panel__h">MARKING</div>
            <div className="panel__slider">
              {MARKING.map(([v, l]) => (
                <button key={v} className={"pbtn pbtn--sm" + (marking === v ? " is-on" : "")} onClick={() => setMarking(v)}>{l}</button>
              ))}
            </div>
          </div>
          <div className="panel panel--readout">
            <div className="panel__h">INSTRUCTIONS</div>
            <div className="readout">
              <div className="readout__row" style={{cursor: "pointer"}} onClick={() => setCounter(!counter)}>
                <span>COUNTER-ATTACK</span><b className={counter ? "readout__good" : ""}>{counter ? "ON" : "OFF"}</b>
              </div>
              <div className="readout__row" style={{cursor: "pointer"}} onClick={() => setOffside(!offside)}>
                <span>OFFSIDE TRAP</span><b className={offside ? "readout__good" : ""}>{offside ? "ON" : "OFF"}</b>
              </div>
              <div className="readout__row" style={{cursor: "pointer"}} onClick={() => setHighBalls(!highBalls)}>
                <span>HIGH BALLS</span><b className={highBalls ? "readout__good" : ""}>{highBalls ? "ON" : "OFF"}</b>
              </div>
              <div className="readout__row" style={{cursor: "pointer"}} onClick={() => setLongShots(!longShots)}>
                <span>LONG SHOTS</span><b className={longShots ? "readout__good" : ""}>{longShots ? "ON" : "OFF"}</b>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

/* ===== LEAGUE TABLE ===== */
const LeagueTable = () => {
  const d = (window.PM_DATA || {});
  const lt = d.leagueTable || null;

  // clubes.form is a digit string: 0=W 1=L 2=D. Take the last 5 and convert.
  const parseForm = (s) => {
    const map = { "0": "W", "1": "L", "2": "D" };
    const str = (s || "").toString();
    const out = [];
    for (let i = Math.max(0, str.length - 5); i < str.length; i++) {
      const ch = map[str[i]]; if (ch) out.push(ch);
    }
    while (out.length < 5) out.push("D");
    return out;
  };
  const divLetter = (n) => (n >= 1 && n <= 7) ? "ABCDEFG"[n - 1] : ("D" + n);

  const demoRows = [
    { pos: 1, name: "Juventino FC",    p: 24, w: 18, d: 4, l: 2, gd: 42, pts: 58, form: ["W","W","W","D","W"] },
    { pos: 2, name: "Bitcoin FC",      p: 24, w: 17, d: 3, l: 4, gd: 31, pts: 54, form: ["W","L","W","W","W"] },
    { pos: 3, name: "Saraiva",         p: 24, w: 15, d: 5, l: 4, gd: 22, pts: 50, form: ["D","L","W","D","W"] },
    { pos: 4, name: "AVieira",         p: 24, w: 14, d: 5, l: 5, gd: 15, pts: 47, form: ["W","W","L","W","D"] },
    { pos: 5, name: "Giannis",         p: 24, w: 13, d: 4, l: 7, gd: 8,  pts: 43, form: ["L","W","D","W","W"] },
    { pos: 6, name: "FC Odivelas",     p: 24, w: 11, d: 6, l: 7, gd: 3,  pts: 39, form: ["W","W","D","L","W"] },
    { pos: 7, name: "Alas",            p: 24, w: 10, d: 5, l: 9, gd: -4, pts: 35, form: ["L","W","L","D","W"] },
    { pos: 8, name: "Frozen Penguin",  p: 24, w:  8, d: 4, l:12, gd: -14, pts: 28, form: ["L","D","W","L","L"] },
    { pos: 9, name: "Pelouros FC",     p: 24, w:  6, d: 3, l:15, gd: -28, pts: 21, form: ["L","L","D","L","L"] },
  ];

  const rows = (lt && Array.isArray(lt.rows) && lt.rows.length > 0
    ? lt.rows.map(r => ({ ...r, form: parseForm(r.form) }))
    : demoRows);
  const total = rows.length;
  const div = lt ? (lt.divisao || 1) : 1;
  const totalDivisions = lt ? (lt.totalDivisions || 0) : 0;
  const isTopDiv    = div === 1;
  const isBottomDiv = totalDivisions > 0 && div === totalDivisions;

  // Zone rules mirror the engine's season-change script (patch_mudanca_epoca):
  //   Top division      → no promotion, bottom 2 relegated.
  //   Middle divisions  → position 1 promoted, bottom 2 relegated.
  //   Bottom division   → position 1 promoted, no relegation.
  const zoneFor = (pos) => {
    if (!isTopDiv && pos === 1) return "promo";
    if (!isBottomDiv && pos > total - 2) return "releg";
    return "";
  };

  const title = lt
    ? `DIVISION ${divLetter(div)}${div === 1 ? "" : "-" + lt.serie} · ${(lt.country || "").toUpperCase()}`
    : "DIVISION A-2 · PORTUGAL · SEASON 47";
  const subtitleDivisions = totalDivisions > 0 ? totalDivisions : 14;

  return (
    <section className="league" id="league">
      <div className="sec-head">
        <div className="sec-eye">▸ 03. CLIMB THE PYRAMID</div>
        <h2 className="sec-h2">{subtitleDivisions} divisions. Promotion, relegation, <span>and bragging rights.</span></h2>
      </div>
      <div className="league__wrap">
        <div className="league__head">
          <span className="league__title">{title}</span>
        </div>
        <table className="tbl">
          <thead>
            <tr>
              <th>#</th><th>CLUB</th>
              <th className="tbl__c">P</th><th className="tbl__c">W</th><th className="tbl__c">D</th><th className="tbl__c">L</th>
              <th className="tbl__c">GD</th><th className="tbl__c">PTS</th><th>LAST 5</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((r, i) => {
              const zone = zoneFor(r.pos);
              return (
                <tr key={r.pos + "-" + i} className={"tbl__row" + (zone ? " tbl__row--" + zone : "")}>
                  <td className="tbl__pos">{r.pos}</td>
                  <td className="tbl__name">{r.name}</td>
                  <td className="tbl__c">{r.p}</td>
                  <td className="tbl__c">{r.w}</td>
                  <td className="tbl__c">{r.d}</td>
                  <td className="tbl__c">{r.l}</td>
                  <td className="tbl__c">{r.gd > 0 ? "+" + r.gd : r.gd}</td>
                  <td className="tbl__c tbl__pts">{r.pts}</td>
                  <td>
                    <span className="tbl__form">
                      {r.form.map((f, fi) => <span key={fi} className={"formdot formdot--sm formdot--" + f}>{f}</span>)}
                    </span>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
        <div className="league__legend">
          {!isTopDiv && <span><i className="lg-swatch lg-swatch--promo"/> PROMOTION</span>}
          {!isBottomDiv && <span><i className="lg-swatch lg-swatch--releg"/> RELEGATION</span>}
        </div>
      </div>
    </section>
  );
};

/* ===== TROPHY CABINET ===== */
const Trophies = () => {
  const shelf = [
    { name: "LEAGUE A-1",    holder: "Juventino",       count: 14, rarity: "gold" },
    { name: "LEAGUE A-2",    holder: "Bitcoin FC",      count: 8,  rarity: "gold" },
    { name: "WORLD CUP S46", holder: "Portugal",        count: 1,  rarity: "gold" },
    { name: "DOMESTIC CUP",  holder: "Saraiva",         count: 5,  rarity: "silver" },
    { name: "TOP SCORER",    holder: "R. Neves · 34G",  count: 1,  rarity: "bronze" },
    { name: "GOLDEN GLOVE",  holder: "M. Costa · 18CS", count: 1,  rarity: "silver" },
  ];
  return (
    <section className="trophies">
      <div className="sec-head">
        <div className="sec-eye">▸ HALL OF CHAMPIONS</div>
        <h2 className="sec-h2">18 seasons of silverware. <span>Your cabinet is empty.</span></h2>
      </div>
      <div className="cabinet">
        <div className="cabinet__shelf">
          {shelf.map((s,i) => (
            <div key={i} className={"trophy trophy--" + s.rarity}>
              <div className="trophy__icon"><TrophyIllus tone={s.rarity}/></div>
              <div className="trophy__name">{s.name}</div>
              <div className="trophy__holder">{s.holder}</div>
              <div className="trophy__count">×{s.count}</div>
            </div>
          ))}
        </div>
        <div className="cabinet__plank"/>
      </div>
    </section>
  );
};

/* ===== USER TESTIMONIAL (random good review) ===== */
const TESTIMONIALS = [
  { body: "Been playing on and off since 2011. No other manager game has this depth of training and tactics.", author: "DrunkenDuck", meta: "CY · 14 years" },
  { body: "The friends system and country chat makes this feel like a real community, not just a game.", author: "fr0z3nshad0", meta: "GR · Div B-2" },
  { body: "Bought into PMFan once and never looked back. The amateurs league is pure chaos in the best way.", author: "Mafalda", meta: "PT · 1000+ games" },
  { body: "Live matches with real friends across the globe. That's the part nobody else gets right.", author: "Juventino", meta: "IT · Cup finalist" },
  { body: "I love the seasons resetting — every year I get to re-build, re-scout, re-plan. Never gets old.", author: "Skywalker66", meta: "BR · Div A" },
  { body: "Tiny learning curve, then a lifetime of deep decisions. Exactly what I wanted.", author: "Giannis", meta: "GR · 5 years" },
];
const Testimonial = () => {
  const [t] = React.useState(() => TESTIMONIALS[Math.floor(Math.random() * TESTIMONIALS.length)]);
  return (
    <blockquote className="greg__quote">
      <p>&ldquo;{t.body}&rdquo;</p>
      <footer><b>— {t.author}</b><span>{t.meta}</span></footer>
    </blockquote>
  );
};

/* ===== REGISTER (inline, game-style) ===== */
const GameRegister = () => {
  const d = (window.PM_DATA || {});
  const T = d.t || {};
  const countries = d.countries || [];
  const defaultCountry = d.defaultCountryId || "";
  const err = d.registrationError || "";
  const initials = (name) => {
    const clean = (name || "").toUpperCase().replace(/[^A-Z]/g, "");
    return (clean || "???").slice(0, 3);
  };

  // Claim preview: if the visitor picked a club in the ClubPicker, restore it
  // here so the identity of what they're taking over is visible while they
  // fill the form.
  const [claim, setClaim] = React.useState(null);
  const [teamName, setTeamName] = React.useState("");

  React.useEffect(() => {
    const loadClaim = () => {
      try {
        const id = localStorage.getItem("pm_claim_club_id");
        if (id && Array.isArray(d.openClubs)) {
          const found = d.openClubs.find(c => String(c.id) === String(id));
          if (found) {
            setClaim(prev => {
              // Only seed the team-name input when the claimed club
              // actually changes (or was unset). If the visitor already
              // typed a custom name against the same claim, keep it.
              if (!prev || String(prev.id) !== String(found.id)) {
                setTeamName(found.name || "");
              }
              return found;
            });
            return;
          }
        }
      } catch (e) {}
      setClaim(null);
    };
    loadClaim();
    const onChange = () => loadClaim();
    window.addEventListener("pm:claim-changed", onChange);
    window.addEventListener("storage", onChange);
    return () => {
      window.removeEventListener("pm:claim-changed", onChange);
      window.removeEventListener("storage", onChange);
    };
  }, []);

  const cancelClaim = () => {
    try { localStorage.removeItem("pm_claim_club_id"); } catch (e) {}
    setClaim(null);
    setTeamName("");
    try { window.dispatchEvent(new CustomEvent("pm:claim-changed")); } catch (e) {}
  };

  return (
    <section className="greg" id="register">
      <div className="greg__inner">
        <div className="greg__side">
          <div className="sec-eye">▸ {T.newManager || "NEW MANAGER"}</div>
          <h2 className="sec-h2">{T.createProfile1 || "Create your"} <span>{T.createProfile2 || "manager profile."}</span></h2>
          <p className="sec-lede">{T.createLede || "60 seconds. No card. No download."}</p>
          {d.stats && (
            <div className="greg__meta">
              <div><b>{d.stats.managers || ""}</b><span>{T.onlineNow || "ONLINE NOW"}</span></div>
              <div><b>{d.stats.joinedToday || ""}</b><span>{T.joinedToday || "JOINED TODAY"}</span></div>
              <div><b>{d.stats.rating || "4.6★"}</b><span>{T.reviews || "REVIEWS"}</span></div>
            </div>
          )}
          <Testimonial/>
        </div>
        <div className="greg__form">
          {err && (
            <div style={{marginBottom: 14, padding: "10px 14px", border: "1px solid var(--g-red)", borderRadius: 6, background: "#fdecea", color: "var(--g-red)", fontFamily: "var(--mono)", fontSize: 12}}>
              {err}
            </div>
          )}
          {claim && (
            <div style={{
              display: "flex", alignItems: "center", gap: 14,
              padding: "14px 16px", marginBottom: 18,
              background: "var(--g-paper)", border: "2px solid var(--g-green)", borderRadius: 10,
              boxShadow: "0 2px 10px -4px rgba(47,122,63,0.25)",
              position: "relative",
            }}>
              <div style={{width: 44, height: 50, flexShrink: 0, display: "grid", placeItems: "center"}}>
                <Crest primary={claim.body} secondary={claim.collar} initials={initials(teamName || claim.name)} size={44}/>
              </div>
              <div style={{flex: 1, minWidth: 0, paddingRight: 24}}>
                <div style={{fontFamily: "var(--mono)", fontSize: 9, letterSpacing: 2, color: "var(--g-green)", fontWeight: 700, textTransform: "uppercase"}}>
                  Claiming club
                </div>
                <div title={teamName || claim.name} style={{fontFamily: "var(--display)", fontSize: 16, fontWeight: 800, color: "var(--g-ink)", lineHeight: 1.2, marginTop: 3, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap"}}>
                  {teamName || claim.name}
                </div>
                <div style={{fontFamily: "var(--mono)", fontSize: 10, color: "var(--g-mute)", marginTop: 4, display: "flex", alignItems: "center", gap: 6}}>
                  {claim.paisId ? <img src={"/img/bandeiras-small/" + claim.paisId + ".gif"} alt="" style={{height: 10, borderRadius: 1}}/> : null}
                  <span>DIV {(claim.divisao >= 1 && claim.divisao <= 7) ? "ABCDEFG"[claim.divisao - 1] : "D" + claim.divisao}{claim.divisao === 1 ? "" : "-" + claim.serie}</span>
                </div>
              </div>
              <button type="button" onClick={cancelClaim} aria-label="Cancel claim" style={{
                position: "absolute", top: 8, right: 10,
                width: 24, height: 24, display: "grid", placeItems: "center",
                background: "transparent", border: 0, color: "var(--g-mute)",
                fontSize: 18, lineHeight: 1, cursor: "pointer", borderRadius: 4,
              }}>×</button>
            </div>
          )}
          <a href="#g" onClick={(e) => { e.preventDefault(); if (typeof regGmail === 'function') regGmail(); else parent.location = 'gmail.asp?reg=1'; }} className="greg__google">
            <svg width="18" height="18" viewBox="0 0 18 18"><path d="M17.64 9.2c0-.64-.06-1.25-.17-1.84H9v3.49h4.84a4.14 4.14 0 0 1-1.8 2.72v2.26h2.92c1.71-1.57 2.7-3.9 2.7-6.63z" fill="#4285F4"/><path d="M9 18c2.43 0 4.47-.81 5.96-2.18l-2.92-2.26a5.4 5.4 0 0 1-3.04.86 5.34 5.34 0 0 1-5.01-3.7H.92v2.33A9 9 0 0 0 9 18z" fill="#34A853"/><path d="M3.99 10.72a5.4 5.4 0 0 1-.28-1.72c0-.6.1-1.18.28-1.72V4.95H.92a9 9 0 0 0 0 8.1l3.07-2.33z" fill="#FBBC05"/><path d="M9 3.58c1.32 0 2.5.46 3.44 1.35l2.58-2.58A9 9 0 0 0 9 0 9 9 0 0 0 .92 4.95l3.07 2.33A5.34 5.34 0 0 1 9 3.58z" fill="#EA4335"/></svg>
            {T.continueGoogle || "CONTINUE WITH GOOGLE"}
          </a>
          <div className="greg__or"><span>{T.orCreate || "OR CREATE ACCOUNT"}</span></div>
          <form method="POST" action="default.asp?action=registo">
            <input type="text" name="address" defaultValue="" tabIndex="-1" autoComplete="off" style={{position: "absolute", left: "-9999px", width: 1, height: 1, opacity: 0}} aria-hidden="true"/>
            <input type="hidden" name="claim_club_id" value={claim ? String(claim.id) : ""} readOnly/>
            <div className="greg__grid">
              <label><span>{T.username || "USERNAME"}</span>
                <input name="login" required minLength={4} maxLength={20} pattern=".{4,20}" title={T.usernameHint || "4-20 characters"}/>
              </label>
              <label><span>{T.email || "EMAIL"}</span>
                <input type="email" name="mail" required/>
              </label>
              <label><span>{T.password || "PASSWORD"}</span>
                <input type="password" name="password" required minLength={5} pattern=".{5,}"/>
              </label>
              <label><span>{T.country || "COUNTRY"}</span>
                <select name="pais" defaultValue={defaultCountry}>
                  {countries.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                </select>
              </label>
              <label><span>{T.realName || "NAME"}</span>
                <input name="nomepp" required/>
              </label>
              <label><span>{T.teamName || "TEAM NAME"}</span>
                <input name="nomeclube" required minLength={3} value={teamName} onChange={(e) => setTeamName(e.target.value)}/>
              </label>
            </div>
            <button type="submit" className="gbtn gbtn--cta gbtn--full gbtn--xl">▶ {T.getTeamEnter || "GET A TEAM · ENTER WORLD"}</button>
          </form>
          <div className="greg__fine" dangerouslySetInnerHTML={{__html: T.termsNote || 'By continuing you accept the <a href="tos.asp">Terms</a> and <a href="privacy_policy.asp">Privacy Policy</a>.'}}/>
        </div>
      </div>
    </section>
  );
};

/* ===== FINAL SPLASH ===== */
const GameFinal = () => {
  const d = (window.PM_DATA || {});
  const T = d.t || {};
  const s = d.stats || {};
  return (
    <section className="gfinal">
      <div className="gfinal__scanlines" aria-hidden/>
      <div className="gfinal__inner">
        <div className="gfinal__mini">◆ {(T.season || "SEASON")} {s.season || ""} · {(T.week || "WEEK")} {s.week || ""} · {T.acceptingManagers || "NOW ACCEPTING NEW MANAGERS"} ◆</div>
        <h2 className="gfinal__h2" dangerouslySetInnerHTML={{__html: T.clubWaiting || "YOUR CLUB<br/>IS WAITING."}}/>
        <a href="#register" className="gbtn gbtn--cta gbtn--giant">▶ {T.getTeam || "GET A TEAM"}</a>
        <div className="gfinal__meta">{T.finalMeta || "KEYBOARD: ENTER · MOUSE: CLICK · TAP: TAP"}</div>
      </div>
    </section>
  );
};

/* ===== FOOTER ===== */
const GameFooter = () => {
  const d = (window.PM_DATA || {});
  const T = d.t || {};
  const year = new Date().getFullYear();
  return (
    <footer className="gfoot">
      <div className="gfoot__bot">{T.footerCopy || ("© " + year + " PLANETARIUM MANAGER · BUILT BY PLAYERS, FOR PLAYERS · EST. 2008")}</div>
    </footer>
  );
};

Object.assign(window, { ClubPicker, TacticsBoard, LeagueTable, Trophies, GameRegister, GameFinal, GameFooter });
