const { Icon: MgIcon } = window.PryzeDesignSystem_b2bad9;
const { USER: MG_USER } = window.PryzeData;
const { MG_STORES, MG_PERIODS, mgMetrics, MG_BUBBLES, mgStaff, MG_COMPANY } = window.PryzeManagerData;

const mgPct = n => (n > 0 ? '+' : '') + n + '%';
const mgStore = id => MG_STORES.find(s => s.id === id) || MG_STORES[0];
const mgPeriod = k => MG_PERIODS.find(p => p.k === k) || MG_PERIODS[1];

/* ── sheet shell (Apple-style, grabber + big title) ─────── */
function MgSheet({ title, sub, onClose, children }) {
  return (
    <div className="mg-back" onClick={onClose}>
      <div className="mg-sheet" onClick={e => e.stopPropagation()}>
        <span className="mg-grab" />
        <p className="mg-sheet-t">{title}</p>
        {sub && <p className="mg-sheet-s">{sub}</p>}
        {children}
      </div>
    </div>
  );
}

function MgHead({ store, onStore, onBack, onShare }) {
  const [open, setOpen] = React.useState(false);
  const cur = mgStore(store);
  return (
    <React.Fragment>
      <div className="mg-head">
        <button className="mg-crumb" onClick={onBack}><MgIcon name="arrow-left" size={15} weight="bold" color="var(--fg-secondary)" />Back to my shift</button>
        <span className="mg-head-right">
          {onShare && <button className="mg-share-open" onClick={onShare}><MgIcon name="share-network" size={14} weight="bold" color="var(--color-primary)" />Share</button>}
          <span className="mg-me">{MG_USER.photo ? <img src={MG_USER.photo} alt="" /> : 'M'}</span>
        </span>
      </div>
      <span className="mg-store-slot">
        <button className="mg-chip-store" onClick={() => setOpen(true)}>
          <span className={'mg-dot mg-g-' + cur.grade} />{cur.name}
          <MgIcon name="caret-up-down" size={13} weight="bold" color="var(--fg-muted)" />
        </button>
      </span>
      {open && (
        <MgSheet title="Your stores" sub={`You manage ${MG_STORES.length}. Everything follows this pick.`} onClose={() => setOpen(false)}>
          <div className="mg-rows">
            {MG_STORES.map(s => (
              <button key={s.id} className={'mg-row' + (s.id === store ? ' is-on' : '')} onClick={() => { onStore(s.id); setOpen(false); }}>
                <span className={'mg-badge mg-g-' + s.grade}>{s.grade}</span>
                <span className="mg-row-txt"><b>{s.name}</b><em>{s.city} · {s.staff} people</em></span>
                <span className="mg-row-side">{'#' + s.rank}</span>
              </button>
            ))}
          </div>
        </MgSheet>
      )}
    </React.Fragment>
  );
}

/* ── Pulse ──────────────────────────────────────────────── */
function MgHero({ store, period }) {
  const s = mgStore(store), p = mgPeriod(period), m = mgMetrics(store, period);
  return (
    <div className="mg-hero">
      <div className="mg-hero-top">
        <span className="mg-hero-grade">{s.grade}</span>
        <div className="mg-hero-say">
          <p className="mg-hero-lbl">Pryze health · {p.word}</p>
          <span className="mg-hero-rank">{'#' + s.rank}<em>of {s.of} stores</em></span>
          <span className="mg-hero-pct">{MG_COMPANY.pctile}th percentile company-wide</span>
        </div>
      </div>
      <div className="mg-hero-foot">
        <span className="mg-hero-store">{s.name}</span>
        <span className={'mg-delta' + (m.delta >= 0 ? '' : ' is-down')}>
          <MgIcon name={m.delta >= 0 ? 'arrow-up-right' : 'arrow-down-right'} size={12} weight="bold" color="currentColor" />
          {mgPct(m.delta)} vs {p.prev}
        </span>
      </div>
    </div>
  );
}

function MgSignups({ store }) {
  const s = mgStore(store);
  const pct = Math.round(s.staff / s.head * 100);
  const full = pct >= 100;
  return (
    <div className={'mg-sec mg-signup' + (full ? ' is-full' : '')}>
      <div className="mg-sec-head">
        <p className="mg-lbl">Team signed up</p>
        {full && <span className="mg-signup-tag"><MgIcon name="confetti" size={13} weight="fill" color="#0E1408" />6 weeks at 100%</span>}
      </div>
      <div className="mg-thin">
        <span className="mg-thin-n">{s.staff}<em>/{s.head}</em></span>
        <span className="mg-thin-mid">
          <span className="mg-thin-bar"><i style={{ width: pct + '%' }} /></span>
        </span>
        <span className="mg-thin-pct">{pct}%</span>
      </div>
      <p className="mg-read">{full
        ? 'Whole roster is on Pryze and has stayed there. Rare — say it out loud at huddle.'
        : `${s.head - s.staff} people left to bring on.`}</p>
    </div>
  );
}

function MgBubbles() {
  const total = MG_BUBBLES.reduce((a, b) => a + b.n, 0);
  const max = Math.max(...MG_BUBBLES.map(b => b.n));
  const [sel, setSel] = React.useState(MG_BUBBLES[0].cat);
  const cur = MG_BUBBLES.find(b => b.cat === sel) || MG_BUBBLES[0];
  return (
    <div className="mg-sec">
      <p className="mg-lbl">Goal categories</p>
      <div className="mg-bubs">
        {MG_BUBBLES.map(b => {
          const d = 46 + Math.round(b.n / max * 56);
          return (
            <button key={b.cat} className={'mg-bub' + (sel === b.cat ? ' is-on' : '')} onClick={() => setSel(b.cat)} style={{ width: d, height: d, background: b.c }}>
              <b>{b.n}</b><em>{b.cat}</em>
            </button>
          );
        })}
      </div>
      <p className="mg-read"><b>{cur.cat}</b> is {Math.round(cur.n / total * 100)}% of everything crushed {cur.n < 60 ? '— thin, worth setting a goal here.' : '— healthy.'}</p>
    </div>
  );
}

function MgMvps({ store, onKudos }) {
  const [mode, setMode] = React.useState('golds');
  const [sent, setSent] = React.useState({});
  const top = [...mgStaff(store)].sort((a, b) => b[mode] - a[mode]).slice(0, 3);
  React.useEffect(() => { setSent({}); }, [store]);
  return (
    <div className="mg-sec">
      <div className="mg-sec-head">
        <p className="mg-lbl">Pryze MVPs</p>
        <div className="mg-seg mg-seg-sm">
          <button className={mode === 'golds' ? 'is-on' : ''} onClick={() => setMode('golds')}>Goals</button>
          <button className={mode === 'hours' ? 'is-on' : ''} onClick={() => setMode('hours')}>Hours</button>
        </div>
      </div>
      <div className="mg-list">
        {top.map((p, i) => (
          <div className={'mg-item mg-pos-' + i} key={p.id}>
            <span className="mg-pos">{i + 1}</span>
            <span className="mg-face mg-face-sm">{p.photo ? <img src={p.photo} alt="" /> : p.name[0]}</span>
            <span className="mg-item-txt"><b>{p.name}</b><em>{p[mode]} {mode === 'golds' ? 'goals' : 'hrs'}{i === 0 ? ` · ${p.streak} day streak` : ''}</em></span>
            <button className={'mg-clap' + (sent[p.id] ? ' is-sent' : '')} disabled={!!sent[p.id]} aria-label="Send kudos"
              onClick={() => { setSent(v => ({ ...v, [p.id]: 1 })); onKudos({ kind: 'kudos', name: p.name, photo: p.photo }); }}>
              <MgIcon name={sent[p.id] ? 'check' : 'hands-clapping'} size={15} weight="fill" color="#0E1408" />
            </button>
          </div>
        ))}
      </div>
    </div>
  );
}

function MgWins({ store, period }) {
  const m = mgMetrics(store, period), s = mgStore(store);
  const wins = [
    `${Math.round(m.engaged * 100)}% of the roster banked at least one goal — ${m.engaged > 0.7 ? 'best engagement in your district' : 'under the 70% line you want'}.`,
    `Goals peak between 10a and 2p. Your afternoon block is the soft spot — set something that lands then.`,
    `${m.redeemed.toLocaleString()} points were cashed out. People who redeem come back with better streaks.`,
    `${s.staff - m.users} people haven't played yet. One awarded point each is usually what starts them.`,
  ];
  return (
    <div className="mg-sec">
      <p className="mg-lbl">deeper wins</p>
      <div className="mg-wins">
        {wins.map((w, i) => <p className="mg-win" key={i}>{w}</p>)}
      </div>
    </div>
  );
}

function MgPulse({ store, period, onToast, onPop }) {
  const { MgReport } = window.PryzeManagerPanels;
  return (
    <React.Fragment>
      <MgHero store={store} period={period} />
      <MgSignups store={store} />
      <MgReport store={store} period={period} onDone={onToast} onPop={onPop} />
      <MgBubbles />
      <MgMvps store={store} onKudos={onPop} />
      <MgWins store={store} period={period} />
    </React.Fragment>
  );
}

/* ── shell ──────────────────────────────────────────────── */
const MG_NAV = [
  { k: 'pulse', label: 'Pulse', icon: 'pulse', h: 'How the store is doing' },
  { k: 'give', label: 'Give points', icon: 'sparkle', h: 'Give points' },
];

function ManagerScreen({ onBack, onBoostSent }) {
  const [store, setStore] = React.useState('s1');
  const [period, setPeriod] = React.useState('week');
  const [tab, setTab] = React.useState('pulse');
  const [toast, setToast] = React.useState(null);
  const [share, setShare] = React.useState(false);
  const [pop, setPop] = React.useState(null);
  const onPop = d => setPop({ ...d, k: Date.now() });
  React.useEffect(() => { if (!pop) return; const t = setTimeout(() => setPop(null), 4600); return () => clearTimeout(t); }, [pop]);
  const onToast = msg => { setToast({ msg, k: Date.now() }); setTimeout(() => setToast(t => (t && t.k && Date.now() - t.k > 3000 ? null : t)), 3300); };
  React.useEffect(() => { if (!toast) return; const t = setTimeout(() => setToast(null), 3200); return () => clearTimeout(t); }, [toast]);
  const nav = MG_NAV.find(n => n.k === tab);
  const timed = tab === 'pulse';
  const { MgGive, MgShareCard } = window.PryzeManagerPanels;
  return (
    <div className="mg-screen">
      <MgHead store={store} onStore={setStore} onBack={onBack} onShare={tab === 'pulse' ? () => setShare(true) : null} />
      <div className="mg-scroll" key={tab}>
        <div className="mg-intro">
          <h1 className="mg-h1">{nav.h}</h1>
          {nav.s && <p className="mg-sub">{nav.s}</p>}
          {timed && (
            <div className="mg-seg mg-seg-sm mg-seg-time">
              {MG_PERIODS.map(p => (
                <button key={p.k} className={period === p.k ? 'is-on' : ''} onClick={() => setPeriod(p.k)}>{p.label}</button>
              ))}
            </div>
          )}
        </div>
        {tab === 'pulse' && <MgPulse store={store} period={period} onToast={onToast} onPop={onPop} />}
        {tab === 'give' && <MgGive store={store} onDone={onToast} onPop={onPop} onBoostSent={onBoostSent} />}
      </div>
      <nav className="mg-nav">
        {MG_NAV.map(n => (
          <button key={n.k} className={'mg-navbtn' + (tab === n.k ? ' is-on' : '')} onClick={() => setTab(n.k)}>
            <MgIcon name={n.icon} size={20} weight={tab === n.k ? 'fill' : 'regular'} color={tab === n.k ? 'var(--color-primary)' : 'var(--fg-muted)'} />
            {n.label}
          </button>
        ))}
      </nav>
      {pop && <MgPop {...pop} onClose={() => setPop(null)} />}
      {share && <MgShareCard store={store} period={period} onClose={() => setShare(false)} onDone={onToast} />}
      {toast && <div className="mg-toast" key={toast.k}><MgIcon name="check-circle" size={16} weight="fill" color="var(--lime-500)" />{toast.msg}</div>}
    </div>
  );
}

function MgPop({ kind, name, photo, pts, label, goal, k, onClose }) {
  const first = (name || '').split(' ')[0];
  const head = kind === 'kudos' ? 'KUDOS!' : kind === 'boost' ? 'BOOSTED!' : 'POINTS IN!';
  const line = kind === 'kudos' ? 'Your manager just clapped for you.'
    : kind === 'boost' ? `${label} on "${goal}" — clock's ticking.`
    : `+${pts} points hit your balance.`;
  return (
    <div className="mg-popback" onClick={onClose}>
      <div className="mg-pop" key={k} onClick={e => e.stopPropagation()}>
        <span className="mg-pop-conf">{Array.from({ length: 22 }).map((_, i) => (
          <i key={i} style={{ left: (4 + i * 4.3) + '%', '--d': (i * 0.05).toFixed(2) + 's', '--c': ['#FF5A2E', '#C6FF3D', '#9C8FFF', '#FFD23F'][i % 4] }} />
        ))}</span>
        <span className="mg-pop-tag">{first}'s phone · right now</span>
        <span className="mg-pop-face">{photo ? <img src={photo} alt="" /> : (first || '?')[0]}</span>
        <p className="mg-pop-head">{head}</p>
        <p className="mg-pop-line">{line}</p>
        <button className="mg-pop-ok" onClick={onClose}>Nice</button>
      </div>
    </div>
  );
}

window.PryzeManager = { ManagerScreen, MgSheet, MgPop };
