/* Zamestnanci — zoznam + detail */

function Employees({ selectedId, goEmployee, goList, goExport, version }) {
  if (selectedId) return <EmployeeDetail eid={selectedId} goList={goList} goExport={goExport} />;
  return <EmployeeList goEmployee={goEmployee} />;
}

function EmployeeList({ goEmployee }) {
  const [q, setQ] = React.useState("");
  const [filter, setFilter] = React.useState("all");
  const today = TD.fmt(TD.TODAY);

  let list = TD.EMPLOYEES.filter(e =>
    (filter === "all" || e.pos === filter) &&
    e.name.toLowerCase().includes(q.toLowerCase())
  );

  return (
    <div>
      <div className="section-head">
        <div className="seg">
          <button className={filter === "all" ? "on" : ""} onClick={() => setFilter("all")}>Všetci ({TD.EMPLOYEES.length})</button>
          {Object.values(TD.POSITIONS).map(p => {
            const n = TD.EMPLOYEES.filter(e => e.pos === p.id).length;
            return <button key={p.id} className={filter === p.id ? "on" : ""} onClick={() => setFilter(p.id)}>{p.label} ({n})</button>;
          })}
        </div>
        <div className="search">
          <Icon.search width="16" height="16" />
          <input placeholder="Hľadať zamestnanca…" value={q} onChange={e => setQ(e.target.value)} />
        </div>
      </div>

      <div className="card" style={{ padding: "6px 8px 8px" }}>
        <table className="table">
          <thead><tr><th>Zamestnanec</th><th>Pozícia</th><th>Stav dnes</th><th style={{ textAlign: "right" }}>Tento mesiac</th><th style={{ textAlign: "right" }}>Hod. sadzba</th><th></th></tr></thead>
          <tbody>
            {list.map(e => {
              const rt = TD.records[e.id + "|" + today];
              const mh = TD.monthHours(e.id);
              return (
                <tr key={e.id} className="clickable" onClick={() => goEmployee(e.id)}>
                  <td><div className="cell-name"><Avatar emp={e} size={40} /><div><b>{e.name}</b><div className="faint" style={{ fontSize: 12.5, marginTop: 1 }}>{e.email}</div></div></div></td>
                  <td><PositionPill pos={e.pos} /></td>
                  <td>{rt ? <StatusBadge status={rt.status} /> : <span className="badge off"><span className="dot"></span>Voľno</span>}</td>
                  <td style={{ textAlign: "right" }} className="tnum"><b>{fmtH(mh)}</b></td>
                  <td style={{ textAlign: "right" }} className="tnum muted">{fmtEur(e.rate)}/h</td>
                  <td style={{ textAlign: "right", width: 30 }}><Icon.chevR width="17" height="17" style={{ color: "var(--ink-faint)" }} /></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function EmployeeDetail({ eid, goList, goExport }) {
  const e = TD.empById(eid);
  const recs = TD.recordsForEmployee(eid).slice().reverse();
  const s = TD.monthSummary(eid);
  const [view, setView] = React.useState("cal"); // cal | list

  return (
    <div>
      <button className="btn ghost sm" onClick={goList} style={{ marginBottom: 18 }}><Icon.back width="16" height="16" /> Späť na zoznam</button>

      <div className="card emp-hero">
        <Avatar emp={e} size={76} />
        <div className="emp-hero-main">
          <h2 style={{ fontSize: 26 }}>{e.name}</h2>
          <div style={{ display: "flex", alignItems: "center", gap: 16, marginTop: 7, flexWrap: "wrap" }}>
            <PositionPill pos={e.pos} />
            <span className="emp-meta"><Icon.phone width="14" height="14" />{e.phone}</span>
            <span className="emp-meta"><Icon.mail width="14" height="14" />{e.email}</span>
            <span className="emp-meta"><Icon.card width="14" height="14" />NFC {e.nfc}</span>
          </div>
          <div className="muted" style={{ fontSize: 12.5, marginTop: 8 }}>V družstve od {fmtDateLong(e.since)}</div>
        </div>
        <button className="btn orange" onClick={() => goExport(eid)}><Icon.pdf width="17" height="17" /> Export PDF</button>
      </div>

      <div className="stats stats-5" style={{ margin: "22px 0" }}>
        <div className="stat"><div className="k"><Icon.hours width="15" height="15" />Hodiny / {TD.MONTHS[TD.MONTH]}</div><div className="v tnum">{fmtH(s.worked).replace(" h", "")}<small> h</small></div><div className="meta">{Math.round(s.night)} h nočné</div></div>
        <div className="stat"><div className="k"><Icon.calendar width="15" height="15" />Odpracované dni</div><div className="v tnum">{s.daysWorked}</div><div className="meta">{s.late} meškaní</div></div>
        <div className="stat"><div className="k"><Icon.sun width="15" height="15" />Víkend / sviatok</div><div className="v tnum">{Math.round(s.sat + s.sun + s.holiday)}<small> h</small></div><div className="meta">So+Ne+sviatok</div></div>
        <div className="stat"><div className="k"><Icon.today width="15" height="15" />Dovolenka</div><div className="v tnum">{s.vac.left}<small> dní</small></div><div className="meta">z {s.vac.ent} · čerpané {s.vac.taken}</div></div>
        <div className="stat"><div className="k"><Icon.euro width="15" height="15" />Hrubá mzda (odhad)</div><div className="v tnum" style={{ color: "var(--sage-dark)" }}>{fmtEur(s.wage)}</div><div className="meta">{fmtEur(e.rate)}/h</div></div>
      </div>

      {s.absDays > 0 && (
        <div className="abs-summary">
          <span className="abs-summary-t">Neprítomnosť tento mesiac:</span>
          {["dovolenka", "pn", "ocr", "paragraf", "neplatene"].map(k => s.abs[k] ? <span key={k} className="abs-count big"><AbsChip type={k} />{s.abs[k]} {s.abs[k] === 1 ? "deň" : "dní"}</span> : null)}
        </div>
      )}

      <div className="card" style={{ padding: 0 }}>
        <div className="emp-cal-head">
          <h2 style={{ fontSize: 18 }}>Dochádzka — {TD.MONTHS[TD.MONTH]} {TD.YEAR}</h2>
          <div className="seg sm">
            <button className={view === "cal" ? "on" : ""} onClick={() => setView("cal")}><Icon.calendar width="14" height="14" /> Kalendár</button>
            <button className={view === "list" ? "on" : ""} onClick={() => setView("list")}><Icon.report width="14" height="14" /> Zoznam</button>
          </div>
        </div>
        {view === "cal" ? (
          <div style={{ padding: "8px 18px 20px" }}><MonthCalendar eid={eid} /></div>
        ) : (
          <table className="table">
            <thead><tr><th>Dátum</th><th>Zmena</th><th>Príchod</th><th>Odchod</th><th>Prestávka</th><th style={{ textAlign: "right" }}>Hodiny</th><th>Stav</th></tr></thead>
            <tbody>
              {recs.map(r => {
                const d = new Date(r.date);
                const isToday = r.date === TD.fmt(TD.TODAY);
                const ab = TD.isAbsence(r.status);
                return (
                  <tr key={r.date} style={isToday ? { background: "var(--orange-tint)" } : null}>
                    <td><b style={{ fontWeight: 600 }}>{TD.DOW[TD.dowOf(r.date)]} {d.getDate()}.{d.getMonth() + 1}.</b>{isToday && <span className="faint" style={{ fontSize: 11, marginLeft: 6 }}>dnes</span>}</td>
                    <td>{ab ? <span className="faint">—</span> : <ShiftTag shift={r.shift} />}</td>
                    <td className="tnum">{r.in || <span className="faint">—</span>}</td>
                    <td className="tnum">{r.out || (r.in ? <span className="muted">v práci</span> : <span className="faint">—</span>)}</td>
                    <td className="tnum muted">{r.breakMin ? r.breakMin + " min" : <span className="faint">—</span>}</td>
                    <td className="tnum" style={{ textAlign: "right" }}>{r.hours ? <b>{fmtH(r.hours)}</b> : <span className="faint">—</span>}</td>
                    <td><StatusBadge status={r.status} /></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { Employees });
