function empState(e, punches, today) {
  const open = punches.find((p) => p.emp === e.id && p.date === today && p.open);
  const done = punches.filter((p) => p.emp === e.id && p.date === today && !p.open);
  return { open, onBreak: open && open.onBreak != null, done };
}
const initials = (n) => n.split(' ').map((w) => w[0]).join('').slice(0, 2);

function TimeClock() {
  const { L, lang, fmt, P, employees, punches, now } = useMizo();
  const pf = usePayFmt();
  const [who, setWho] = React.useState(null);
  const today = P.days[P.TODAY];
  const states = employees.map((e) => ({ e, ...empState(e, punches, today), sh: e.sched[2] }));
  const working = states.filter((s) => s.open && !s.onBreak);
  const onBreak = states.filter((s) => s.onBreak);
  const costHr = states.filter((s) => s.open).reduce((a, s) => a + (s.e.type === 'salary' ? s.e.salary / 80 : s.e.rate), 0);
  const todayHrs = punches.filter((p) => p.date === today).reduce((a, p) => a + P.worked(p, now), 0);
  const feed = [];
  punches.filter((p) => p.date === today).forEach((p) => {
    const n = employees.find((e) => e.id === p.emp).name;
    feed.push({ t: p.in, n, a: L('clocked in', 'a pointé son entrée'), ic: 'sign-in' });
    if (p.onBreak != null) feed.push({ t: p.onBreak, n, a: L('started a break', 'a commencé sa pause'), ic: 'coffee' });
    if (p.out != null) feed.push({ t: p.out, n, a: L('clocked out', 'a pointé sa sortie'), ic: 'sign-out' });
  });
  feed.sort((a, b) => b.t - a.t);

  return (
    <div className="clock-layout">
      <section className="panel clock-main">
        <div className="clock-head">
          <div>
            <div className="clock-time tnum">{pf.time(now)}</div>
            <div className="muted">{new Intl.DateTimeFormat(lang === 'fr' ? 'fr-CA' : 'en-CA', { weekday: 'long', month: 'long', day: 'numeric' }).format(new Date(today + 'T12:00'))} · <span className="tag tag-neutral">{L('Demo time', 'Heure démo')}</span></div>
          </div>
          <p className="clock-hint">{L('Tap your name, then enter your 4-digit PIN.', 'Touchez votre nom, puis entrez votre NIP à 4 chiffres.')}</p>
        </div>
        <div className="emp-grid">
          {states.map(({ e, open, onBreak: ob, done, sh }) => {
            const st = ob ? 'break' : open ? 'in' : 'off';
            return (
              <button key={e.id} className={'emp-tile ' + st} onClick={() => setWho(e.id)}>
                <span className="emp-av lg">{initials(e.name)}</span>
                <span className="emp-tile-name">{e.name.split(' ')[0]} <span className="muted">{e.name.split(' ').slice(1).join(' ')[0]}.</span></span>
                <span className="emp-tile-st">
                  <i className="st-dot"></i>
                  {st === 'in' ? L(`In since ${pf.time(open.in)}`, `Entré à ${pf.time(open.in)}`) : st === 'break' ? L(`On break · ${Math.round(now - open.onBreak)} min`, `En pause · ${Math.round(now - open.onBreak)} min`) : done.length ? L(`Out at ${pf.time(done[done.length - 1].out)}`, `Sorti à ${pf.time(done[done.length - 1].out)}`) : sh && sh[0] > now ? L(`Shift at ${pf.time(sh[0])}`, `Quart à ${pf.time(sh[0])}`) : L('Not scheduled', 'Pas à l’horaire')}
                </span>
              </button>
            );
          })}
        </div>
      </section>
      <aside className="clock-side">
        <div className="panel">
          <div className="dr-label">{L('On shift now', 'En poste')}</div>
          <div className="clock-big tnum">{working.length + onBreak.length}<span className="muted"> / {employees.length}</span></div>
          <div className="ln"><span>{L('Working', 'Au travail')}</span><b>{working.length}</b></div>
          <div className="ln"><span>{L('On break', 'En pause')}</span><b>{onBreak.length}</b></div>
          <div className="ln"><span>{L('Labour cost right now', 'Coût actuel')}</span><b className="tnum">{fmt.money(costHr)}/h</b></div>
          <div className="ln"><span>{L('Hours worked today', 'Heures aujourd’hui')}</span><b className="tnum">{pf.hrs(todayHrs)}</b></div>
        </div>
        <div className="panel">
          <div className="dr-label">{L('Today’s activity', 'Activité du jour')}</div>
          <ul className="feed">
            {feed.slice(0, 8).map((f, i) => <li key={i}><Icon n={f.ic} /><span><b>{f.n.split(' ')[0]}</b> {f.a}</span><span className="muted tnum">{pf.time(f.t)}</span></li>)}
          </ul>
        </div>
      </aside>
      <PinModal empId={who} onClose={() => setWho(null)} />
    </div>
  );
}

function PinModal({ empId, onClose }) {
  const { L, P, employees, punches, setPunches, now, toast } = useMizo();
  const pf = usePayFmt();
  const [pin, setPin] = React.useState('');
  const [err, setErr] = React.useState(false);
  const [ok, setOk] = React.useState(false);
  React.useEffect(() => { setPin(''); setErr(false); setOk(false); }, [empId]);
  const e = employees.find((x) => x.id === empId);
  const today = P.days[P.TODAY];
  React.useEffect(() => {
    if (!e || pin.length < 4) return;
    if (pin === e.pin) setOk(true); else { setErr(true); setTimeout(() => { setPin(''); setErr(false); }, 650); }
  }, [pin]);
  React.useEffect(() => {
    if (!e || ok) return;
    const k = (ev) => { if (/^[0-9]$/.test(ev.key)) setPin((p) => (p.length < 4 ? p + ev.key : p)); if (ev.key === 'Backspace') setPin((p) => p.slice(0, -1)); };
    window.addEventListener('keydown', k); return () => window.removeEventListener('keydown', k);
  }, [empId, ok]);
  if (!e) return null;
  const st = empState(e, punches, today);
  const first = e.name.split(' ')[0];
  const act = (kind) => {
    const t = Math.round(now);
    if (kind === 'in') setPunches([...punches, { id: e.id + '-' + today + '-' + t, emp: e.id, date: today, in: t, out: null, brk: 0, open: true, status: 'pending', flag: null, log: [] }]);
    else setPunches(punches.map((p) => {
      if (p !== st.open) return p;
      if (kind === 'break') return { ...p, onBreak: t };
      if (kind === 'endbreak') return { ...p, brk: p.brk + (t - p.onBreak), onBreak: null };
      const brk = p.onBreak != null ? p.brk + (t - p.onBreak) : p.brk;
      return { ...p, out: t, open: false, onBreak: null, brk };
    }));
    const msg = { in: L(`${first} clocked in at ${pf.time(t)}`, `${first} : entrée à ${pf.time(t)}`), break: L(`${first} is on break`, `${first} est en pause`), endbreak: L(`Welcome back, ${first}`, `Bon retour, ${first}`), out: L(`${first} clocked out at ${pf.time(t)}`, `${first} : sortie à ${pf.time(t)}`) }[kind];
    toast(msg); onClose();
  };
  const keys = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '', '0', '⌫'];
  return (
    <Modal open={!!e} onClose={onClose} title={<span className="pin-title"><span className="emp-av">{initials(e.name)}</span>{e.name}</span>}>
      {!ok ? (
        <div className="pin">
          <div className="muted">{L('Enter your PIN', 'Entrez votre NIP')}</div>
          <div className={'pin-dots' + (err ? ' err' : '')}>{[0, 1, 2, 3].map((i) => <i key={i} className={i < pin.length ? 'on' : ''}></i>)}</div>
          <div className="pin-msg">{err ? <span className="txt-neg">{L('That PIN didn’t match. Try again.', 'NIP incorrect. Réessayez.')}</span> : <span className="muted sm">{L('Demo PIN', 'NIP démo')}: {e.pin}</span>}</div>
          <div className="keypad">
            {keys.map((k, i) => k === '' ? <span key={i}></span> : <button key={i} className="key" aria-label={k === '⌫' ? 'Delete' : k} onClick={() => setPin((p) => (k === '⌫' ? p.slice(0, -1) : p.length < 4 ? p + k : p))}>{k === '⌫' ? <Icon n="backspace" /> : k}</button>)}
          </div>
        </div>
      ) : (
        <div className="pin-actions">
          <div className="muted">{st.onBreak ? L(`On break since ${pf.time(st.open.onBreak)}`, `En pause depuis ${pf.time(st.open.onBreak)}`) : st.open ? L(`Working since ${pf.time(st.open.in)} · ${pf.hrs(P.worked(st.open, now))}`, `Au travail depuis ${pf.time(st.open.in)} · ${pf.hrs(P.worked(st.open, now))}`) : L(`Kaliméra, ${first}. It’s ${pf.time(now)}.`, `Kaliméra, ${first}. Il est ${pf.time(now)}.`)}</div>
          {!st.open ? <button className="btn btn-primary bigbtn" onClick={() => act('in')}><Icon n="sign-in" />{L('Clock in', 'Pointer l’entrée')}</button> : null}
          {st.open && !st.onBreak ? <><button className="btn btn-secondary bigbtn" onClick={() => act('break')}><Icon n="coffee" />{L('Start break', 'Commencer la pause')}</button><button className="btn btn-primary bigbtn" onClick={() => act('out')}><Icon n="sign-out" />{L('Clock out', 'Pointer la sortie')}</button></> : null}
          {st.onBreak ? <><button className="btn btn-primary bigbtn" onClick={() => act('endbreak')}><Icon n="play" />{L('End break', 'Terminer la pause')}</button><button className="btn btn-secondary bigbtn" onClick={() => act('out')}><Icon n="sign-out" />{L('Clock out', 'Pointer la sortie')}</button></> : null}
        </div>
      )}
    </Modal>
  );
}

function Team() {
  const { L, lang, fmt, employees } = useMizo();
  const [edit, setEdit] = React.useState(null);
  const yrs = (d) => Math.floor((new Date('2026-10-28') - new Date(d)) / 3.156e10);
  return (
    <>
      <div className="section-head"><div><h3>{employees.length} {L('people on payroll', 'personnes sur la paie')}</h3><p className="muted">{L('Owner draws are not included.', 'Les prélèvements de la propriétaire ne sont pas inclus.')}</p></div><button className="btn btn-primary" onClick={() => setEdit('new')}><Icon n="user-plus" />{L('Add employee', 'Ajouter un employé')}</button></div>
      <div className="panel panel-flush">
        <div className="table-scroll">
          <table className="table mtable">
            <thead><tr><th>{L('Name', 'Nom')}</th><th>{L('Role', 'Poste')}</th><th className="num">{L('Pay', 'Salaire')}</th><th className="hide-sm">{L('With us', 'Ancienneté')}</th><th className="hide-sm">{L('Phone', 'Téléphone')}</th><th></th></tr></thead>
            <tbody>
              {employees.map((e) => (
                <tr key={e.id} className="clickable" onClick={() => setEdit(e.id)}>
                  <td><div className="emp-cell"><span className="emp-av">{initials(e.name)}</span><span className="cell-main">{e.name}</span></div></td>
                  <td>{e.role[lang]}</td>
                  <td className="num tnum">{e.type === 'salary' ? fmt.money0(e.salary * 26) + L('/yr', '/an') : fmt.money(e.rate) + '/h'}</td>
                  <td className="hide-sm muted">{yrs(e.hired) < 1 ? L('< 1 year', '< 1 an') : yrs(e.hired) + L(' yrs', ' ans')}</td>
                  <td className="hide-sm tnum muted">{e.phone}</td>
                  <td className="num"><button className="btn btn-ghost">{L('Edit', 'Modifier')}</button></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
      <EmpModal id={edit} onClose={() => setEdit(null)} />
    </>
  );
}

function EmpModal({ id, onClose }) {
  const { L, employees, setEmployees, toast } = useMizo();
  const cur = employees.find((e) => e.id === id);
  const [f, setF] = React.useState({});
  React.useEffect(() => { if (id) setF(cur ? { name: cur.name, role: cur.role.en, rate: cur.type === 'salary' ? cur.salary * 26 : cur.rate, type: cur.type, pin: cur.pin, phone: cur.phone } : { name: '', role: '', rate: '', type: 'hourly', pin: '', phone: '' }); }, [id]);
  if (!id) return null;
  const pinOk = /^\d{4}$/.test(f.pin || ''), pinTaken = employees.some((e) => e.pin === f.pin && e.id !== id);
  const ok = (f.name || '').trim() && (f.role || '').trim() && Number(f.rate) > 0 && pinOk && !pinTaken;
  const save = () => {
    const patch = { name: f.name.trim(), role: { en: f.role, fr: cur && cur.role.en === f.role ? cur.role.fr : f.role }, type: f.type, rate: f.type === 'hourly' ? Number(f.rate) : 0, salary: f.type === 'salary' ? Number(f.rate) / 26 : 0, pin: f.pin, phone: f.phone };
    if (cur) setEmployees(employees.map((e) => (e.id === id ? { ...e, ...patch } : e)));
    else setEmployees([...employees, { id: 'e' + Date.now(), hired: '2026-10-28', sched: {}, ...patch }]);
    toast(cur ? L('Employee updated', 'Employé mis à jour') : L(`${patch.name} added to the team`, `${patch.name} ajouté à l’équipe`)); onClose();
  };
  return (
    <Modal open onClose={onClose} title={cur ? cur.name : L('Add employee', 'Ajouter un employé')} actions={<><button className="btn btn-secondary" onClick={onClose}>{L('Cancel', 'Annuler')}</button><button className="btn btn-primary" disabled={!ok} onClick={save}>{L('Save', 'Enregistrer')}</button></>}>
      <div className="form-grid">
        <div className="field span-2"><label>{L('Full name', 'Nom complet')}</label><input className="input" value={f.name || ''} onChange={(e) => setF({ ...f, name: e.target.value })} /></div>
        <div className="field"><label>{L('Role', 'Poste')}</label><input className="input" value={f.role || ''} placeholder={L('e.g. Line cook', 'ex. Cuisinier')} onChange={(e) => setF({ ...f, role: e.target.value })} /></div>
        <div className="field"><label>{L('Phone', 'Téléphone')}</label><input className="input" value={f.phone || ''} onChange={(e) => setF({ ...f, phone: e.target.value })} /></div>
        <div className="field"><label>{L('Paid by', 'Payé')}</label><Seg size="sm" value={f.type} onChange={(v) => setF({ ...f, type: v })} options={[['hourly', L('Hour', 'À l’heure')], ['salary', L('Salary', 'Salaire')]]} /></div>
        <div className="field"><label>{f.type === 'salary' ? L('Yearly salary (CAD)', 'Salaire annuel (CAD)') : L('Hourly rate (CAD)', 'Taux horaire (CAD)')}</label><input className="input" type="number" step="0.25" value={f.rate} onChange={(e) => setF({ ...f, rate: e.target.value })} /></div>
        <div className="field"><label>{L('Time clock PIN (4 digits)', 'NIP de pointage (4 chiffres)')}</label><input className="input" inputMode="numeric" maxLength="4" value={f.pin || ''} onChange={(e) => setF({ ...f, pin: e.target.value.replace(/\D/g, '') })} />{f.pin && !pinOk ? <div className="txt-warn sm">{L('Use exactly 4 digits.', 'Utilisez 4 chiffres.')}</div> : pinTaken ? <div className="txt-neg sm">{L('Another employee already uses this PIN.', 'Ce NIP est déjà utilisé.')}</div> : null}</div>
      </div>
    </Modal>
  );
}
Object.assign(window, { TimeClock, Team });
