// hydor-page-team.jsx — Notification Centre (owner), Human Resources, Customer Success, Customer Finder.
// Depends on engine + ui + forms.

const fmtJOD0 = (n) => Hydor.fmtMoney0(n) + " JOD";
// metric-aware target / achievement formatting (Call Center = visits, others = money)
const isVisitMetric = (perfOrDept) => perfOrDept && perfOrDept.metric === "visits";
const fmtTargetVal = (n, metric) => metric === "visits" ? (Math.round(n) + " visit" + (Math.round(n) === 1 ? "" : "s")) : fmtJOD0(n);
const perfAchieved = (p) => p ? (p.metric === "visits" ? p.monthVisits : p.monthSales) : 0;
function usersById() { const m = {}; Hydor.getState().users.forEach((u) => (m[u.id] = u)); return m; }
function partyById(id) { return Hydor.getState().parties.find((p) => p.id === id); }
function prodById(id) { return Hydor.getState().products.find((p) => p.id === id); }
const TODAY = () => new Date().toISOString().slice(0, 10);

/* ===================================================================
   NOTIFICATION CENTRE  (owner only — gated in app shell)
   =================================================================== */
function NotificationsPage({ goToTx }) {
  const s = useHydor();
  const d = useDerive();
  const [tab, setTab] = React.useState("open");
  const list = s.notifications.filter((n) => tab === "all" ? true : tab === "open" ? !n.resolved : n.resolved);
  const flagged = s.transactions.filter((t) => !t.deleted && t.type === "sale" && t.flagged);

  return (
    <div className="content-narrow" style={{ maxWidth: 980 }}>
      <div className="stat-strip" style={{ gridTemplateColumns: "repeat(3,1fr)" }}>
        <div className="mini-stat" style={{ borderLeft: "3px solid var(--neg)" }}><div className="ms-label">Open notifications</div><div className="ms-value">{d.openNotifs}</div><div className="ms-sub">need your review</div></div>
        <div className="mini-stat" style={{ borderLeft: "3px solid var(--warn)" }}><div className="ms-label">Flagged sales</div><div className="ms-value">{d.flaggedSales}</div><div className="ms-sub">below the markup floor</div></div>
        <div className="mini-stat" style={{ borderLeft: "3px solid var(--accent)" }}><div className="ms-label">Pending leave</div><div className="ms-value">{d.pendingLeave}</div><div className="ms-sub">awaiting approval</div></div>
      </div>

      <div className="tabs">
        {[["open", "Open"], ["resolved", "Resolved"], ["all", "All"]].map(([k, l]) => (
          <button key={k} className={"tab" + (tab === k ? " on" : "")} onClick={() => setTab(k)}>{l}{k === "open" && d.openNotifs ? ` (${d.openNotifs})` : ""}</button>
        ))}
        <div className="grow" style={{ flex: 1 }} />
        {s.notifications.some((n) => !n.read) && <Btn sm variant="ghost" icon="check" onClick={() => Hydor.markAllNotifsRead()}>Mark all read</Btn>}
      </div>

      <div className="hx-panel" style={{ overflow: "hidden" }}>
        {list.length === 0 ? (
          <Empty icon="bell" title={tab === "open" ? "Nothing needs your attention" : "Nothing here"}>Sales below the markup floor, leave requests and other items that need the owner appear here.</Empty>
        ) : list.map((n) => {
          // every notification gets a destination the CURRENT user can actually reach
          const canCC = Hydor.canU(Hydor.currentUser(), "seeVisitQueue");
          const goHR = () => { window.__hydorGoHR && window.__hydorGoHR(); };
          const goTxn = () => { Hydor.markNotifRead(n.id); goToTx(n.txId); };
          let rowNav = null, actionLabel = null, actionFn = null;
          if (n.txId) { rowNav = goTxn; actionLabel = "Open transaction"; actionFn = goTxn; }
          else if (n.type === "late" || n.type === "attendance_exception") { rowNav = goHR; actionLabel = "Record action in HR"; actionFn = goHR; }
          else if (n.type === "leave") { rowNav = goHR; actionLabel = "Review in HR"; actionFn = goHR; }
          else if (n.type === "approval") { rowNav = () => { Hydor.markNotifRead(n.id); window.__hydorGoPage && window.__hydorGoPage("transactions"); }; actionLabel = "Review approval"; actionFn = rowNav; }
          else if ((n.type === "visit_end" || n.type === "appointment" || n.type === "appointment_override") && canCC) { rowNav = () => { Hydor.markNotifRead(n.id); window.__hydorGoPage && window.__hydorGoPage("callcenter"); }; actionLabel = "Open Call Center"; actionFn = rowNav; }
          return (
          <div key={n.id} onClick={rowNav ? () => { Hydor.markNotifRead(n.id); rowNav(); } : undefined}
            style={{ display: "flex", gap: 13, alignItems: "flex-start", padding: "15px 20px", borderBottom: "1px solid var(--border-2)", opacity: n.resolved ? 0.6 : 1, cursor: rowNav ? "pointer" : "default", background: !n.read ? "var(--accent-soft)" : undefined }}>
            <div style={{ width: 34, height: 34, borderRadius: 9, display: "grid", placeItems: "center", flex: "none", background: n.sev === "high" ? "#ff6b7d18" : n.sev === "med" ? "#ffc24b18" : "#ffffff0c", color: n.sev === "high" ? "var(--neg)" : n.sev === "med" ? "var(--warn)" : "var(--text-3)" }}>
              <Icon name={n.type === "belowfloor" ? "warn" : n.type === "leave" ? "calendar" : n.type === "late" || n.type === "attendance_exception" ? "clock" : n.type === "visit_end" ? "pin" : n.type === "appointment" || n.type === "appointment_override" ? "calendar" : n.type === "approval" ? "unlock" : "alert"} size={17} />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span style={{ fontSize: 13.5, fontWeight: 600 }}>{n.title}</span>
                {!n.read && <span style={{ width: 7, height: 7, borderRadius: "50%", background: "var(--accent)" }} />}
                <span className="hx-num" style={{ fontSize: 11, color: "var(--text-3)", marginLeft: "auto" }}>{Hydor.fmtDate(n.ts)}</span>
              </div>
              <div style={{ fontSize: 13, color: "var(--text-2)", lineHeight: 1.5, marginTop: 3 }}>{n.body}</div>
              <div style={{ display: "flex", gap: 8, marginTop: 9 }} onClick={(e) => e.stopPropagation()}>
                {actionLabel && <Btn sm icon={n.txId ? "ledger" : n.type === "approval" ? "unlock" : (n.type === "visit_end" || n.type === "appointment" || n.type === "appointment_override") ? "phone" : "briefcase"} onClick={actionFn}>{actionLabel}</Btn>}
                {!n.resolved
                  ? <Btn sm variant="ghost" icon="check" onClick={() => Hydor.resolveNotif(n.id, true)}>Mark resolved</Btn>
                  : <Btn sm variant="ghost" icon="refresh" onClick={() => Hydor.resolveNotif(n.id, false)}>Reopen</Btn>}
              </div>
            </div>
          </div>
          );
        })}
      </div>
    </div>
  );
}

/* ===================================================================
   HUMAN RESOURCES
   =================================================================== */
function HRPage({ onDrill }) {
  const s = useHydor();
  const d = useDerive();
  const push = useToast();
  const me = Hydor.currentUser();
  const role = useRole();
  const canMoney = Hydor.can(role, "seeMoney");
  const canHR = Hydor.can(role, "manageHR");
  const canApprove = Hydor.can(role, "approveLeave");
  const canTargets = Hydor.can(role, "setTargets");
  const [edit, setEdit] = React.useState(null);     // employee HR edit
  const [review, setReview] = React.useState(null);  // add review for user
  const [leaveForm, setLeaveForm] = React.useState(false);
  const byId = usersById();
  const team = s.users.filter((u) => u.active);
  const pending = s.leaveRequests.filter((l) => l.status === "pending");

  // STAFF SELF-VIEW (no manageHR) -------------------------------------------------
  if (!canHR) {
    const my = me ? d.userPerf[me.id] : null;
    const myLeave = s.leaveRequests.filter((l) => l.userId === (me && me.id));
    const myReviews = s.reviews.filter((r) => r.userId === (me && me.id));
    const acc = me ? Hydor.leaveAccrual(me) : { accrued: 0, available: 0, months: 0 };
    // team managers see their team roll-up
    const isLead = me && me.role === "teamlead";
    const team = isLead ? s.users.filter((u) => u.active && u.reportsTo === me.id) : [];
    const teamSales = team.reduce((a, u) => a + ((d.userPerf[u.id] && d.userPerf[u.id].monthSales) || 0), 0) + (my ? my.monthSales : 0);
    const teamAttain = me && me.teamTarget > 0 ? teamSales / me.teamTarget : null;
    return (
      <div className="content-narrow" style={{ maxWidth: 880 }}>
        <div className="hx-panel hx-panel-pad" style={{ marginBottom: 14 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
            <h3 className="hx-h2">My performance</h3>
            <Btn variant="primary" icon="calendar" onClick={() => setLeaveForm(true)}>Request leave</Btn>
          </div>
          {my && my.target > 0 ? (
            <>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5, color: "var(--text-2)", marginBottom: 8 }}>
                <span>Monthly {isVisitMetric(my) ? "visits" : "sales"} target</span>
                <span className="hx-num">{my.attainment != null ? (my.attainment * 100).toFixed(0) + "%" : "—"} — {fmtTargetVal(perfAchieved(my), my.metric)} of {fmtTargetVal(my.target, my.metric)}</span>
              </div>
              <div className="hx-perfbar"><div className="hx-perfbar-track"><div className={"hx-perfbar-fill " + ((my.attainment || 0) >= 1 ? "over" : "under")} style={{ width: Math.min(100, (my.attainment || 0) * 100) + "%" }} /></div>
                <div className={"hx-perfbar-val " + ((my.attainment || 0) >= 1 ? "over" : "under")}>{my.attainment != null ? (my.attainment * 100).toFixed(0) + "%" : "—"}</div></div>
            </>
          ) : <p className="hx-sub">No sales target set for you yet. Your manager assigns this.</p>}
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 14, marginTop: 18 }}>
            {my && isVisitMetric(my)
              ? <div className="mini-stat"><div className="ms-label">Visits this month</div><div className="ms-value">{my ? my.monthVisits : 0}</div><div className="ms-sub">customer selected</div></div>
              : <div className="mini-stat"><div className="ms-label">Deals closed</div><div className="ms-value">{my ? my.txns : 0}</div><div className="ms-sub">all time</div></div>}
            <div className="mini-stat"><div className="ms-label">Annual leave</div><div className="ms-value">{acc.available}</div><div className="ms-sub">days available · {acc.accrued} accrued</div></div>
            <div className="mini-stat"><div className="ms-label">Department</div><div className="ms-value" style={{ fontSize: 16, fontFamily: "var(--font)" }}>{me ? me.department : "—"}</div></div>
          </div>
        </div>

        <div className="hx-panel hx-panel-pad" style={{ marginBottom: 14 }}>
          <h3 className="hx-h2" style={{ marginBottom: 12 }}>My leave requests</h3>
          {myLeave.length === 0 ? <p className="hx-sub">No requests yet.</p> : (
            <table className="hx-table"><thead><tr><th>Type</th><th>Dates</th><th className="r">Days</th><th>Status</th></tr></thead>
              <tbody>{myLeave.map((l) => (
                <tr key={l.id}><td>{Hydor.cap(l.kind)}</td><td className="num" style={{ color: "var(--text-2)" }}>{Hydor.fmtDate(l.fromDate)} – {Hydor.fmtDate(l.toDate)}</td><td className="r num">{l.days}</td>
                  <td><Badge color={l.status === "approved" ? "green" : l.status === "rejected" ? "red" : "amber"} dot>{l.status}</Badge></td></tr>
              ))}</tbody></table>
          )}
        </div>

        {isLead && (
          <div className="hx-panel hx-panel-pad" style={{ marginBottom: 14 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
              <h3 className="hx-h2">My team ({team.length})</h3>
              <span className="hx-sub">Team sales this month: <b className="hx-num" style={{ color: "var(--text)" }}>{fmtJOD0(teamSales)}</b></span>
            </div>
            {me.teamTarget > 0 && (
              <div style={{ marginBottom: 14 }}>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5, color: "var(--text-2)", marginBottom: 6 }}><span>Team target attainment</span><span className="hx-num">{teamAttain != null ? (teamAttain * 100).toFixed(0) + "%" : "—"} of {fmtJOD0(me.teamTarget)}</span></div>
                <div className="hx-perfbar"><div className="hx-perfbar-track"><div className={"hx-perfbar-fill " + ((teamAttain || 0) >= 1 ? "over" : "under")} style={{ width: Math.min(100, (teamAttain || 0) * 100) + "%" }} /></div><div className={"hx-perfbar-val " + ((teamAttain || 0) >= 1 ? "over" : "under")}>{teamAttain != null ? (teamAttain * 100).toFixed(0) + "%" : "—"}</div></div>
              </div>
            )}
            {team.length === 0 ? <p className="hx-sub">No team members assigned yet. The founder assigns salespeople to you in Settings → Accounts.</p> : (
              <table className="hx-table"><thead><tr><th>Member</th><th style={{ width: 200 }}>Target attainment</th><th className="r">Sales (this month)</th></tr></thead>
                <tbody>{team.map((u) => { const p = d.userPerf[u.id] || {}; const at = p.attainment; return (
                  <tr key={u.id}>
                    <td><span className="hx-emp" style={{ gap: 10 }}><span className="hx-emp-badge">{u.name.slice(0, 1)}</span><span style={{ fontWeight: 500 }}>{u.name}</span></span></td>
                    <td>{u.monthlyTarget > 0 ? (<div className="hx-perfbar"><div className="hx-perfbar-track"><div className={"hx-perfbar-fill " + ((at || 0) >= 1 ? "over" : "under")} style={{ width: Math.min(100, (at || 0) * 100) + "%" }} /></div><div className={"hx-perfbar-val " + ((at || 0) >= 1 ? "over" : "under")}>{at != null ? (at * 100).toFixed(0) + "%" : "—"}</div></div>) : <span style={{ color: "var(--text-3)", fontSize: 12 }}>no target</span>}</td>
                    <td className="r num">{isVisitMetric(p) ? ((p.monthVisits || 0) + " visit" + ((p.monthVisits || 0) === 1 ? "" : "s")) : fmtJOD0(p.monthSales || 0)}</td>
                  </tr>
                ); })}</tbody></table>
            )}
          </div>
        )}

        {myReviews.length > 0 && (
          <div className="hx-panel hx-panel-pad">
            <h3 className="hx-h2" style={{ marginBottom: 12 }}>My reviews</h3>
            {myReviews.map((r) => (
              <div key={r.id} style={{ padding: "10px 0", borderBottom: "1px solid var(--border-2)" }}>
                <div style={{ display: "flex", justifyContent: "space-between" }}><b style={{ fontSize: 13 }}>{r.period}</b><span className="hx-num" style={{ color: "var(--accent-2)" }}>★ {r.score.toFixed(1)}/5</span></div>
                {r.strengths && <div style={{ fontSize: 12.5, color: "var(--text-2)", marginTop: 4 }}><b>Strengths:</b> {r.strengths}</div>}
                {r.improve && <div style={{ fontSize: 12.5, color: "var(--text-2)", marginTop: 2 }}><b>Focus:</b> {r.improve}</div>}
              </div>
            ))}
          </div>
        )}
        {leaveForm && <LeaveForm userId={me && me.id} onClose={() => setLeaveForm(false)} />}
      </div>
    );
  }

  // MANAGER+ VIEW -----------------------------------------------------------------
  return (
    <div>
      {pending.length > 0 && canApprove && (
        <div className="hx-panel hx-panel-pad" style={{ marginBottom: 14, border: "1px solid var(--warn)" }}>
          <h3 className="hx-h2" style={{ marginBottom: 12, display: "flex", alignItems: "center", gap: 8 }}><Icon name="calendar" size={16} style={{ color: "var(--warn)" }} />Leave awaiting approval ({pending.length})</h3>
          {pending.map((l) => { const u = byId[l.userId]; return (
            <div key={l.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 0", borderBottom: "1px solid var(--border-2)" }}>
              <span className="hx-emp-badge">{u ? u.name.slice(0, 1) : "?"}</span>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13.5, fontWeight: 500 }}>{u ? u.name : "—"} · {Hydor.cap(l.kind)} leave · {l.days} day{l.days !== 1 ? "s" : ""}</div>
                <div style={{ fontSize: 12, color: "var(--text-3)" }}>{Hydor.fmtDate(l.fromDate)} – {Hydor.fmtDate(l.toDate)}{l.reason ? " · " + l.reason : ""}</div>
              </div>
              <Btn sm variant="primary" icon="check" onClick={() => { Hydor.decideLeave(l.id, true, me && me.id); push("Leave approved."); }}>Approve</Btn>
              <Btn sm variant="ghost" icon="x" onClick={() => { Hydor.decideLeave(l.id, false, me && me.id); push("Leave rejected."); }}>Reject</Btn>
            </div>
          ); })}
        </div>
      )}

      <AttendanceToday s={s} byId={byId} team={team} push={push} />

      <div className="hx-panel" style={{ overflow: "hidden", marginBottom: 14 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "16px 20px", borderBottom: "1px solid var(--border)" }}>
          <h3 className="hx-h2">Team · {team.length} people</h3>
          {canMoney && <span className="hx-sub">Payroll/mo: <b className="hx-num" style={{ color: "var(--text)" }}>{fmtJOD0(team.reduce((a, u) => a + (u.salary || 0), 0))}</b></span>}
        </div>
        <table className="hx-table">
          <thead><tr><th>Employee</th><th>Department</th><th>Role</th><th style={{ width: 200 }}>Target attainment (this month)</th><th className="r">Achieved</th><th className="r">Leave</th>{canMoney && <th className="r">Salary</th>}<th></th></tr></thead>
          <tbody>
            {team.map((u) => { const p = d.userPerf[u.id]; const att = p && p.attainment; return (
              <tr key={u.id}>
                <td><span className="hx-emp" style={{ gap: 10 }}><span className="hx-emp-badge">{u.name.slice(0, 1)}</span><span><span style={{ fontWeight: 500 }}>{u.name}</span>{u.code && <span className="hx-code" style={{ marginLeft: 7 }}>{u.code}</span>}</span></span></td>
                <td style={{ color: "var(--text-2)", fontSize: 12.5 }}>{u.department}</td>
                <td><Badge color={u.role === "owner" ? "purple" : u.role === "cofounder" ? "blue" : u.role === "manager" ? "blue" : u.role === "accountant" ? "amber" : "green"}>{Hydor.ROLE_INFO[u.role].short}</Badge></td>
                <td>{u.monthlyTarget > 0 ? (
                  <div className="hx-perfbar"><div className="hx-perfbar-track"><div className={"hx-perfbar-fill " + ((att || 0) >= 1 ? "over" : "under")} style={{ width: Math.min(100, (att || 0) * 100) + "%" }} /></div>
                    <div className={"hx-perfbar-val " + ((att || 0) >= 1 ? "over" : "under")}>{att != null ? (att * 100).toFixed(0) + "%" : "—"}</div></div>
                ) : <span style={{ color: "var(--text-3)", fontSize: 12 }}>no target</span>}</td>
                <td className="r num" style={{ color: "var(--text-2)", whiteSpace: "nowrap" }}>{p && isVisitMetric(p) ? (p.monthVisits + " visit" + (p.monthVisits === 1 ? "" : "s")) : (canMoney ? Hydor.fmtMoney0(p ? p.monthSales : 0) : "—")}</td>
                <td className="r num" style={{ color: "var(--text-2)" }}>{Hydor.leaveAccrual(u).available}d</td>
                {canMoney && <td className="r num">{u.salary > 0 ? Hydor.fmtMoney0(u.salary) : "—"}</td>}
                <td className="r no-print">
                  <div style={{ display: "flex", gap: 2, justifyContent: "flex-end" }}>
                    <Btn variant="ghost" sm icon="award" title="Add review" onClick={() => setReview(u)} />
                    {canTargets && <Btn variant="ghost" sm icon="edit" title="Edit targets / salary" onClick={() => setEdit(u)} />}
                  </div>
                </td>
              </tr>
            ); })}
          </tbody>
        </table>
      </div>

      {/* recent reviews */}
      {s.reviews.length > 0 && (
        <div className="hx-panel hx-panel-pad">
          <h3 className="hx-h2" style={{ marginBottom: 12 }}>Recent performance reviews</h3>
          {s.reviews.slice(0, 6).map((r) => { const u = byId[r.userId]; return (
            <div key={r.id} style={{ display: "flex", gap: 12, padding: "10px 0", borderBottom: "1px solid var(--border-2)" }}>
              <span className="hx-emp-badge">{u ? u.name.slice(0, 1) : "?"}</span>
              <div style={{ flex: 1 }}>
                <div style={{ display: "flex", justifyContent: "space-between" }}><b style={{ fontSize: 13 }}>{u ? u.name : "—"} · {r.period}</b><span className="hx-num" style={{ color: "var(--accent-2)" }}>★ {r.score.toFixed(1)}</span></div>
                {r.strengths && <div style={{ fontSize: 12.5, color: "var(--text-2)", marginTop: 3 }}>{r.strengths}</div>}
              </div>
            </div>
          ); })}
        </div>
      )}

      {edit && <EmployeeHRForm user={edit} onClose={() => setEdit(null)} />}
      {review && <ReviewForm user={review} byId={me} onClose={() => setReview(null)} />}
    </div>
  );
}

/* ===== Attendance today (manager HR summary) ===== */
const LATE_TIER = {
  ok: { label: "On time", color: "var(--pos)", badge: "green" },
  minor: { label: "Late", color: "var(--warn)", badge: "amber" },
  deduction: { label: "Late · deduction", color: "var(--neg)", badge: "red" },
  investigation: { label: "Late · investigation", color: "var(--neg)", badge: "red" },
};
const ACT_OPTS = [
  { key: "verbal", label: "Verbal warning" },
  { key: "written", label: "Written reprimand" },
  { key: "deduction", label: "Salary deduction" },
  { key: "investigation", label: "Refer to investigation" },
  { key: "excused", label: "Excused (prior notice)" },
];
function AttendanceToday({ s, byId, team, push }) {
  const [act, setAct] = React.useState(null);   // entry to act on
  const [miss, setMiss] = React.useState(null); // missing-clock entry to act on
  const today = new Date().toISOString().slice(0, 10);
  const cfg = s.meta.attendance || { workStart: "09:00" };
  const todays = s.attendance.filter((a) => (a.ts || "").slice(0, 10) === today);
  // first check-in per user today
  const checkinByUser = {};
  todays.filter((a) => a.type === "checkin").forEach((a) => { if (!checkinByUser[a.userId] || a.ts < checkinByUser[a.userId].ts) checkinByUser[a.userId] = a; });
  const present = Object.keys(checkinByUser).length;
  const lateEntries = Object.values(checkinByUser).filter((a) => a.lateTier && a.lateTier !== "ok").sort((a, b) => b.lateBy - a.lateBy);
  const notIn = team.filter((u) => !checkinByUser[u.id]);
  const needAction = lateEntries.filter((a) => !a.action);
  const missing = Hydor.missingClockToday();

  return (
    <div className="hx-panel hx-panel-pad" style={{ marginBottom: 14 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14, flexWrap: "wrap", gap: 10 }}>
        <h3 className="hx-h2" style={{ display: "flex", alignItems: "center", gap: 8 }}><Icon name="clock" size={16} style={{ color: "var(--accent-2)" }} />Attendance today</h3>
        <span className="hx-sub">Shift starts <b className="hx-num" style={{ color: "var(--text)" }}>{cfg.workStart}</b> · {cfg.graceMin}-min grace</span>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 12, marginBottom: needAction.length ? 18 : 4 }}>
        <div className="mini-stat" style={{ borderLeft: "3px solid var(--pos)" }}><div className="ms-label">Checked in</div><div className="ms-value">{present}<span style={{ fontSize: 14, color: "var(--text-3)" }}> / {team.length}</span></div></div>
        <div className="mini-stat" style={{ borderLeft: "3px solid var(--warn)" }}><div className="ms-label">Late today</div><div className="ms-value">{lateEntries.length}</div></div>
        <div className="mini-stat" style={{ borderLeft: "3px solid var(--text-3)" }}><div className="ms-label">Not in yet</div><div className="ms-value">{notIn.length}</div></div>
      </div>

      {needAction.length > 0 && (
        <div style={{ border: "1px solid #ff6b7d33", background: "#ff6b7d0d", borderRadius: 12, padding: "12px 14px", marginBottom: 16 }}>
          <div style={{ fontSize: 12, fontWeight: 600, color: "var(--neg)", marginBottom: 10, letterSpacing: ".03em" }}>NEEDS ACTION · {needAction.length}</div>
          {needAction.map((a) => { const u = byId[a.userId]; const tier = LATE_TIER[a.lateTier]; return (
            <div key={a.id} style={{ display: "flex", alignItems: "center", gap: 11, padding: "8px 0", borderBottom: "1px solid var(--border-2)" }}>
              {a.photo ? <img src={a.photo} alt="" style={{ width: 38, height: 38, borderRadius: 9, objectFit: "cover", flex: "none" }} /> : <span className="hx-emp-badge" style={{ flex: "none" }}>{u ? u.name.slice(0, 1) : "?"}</span>}
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{u ? u.name : a.employeeCode} · <span style={{ color: tier.color }}>{a.lateBy} min late</span></div>
                <div style={{ fontSize: 11.5, color: "var(--text-3)" }}>{Hydor.fmtDate ? "" : ""}Checked in {new Date(a.ts).toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" })} · {a.lateTier === "investigation" ? "over 1h — investigation" : a.lateTier === "deduction" ? "over 30 min — deduction" : "verbal/written/deduction"}</div>
              </div>
              <Btn sm variant="primary" onClick={() => setAct(a)}>Record action</Btn>
            </div>
          ); })}
        </div>
      )}

      {missing.length > 0 && (
        <div style={{ border: "1px solid #5fd0ff44", background: "#5fd0ff0d", borderRadius: 12, padding: "12px 14px", marginBottom: 16 }}>
          <div style={{ fontSize: 12, fontWeight: 600, color: "var(--accent-2)", marginBottom: 10, letterSpacing: ".03em" }}>MISSING CLOCK-OUT · {missing.length}</div>
          {missing.map((m) => { const ci = checkinByUser[m.user.id]; return (
            <div key={m.user.id} style={{ display: "flex", alignItems: "center", gap: 11, padding: "8px 0", borderBottom: "1px solid var(--border-2)" }}>
              <span className="hx-emp-badge" style={{ flex: "none" }}>{m.user.name.slice(0, 1)}</span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{m.user.name}</div>
                <div style={{ fontSize: 11.5, color: "var(--text-3)" }}>Checked in{ci ? " " + new Date(ci.ts).toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" }) : ""} · never clocked out</div>
              </div>
              {ci && (ci.action
                ? <Badge color="green" dot>{ci.action.type}</Badge>
                : <Btn sm variant="primary" onClick={() => setMiss(ci)}>Record action</Btn>)}
            </div>
          ); })}
        </div>
      )}

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
        {team.map((u) => {
          const a = checkinByUser[u.id];
          const tier = a ? LATE_TIER[a.lateTier] : null;
          return (
            <div key={u.id} style={{ display: "flex", alignItems: "center", gap: 10, padding: "9px 12px", borderRadius: 10, background: "var(--bg-2)", border: "1px solid var(--border)" }}>
              <span style={{ width: 8, height: 8, borderRadius: "50%", flex: "none", background: a ? tier.color : "var(--text-3)" }}></span>
              <span style={{ fontSize: 12.5, fontWeight: 500, flex: 1, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{u.name}</span>
              {a ? (
                <span className="hx-num" style={{ fontSize: 12, color: tier.color }}>{new Date(a.ts).toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" })}{a.lateBy > 0 ? " · +" + a.lateBy + "m" : ""}</span>
              ) : <span style={{ fontSize: 11.5, color: "var(--text-3)" }}>not in</span>}
              {a && a.action && <Icon name="check" size={13} style={{ color: "var(--pos)" }} title={"Action: " + a.action.type} />}
            </div>
          );
        })}
      </div>

      {act && <LateActionForm entry={act} user={byId[act.userId]} onClose={() => setAct(null)} push={push} />}
      {miss && <MissingClockForm entry={miss} user={byId[miss.userId]} onClose={() => setMiss(null)} push={push} />}
    </div>
  );
}

function LateActionForm({ entry, user, onClose, push }) {
  const suggested = entry.lateTier === "investigation" ? "investigation" : entry.lateTier === "deduction" ? "deduction" : "verbal";
  const [type, setType] = React.useState(suggested);
  const [amount, setAmount] = React.useState("");
  const [note, setNote] = React.useState("");
  const save = () => {
    if (type === "deduction" && Hydor.num(amount, 0) <= 0) return push("Enter the deduction amount.", "err");
    Hydor.setAttendanceAction(entry.id, { type, amount, note });
    push("Action recorded.");
    onClose();
  };
  return (
    <Modal title={"Late arrival · " + (user ? user.name : entry.employeeCode)} onClose={onClose} foot={<>
      <Btn variant="ghost" onClick={onClose}>Cancel</Btn>
      <Btn variant="primary" icon="check" onClick={save}>Record action</Btn>
    </>}>
      <div style={{ display: "flex", gap: 12, alignItems: "center", marginBottom: 16, padding: "12px 14px", background: "var(--bg-2)", borderRadius: 12, border: "1px solid var(--border)" }}>
        {entry.photo ? <img src={entry.photo} alt="" style={{ width: 52, height: 52, borderRadius: 10, objectFit: "cover" }} /> : <span className="hx-emp-badge" style={{ width: 40, height: 40 }}>{user ? user.name.slice(0, 1) : "?"}</span>}
        <div style={{ fontSize: 12.5, color: "var(--text-2)", lineHeight: 1.6 }}>
          Checked in <b className="hx-num" style={{ color: "var(--text)" }}>{new Date(entry.ts).toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" })}</b> · <b style={{ color: "var(--neg)" }}>{entry.lateBy} min late</b><br />
          {entry.lateTier === "investigation" ? "Over 1 hour — policy refers this to the investigation committee unless prior notice was given." : entry.lateTier === "deduction" ? "Over 30 minutes — a salary deduction applies." : "Over 10 minutes — choose a corrective action."}
        </div>
      </div>
      <div className="form-grid">
        <Field label="Action" span2>
          <select className="sel" value={type} onChange={(e) => setType(e.target.value)}>
            {ACT_OPTS.map((o) => <option key={o.key} value={o.key}>{o.label}</option>)}
          </select>
        </Field>
        {type === "deduction" && (
          <Field label="Deduction amount" span2 hint="Set by the founder or manager">
            <Affix affix="JOD"><input className="inp num" type="number" value={amount} onChange={(e) => setAmount(e.target.value)} style={{ paddingRight: 44 }} autoFocus /></Affix>
          </Field>
        )}
        <Field label="Note" span2><input className="inp" value={note} onChange={(e) => setNote(e.target.value)} placeholder="Optional — reason / context" /></Field>
      </div>
    </Modal>
  );
}

function MissingClockForm({ entry, user, onClose, push }) {
  const [type, setType] = React.useState("verbal");
  const [note, setNote] = React.useState("");
  const opts = [
    { key: "verbal", label: "Verbal warning" },
    { key: "written", label: "Written warning" },
    { key: "overlook", label: "Overlook — record a full day's work" },
  ];
  const save = () => {
    Hydor.setAttendanceAction(entry.id, { type, note, fullDay: type === "overlook" });
    push(type === "overlook" ? "Recorded a full working day." : "Action recorded.");
    onClose();
  };
  return (
    <Modal title={"Missing clock-out · " + (user ? user.name : entry.employeeCode)} onClose={onClose} foot={<>
      <Btn variant="ghost" onClick={onClose}>Cancel</Btn>
      <Btn variant="primary" icon="check" onClick={save}>Record</Btn>
    </>}>
      <p className="hx-sub" style={{ marginBottom: 14 }}>{user ? user.name : "This employee"} checked in but never clocked out today. The founder, manager and HR are notified. Choose how to handle it.</p>
      <div className="form-grid">
        <Field label="Action" span2>
          <select className="sel" value={type} onChange={(e) => setType(e.target.value)}>
            {opts.map((o) => <option key={o.key} value={o.key}>{o.label}</option>)}
          </select>
        </Field>
        <Field label="Note" span2><input className="inp" value={note} onChange={(e) => setNote(e.target.value)} placeholder="Optional context" /></Field>
      </div>
    </Modal>
  );
}

function LeaveForm({ userId, onClose }) {
  const push = useToast();
  const [f, setF] = React.useState({ kind: "sick", fromDate: TODAY(), toDate: TODAY(), reason: "" });
  const set = (k, v) => setF((p) => ({ ...p, [k]: v }));
  const days = f.fromDate && f.toDate ? Math.max(1, Math.round((new Date(f.toDate) - new Date(f.fromDate)) / 86400000) + 1) : 1;
  const save = () => { Hydor.requestLeave({ ...f, userId, days }); push("Leave request submitted."); onClose(); };
  return (
    <Modal title="Request leave" onClose={onClose} foot={<><Btn variant="ghost" onClick={onClose}>Cancel</Btn><Btn variant="primary" icon="check" onClick={save}>Submit request</Btn></>}>
      <div className="form-grid">
        <Field label="Leave type" span2>
          <div className="hx-seg" style={{ width: "100%", display: "flex" }}>
            {["sick", "annual", "unpaid"].map((k) => <button key={k} className={f.kind === k ? "on" : ""} style={{ flex: 1 }} onClick={() => set("kind", k)}>{Hydor.cap(k)}</button>)}
          </div>
        </Field>
        <Field label="From"><input className="inp" type="date" value={f.fromDate} onChange={(e) => set("fromDate", e.target.value)} /></Field>
        <Field label="To"><input className="inp" type="date" value={f.toDate} onChange={(e) => set("toDate", e.target.value)} /></Field>
        <Field label="Reason" span2 hint={`${days} day${days !== 1 ? "s" : ""} requested`}><input className="inp" value={f.reason} onChange={(e) => set("reason", e.target.value)} placeholder="Optional note for your manager" /></Field>
      </div>
    </Modal>
  );
}

function EmployeeHRForm({ user, onClose }) {
  const push = useToast();
  const depts = ["Management", "Sales", "Customer Success", "Call Center", "Installation & Technical", "Finance", "Operations"];
  const [f, setF] = React.useState({ department: user.department, monthlyTarget: user.monthlyTarget, salary: user.salary, hireDate: user.hireDate || "", leaveBalance: user.leaveBalance });
  const set = (k, v) => setF((p) => ({ ...p, [k]: v }));
  const canMoney = Hydor.can(useRole(), "seeMoney");
  const save = () => { try { Hydor.updateUser(user.id, f); push("Saved. Salary syncs to the recurring cost registry."); onClose(); } catch (e) { push(e.message, "err"); } };
  return (
    <Modal title={"Targets & HR · " + user.name} onClose={onClose} foot={<><Btn variant="ghost" onClick={onClose}>Cancel</Btn><Btn variant="primary" icon="check" onClick={save}>Save</Btn></>}>
      <div className="form-grid">
        <Field label="Department"><select className="sel" value={f.department} onChange={(e) => set("department", e.target.value)}>{depts.map((dd) => <option key={dd}>{dd}</option>)}</select></Field>
        <Field label="Hire date"><input className="inp" type="date" value={f.hireDate} onChange={(e) => set("hireDate", e.target.value)} /></Field>
        <Field label={f.department === "Call Center" ? "Monthly visits target" : "Monthly sales target"} hint={f.department === "Call Center" ? "Completed visits / month (customer selected)" : "What this person should achieve / month"}>
          {f.department === "Call Center"
            ? <Affix affix="visits"><input className="inp num" type="number" value={f.monthlyTarget} onChange={(e) => set("monthlyTarget", e.target.value)} style={{ paddingRight: 52 }} /></Affix>
            : <Affix affix="JOD"><input className="inp num" type="number" value={f.monthlyTarget} onChange={(e) => set("monthlyTarget", e.target.value)} style={{ paddingRight: 44 }} /></Affix>}
        </Field>
        <Field label="Leave balance" hint="Days remaining this year"><input className="inp num" type="number" value={f.leaveBalance} onChange={(e) => set("leaveBalance", e.target.value)} /></Field>
        {canMoney && <Field label="Monthly salary" span2 hint="Auto-posts to Company Costs under Salaries each month"><Affix affix="JOD"><input className="inp num" type="number" value={f.salary} onChange={(e) => set("salary", e.target.value)} style={{ paddingRight: 44 }} /></Affix></Field>}
      </div>
    </Modal>
  );
}

function ReviewForm({ user, byId, onClose }) {
  const push = useToast();
  const [f, setF] = React.useState({ period: new Date().getFullYear() + " " + (new Date().getMonth() < 6 ? "H1" : "H2"), score: 4, strengths: "", improve: "" });
  const set = (k, v) => setF((p) => ({ ...p, [k]: v }));
  const save = () => { Hydor.addReview({ ...f, userId: user.id, by: byId && byId.id }); push("Review recorded."); onClose(); };
  return (
    <Modal title={"Review · " + user.name} onClose={onClose} foot={<><Btn variant="ghost" onClick={onClose}>Cancel</Btn><Btn variant="primary" icon="check" onClick={save}>Save review</Btn></>}>
      <div className="form-grid">
        <Field label="Period"><input className="inp" value={f.period} onChange={(e) => set("period", e.target.value)} /></Field>
        <Field label="Score (1–5)"><input className="inp num" type="number" min="1" max="5" step="0.5" value={f.score} onChange={(e) => set("score", e.target.value)} /></Field>
        <Field label="Strengths" span2><input className="inp" value={f.strengths} onChange={(e) => set("strengths", e.target.value)} placeholder="What they did well" /></Field>
        <Field label="Focus areas" span2><input className="inp" value={f.improve} onChange={(e) => set("improve", e.target.value)} placeholder="Where to improve" /></Field>
      </div>
    </Modal>
  );
}

/* ===================================================================
   CUSTOMER SUCCESS  (follow-ups, KPIs, incentives)
   =================================================================== */
const FU_KINDS = { service: ["Service check", "heart"], reorder: ["Supplier reorder", "box"], installment: ["Installment due", "money"], warranty: ["Warranty", "award"], quote: ["Quote follow-up", "ledger"], call: ["Call back", "phone"] };

function FollowupsPage() {
  const s = useHydor();
  const d = useDerive();
  const push = useToast();
  const me = Hydor.currentUser();
  const role = useRole();
  const canMoney = Hydor.can(role, "seeMoney");
  const canAssign = Hydor.can(role, "assignFollowups");
  const canTargets = Hydor.can(role, "setTargets");
  const byId = usersById();
  const [kindF, setKindF] = React.useState("all");
  const [mineOnly, setMineOnly] = React.useState(!canAssign);
  const [add, setAdd] = React.useState(false);
  const [complete, setComplete] = React.useState(null);
  const [rule, setRule] = React.useState(false);

  const today = TODAY();
  let rows = s.followups.filter((f) => f.status !== "done");
  if (kindF !== "all") rows = rows.filter((f) => f.kind === kindF);
  if (mineOnly && me) rows = rows.filter((f) => f.assignedTo === me.id);
  rows = rows.sort((a, b) => (a.dueDate < b.dueDate ? -1 : 1));

  // CS leaderboard (completed + converted this period)
  const csReps = s.users.filter((u) => u.active && u.department === "Customer Success");
  const inc = s.meta.csIncentive || { mode: "percent", value: 3 };
  const repStats = csReps.map((u) => {
    const done = s.followups.filter((f) => f.assignedTo === u.id && f.status === "done");
    const secured = done.filter((f) => f.converted);
    const securedVal = secured.reduce((a, f) => a + (f.saleValue || 0), 0);
    const incentive = inc.mode === "percent" ? securedVal * (inc.value / 100) : secured.length * inc.value;
    return { u, done: done.length, secured: secured.length, securedVal, incentive, conv: done.length ? secured.length / done.length : 0 };
  }).sort((a, b) => b.secured - a.secured);

  return (
    <div>
      <div className="stat-strip" style={{ gridTemplateColumns: "repeat(4,1fr)" }}>
        <div className="mini-stat" style={{ borderLeft: "3px solid var(--neg)" }}><div className="ms-label">Overdue</div><div className="ms-value">{d.followupBuckets.overdue}</div><div className="ms-sub">past due date</div></div>
        <div className="mini-stat" style={{ borderLeft: "3px solid var(--warn)" }}><div className="ms-label">Due today</div><div className="ms-value">{d.followupBuckets.today}</div></div>
        <div className="mini-stat" style={{ borderLeft: "3px solid var(--accent)" }}><div className="ms-label">Upcoming</div><div className="ms-value">{d.followupBuckets.upcoming}</div></div>
        <div className="mini-stat" style={{ borderLeft: "3px solid var(--pos)" }}><div className="ms-label">Completed</div><div className="ms-value">{d.followupBuckets.done}</div></div>
      </div>

      <div className="toolbar">
        <select className="sel" style={{ width: 170 }} value={kindF} onChange={(e) => setKindF(e.target.value)}>
          <option value="all">All types</option>
          {Object.entries(FU_KINDS).map(([k, v]) => <option key={k} value={k}>{v[0]}</option>)}
        </select>
        {canAssign && <label style={{ display: "flex", alignItems: "center", gap: 7, fontSize: 12.5, color: "var(--text-2)", cursor: "pointer" }}><input type="checkbox" checked={mineOnly} onChange={(e) => setMineOnly(e.target.checked)} />Only mine</label>}
        <div className="grow" />
        {canAssign && <Btn variant="primary" icon="plus" onClick={() => setAdd(true)}>New follow-up</Btn>}
      </div>

      <div className="hx-panel" style={{ overflow: "hidden", marginBottom: 16 }}>
        {rows.length === 0 ? (
          <Empty icon="phone" title="No open follow-ups">Service checks, supplier reorders, installment reminders, warranty and quote follow-ups appear here.</Empty>
        ) : (
          <table className="hx-table">
            <thead><tr><th>Type</th><th>Customer / supplier</th><th>Note</th><th>Due</th><th>Owner</th><th></th></tr></thead>
            <tbody>
              {rows.map((f) => {
                const meta = FU_KINDS[f.kind] || ["Follow-up", "phone"];
                const overdue = f.dueDate < today; const due = f.dueDate === today;
                const party = partyById(f.partyId); const owner = byId[f.assignedTo];
                return (
                  <tr key={f.id}>
                    <td><span style={{ display: "inline-flex", alignItems: "center", gap: 7 }}><Icon name={meta[1]} size={14} style={{ color: "var(--accent-2)" }} />{meta[0]}</span></td>
                    <td style={{ fontWeight: 500 }}>{party ? party.name : "—"}{party && party.phone && <span style={{ display: "block", fontSize: 11.5, color: "var(--text-3)" }}>{party.phone}</span>}</td>
                    <td style={{ color: "var(--text-2)", fontSize: 12.5, maxWidth: 280 }}>{f.note}</td>
                    <td className="num" style={{ color: overdue ? "var(--neg)" : due ? "var(--warn)" : "var(--text-2)", whiteSpace: "nowrap" }}>{Hydor.fmtDate(f.dueDate)}{overdue && <Badge color="red">overdue</Badge>}</td>
                    <td>{owner ? <span className="hx-emp-badge" title={owner.name}>{owner.name.slice(0, 1)}</span> : <span style={{ color: "var(--text-3)", fontSize: 12 }}>—</span>}</td>
                    <td className="r no-print"><div style={{ display: "flex", gap: 2, justifyContent: "flex-end" }}>
                      <Btn variant="ghost" sm icon="check" onClick={() => setComplete(f)}>Complete</Btn>
                      {canAssign && <Btn variant="ghost" sm icon="trash" onClick={() => { Hydor.deleteFollowup(f.id); push("Removed."); }} />}
                    </div></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>

      {/* CS leaderboard + incentives */}
      <div className="hx-panel hx-panel-pad">
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
          <h3 className="hx-h2">Customer Success — secured sales{canMoney ? " & incentives" : ""}</h3>
          {canTargets && <Btn sm icon="settings" onClick={() => setRule(true)}>Incentive rule</Btn>}
        </div>
        <p className="hx-sub" style={{ marginBottom: 14 }}>Incentive rule: <b style={{ color: "var(--text-2)" }}>{inc.mode === "percent" ? inc.value + "% of secured sale value" : Hydor.fmtMoney0(inc.value) + " JOD per secured sale"}</b>{canMoney ? "" : " · amounts hidden for your role"}</p>
        {csReps.length === 0 ? <p className="hx-sub">No Customer Success team members yet. Set a person's department to “Customer Success” in HR.</p> : (
          <table className="hx-table">
            <thead><tr><th>Rep</th><th className="r">Calls done</th><th className="r">Secured sales</th><th className="r">Conversion</th>{canMoney && <><th className="r">Sales value</th><th className="r">Incentive</th></>}</tr></thead>
            <tbody>{repStats.map((r) => (
              <tr key={r.u.id}>
                <td><span className="hx-emp" style={{ gap: 10 }}><span className="hx-emp-badge">{r.u.name.slice(0, 1)}</span><span style={{ fontWeight: 500 }}>{r.u.name}</span></span></td>
                <td className="r num">{r.done}</td>
                <td className="r num" style={{ color: "var(--pos)" }}>{r.secured}</td>
                <td className="r num">{(r.conv * 100).toFixed(0)}%</td>
                {canMoney && <><td className="r num">{Hydor.fmtMoney0(r.securedVal)}</td><td className="r num" style={{ color: "var(--accent-2)", fontWeight: 600 }}>{Hydor.fmtMoney0(r.incentive)}</td></>}
              </tr>
            ))}</tbody>
          </table>
        )}
      </div>

      {add && <FollowupForm onClose={() => setAdd(false)} />}
      {complete && <CompleteFollowupForm fu={complete} onClose={() => setComplete(null)} />}
      {rule && <IncentiveRuleForm onClose={() => setRule(false)} />}
    </div>
  );
}

function FollowupForm({ onClose }) {
  const s = Hydor.getState();
  const push = useToast();
  const [f, setF] = React.useState({ kind: "service", partyId: "", note: "", dueDate: TODAY(), assignedTo: "" });
  const set = (k, v) => setF((p) => ({ ...p, [k]: v }));
  const reps = s.users.filter((u) => u.active);
  const save = () => { Hydor.addFollowup(f); push("Follow-up scheduled."); onClose(); };
  return (
    <Modal title="New follow-up" onClose={onClose} foot={<><Btn variant="ghost" onClick={onClose}>Cancel</Btn><Btn variant="primary" icon="check" onClick={save}>Schedule</Btn></>}>
      <div className="form-grid">
        <Field label="Type"><select className="sel" value={f.kind} onChange={(e) => set("kind", e.target.value)}>{Object.entries(FU_KINDS).map(([k, v]) => <option key={k} value={k}>{v[0]}</option>)}</select></Field>
        <Field label="Due date"><input className="inp" type="date" value={f.dueDate} onChange={(e) => set("dueDate", e.target.value)} /></Field>
        <Field label="Customer / supplier" span2><select className="sel" value={f.partyId} onChange={(e) => set("partyId", e.target.value)}><option value="">— none —</option>{s.parties.map((p) => <option key={p.id} value={p.id}>{p.name} ({p.type})</option>)}</select></Field>
        <Field label="Assign to"><select className="sel" value={f.assignedTo} onChange={(e) => set("assignedTo", e.target.value)}><option value="">— unassigned —</option>{reps.map((u) => <option key={u.id} value={u.id}>{u.name}</option>)}</select></Field>
        <Field label="Note" span2><input className="inp" value={f.note} onChange={(e) => set("note", e.target.value)} placeholder="What to do / talk about" /></Field>
      </div>
    </Modal>
  );
}

function CompleteFollowupForm({ fu, onClose }) {
  const push = useToast();
  const [converted, setConverted] = React.useState(false);
  const [saleValue, setSaleValue] = React.useState("");
  const [outcome, setOutcome] = React.useState("");
  const save = () => { Hydor.completeFollowup(fu.id, outcome, converted, saleValue); push("Follow-up completed."); onClose(); };
  return (
    <Modal title="Complete follow-up" onClose={onClose} foot={<><Btn variant="ghost" onClick={onClose}>Cancel</Btn><Btn variant="primary" icon="check" onClick={save}>Mark complete</Btn></>}>
      <div className="form-grid">
        <Field label="Outcome / notes" span2><input className="inp" value={outcome} onChange={(e) => setOutcome(e.target.value)} placeholder="e.g. Customer scheduled a service visit" autoFocus /></Field>
        <label className="span2" style={{ display: "flex", alignItems: "center", gap: 9, fontSize: 13.5, cursor: "pointer", color: "var(--text-2)" }}>
          <input type="checkbox" checked={converted} onChange={(e) => setConverted(e.target.checked)} /> This call secured a sale (counts toward incentive)
        </label>
        {converted && <Field label="Sale value secured" span2><Affix affix="JOD"><input className="inp num" type="number" value={saleValue} onChange={(e) => setSaleValue(e.target.value)} style={{ paddingRight: 44 }} placeholder="0" autoFocus /></Affix></Field>}
      </div>
    </Modal>
  );
}

function IncentiveRuleForm({ onClose }) {
  const push = useToast();
  const cur = Hydor.getState().meta.csIncentive || { mode: "percent", value: 3 };
  const [f, setF] = React.useState({ mode: cur.mode, value: cur.value });
  const save = () => { Hydor.setMeta({ csIncentive: { mode: f.mode, value: Hydor.num(f.value, 0) } }); push("Incentive rule updated."); onClose(); };
  return (
    <Modal title="Customer Success incentive rule" onClose={onClose} foot={<><Btn variant="ghost" onClick={onClose}>Cancel</Btn><Btn variant="primary" icon="check" onClick={save}>Save rule</Btn></>}>
      <div className="form-grid">
        <Field label="Incentive type" span2>
          <div className="hx-seg" style={{ width: "100%", display: "flex" }}>
            <button className={f.mode === "percent" ? "on" : ""} style={{ flex: 1 }} onClick={() => setF((p) => ({ ...p, mode: "percent" }))}>% of sale value</button>
            <button className={f.mode === "fixed" ? "on" : ""} style={{ flex: 1 }} onClick={() => setF((p) => ({ ...p, mode: "fixed" }))}>Fixed per sale</button>
          </div>
        </Field>
        <Field label={f.mode === "percent" ? "Percentage" : "Amount per secured sale"} span2>
          <Affix affix={f.mode === "percent" ? "%" : "JOD"}><input className="inp num" type="number" value={f.value} onChange={(e) => setF((p) => ({ ...p, value: e.target.value }))} style={{ paddingRight: 44 }} /></Affix>
        </Field>
        <p className="hx-sub span2" style={{ margin: 0 }}>Only the founder and co-founder can set this rule. Reps see their secured-sale count; incentive amounts are visible only to founder/co-founder.</p>
      </div>
    </Modal>
  );
}

/* ===================================================================
   CUSTOMER FINDER  (prospecting CRM + Maps-assisted discovery)
   =================================================================== */
const PIPE = [["new", "New", "gray"], ["contacted", "Contacted", "amber"], ["qualified", "Qualified", "blue"], ["won", "Won", "green"], ["lost", "Lost", "red"]];

function FinderPage() {
  const s = useHydor();
  const role = useRole();
  const canMoney = Hydor.can(role, "seeCostProfit");
  const push = useToast();
  const byId = usersById();
  const [edit, setEdit] = React.useState(null);
  const [bizType, setBizType] = React.useState("swimming pools");
  const [area, setArea] = React.useState("Amman, Jordan");
  const [statusF, setStatusF] = React.useState("all");

  const list = s.prospects.filter((p) => statusF === "all" || p.status === statusF);
  const counts = {}; PIPE.forEach(([k]) => (counts[k] = s.prospects.filter((p) => p.status === k).length));
  const pipeValue = s.prospects.filter((p) => p.status !== "lost" && p.status !== "won").reduce((a, p) => a + (p.estValue || 0), 0);

  const searchMaps = () => {
    const q = encodeURIComponent(`${bizType} in ${area}`);
    window.open(`https://www.google.com/maps/search/?api=1&query=${q}`, "_blank", "noopener");
  };

  return (
    <div>
      {/* discover panel */}
      <div className="hx-panel hx-panel-pad" style={{ marginBottom: 14 }}>
        <h3 className="hx-h2" style={{ marginBottom: 4 }}>Discover prospects</h3>
        <p className="hx-sub" style={{ marginBottom: 16 }}>Find candidate businesses on Google Maps, then add the good ones to your pipeline. (A live Google Places connection can auto-import results — ask to switch that on.)</p>
        <div style={{ display: "flex", gap: 12, flexWrap: "wrap", alignItems: "flex-end" }}>
          <Field label="Business type"><input className="inp" style={{ width: 220 }} value={bizType} onChange={(e) => setBizType(e.target.value)} placeholder="hotels, pools, gyms…" /></Field>
          <Field label="Area"><input className="inp" style={{ width: 220 }} value={area} onChange={(e) => setArea(e.target.value)} placeholder="Amman, Jordan" /></Field>
          <Btn variant="primary" icon="compass" onClick={searchMaps}>Search Google Maps</Btn>
          <div className="grow" style={{ flex: 1 }} />
          <Btn icon="plus" onClick={() => setEdit({})}>Add prospect</Btn>
        </div>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginTop: 14 }}>
          {["water filter customers", "swimming pools", "hotels & resorts", "gyms & spas", "restaurants", "residential compounds", "factories"].map((t) => (
            <button key={t} className="chip" onClick={() => setBizType(t)}>{t}</button>
          ))}
        </div>
      </div>

      {/* pipeline stat strip */}
      <div className="stat-strip" style={{ gridTemplateColumns: "repeat(" + (canMoney ? 6 : 5) + ",1fr)" }}>
        {PIPE.map(([k, l, c]) => (
          <div key={k} className="mini-stat" style={{ cursor: "pointer", borderLeft: "3px solid var(--" + (c === "green" ? "pos" : c === "red" ? "neg" : c === "amber" ? "warn" : c === "blue" ? "accent" : "grid") + ")" }} onClick={() => setStatusF(statusF === k ? "all" : k)}>
            <div className="ms-label">{l}</div><div className="ms-value">{counts[k]}</div>
          </div>
        ))}
        {canMoney && <div className="mini-stat" style={{ borderLeft: "3px solid var(--accent-2)" }}><div className="ms-label">Open pipeline</div><div className="ms-value">{Hydor.fmtMoney0(pipeValue)}</div><div className="ms-sub">JOD est.</div></div>}
      </div>

      <div className="toolbar">
        <div className="chip-row">
          <button className={"chip" + (statusF === "all" ? " on" : "")} onClick={() => setStatusF("all")}>All ({s.prospects.length})</button>
          {PIPE.map(([k, l]) => <button key={k} className={"chip" + (statusF === k ? " on" : "")} onClick={() => setStatusF(k)}>{l}</button>)}
        </div>
      </div>

      <div className="hx-panel" style={{ overflow: "hidden" }}>
        {list.length === 0 ? (
          <Empty icon="compass" title="No prospects yet">Use the discovery tool above to find businesses, then add the promising ones here to work them through your pipeline.</Empty>
        ) : (
          <table className="hx-table">
            <thead><tr><th>Business</th><th>Segment</th><th>Location</th><th>Source</th><th>Stage</th><th>Owner</th>{canMoney && <th className="r">Est. value</th>}<th></th></tr></thead>
            <tbody>
              {list.map((p) => { const st = PIPE.find((x) => x[0] === p.status) || PIPE[0]; const owner = byId[p.assignedTo]; return (
                <tr key={p.id}>
                  <td><span style={{ fontWeight: 500 }}>{p.name}</span>{p.phone && <span style={{ display: "block", fontSize: 11.5, color: "var(--text-3)" }}>{p.phone}</span>}</td>
                  <td style={{ color: "var(--text-2)", fontSize: 12.5 }}>{p.segment || "—"}</td>
                  <td style={{ color: "var(--text-2)", fontSize: 12.5 }}>{p.location || "—"}</td>
                  <td><Badge color="gray">{p.source}</Badge></td>
                  <td><Badge color={st[2]} dot>{st[1]}</Badge></td>
                  <td>{owner ? <span className="hx-emp-badge" title={owner.name}>{owner.name.slice(0, 1)}</span> : <span style={{ color: "var(--text-3)", fontSize: 12 }}>—</span>}</td>
                  {canMoney && <td className="r num">{p.estValue ? Hydor.fmtMoney0(p.estValue) : "—"}</td>}
                  <td className="r no-print"><div style={{ display: "flex", gap: 2, justifyContent: "flex-end" }}>
                    {p.status !== "won" && <Btn variant="ghost" sm icon="check" title="Convert to customer" onClick={() => { Hydor.convertProspect(p.id); push(p.name + " converted to a customer."); }} />}
                    <Btn variant="ghost" sm icon="edit" onClick={() => setEdit(p)} />
                    <Btn variant="ghost" sm icon="trash" onClick={() => { Hydor.deleteProspect(p.id); push("Prospect removed."); }} />
                  </div></td>
                </tr>
              ); })}
            </tbody>
          </table>
        )}
      </div>

      {edit && <ProspectForm editing={edit.id ? edit : null} onClose={() => setEdit(null)} />}
    </div>
  );
}

Object.assign(window, { NotificationsPage, HRPage, FollowupsPage, FinderPage });
