/* iBD Coliseum — tiers: badge + profile modal */

// Distinct emblem per rank (material-themed, escalating prestige).
// Fill uses currentColor (set to the tier color by the parent); white facet
// lines add shine. Diamond gets extra facets + sparkles to outrank Platinum.
function TierEmblem({ tier, className, style }) {
  const f = { fill: "currentColor" };
  const shine = { fill: "none", stroke: "#fff", strokeOpacity: 0.34, strokeWidth: 1.1, strokeLinejoin: "round", strokeLinecap: "round" };
  const spark = { fill: "none", stroke: "currentColor", strokeWidth: 1.4, strokeLinecap: "round" };
  const E = {
    cardboard: <>
      <polygon points="12,2.6 20.5,7 12,11.4 3.5,7" {...f} opacity="0.5" />
      <polygon points="3.5,7 12,11.4 12,21.4 3.5,17" {...f} opacity="0.95" />
      <polygon points="20.5,7 12,11.4 12,21.4 20.5,17" {...f} opacity="0.72" />
      <path d="M12 11.4V21.4M9 5.2l6 3.1" {...shine} />
    </>,
    wood: <>
      {/* chunky diagonal log — sized to match other tier emblems */}
      <g transform="translate(12 12) rotate(-38) scale(1.16) translate(-12 -12)">
        <path
          d="M6.95 9.85 H17.05 A3.15 3.15 0 0 1 17.05 16.15 H6.95 A3.15 3.15 0 0 1 6.95 9.85 Z"
          {...f}
        />
        <circle cx="3.8" cy="13" r="2" fill="none" stroke="#fff" strokeOpacity="0.45" strokeWidth="1" />
        <circle cx="3.8" cy="13" r="0.95" fill="#fff" fillOpacity="0.38" />
        <path d="M10 12 H19.5" {...shine} />
        <path d="M10 14.4 H18" {...shine} strokeOpacity="0.26" />
      </g>
    </>,
    iron: <>
      <polygon points="12,3 21,7.2 12,11.4 3,7.2" {...f} opacity="0.6" />
      <polygon points="3,7.2 12,11.4 12,20.6 3,16.4" {...f} opacity="0.95" />
      <polygon points="21,7.2 12,11.4 12,20.6 21,16.4" {...f} opacity="0.78" />
      <path d="M7 6.1l8 3.7M12 11.4v9.2" {...shine} />
      <path d="M5.4 9.1l2.2 1" {...shine} />
    </>,
    bronze: <>
      <polygon points="12,2.6 20.4,7.3 20.4,16.7 12,21.4 3.6,16.7 3.6,7.3" {...f} />
      <circle cx="12" cy="12" r="4.6" {...shine} />
      <circle cx="12" cy="12" r="1.4" fill="#fff" fillOpacity="0.4" />
    </>,
    silver: <>
      <circle cx="12" cy="12" r="8.7" {...f} />
      <path d="M12 6.6l1.6 3.7 4 .3-3.1 2.6 1 3.9L12 15l-3.5 2.1 1-3.9-3.1-2.6 4-.3L12 6.6Z" fill="#fff" fillOpacity="0.5" />
    </>,
    gold: <>
      <path d="M3 8.2l4.2 3.6L12 4.8l4.8 7 4.2-3.6-2 10.4H5L3 8.2Z" {...f} />
      <rect x="5" y="19" width="14" height="2.4" rx="0.7" {...f} />
      <circle cx="12" cy="9.6" r="1.1" fill="#fff" fillOpacity="0.5" />
      <circle cx="6.6" cy="9.4" r="0.9" fill="#fff" fillOpacity="0.45" />
      <circle cx="17.4" cy="9.4" r="0.9" fill="#fff" fillOpacity="0.45" />
    </>,
    platinum: <>
      <path d="M7 3.4h10l4 5.8-9 11.4L3 9.2 7 3.4Z" {...f} />
      <path d="M3 9.2h18M9 3.4l-1.6 5.8L12 20.6M15 3.4l1.6 5.8L12 20.6" {...shine} />
    </>,
    diamond: <>
      <path d="M5.2 3.8h13.6l3.4 5.6-10.2 11.8L1.8 9.4 5.2 3.8Z" {...f} />
      <path d="M1.8 9.4h20.4M5.2 3.8l2.6 5.6 4.4 11.8M18.8 3.8l-2.6 5.6-4.4 11.8M9 3.8l-1.2 5.6M15 3.8l1.2 5.6" {...shine} />
      <polygon points="7.8,9.4 16.2,9.4 12,5 7.8,9.4" fill="#fff" fillOpacity="0.22" />
      <path d="M21 2.2v2.6M19.7 3.5h2.6" {...spark} opacity="0.95" />
      <path d="M3.4 13.6v2M2.4 14.6h2" {...spark} opacity="0.85" />
    </>,
  };
  return (
    <svg viewBox="0 0 24 24" className={className} style={style} aria-hidden="true">
      {E[tier] || E.cardboard}
    </svg>
  );
}

function TierBadge({ points, size, showName, onClick, title }) {
  const { tierFor } = window.COLISEUM_DATA;
  const { tier } = tierFor(points);
  return (
    <span
      className={"tier-badge" + (size === "sm" ? " sm" : "") + (onClick ? " clickable" : "")}
      style={{ "--tier": tier.color }}
      onClick={onClick}
      title={title || `${tier.name} tier · ${points} pts`}
    >
      <TierEmblem tier={tier.id} className="ic" />
      {showName && <span className="tn">{tier.name}</span>}
    </span>
  );
}

function PfTeamPick({ teams, value, onChange }) {
  const [open, setOpen] = React.useState(false);
  const rootRef = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const onDoc = (e) => {
      if (!rootRef.current?.contains(e.target)) setOpen(false);
    };
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, [open]);
  const display = value || "Choose your team…";
  return (
    <div className="pf-team-pick" ref={rootRef}>
      <Icon name="users" className="ic" />
      <button
        type="button"
        className={"pf-team-trigger" + (value ? "" : " muted")}
        onClick={() => setOpen((o) => !o)}
        aria-haspopup="listbox"
        aria-expanded={open}
      >
        {display}
        <Icon name="chevron" className="ic pf-team-chev" />
      </button>
      {open && (
        <ul className="pf-team-menu" role="listbox" aria-label="Choose your team">
          {teams.map((t) => (
            <li key={t}>
              <button
                type="button"
                role="option"
                aria-selected={t === value}
                className={t === value ? "sel" : undefined}
                onClick={() => { onChange(t); setOpen(false); }}
              >
                {t}
              </button>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

function ProfileModal({ stats, isYou, avatarImg, myTeam, onSetTeam, onClose }) {
  const { TIERS, tierFor, avatarColor, initials, CATEGORIES, TEAMS } = window.COLISEUM_DATA;
  const { tier, next, toNext, progress, index } = tierFor(stats.points);
  const currentTeam = isYou ? (myTeam || stats.team) : stats.team;

  return (
    <div className="overlay" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal profile-modal" role="dialog" aria-modal="true">
        <button className="x x-float" onClick={onClose} aria-label="Close"><Icon name="x" className="ic" style={{ width: 16, height: 16 }} /></button>

        <div className="pf-head" style={{ "--tier": tier.color }}>
          <span className="pf-av"
            style={(isYou && avatarImg) ? { backgroundImage: `url("${avatarImg}")`, backgroundSize: "cover", backgroundPosition: "center" } : { background: avatarColor(stats.author) }}>
            {(isYou && avatarImg) ? null : initials(stats.author)}
          </span>
          <div className="pf-id">
            <div className="pf-name">{stats.author}{isYou && <span className="you-tag">You</span>}</div>
            {isYou && onSetTeam ? (
              <PfTeamPick
                teams={TEAMS || []}
                value={(TEAMS || []).includes(currentTeam) ? currentTeam : ""}
                onChange={onSetTeam}
              />
            ) : (
              <div className="pf-team">{currentTeam}</div>
            )}
            <span className="pf-tier"><TierEmblem tier={tier.id} className="ic" />{tier.name} tier</span>
          </div>
          <div className="pf-points">
            <div className="v">{stats.points.toLocaleString()}</div>
            <div className="l">points</div>
          </div>
        </div>

        <div className="pf-body">
          {/* progress to next */}
          <div className="pf-prog" style={{ "--next": next ? next.color : tier.color }}>
            <div className="pf-prog-head">
              {next
                ? <div className="pp-goal">
                    <span className="pp-num">{toNext.toLocaleString()}</span>
                    <span className="pp-rest">pts to <span className="pp-next"><TierEmblem tier={next.id} className="ic" />{next.name}</span></span>
                  </div>
                : <div className="pp-goal"><span className="pp-max"><TierEmblem tier={tier.id} className="ic" />Top tier reached — Diamond</span></div>}
              <span className="pf-prog-pct">{Math.round(progress * 100)}%</span>
            </div>
            <div className="pf-prog-bar">
              <i style={{ width: (progress * 100) + "%", background: `linear-gradient(90deg, ${tier.color}, ${next ? next.color : tier.color})` }}></i>
            </div>
            <div className="pf-prog-ends">
              <span style={{ color: tier.color }}>{tier.name} · {tier.min.toLocaleString()}</span>
              {next && <span style={{ color: next.color }}>{next.name} · {next.min.toLocaleString()}</span>}
            </div>
          </div>

          {/* tier ladder */}
          <div className="pf-ladder">
            {TIERS.map((tr, i) => (
              <div key={tr.id} className={"pf-rung" + (i === index ? " current" : "") + (i < index ? " passed" : "")} style={{ "--tier": tr.color }}>
                <span className="pf-gem"><TierEmblem tier={tr.id} className="ic" /></span>
                <span className="pf-rn">{tr.name}</span>
                <span className="pf-rmin">{tr.min.toLocaleString()}</span>
                {i === index && <span className="pf-here">You're here</span>}
              </div>
            ))}
          </div>

          {/* how points are earned + breakdown */}
          <div className="pf-stats">
            <div className="pf-stat"><div className="v">{stats.submissions}</div><div className="l">Submissions<span>×30 pts</span></div></div>
            <div className="pf-stat"><div className="v">{stats.upvotesGiven || 0}</div><div className="l">Upvotes given<span>×10 pts</span></div></div>
            <div className="pf-stat"><div className="v">{stats.commentsMade || 0}</div><div className="l">Comments<span>×10 pts</span></div></div>
            <div className="pf-stat"><div className="v" style={{ color: tier.color }}>{tier.name}</div><div className="l">Current tier<span>of {TIERS.length}</span></div></div>
          </div>

          {/* their contributions */}
          {stats.cards.length > 0 && (
            <div className="pf-contrib">
              <div className="pf-contrib-h">Contributions</div>
              {stats.cards.map((c) => {
                const cm = CATEGORIES.find((x) => x.id === c.cat) || { color: "var(--accent)" };
                return (
                  <div className="pf-crow" key={c.id}>
                    <span className="dot" style={{ background: cm.color }}></span>
                    <span className="t">{c.title}</span>
                    <span className="v"><Icon name="up" className="ic" />{c.votes}</span>
                  </div>
                );
              })}
            </div>
          )}
          {stats.cards.length === 0 && (
            <div className="pf-empty">No submissions yet — share your first AI use-case to climb out of <b>Cardboard</b>. Each post is +30 pts, and every upvote it earns is +10.</div>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { TierBadge, ProfileModal });
