const { Icon } = window.PryzeDesignSystem_b2bad9;
const { USER, COMPANIES, LEADERBOARD_PEERS, FILLER_PEERS } = window.PryzeData;

/* Rank across the whole Pryze universe, not just the store. */
const UNIVERSE = [...LEADERBOARD_PEERS, ...(FILLER_PEERS || [])];
const RANK = UNIVERSE.filter(p => p.points > USER.points).length + 1;
const FIELD = UNIVERSE.length + 1;
const PCT = Math.max(1, Math.round((RANK / FIELD) * 100));
/* Three card levels — never letter grades. Everyone is somebody here. */
const LEVELS = [
  { key: 'starter', name: 'STARTER', blurb: 'ON THE COME UP' },
  { key: 'regular', name: 'REGULAR', blurb: 'RUNS THE FLOOR' },
  { key: 'allstar', name: 'ALL-STAR', blurb: 'TOP OF THE BOARD' },
];
const levelFor = pct => pct <= 5 ? LEVELS[2] : pct <= 25 ? LEVELS[1] : LEVELS[0];

const SHARE_TO = [
  { key: 'imessage', label: 'Messages', icon: 'chat-circle-dots', bg: '#2FCB53' },
  { key: 'whatsapp', label: 'WhatsApp', icon: 'whatsapp-logo', bg: '#25D366' },
  { key: 'instagram', label: 'Story', icon: 'instagram-logo', bg: '#E1306C' },
  { key: 'save', label: 'Save', icon: 'download-simple', bg: 'var(--neutral-600)' },
];

/* Panini-style: prizm border, chamfered window, nameplate under the photo. */
function BragCard({ tilt, level }) {
  const LV = level ? (LEVELS.find(l => l.key === level) || levelFor(PCT)) : levelFor(PCT);
  const company = COMPANIES && COMPANIES[USER.company];
  const initials = USER.name.split(' ').map(w => w[0]).join('').slice(0, 2);
  return (
    <div className={`bc-card bc-lv-${LV.key}`} style={{ transform: `rotateY(${tilt.x}deg) rotateX(${-tilt.y}deg)` }}>
      <span className="bc-prizm" style={{ backgroundPosition: `${50 + tilt.x * 4}% ${50 + tilt.y * 4}%` }} />
      <span className="bc-shine" />
      <div className="bc-inner">
        <span className="bc-rail">PRYZE COMMERCIAL / SEASON 26 / ST. CLOUD</span>
        <div className="bc-brandbar">
          <span className="bc-brand">PRYZE<i>★</i></span>
          {company && (company.logo
            ? <img className="bc-club" src={company.logo} alt={company.name} />
            : <span className="bc-club bc-club-fb" style={{ background: company.bg }}>{company.name[0]}</span>)}
          <span className="bc-topright">
            <span className="bc-pos">{USER.role}</span>
            <span className="bc-lvl">{LV.name}<em>{LV.blurb}</em></span>
          </span>
        </div>
        <div className="bc-window">
          <span className="bc-rays" />
          <span className="bc-dots" />
          {USER.photo ? <img src={USER.photo} alt="" /> : <span className="bc-portrait-fb">{initials}</span>}
          <span className="bc-tick bc-tick-a" /><span className="bc-tick bc-tick-b" />
          <span className="bc-big">{USER.points.toLocaleString()}<em>PTS</em></span>
          <span className="bc-seal"><b>TOP</b><span>{PCT + '%'}</span></span>
        </div>
        <div className="bc-plate">
          <p className="bc-name">{USER.name}</p>
          <p className="bc-role">{USER.store}</p>
        </div>
        <div className="bc-stats">
          <span className="bc-stat"><b>#{RANK}</b><em>RANK</em></span>
          <span className="bc-stat"><b>{USER.kudos}</b><em>KUDOS</em></span>
          <span className="bc-stat"><b>{USER.streak}</b><em>STREAK</em></span>
          <span className="bc-stat"><b>{USER.goals}</b><em>GOALS</em></span>
        </div>
        <div className="bc-foot">
          <span className="bc-bars">{Array.from({ length: 22 }).map((_, i) => <i key={i} style={{ opacity: (i * 7 % 5) / 6 + .25 }} />)}</span>
          <span className="bc-verified">VERIFIED BY PRYZE</span>
        </div>
      </div>
    </div>
  );
}

function BragScreen({ onBack, level }) {
  const [tilt, setTilt] = React.useState({ x: 0, y: 0 });
  const [sent, setSent] = React.useState(null);
  const drag = React.useRef(false);
  React.useEffect(() => { if (!sent) return; const t = setTimeout(() => setSent(null), 1600); return () => clearTimeout(t); }, [sent]);
  const move = e => {
    const r = e.currentTarget.getBoundingClientRect();
    const nx = ((e.clientX - r.left) / r.width - 0.5) * 2, ny = ((e.clientY - r.top) / r.height - 0.5) * 2;
    setTilt({ x: nx * 14, y: ny * 14 });
  };
  return (
    <div className="bg-screen">
      <div className="bg-top">
        <button className="bg-back" onClick={onBack} aria-label="Back"><Icon name="arrow-left" size={17} weight="bold" color="#fff" /></button>
        <p className="bg-title">Your card</p>
        <span style={{ width: 36 }} />
      </div>
      <div className="bg-stage"
        onPointerDown={e => { drag.current = true; move(e); }}
        onPointerMove={e => { if (drag.current) move(e); }}
        onPointerUp={() => { drag.current = false; setTilt({ x: 0, y: 0 }); }}
        onPointerLeave={() => { drag.current = false; setTilt({ x: 0, y: 0 }); }}>
        <BragCard tilt={tilt} level={level} />
      </div>
      <p className="bg-hint"><i>🃏</i>tilt the card to catch the shine</p>
      <div className="bg-bar">
        <div className="bg-icons">
          {SHARE_TO.map(s => (
            <button className="bg-icon" key={s.key} aria-label={s.label} onClick={() => setSent(s.key === 'save' ? 'Saved' : s.label)}>
              <span className="bg-icon-dot" style={{ background: s.bg }}><Icon name={s.icon} size={18} weight="fill" color="#fff" /></span>
            </button>
          ))}
          <button className="bg-share" onClick={() => setSent('Sharing…')}>
            <Icon name="share-network" size={16} weight="bold" color="#14170A" />Share
          </button>
        </div>
      </div>
      {sent && <p className="bg-toast">{sent}</p>}
    </div>
  );
}

window.PryzeBrag = { BragScreen, BragCard, LEVELS };
