/* Written warnings: explicit response, server-confirmed only. No offline salary mutation. */
function useWarningText() {
  const lang = useLang();
  return (ar, en) => lang === "ar" ? ar : en;
}
function useWarningDecision() {
  const [busy, setBusy] = React.useState(false), [error, setError] = React.useState("");
  const [uncertain, setUncertain] = React.useState(false);
  const ticket = React.useRef(null), running = React.useRef(false);
  const w = useWarningText();
  async function send(intent) {
    if (running.current) return false;
    running.current = true; setBusy(true); setError("");
    if (!ticket.current) ticket.current = { ...intent, kind: "employeeWarning", opId: "warn-" + crypto.randomUUID() };
    try {
      const r = await Hydor.submitEmployeeWarningOp(ticket.current);
      if (!r.ok) {
        const messages = {
          warning_month_closed: w("شهر الخصم معتمد أو مدفوع أو انتهى. يلزم أن تلغي الإدارة الإنذار وتعيد إصداره لشهر مفتوح. ما زال بإمكان الموظف طلب التحقيق.", "The deduction month is approved, paid or past. Management must cancel and reissue for an open month. Investigation is still available."),
          warning_conflict: w("تغيّرت حالة الإنذار؛ حدّث الصفحة وراجعه مجددًا.", "The warning changed; refresh and review it again."),
          warning_terminal: w("تم الرد على هذا الإنذار بالفعل، ولا يمكن تغيير الرد هنا.", "This warning already has a response and cannot be changed here."),
          warning_authority: w("لا يملك الحساب الحالي صلاحية هذا الإجراء.", "This account cannot perform this action."),
          "not-authenticated": w("سجّل الدخول من جديد للمتابعة.", "Sign in again to continue."),
          "server-capability": w("هذه الميزة تحتاج إصدار الخادم الجديد؛ لم تُحفظ أي موافقة.", "This feature needs the updated server; no acceptance was saved.")
        };
        setError(messages[r.code] || w("لم يؤكد الخادم الإجراء. راجع اتصالك ثم أعد المحاولة؛ لن نكرر الخصم.", "The server did not confirm this action. Check the connection and retry; the deduction will not be repeated."));
        setUncertain(!r.definitive);
        if (r.definitive) ticket.current = null;
        return false;
      }
      ticket.current = null; setUncertain(false); return true;
    } catch (e) {
      setUncertain(true); setError(w("تعذّر التأكد من الحفظ. أعد نفس المحاولة للتحقق.", "Unable to confirm the save. Retry the same action to verify it.")); return false;
    } finally { running.current = false; setBusy(false); }
  }
  return { busy, error, uncertain, send, retry: () => send(ticket.current) };
}
function WarningDetails({ warning: x }) {
  const w = useWarningText();
  const status = { pending: w("بانتظار رد الموظف — لم يخصم شيء", "Awaiting employee response — no deduction"),
    accepted: w("وافق الموظف", "Accepted by employee"), investigation: w("قيد التحقيق — الخصم معلّق", "Under investigation — deduction suspended"), cancelled: w("ملغى — دون خصم", "Cancelled — no deduction") };
  return <div style={{ lineHeight: 1.8, overflowWrap: "anywhere" }}>
    <p style={{ color: x.status === "investigation" ? "var(--warn)" : "var(--text-2)" }}>{status[x.status]}</p>
    <h3 className="hx-h2">{x.employeeName}</h3>
    <p style={{ whiteSpace: "pre-wrap", fontWeight: 700 }}>{x.reason}</p>
    {x.details && <p style={{ whiteSpace: "pre-wrap" }}>{x.details}</p>}
    <div style={{ padding: 14, background: "var(--bg-2)", borderRadius: 10 }}>
      {w("قيمة الخصم المقترح", "Proposed deduction")}: <b>{Hydor.fmtMoney(x.amount)} JOD</b>
      {" · "}{w("شهر الراتب", "Payroll month")}: <b>{x.payrollMonth}</b>
      {x.status === "accepted" && <div>{x.amount > 0 ? w("أضيف إلى خصومات الراتب بعد الموافقة، مرة واحدة.", "Added once to payroll deductions after acceptance.") : w("إنذار دون خصم مالي.", "Warning without a financial deduction.")}</div>}
    </div>
    <small className="hx-sub">{w("صدر بتاريخ", "Issued at")}: {new Date(x.issuedAt).toLocaleString(undefined, { timeZone: "Asia/Amman" })}</small>
    {x.responseNote && <p>{w("رد الموظف", "Employee response")}: {x.responseNote}</p>}
    {x.respondedAt && <div className="hx-sub">{w("وقت الرد", "Responded at")}: {new Date(x.respondedAt).toLocaleString(undefined, { timeZone: "Asia/Amman" })}</div>}
  </div>;
}
function WarningResponse({ warning: x }) {
  const w = useWarningText(), d = useWarningDecision();
  const [note, setNote] = React.useState(""), [consent, setConsent] = React.useState(false);
  const send = (action) => d.send({ action, warningId: x.id, payload: { revision: x.revision, note } });
  return <>
    <WarningDetails warning={x} />
    <p>{w("اختر ردك للمتابعة. طلب التحقيق يفتح النظام ولا يضيف خصمًا. قراءة الإنذار وحدها ليست موافقة.", "Choose a response to continue. Requesting investigation unlocks the system without applying a deduction. Reading is not acceptance.")}</p>
    <label style={{ display: "block", margin: "14px 0" }}>{w("رد أو توضيح (اختياري)", "Response or clarification (optional)")}
      <textarea className="inp" rows={3} maxLength={1000} value={note} disabled={d.busy || d.uncertain} onChange={(e) => setNote(e.target.value)} /></label>
    <label style={{ display: "flex", gap: 10, alignItems: "start", padding: "12px 0" }}>
      <input type="checkbox" checked={consent} disabled={d.busy || d.uncertain} onChange={(e) => setConsent(e.target.checked)} />
      {w("أوافق على الإنذار وعلى حسم المبلغ المذكور من شهر الراتب الموضح أعلاه.", "I accept this warning and the stated deduction from the payroll month shown above.")}
    </label>
    <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
      <Btn variant="primary" disabled={!consent || d.busy || d.uncertain} onClick={() => send("accept")}>{w("أوافق على الإنذار والخصم", "Accept warning and deduction")}</Btn>
      <Btn disabled={d.busy || d.uncertain} onClick={() => send("investigate")}>{w("أرفض وأطلب تحقيقًا", "Reject and request investigation")}</Btn>
    </div>
    {d.busy && <p role="status">{w("بانتظار تأكيد الخادم…", "Waiting for server confirmation…")}</p>}
    {d.error && <p role="alert" style={{ color: "var(--neg)" }}>{d.error}</p>}
    {d.uncertain && <Btn onClick={d.retry} disabled={d.busy}>{w("إعادة نفس المحاولة للتحقق", "Retry the same action")}</Btn>}
  </>;
}
function EmployeeWarningGate({ warnings }) {
  const w = useWarningText();
  const out = () => { Hydor.logout(); if (window.HydorAPI && window.HydorAPI.isAuthed()) window.HydorAPI.logout().catch(() => {}); };
  return <main style={{ minHeight: "100dvh", padding: "clamp(16px,4vw,48px)", background: "var(--bg)", color: "var(--text)" }}>
    <div className="hx-panel hx-panel-pad" style={{ maxWidth: 740, margin: "0 auto" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
        <h2>{w("إنذار خطي يتطلب ردك", "Written warning — response required")}</h2><Btn onClick={out}>{w("تسجيل الخروج", "Sign out")}</Btn>
      </div>
      <p className="hx-sub">{w("الرد على الإنذار لا يغيّر سجل حضورك ولا يلغي بداية ورديتك.", "Responding to this warning does not change your attendance record or cancel your check-in.")} {warnings.length > 1 ? "(" + warnings.length + ")" : ""}</p>
      <WarningResponse key={warnings[0].id + ":" + warnings[0].revision} warning={warnings[0]} />
    </div>
  </main>;
}
function IssueWarningForm({ onClose }) {
  const s = useHydor(), w = useWarningText(), d = useWarningDecision();
  const month = window.HydorEmployeeWarnings.ammanDay().slice(0, 7);
  const [f, setF] = React.useState({ employeeId: "", reason: "", details: "", amount: "0", payrollMonth: month });
  const set = (k, v) => setF((p) => ({ ...p, [k]: v }));
  const ready = f.employeeId && f.reason.trim().length >= 3 && f.amount !== "" && Number.isFinite(Number(f.amount)) && Number(f.amount) >= 0;
  const save = async () => { if (await d.send({ action: "issue", payload: { ...f, amount: Number(f.amount) } })) onClose(); };
  return <Modal title={w("إصدار إنذار خطي", "Issue written warning")} onClose={d.busy || d.uncertain ? () => {} : onClose} foot={<>
    <Btn disabled={d.busy || d.uncertain} onClick={onClose}>{w("إلغاء", "Cancel")}</Btn>
    <Btn variant="primary" disabled={!ready || d.busy || d.uncertain} onClick={save}>{w("إرسال للموظف دون خصم الآن", "Send to employee — no deduction yet")}</Btn></>}>
    <fieldset disabled={d.busy || d.uncertain} style={{ border: 0, padding: 0, minWidth: 0 }} className="form-grid">
      <Field label={w("الموظف", "Employee")} span2><select className="sel" aria-label={w("الموظف", "Employee")} value={f.employeeId} onChange={(e) => set("employeeId", e.target.value)}>
        <option value="">{w("اختر الموظف", "Select employee")}</option>
        {s.users.filter((u) => u.active !== false && !u.deleted && !window.HydorEmployeeWarnings.founder(u)).map((u) => <option key={u.id} value={u.id}>{u.name} · {u.code}</option>)}
      </select></Field>
      <Field label={w("سبب الإنذار", "Warning reason")} span2><input className="inp" aria-label={w("سبب الإنذار", "Warning reason")} maxLength={300} value={f.reason} onChange={(e) => set("reason", e.target.value)} /></Field>
      <Field label={w("تفاصيل إضافية (اختياري)", "Additional details (optional)")} span2><textarea className="inp" aria-label={w("تفاصيل إضافية (اختياري)", "Additional details (optional)")} rows={4} maxLength={3000} value={f.details} onChange={(e) => set("details", e.target.value)} /></Field>
      <Field label={w("الخصم المقترح بالدينار — صفر لإنذار فقط", "Proposed deduction (JOD) — zero for warning only")}><input className="inp" aria-label={w("الخصم المقترح بالدينار", "Proposed deduction (JOD)")} type="number" min="0" max="100000" step="0.001" value={f.amount} onChange={(e) => set("amount", e.target.value)} /></Field>
      <Field label={w("شهر الخصم", "Deduction month")}><input className="inp" aria-label={w("شهر الخصم", "Deduction month")} type="month" min={month} value={f.payrollMonth} onChange={(e) => set("payrollMonth", e.target.value)} /></Field>
    </fieldset>
    <p>{w("تأكد من صحة الواقعة ومطابقة الإجراء لسياسة الشركة والضوابط المعمول بها. لا يطبّق الخصم إلا بموافقة الموظف الصريحة. الرفض يفتح النظام ويعلّق الخصم للتحقيق.", "Verify the facts and applicable company and legal rules. Only explicit employee acceptance applies the deduction. Rejection unlocks the system and suspends the deduction for investigation.")}</p>
    {d.error && <p role="alert" style={{ color: "var(--neg)" }}>{d.error}</p>}
    {d.uncertain && <Btn disabled={d.busy} onClick={async () => { if (await d.retry()) onClose(); }}>{w("إعادة نفس المحاولة للتحقق", "Retry the same action")}</Btn>}
  </Modal>;
}
function WarningCancel({ warning: x }) {
  const w = useWarningText(), d = useWarningDecision();
  const [note, setNote] = React.useState("");
  return <div style={{ marginTop: 16 }}>
    <label>{w("سبب إلغاء الإنذار / نتيجة التحقيق", "Cancellation reason / investigation outcome")}
      <input className="inp" value={note} maxLength={1000} disabled={d.busy || d.uncertain} onChange={(e) => setNote(e.target.value)} /></label>
    <Btn disabled={note.trim().length < 3 || d.busy || d.uncertain} onClick={() => d.send({ action: "cancel", warningId: x.id, payload: { revision: x.revision, note } })}>{w("إلغاء الإنذار دون خصم", "Cancel warning without deduction")}</Btn>
    <p className="hx-sub">{w("إذا أثبت التحقيق الحاجة إلى إنذار جديد، أصدِره بسبب وتفاصيل محدثة ليطّلع الموظف ويرد عليه من جديد. لا يحوّل النظام الرفض إلى موافقة.", "If the investigation warrants a new warning, issue it with updated facts for a new employee response. The system never changes rejection into acceptance.")}</p>
    {d.error && <p role="alert">{d.error}</p>}{d.uncertain && <Btn disabled={d.busy} onClick={d.retry}>{w("إعادة نفس المحاولة", "Retry same action")}</Btn>}
  </div>;
}
function EmployeeWarningsPanel() {
  const s = useHydor(), w = useWarningText(), me = Hydor.currentUser();
  const founder = window.HydorEmployeeWarnings.founder(me);
  const [open, setOpen] = React.useState(false), [issuing, setIssuing] = React.useState(false), [selected, setSelected] = React.useState("");
  const rows = (founder ? (s.employeeWarnings || []) : window.HydorEmployeeWarnings.own(s, me)).slice().sort((a, b) => b.issuedAt.localeCompare(a.issuedAt));
  const chosen = rows.find((x) => x.id === selected);
  const needs = rows.filter((x) => ["pending", "investigation"].includes(x.status)).length;
  return <section className="hx-panel hx-panel-pad" style={{ marginBottom: 14 }}>
    <div style={{ display: "flex", gap: 12, flexWrap: "wrap", alignItems: "center" }}>
      <Btn onClick={() => setOpen(!open)}>{w("الإنذارات الخطية", "Written warnings")} ({needs})</Btn>
      {founder && <Btn variant="primary" onClick={() => setIssuing(true)}>{w("إصدار إنذار", "Issue warning")}</Btn>}
    </div>
    {open && <div style={{ marginTop: 12 }}>
      {!rows.length && <p>{w("لا توجد إنذارات.", "No written warnings.")}</p>}
      {rows.map((x) => <button className="inp" style={{ display: "block", width: "100%", textAlign: "start", margin: "8px 0", whiteSpace: "normal" }} key={x.id} onClick={() => setSelected(x.id)}>
        {x.employeeName} — {x.reason} · {x.status === "investigation" ? w("قيد التحقيق", "Under investigation") : x.status === "pending" ? w("بانتظار الرد", "Awaiting response") : x.status === "accepted" ? w("تمت الموافقة", "Accepted") : w("ملغى", "Cancelled")}
      </button>)}
    </div>}
    {issuing && <IssueWarningForm onClose={() => setIssuing(false)} />}
    {chosen && <Modal title={w("تفاصيل الإنذار", "Warning details")} onClose={() => setSelected("")}>
      <WarningDetails warning={chosen} />
      {founder && ["pending", "investigation"].includes(chosen.status) && <WarningCancel key={chosen.id + chosen.revision} warning={chosen} />}
      {chosen.events.map((e, i) => <p className="hx-sub" key={i}>{new Date(e.at).toLocaleString(undefined, { timeZone: "Asia/Amman" })} · {e.note}</p>)}
    </Modal>}
  </section>;
}
Object.assign(window, { EmployeeWarningGate, EmployeeWarningsPanel });
