// ════════════ TEAM · roster, hiring, time off ════════════
const { Icon, Spark, Pex, Avatar, Card, Btn, Pill, Label, Num, Toggle, Field, Select } = window;

window.SCREENS['team'] = function Team({ sub }) {
  const P = window.PX; const { go } = window.useApp();
  const active = (sub || '').split('/')[0] || 'roster';
  const nav = [
    { label: 'People ops', items: [
      { k: 'roster', icon: 'users', label: 'Roster', badge: 4 },
      { k: 'hiring', icon: 'userPlus', label: 'Hiring', badge: 1, tone: 'spark' },
      { k: 'timeoff', icon: 'calendar', label: 'Time off', badge: 2, tone: 'amber' },
      { k: 'permissions', icon: 'lock', label: 'Permissions' },
    ]},
    { label: 'Linked', items: [
      { k: 'payroll', icon: 'dollar', label: 'Payroll →' },
    ]},
  ];
  const onNav = (k) => k === 'payroll' ? go('money/payroll') : go('team' + (k === 'roster' ? '' : '/' + k));
  return (
    <window.SubLayout title="Team" nav={nav} active={active} onNav={onNav}>
      {active === 'roster' && <TeamRoster/>}
      {active === 'hiring' && <TeamHiring/>}
      {active === 'timeoff' && <TeamTimeOff/>}
      {active === 'permissions' && <TeamPermissions/>}
    </window.SubLayout>
  );
};

const TEAM = [
  { name: 'Rosa Kim', role: 'Head baker', type: 'Salary', pay: '$1,840 / period', card: 'Operating ••4290', role2: 'Admin', tone: 'sage', start: '2019' },
  { name: 'Diego Torres', role: 'Baker', type: 'Hourly · $24/hr', pay: '~$1,520 / period', card: 'Virtual ••9012', role2: 'Member', tone: 'sky', start: '2021' },
  { name: 'Ethan Brooks', role: 'Counter', type: 'Hourly · $20/hr', pay: '~$980 / period', card: '—', role2: 'Member', tone: 'neutral', start: '2023' },
  { name: 'Priya Venkatesan', role: 'Marketing (PT)', type: 'Contract', pay: '$1,100 / period', card: 'Virtual ••7731', role2: 'Member', tone: 'plum', start: '2024' },
];

const EMP_TYPES = ['Salary', 'Hourly', 'Contract'];
const EMP_ACCESS = ['Admin', 'Member'];

function TeamRoster() {
  const P = window.PX; const { go, toast } = window.useApp();
  const [team, setTeam] = React.useState(TEAM);
  const [showAdd, setShowAdd] = React.useState(false);
  const [editIdx, setEditIdx] = React.useState(null);
  const addPerson = (p) => { setTeam(t => [...t, p]); setShowAdd(false); toast(`${p.name} added to the roster.`, { tone: 'sage', icon: 'check' }); };
  const savePerson = (i, patch) => { setTeam(t => t.map((p, j) => j === i ? { ...p, ...patch } : p)); setEditIdx(null); toast('Teammate updated.', { tone: 'sage', icon: 'check' }); };
  const removePerson = (i) => { const p = team[i]; setTeam(t => t.filter((_, j) => j !== i)); setEditIdx(null); toast(`${p.name} removed from the roster.`, { icon: 'trash' }); };
  return (
    <div style={{ fontFamily: P.sans, padding: 24 }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', marginBottom: 18 }}>
        <div style={{ flex: 1 }}><div style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 26, color: P.ink }}>Roster</div><div style={{ fontSize: 12.5, color: P.ink3 }}>{team.length} people · next payroll Friday Mar 14 · $5,440</div></div>
        <Btn kind="default" size="sm" icon="play" onClick={() => go('money/payroll')}>Run payroll</Btn>
        <Btn kind="spark" size="sm" icon="userPlus" style={{ marginLeft: 8 }} onClick={() => setShowAdd(true)}>Add person</Btn>
      </div>
      <Card pad={0}>
        <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr 1.1fr 90px 70px', gap: 12, padding: '11px 18px', borderBottom: `1px solid ${P.line}` }}>
          {['Person', 'Pay', 'Card', 'Access', ''].map((h, i) => <Label key={i}>{h}</Label>)}
        </div>
        {team.map((t, i) => (
          <div key={i} style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr 1.1fr 90px 70px', gap: 12, padding: '13px 18px', borderBottom: i < team.length - 1 ? `1px solid ${P.line}` : 'none', alignItems: 'center' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}><Avatar name={t.name} size={34}/><div><div style={{ fontSize: 13.5, color: P.ink, fontWeight: 500 }}>{t.name}</div><div style={{ fontSize: 11, color: P.ink3 }}>{t.role} · since {t.start}</div></div></div>
            <div><div style={{ fontSize: 12.5, color: P.ink }}>{t.pay}</div><div style={{ fontSize: 11, color: P.ink3 }}>{t.type}</div></div>
            <span style={{ fontSize: 12, color: t.card === '—' ? P.ink4 : P.ink2, fontFamily: t.card === '—' ? P.sans : P.mono }}>{t.card === '—' ? 'No card' : t.card}</span>
            <span><Pill tone={t.role2 === 'Admin' ? 'sage' : 'neutral'}>{t.role2}</Pill></span>
            <span onClick={() => setEditIdx(i)} style={{ cursor: 'pointer', display: 'inline-flex' }}><Icon name="dotsV" size={16} color={P.ink4}/></span>
          </div>
        ))}
      </Card>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 12, fontSize: 12, color: P.ink3 }}><Pex size={18}/>Ethan has no card yet — issue a virtual card with a weekly limit so he can buy supplies. <span onClick={() => go('money/cards')} style={{ color: P.spark, cursor: 'pointer', fontWeight: 500 }}>Issue card →</span></div>

      {showAdd && <EmployeeModal onClose={() => setShowAdd(false)} onSave={addPerson}/>}
      {editIdx != null && <EmployeeModal initial={team[editIdx]} onClose={() => setEditIdx(null)} onSave={(p) => savePerson(editIdx, p)} onRemove={() => removePerson(editIdx)}/>}
    </div>
  );
}

// ── Add / edit teammate ──────────────────────────────────────
function EmployeeModal({ initial, onClose, onSave, onRemove }) {
  const P = window.PX; const { toast } = window.useApp();
  const editing = !!initial;
  const [name, setName] = React.useState(initial ? initial.name : '');
  const [role, setRole] = React.useState(initial ? initial.role : '');
  const [type, setType] = React.useState(initial ? (EMP_TYPES.find(t => (initial.type || '').startsWith(t)) || 'Hourly') : 'Hourly');
  const [pay, setPay] = React.useState(initial ? initial.pay : '');
  const [access, setAccess] = React.useState(initial ? initial.role2 : 'Member');
  const save = () => {
    if (!name.trim()) { toast('Add a name first.', { tone: 'rose', icon: 'alert' }); return; }
    onSave({
      name: name.trim(), role: role.trim() || 'Teammate', type, pay: pay.trim() || '— / period',
      card: initial ? initial.card : '—', role2: access, tone: initial ? initial.tone : 'neutral',
      start: initial ? initial.start : String(new Date().getFullYear()),
    });
  };
  return (
    <window.Modal title={editing ? 'Edit teammate' : 'Add a teammate'} w={520} onClose={onClose}
      foot={<>{editing && <Btn kind="danger" icon="trash" onClick={onRemove}>Remove</Btn>}<div style={{ flex: 1 }}/><Btn kind="ghost" onClick={onClose}>Cancel</Btn><Btn kind="primary" icon="check" onClick={save}>{editing ? 'Save' : 'Add person'}</Btn></>}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        <Field label="Name" placeholder="Jordan Rivera" value={name} onChange={setName} style={{ gridColumn: '1 / -1' }}/>
        <Field label="Role" placeholder="e.g. Baker" value={role} onChange={setRole}/>
        <Select label="Type" value={type} onChange={setType} options={EMP_TYPES}/>
        <Field label="Pay" placeholder="$1,200 / period" value={pay} onChange={setPay}/>
        <Select label="Access" value={access} onChange={setAccess} options={EMP_ACCESS}/>
      </div>
    </window.Modal>
  );
}

// ── HIRING ────────────────────────────────────────────────────
const HIRING_STAGES = ['Applied', 'Screening', 'Interview', 'Offer'];
const HIRING_TONE = { Applied: 'neutral', Screening: 'sky', Interview: 'amber', Offer: 'sage' };

function TeamHiring() {
  const P = window.PX; const { toast } = window.useApp();
  const [roles, setRoles] = React.useState([
    { id: 'role-baker', title: 'Weekend baker · part-time', meta: '$22–26/hr · Sat–Sun · posted on your site, Indeed & Poached · open 8 days' },
  ]);
  const [editRole, setEditRole] = React.useState(null);
  const [showPost, setShowPost] = React.useState(false);
  const [cands, setCands] = React.useState([
    { id: 'c-noah', name: 'Noah Pierce', note: '2d ago', stage: 'Applied' },
    { id: 'c-mara', name: 'Mara Lindqvist', note: '3d ago', stage: 'Applied' },
    { id: 'c-tariq', name: 'Tariq Hassan', note: '5d ago', stage: 'Applied' },
    { id: 'c-grace', name: 'Grace Liu', note: 'Pex screened · strong', stage: 'Screening' },
    { id: 'c-owen', name: 'Owen Butler', note: 'Pex screened', stage: 'Screening' },
    { id: 'c-sofia', name: 'Sofia Real', note: 'Sat 10am', stage: 'Interview' },
  ]);
  const [openId, setOpenId] = React.useState(null);
  const openCand = cands.find(c => c.id === openId);

  const moveCand = (id, stage) => { setCands(cs => cs.map(c => c.id === id ? { ...c, stage } : c)); toast(`Moved to ${stage}.`, { icon: 'check', tone: stage === 'Offer' ? 'sage' : undefined }); };
  const addRole = (r) => { setRoles(rs => [...rs, { ...r, id: window.pxid('role') }]); setShowPost(false); toast('Role posted to your site, Indeed & Poached.', { tone: 'sage', icon: 'check' }); };
  const saveRole = (id, patch) => { setRoles(rs => rs.map(r => r.id === id ? { ...r, ...patch } : r)); setEditRole(null); toast('Job post updated.', { tone: 'sage', icon: 'check' }); };
  const draftInvite = () => { setCands(cs => cs.map(c => c.id === 'c-grace' ? { ...c, stage: 'Interview', note: 'Trial shift · invite drafted' } : c)); toast('Trial shift invite drafted — Grace moved to Interview.', { tone: 'sage', icon: 'check' }); };

  return (
    <div style={{ fontFamily: P.sans, padding: 24 }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', marginBottom: 18 }}>
        <div style={{ flex: 1 }}><div style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 26, color: P.ink }}>Hiring</div><div style={{ fontSize: 12.5, color: P.ink3 }}>{roles.length} open role{roles.length === 1 ? '' : 's'} · {cands.length} candidates</div></div>
        <Btn kind="spark" size="sm" icon="plus" onClick={() => setShowPost(true)}>Post a role</Btn>
      </div>

      {/* open roles */}
      {roles.map((r, i) => (
        <Card key={r.id} pad={18} style={{ marginBottom: 14, display: 'flex', alignItems: 'center', gap: 16 }}>
          <div style={{ width: 46, height: 46, borderRadius: 12, background: P.sparkTint, color: P.spark, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="briefcase" size={22}/></div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 15, fontWeight: 600, color: P.ink }}>{r.title}</div>
            <div style={{ fontSize: 12, color: P.ink3, marginTop: 2 }}>{r.meta}</div>
          </div>
          <div style={{ textAlign: 'right' }}><Num size={22}>{i === 0 ? cands.length : 0}</Num><div style={{ fontSize: 11, color: P.ink3 }}>candidates</div></div>
          <Btn kind="default" size="sm" onClick={() => setEditRole(r)}>Edit post</Btn>
        </Card>
      ))}

      {/* pipeline */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 12, marginTop: 4 }}>
        {HIRING_STAGES.map((stage) => {
          const items = cands.filter(c => c.stage === stage);
          return (
            <div key={stage} style={{ background: P.sunk, borderRadius: 12, padding: 10, minHeight: 220 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 7, padding: '4px 6px 10px' }}>
                <span style={{ width: 8, height: 8, borderRadius: 8, background: HIRING_TONE[stage] === 'neutral' ? P.ink4 : P[HIRING_TONE[stage]] }}/>
                <span style={{ fontSize: 12.5, fontWeight: 600, color: P.ink, flex: 1 }}>{stage}</span>
                <span style={{ fontSize: 11, color: P.ink3 }}>{items.length}</span>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {items.map((p) => (
                  <div key={p.id} onClick={() => setOpenId(p.id)} style={{ background: P.card, border: `1px solid ${P.line}`, borderRadius: 10, padding: 11, cursor: 'pointer', boxShadow: P.shSm }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><Avatar name={p.name} size={26}/><span style={{ fontSize: 12.5, fontWeight: 600, color: P.ink }}>{p.name}</span></div>
                    <div style={{ fontSize: 10.5, color: P.ink3, marginTop: 6 }}>{p.note}</div>
                  </div>
                ))}
                {items.length === 0 && <div style={{ fontSize: 11, color: P.ink4, textAlign: 'center', padding: '16px 0' }}>—</div>}
              </div>
            </div>
          );
        })}
      </div>
      <Card pad={16} style={{ marginTop: 16, background: P.sparkWash, border: `1px solid ${P.sparkTint}`, display: 'flex', gap: 11, alignItems: 'center' }}>
        <Pex size={26}/>
        <div style={{ flex: 1, fontSize: 12.5, color: P.ink2, lineHeight: 1.5 }}>I screened the 3 applicants against your last baker hire. <b style={{ color: P.ink }}>Grace Liu</b> stands out — 4 years on a sourdough line. Want me to schedule a Saturday trial shift?</div>
        <Btn kind="spark" size="sm" onClick={draftInvite}>Draft invite · 1 ⚡</Btn>
      </Card>

      {openCand && <CandidateDrawer cand={openCand} onClose={() => setOpenId(null)} onMove={moveCand}/>}
      {showPost && <RoleModal onClose={() => setShowPost(false)} onSave={addRole}/>}
      {editRole && <RoleModal initial={editRole} onClose={() => setEditRole(null)} onSave={(patch) => saveRole(editRole.id, patch)}/>}
    </div>
  );
}

function CandidateDrawer({ cand, onClose, onMove }) {
  const P = window.PX; const { toast } = window.useApp();
  return (
    <window.Drawer title={cand.name} sub="Weekend baker · part-time" tag={<Pill tone={HIRING_TONE[cand.stage]}>{cand.stage}</Pill>} onClose={onClose}
      foot={<><Btn kind="ghost" size="sm" onClick={() => { onMove(cand.id, 'Applied'); }}>Reject</Btn><div style={{ flex: 1 }}/><Btn kind="primary" size="sm" icon="mail" onClick={() => toast(`Message drafted to ${cand.name}.`, { tone: 'sage', icon: 'check' })}>Message</Btn></>}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 18 }}>
        <Avatar name={cand.name} size={44}/>
        <div><div style={{ fontSize: 15, fontWeight: 600, color: P.ink }}>{cand.name}</div><div style={{ fontSize: 12, color: P.ink3 }}>{cand.note}</div></div>
      </div>
      <Label style={{ marginBottom: 8 }}>Move to stage</Label>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 20 }}>
        {HIRING_STAGES.map(s => {
          const on = cand.stage === s;
          return <div key={s} onClick={() => onMove(cand.id, s)} style={{ padding: '7px 13px', borderRadius: 8, fontSize: 12.5, fontWeight: on ? 600 : 500, cursor: 'pointer', background: on ? P.ink : P.sunk, color: on ? '#fff' : P.ink2 }}>{s}</div>;
        })}
      </div>
      <Card pad={14} style={{ background: P.sparkWash, border: `1px solid ${P.sparkTint}` }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 6 }}><Pex size={18}/><span style={{ fontSize: 13, fontWeight: 600, color: P.ink }}>Pex screen</span></div>
        <div style={{ fontSize: 12.5, color: P.ink2, lineHeight: 1.5 }}>{cand.name} applied for the weekend baker role. Compared against your last hire, the fit looks {cand.stage === 'Interview' || cand.stage === 'Offer' ? 'strong' : 'promising'}.</div>
      </Card>
    </window.Drawer>
  );
}

function RoleModal({ initial, onClose, onSave }) {
  const P = window.PX;
  const editing = !!initial;
  const [title, setTitle] = React.useState(initial ? initial.title : '');
  const [pay, setPay] = React.useState(initial ? (initial.pay || '') : '');
  const [meta, setMeta] = React.useState(initial ? initial.meta : '');
  const save = () => {
    if (!title.trim()) return;
    const metaOut = meta.trim() || `${pay.trim() || 'Rate TBD'} · posted on your site, Indeed & Poached · open today`;
    onSave({ title: title.trim(), pay: pay.trim(), meta: metaOut });
  };
  return (
    <window.Modal title={editing ? 'Edit job post' : 'Post a role'} sub={editing ? undefined : 'Pex drafts from your last hire and brand voice'} w={540} onClose={onClose}
      foot={<><Btn kind="ghost" onClick={onClose}>Cancel</Btn><div style={{ flex: 1 }}/><Btn kind="primary" icon="check" disabled={!title.trim()} onClick={save}>{editing ? 'Save post' : 'Post role'}</Btn></>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <Field label="Role title" placeholder="e.g. Weekend baker · part-time" value={title} onChange={setTitle}/>
        <Field label="Pay" placeholder="$22–26/hr" value={pay} onChange={setPay}/>
        <window.TextArea label="Details" placeholder="Schedule, where it's posted, how long it's open…" rows={3} value={meta} onChange={setMeta}/>
      </div>
    </window.Modal>
  );
}

// ── TIME OFF ──────────────────────────────────────────────────
function TeamTimeOff() {
  const P = window.PX; const { toast } = window.useApp();
  const [reqs, setReqs] = React.useState([
    { who: 'Diego Torres', what: 'Vacation · 3 days', when: 'Mar 24–26', status: 'pending' },
    { who: 'Ethan Brooks', what: 'Sick day', when: 'Mar 13', status: 'pending' },
    { who: 'Rosa Kim', what: 'Personal · 1 day', when: 'Mar 28', status: 'approved' },
  ]);
  const pending = reqs.filter(r => r.status === 'pending').length;
  const setStatus = (i, status) => {
    const r = reqs[i];
    setReqs(rs => rs.map((x, j) => j === i ? { ...x, status } : x));
    toast(status === 'approved' ? `${r.who}'s time off approved.` : `${r.who}'s request declined.`, status === 'approved' ? { tone: 'sage', icon: 'check' } : { tone: 'rose', icon: 'x' });
  };
  return (
    <div style={{ fontFamily: P.sans, padding: 24 }}>
      <div style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 26, color: P.ink, marginBottom: 4 }}>Time off</div>
      <div style={{ fontSize: 12.5, color: P.ink3, marginBottom: 18 }}>{pending} request{pending === 1 ? '' : 's'} waiting · coverage looks fine for all</div>
      {reqs.length ? (
        <Card pad={0}>
          {reqs.map((r, i) => (
            <div key={i} style={{ padding: '14px 18px', display: 'flex', alignItems: 'center', gap: 12, borderBottom: i < reqs.length - 1 ? `1px solid ${P.line}` : 'none' }}>
              <Avatar name={r.who} size={34}/>
              <div style={{ flex: 1 }}><div style={{ fontSize: 13.5, color: P.ink, fontWeight: 500 }}>{r.who}</div><div style={{ fontSize: 11.5, color: P.ink3 }}>{r.what} · {r.when}</div></div>
              {r.status === 'approved' && <Pill tone="sage" dot>Approved</Pill>}
              {r.status === 'declined' && <Pill tone="rose" dot>Declined</Pill>}
              {r.status === 'pending' && <><Btn kind="ghost" size="sm" onClick={() => setStatus(i, 'declined')}>Decline</Btn><Btn kind="spark" size="sm" icon="check" onClick={() => setStatus(i, 'approved')}>Approve</Btn></>}
            </div>
          ))}
        </Card>
      ) : <div style={{ padding: '36px 0', textAlign: 'center', color: P.ink3, fontSize: 13 }}>No time-off requests.</div>}
    </div>
  );
}

// ── PERMISSIONS ──────────────────────────────────────────────
function TeamPermissions() {
  const P = window.PX; const { toast } = window.useApp();
  const labels = ['Move money', 'Has a card', 'Approve payroll'];
  const [rows, setRows] = React.useState([
    { name: 'Rosa Kim', role: 'Admin', perms: [true, true, true] },
    { name: 'Diego Torres', role: 'Member', perms: [false, true, false] },
    { name: 'Ethan Brooks', role: 'Member', perms: [false, false, false] },
    { name: 'Priya Venkatesan', role: 'Member', perms: [false, true, false] },
  ]);
  const toggle = (i, j) => {
    const next = !rows[i].perms[j];
    setRows(rs => rs.map((r, ri) => ri === i ? { ...r, perms: r.perms.map((p, pj) => pj === j ? next : p) } : r));
    toast(`${rows[i].name} · ${labels[j]} ${next ? 'on' : 'off'}.`, { icon: next ? 'check' : 'x', tone: next ? 'sage' : undefined });
  };
  return (
    <div style={{ fontFamily: P.sans, padding: 24 }}>
      <div style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 26, color: P.ink, marginBottom: 4 }}>Permissions</div>
      <div style={{ fontSize: 12.5, color: P.ink3, marginBottom: 18 }}>Who can do what with money. Payments over $400 from members need your approval.</div>
      <Card pad={0}>
        <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 100px 1fr 1fr 1fr', gap: 12, padding: '11px 18px', borderBottom: `1px solid ${P.line}` }}>
          {['Person', 'Role', 'Move money', 'Has a card', 'Approve payroll'].map((h, i) => <Label key={i}>{h}</Label>)}
        </div>
        {rows.map((r, i) => (
          <div key={i} style={{ display: 'grid', gridTemplateColumns: '1.5fr 100px 1fr 1fr 1fr', gap: 12, padding: '13px 18px', borderBottom: i < rows.length - 1 ? `1px solid ${P.line}` : 'none', alignItems: 'center' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}><Avatar name={r.name} size={30}/><span style={{ fontSize: 13, color: P.ink, fontWeight: 500 }}>{r.name}</span></div>
            <span><Pill tone={r.role === 'Admin' ? 'sage' : 'neutral'}>{r.role}</Pill></span>
            {r.perms.map((on, j) => <Toggle key={j} on={on} size="sm" onClick={() => toggle(i, j)}/>)}
          </div>
        ))}
      </Card>
    </div>
  );
}
