const { Icon: MpIcon } = window.PryzeDesignSystem_b2bad9;
const { MG_STORES: MP_STORES, MG_REASONS, MG_BOOSTS, MG_WINDOWS, MG_GOALS, MG_CATS, MG_REPORT, MG_COMPANY, mgStaff: mpStaff, mgMetrics: mpMetrics, MG_PERIODS: MP_PERIODS, MG_TIERS, MG_NUDGE_KINDS, MG_DAILY_STATS, MG_CO } = window.PryzeManagerData;

const mpStore = id => MP_STORES.find(s => s.id === id) || MP_STORES[0];

/* one-tap picker row that opens a native-feeling sheet */
function MgPickRow({ label, value, sub, face, onOpen }) {
  return (
    <button className="mg-field" onClick={onOpen}>
      <span className="mg-field-lbl">{label}</span>
      <span className="mg-field-val">
        {face && <span className="mg-face mg-face-sm">{face.photo ? <img src={face.photo} alt="" /> : face.name[0]}</span>}
        <span className="mg-field-txt"><b>{value}</b>{sub && <em>{sub}</em>}</span>
        <MpIcon name="caret-right" size={13} weight="bold" color="var(--fg-muted)" />
      </span>
    </button>
  );
}

/* shared people strip — the first step of both Award and Boost */
function MgPeople({ staff, who, onPick }) {
  return (
    <div className="mg-strip">
      {staff.map(s => (
        <button key={s.id} className={'mg-strip-p' + (s.id === who ? ' is-on' : '')} onClick={() => onPick(s.id)}>
          <span className="mg-face mg-face-md">{s.photo ? <img src={s.photo} alt="" /> : s.name[0]}</span>
          <em>{s.name.split(' ')[0]}</em>
          {s.risk && <i className="mg-risk" />}
        </button>
      ))}
    </div>
  );
}

function MgSwap({ to, label, onGo }) {
  return (
    <button className="mg-swap" onClick={() => onGo(to)}>
      <span>{label}</span>
      <MpIcon name="arrow-right" size={13} weight="bold" color="var(--color-primary)" />
    </button>
  );
}

/* ── Give — award + boost in one toggled screen ─────────── */
function MgStep({ n, title, done, sub, children }) {
  return (
    <div className={'mg-step' + (done ? ' is-done' : '')}>
      <div className="mg-step-head">
        <span className="mg-step-n">{done ? <MpIcon name="check" size={13} weight="bold" color="#0E1408" /> : n}</span>
        <span className="mg-step-txt"><b>{title}</b>{sub && <em>{sub}</em>}</span>
      </div>
      {children}
    </div>
  );
}

function MgGive({ store, onDone, onPop, onBoostSent }) {
  const staff = mpStaff(store), s = mpStore(store);
  const [mode, setMode] = React.useState('award');
  const [scope, setScope] = React.useState('one');
  const [who, setWho] = React.useState(null);
  const [reason, setReason] = React.useState(null);
  const [boost, setBoost] = React.useState(null);
  const [goal, setGoal] = React.useState(null);
  const [note, setNote] = React.useState('');
  React.useEffect(() => { setWho(null); }, [store]);
  const award = mode === 'award';
  const p = staff.find(x => x.id === who);
  const r = MG_REASONS.find(x => x.k === reason);
  const b = MG_BOOSTS.find(x => x.k === boost);
  const g = MG_GOALS.find(x => x.id === goal);
  const team = scope === 'team';
  const whoOk = team || !!p;
  const whoName = team ? 'The whole team' : p ? p.name : null;
  const first = team ? 'Everyone' : p ? p.name.split(' ')[0] : '';
  const ready = whoOk && (award ? !!r : !!b && !!g);
  const reset = () => { setWho(null); setReason(null); setBoost(null); setGoal(null); setNote(''); };
  const submit = () => {
    if (award) {
      onDone(`${first} notified · +${r.pts} pts${team ? ' each' : ''}`);
      onPop({ kind: 'points', name: whoName, photo: team ? null : p.photo, pts: r.pts });
    } else {
      onDone(`${first} boosted · ${b.label}`);
      onPop({ kind: 'boost', name: whoName, photo: team ? null : p.photo, label: b.label, goal: g.title });
      if (onBoostSent) onBoostSent({ label: b.label, goal: g.title, pts: b.pts, from: s.manager || 'Your manager' });
    }
    reset();
  };
  return (
    <React.Fragment>
      <div className="mg-seg mg-seg-mode">
        <button className={award ? 'is-on' : ''} onClick={() => setMode('award')}>Already earned it</button>
        <button className={!award ? 'is-on' : ''} onClick={() => setMode('boost')}>Need it done next</button>
      </div>

      <MgStep n="1" title="Who is it for?" done={whoOk} sub={team ? `All ${s.staff} people on Pryze at ${s.name}` : p ? `${p.name} · ${p.shift}` : 'One person or the whole team'}>
        <div className="mg-seg mg-seg-sm mg-seg-scope">
          <button className={scope === 'one' ? 'is-on' : ''} onClick={() => setScope('one')}>One person</button>
          <button className={team ? 'is-on' : ''} onClick={() => { setScope('team'); setWho(null); }}>Whole team</button>
        </div>
        {!team && <MgPeople staff={staff} who={who} onPick={setWho} />}
        {team && (
          <div className="mg-teamrow">
            <span className="mg-team-faces">{staff.slice(0, 6).map(x => (
              <span className="mg-face mg-face-sm" key={x.id}>{x.photo ? <img src={x.photo} alt="" /> : x.name[0]}</span>
            ))}</span>
            <span className="mg-team-n">+{Math.max(0, s.staff - 6)} more</span>
          </div>
        )}
      </MgStep>

      {award ? (
        <MgStep n="2" title="What did they do?" done={!!r} sub={r ? `${r.label} · +${r.pts} pts` : 'Points are fixed per reason'}>
          <div className="mg-reasons">
            {MG_REASONS.map(x => (
              <button key={x.k} className={'mg-reason' + (reason === x.k ? ' is-on' : '')} onClick={() => setReason(x.k)}>
                <span className="mg-reason-txt"><b>{x.label}</b><em>{x.note}</em></span>
                <span className="mg-reason-pts">+{x.pts}</span>
              </button>
            ))}
          </div>
        </MgStep>
      ) : (
        <MgStep n="2" title="What are they getting?" done={!!b && !!g} sub={b ? (g ? `${b.label} on ${g.title}` : b.label) : 'A boost only pays on one goal'}>
          <div className="mg-reasons">
            {MG_BOOSTS.map(x => (
              <button key={x.k} className={'mg-reason' + (boost === x.k ? ' is-on' : '')} onClick={() => setBoost(x.k)}>
                <span className="mg-reason-txt"><b>{x.label}</b><em>{x.sub}</em></span>
                <span className="mg-reason-pts">{x.pts}</span>
              </button>
            ))}
          </div>
          <p className="mg-lbl mg-lbl-in">On which goal?</p>
          <div className="mg-chips">
            {MG_GOALS.filter(x => x.live).map(x => (
              <button key={x.id} className={'mg-chip' + (goal === x.id ? ' is-on' : '')} onClick={() => setGoal(x.id)}>{x.title}</button>
            ))}
          </div>
        </MgStep>
      )}

      <MgStep n="3" title="Say something?" done={!!note.trim()} sub={note.trim() || 'Optional — shows up in their feed'}>
        <textarea className="mg-note" rows="3" value={note} onChange={e => setNote(e.target.value)}
          placeholder={award ? 'Nobody asked you to do that. Noticed.' : 'Clear this one before close and it counts double.'} />
      </MgStep>

      <div className="mg-dock">
        <p className="mg-dock-say">{ready
          ? award
            ? <React.Fragment><b>{whoName}</b> gets <b>+{r.pts} points</b>{team ? ' each' : ''} for {r.say}.</React.Fragment>
            : <React.Fragment><b>{whoName}</b> gets <b>{b.label}</b> on <b>{g.title}</b>.</React.Fragment>
          : `Finish step ${!whoOk ? 1 : 2} to send.`}</p>
        <button className="mg-cta" disabled={!ready} onClick={submit}>
          <MpIcon name={award ? 'sparkle' : 'lightning'} size={16} weight="fill" color="#fff" />
          {ready ? (award ? `Give ${first} ${r.pts} points` : `Boost ${first}`) : 'Give points'}
        </button>
      </div>
    </React.Fragment>
  );
}

/* ── Report ─────────────────────────────────────────────── */
function MgShareCard({ store, period, onClose, onDone }) {
  const staff = mpStaff(store), s = mpStore(store), m = mpMetrics(store, period);
  const per = MP_PERIODS.find(x => x.k === period) || MP_PERIODS[1];
  const t = MG_TIERS[s.grade] || MG_TIERS.C;
  const co = MG_CO[MG_COMPANY.co] || {};
  const top = [...staff].sort((a, b) => b.golds - a.golds).slice(0, 3);
  return (
    <div className="mg-back" onClick={onClose}>
      <div className="mg-sharewrap" onClick={e => e.stopPropagation()}>
        <div className={'mg-share mg-tier-' + t.k} style={{ background: t.bg }}>
          {t.k === 'a' && <span className="mg-share-conf">{Array.from({ length: 34 }).map((_, i) => (
            <i key={i} className={i % 3 === 0 ? 'is-round' : ''} style={{ left: (i * 2.97) + '%', '--d': (i * 0.13).toFixed(2) + 's', '--t': (2.2 + (i % 5) * 0.4).toFixed(1) + 's', '--c': ['#FF5A2E', '#C6FF3D', '#9C8FFF', '#FFD23F'][i % 4] }} />
          ))}</span>}
          <div className="mg-share-brand">
            <span className="mg-share-co">{co.logo ? <img src={co.logo} alt="" /> : <b>{co.initials || 'W'}</b>}</span>
            <span className="mg-share-co-txt"><b>{s.name}</b><em>{s.city}</em></span>
            <span className="mg-share-pryze">pryze</span>
          </div>
          <div className="mg-share-tape">{t.tape}</div>
          <p className="mg-share-head">{t.head.map((w, i) => <b key={i} className={'mg-w' + i}>{w}</b>)}</p>
          <div className="mg-share-hero">
            <span className="mg-share-grade">{s.grade}<em>grade</em></span>
            <span className="mg-share-blob">
              <b>{m.golds.toLocaleString()}</b>
              <em>goals crushed</em>
            </span>
          </div>
          <div className="mg-share-nums">
            <span className="mg-sn1"><b>{'#' + s.rank}</b><em>{'of ' + s.of + ' stores'}</em></span>
            <span className="mg-sn2"><b>{MG_COMPANY.pctile + 'th'}</b><em>percentile</em></span>
            <span className="mg-sn3"><b>{(m.delta >= 0 ? '+' : '') + m.delta + '%'}</b><em>{'vs ' + per.prev}</em></span>
          </div>
          <div className="mg-share-top">
            <p className="mg-share-lbl">loudest shoutout</p>
            {top.map((x, i) => (
              <span className={'mg-share-p mg-sp' + i} key={x.id}>
                <span className="mg-face mg-face-sm">{x.photo ? <img src={x.photo} alt="" /> : x.name[0]}</span>
                {x.name}<em>{x.golds}</em>
              </span>
            ))}
          </div>
          <p className="mg-share-mark">{per.word} · {t.line}</p>
        </div>
        <div className="mg-share-actions">
          {['Instagram story', 'Team channel', 'Save image'].map(x => (
            <button key={x} className="mg-share-btn" onClick={() => { onDone('Shared to ' + x.toLowerCase()); onClose(); }}>{x}</button>
          ))}
        </div>
      </div>
    </div>
  );
}

function MgReport({ store, period, onDone, onPop }) {
  const staff = mpStaff(store), s = mpStore(store);
  const risks = staff.filter(x => x.risk);
  const [sent, setSent] = React.useState({});
  React.useEffect(() => { setSent({}); }, [store]);
  const vals = { engaged: MG_REPORT.engagedUsers + ' / ' + s.staff, golds: MG_REPORT.goldsToday, pts: MG_REPORT.redeemablePts.toLocaleString(), redeemed: MG_REPORT.redeemed };
  return (
    <React.Fragment>
      <div className="mg-sec">
        <p className="mg-lbl">{new Date().toLocaleDateString('en-US', { weekday: 'long', month: 'short', day: 'numeric' })}</p>
        <div className="mg-quads">
          {MG_DAILY_STATS.map(x => (
            <span className="mg-quad" key={x.k}>
              <i className="mg-quad-ic"><MpIcon name={x.icon} size={15} weight="bold" color="var(--color-primary)" /></i>
              <b>{vals[x.k]}</b>{x.label}
            </span>
          ))}
        </div>
      </div>

      <div className="mg-sec">
        <p className="mg-lbl">Nudge people</p>
        <div className="mg-list">
          {risks.map(x => {
            const k = MG_NUDGE_KINDS[x.risk] || MG_NUDGE_KINDS.quiet;
            return (
              <div className="mg-item" key={x.id}>
                <span className="mg-face mg-face-sm">{x.photo ? <img src={x.photo} alt="" /> : x.name[0]}</span>
                <span className="mg-item-txt"><b>{x.name}</b><em className="mg-why"><MpIcon name={k.icon} size={12} weight="bold" color="var(--fg-muted)" />{k.label}</em></span>
                <button className={'mg-mini' + (sent[x.id] ? ' is-sent' : '')} disabled={!!sent[x.id]}
                  onClick={() => { setSent(v => ({ ...v, [x.id]: 1 })); onDone(`Nudge sent to ${x.name.split(' ')[0]}`); }}>{sent[x.id] ? 'Sent' : 'Nudge'}</button>
              </div>
            );
          })}
          {!risks.length && <p className="mg-read">Nobody slipping today.</p>}
        </div>
      </div>

    </React.Fragment>
  );
}

window.PryzeManagerPanels = { MgGive, MgReport, MgShareCard, MgPeople };
