/* ─── Exit lifecycle: procedure templates + document generation ─────────
 *
 * Two formal procedures, each with their own checklist:
 *
 *   OFFBOARDING_STEPS   — voluntary, notice-period serving
 *   TERMINATION_STEPS   — involuntary, immediate
 *
 * Both attach to the user record as `procedure: { kind, checklist: {sid: bool}, notes: {sid: ""} }`.
 * Documents (relieving letter, experience certificate, etc.) are generated
 * from the user's data and opened in a printable view.
 * ────────────────────────────────────────────────────────────────────── */

const OFFBOARDING_STEPS = [
  { id: "ack",        title: "Resignation acknowledged in writing",   desc: "HR confirms receipt of resignation; manager and reporting line informed.", owner: "HR" },
  { id: "kt_plan",    title: "Knowledge transfer plan documented",    desc: "Successor identified, KT sessions scheduled, docs/runbooks listed.",       owner: "Manager" },
  { id: "handover",   title: "Pending work & projects handed over",   desc: "Open tickets, in-flight projects, and recurring tasks reassigned.",        owner: "Employee + Manager" },
  { id: "assets",     title: "Company assets returned",               desc: "Laptop, ID card, access cards, headset, mobile phone — all checked back in.", owner: "IT + Admin" },
  { id: "exit_intvw", title: "Exit interview completed",              desc: "Confidential conversation with HR — feedback recorded for retention insights.", owner: "HR" },
  { id: "access",     title: "Access revocation scheduled",           desc: "M365, Slack, Linear, Notion, GitHub etc. deprovisioned on last working day.", owner: "IT" },
  { id: "fnf",        title: "Final settlement calculated",           desc: "Last month salary + leave encashment − any dues. Reviewed by Finance.",   owner: "Finance" },
  { id: "relieving",  title: "Relieving letter issued",               desc: "Signed PDF given to the employee on or before last working day.",          owner: "HR" },
  { id: "expcert",    title: "Experience certificate issued",         desc: "Standard format with confirmed dates of employment and role.",             owner: "HR" },
  { id: "filed",      title: "Exit documentation filed",              desc: "Record archived in SharePoint with read-only access.",                     owner: "HR" },
];

const TERMINATION_STEPS = [
  { id: "notice",      title: "Termination notice issued in writing", desc: "Signed termination letter handed to employee or sent by registered post.", owner: "HR + CEO" },
  { id: "access_rev",  title: "Immediate access revocation",          desc: "All M365 / Slack / tools deprovisioned within the same business day.",      owner: "IT" },
  { id: "assets",      title: "Company assets retrieved",             desc: "Laptop, ID card, access cards, devices collected and signed off.",          owner: "IT + Admin" },
  { id: "fnf",         title: "Full & Final settlement processed",    desc: "Final salary + leave encashment + payment in lieu of notice (if any).",    owner: "Finance" },
  { id: "letter",      title: "Termination letter signed",            desc: "Two copies; one acknowledged by employee, one retained by HR.",            owner: "CEO + HR" },
  { id: "legal",       title: "Legal sign-off",                       desc: "Verify cause, severance, and no-suit clauses with legal counsel.",         owner: "Legal" },
  { id: "filed",       title: "Exit documentation filed",             desc: "Record archived in SharePoint with read-only access.",                     owner: "HR" },
];

const procedureFor = (u) => {
  // The HR drawer's row object overrides `status` with the onboarding-record
  // status, but carries the true employment stage on `lifecycle`. Prefer it.
  const s = u.lifecycle || u.status;
  if (s === "notice" || s === "offboarded") return { kind: "offboarding", steps: OFFBOARDING_STEPS };
  if (s === "terminated") return { kind: "termination", steps: TERMINATION_STEPS };
  return null;
};

const procedureProgress = (u) => {
  const proc = procedureFor(u);
  if (!proc) return { done: 0, total: 0, pct: 0 };
  const checklist = (u.procedure || {}).checklist || {};
  const done = proc.steps.filter((s) => checklist[s.id]).length;
  return { done, total: proc.steps.length, pct: Math.round((done / proc.steps.length) * 100), proc };
};

const toggleProcedureStep = (uid, sid) => {
  const users = Store.loadUsers();
  const i = users.findIndex((u) => u.id === uid);
  if (i < 0) return null;
  const cur = users[i].procedure || { checklist: {}, notes: {} };
  cur.checklist = { ...cur.checklist, [sid]: !cur.checklist[sid] };
  users[i].procedure = cur;
  Store.saveUsers(users);
  return users[i];
};

const setProcedureNote = (uid, sid, note) => {
  const users = Store.loadUsers();
  const i = users.findIndex((u) => u.id === uid);
  if (i < 0) return null;
  const cur = users[i].procedure || { checklist: {}, notes: {} };
  cur.notes = { ...cur.notes, [sid]: note };
  users[i].procedure = cur;
  Store.saveUsers(users);
  return users[i];
};

/* ─── Document templates ─────────────────────────────────────────────── */
const todayLong = () => new Date().toLocaleDateString("en-IN", { day: "numeric", month: "long", year: "numeric" });
const longDate = (iso) => iso ? new Date(iso).toLocaleDateString("en-IN", { day: "numeric", month: "long", year: "numeric" }) : "—";

const docTemplates = {
  relieving: (u) => {
    const co = companyProfile(); const ceo = orgCEO(); const mgr = employeeManager(u);
    const signer = ceo.name || Store.loadContent().supportName || "Authorised Signatory";
    return {
    title: "Relieving Letter",
    refNo: `HR/REL/${new Date().getFullYear()}/${u.id.slice(-4).toUpperCase()}`,
    body: [
      `Date: ${todayLong()}`,
      `To,`,
      `${u.name}`,
      ``,
      `Dear ${u.name.split(" ")[0]},`,
      ``,
      `This is to confirm that you have been relieved from your duties as ${u.title} at ${co.name} with effect from ${longDate(u.notice?.lastWorkingDay)}, following the formal resignation submitted by you on ${longDate(u.notice?.startDate)} and the notice period served in accordance with company policy.`,
      ``,
      mgr.name ? `Your engagement was under the reporting line of ${mgr.name} (${mgr.title}).` : `__DROP__`,
      `We confirm that all company assets, credentials, and confidential materials have been returned, and there are no outstanding obligations pending against you.`,
      ``,
      `We thank you for your contributions to ${co.name} during your tenure, and wish you success in all your future endeavours.`,
      ``,
      `For ${co.name}`,
      ``,
      `${signer}`,
      `${ceo.name ? ceo.title : "People & Culture"}`,
    ].filter((l) => l !== `__DROP__`),
    };
  },

  experience: (u) => {
    const co = companyProfile(); const ceo = orgCEO(); const mgr = employeeManager(u);
    const signer = ceo.name || Store.loadContent().supportName || "Authorised Signatory";
    return {
    title: "Experience Certificate",
    refNo: `HR/EXP/${new Date().getFullYear()}/${u.id.slice(-4).toUpperCase()}`,
    body: [
      `Date: ${todayLong()}`,
      ``,
      `TO WHOMSOEVER IT MAY CONCERN`,
      ``,
      `This is to certify that ${u.name} was employed with ${co.name} as ${u.title} from ${longDate(u.startDate)} to ${longDate(u.notice?.lastWorkingDay || u.termination?.lastWorkingDay)}.`,
      ``,
      `During this period, ${u.name.split(" ")[0]} was associated with the ${DEPT_LABELS[u.department]} team${mgr.name ? `, reporting to ${mgr.name} (${mgr.title})` : ``} and made valuable contributions to the organisation. We found ${u.name.split(" ")[0]} to be sincere, hard-working, and professional in all their dealings.`,
      ``,
      `This certificate is issued at the request of the employee.`,
      ``,
      `We wish them success in all their future endeavours.`,
      ``,
      `For ${co.name}`,
      ``,
      `${signer}`,
      `${ceo.name ? ceo.title : "People & Culture"}`,
    ],
    };
  },

  termination: (u) => {
    const co = companyProfile(); const ceo = orgCEO(); const mgr = employeeManager(u);
    return {
    title: "Termination Letter",
    refNo: `HR/TERM/${new Date().getFullYear()}/${u.id.slice(-4).toUpperCase()}`,
    body: [
      `Date: ${todayLong()}`,
      `To,`,
      `${u.name}`,
      ``,
      `Dear ${u.name.split(" ")[0]},`,
      ``,
      `This letter is to formally notify you that your employment with ${co.name} as ${u.title} is being terminated effective ${longDate(u.termination?.lastWorkingDay)}.`,
      ``,
      `Reason for termination: ${u.termination?.reason || "—"}`,
      ``,
      `In accordance with the terms of your employment agreement and company policy, you will receive your final settlement including:`,
      `  • Salary and benefits accrued up to your last working day`,
      `  • Encashment of unused earned leave`,
      `  • Payment in lieu of notice: ${inr(u.termination?.paymentInLieu || 0)}`,
      ``,
      `You are required to return all company assets, including but not limited to your laptop, ID card, access cards, and any other property of the company, on or before your last working day.`,
      ``,
      `Please note that your confidentiality, non-solicitation, and intellectual property obligations under your employment agreement continue to apply post-employment.`,
      ``,
      `For any questions regarding this letter or your final settlement, please contact your reporting manager${mgr.name ? ` (${mgr.name})` : ``} or the HR team.`,
      ``,
      `Sincerely,`,
      `For ${co.name}`,
      ``,
      `${mgr.name || "Reporting Manager"}          ${ceo.name || Store.loadContent().supportName || "Chief Executive Officer"}`,
      `${mgr.name ? mgr.title : "Reporting Manager"}          ${ceo.title}`,
    ],
    };
  },

  fnf: (u) => {
    const rec = Store.loadRecords()[u.id];
    const lastMonth = new Date();
    const slip = computePayslip(u, rec, lastMonth.getMonth() + 1, lastMonth.getFullYear());
    const leaveBalance = u.leaveBalance || DEFAULT_LEAVE_BALANCE();
    const leaveEncashable = (leaveBalance.earned || 0);
    const dailyBasic = Math.round((u.salary?.basic || 0) / 30);
    const leaveEncash = leaveEncashable * dailyBasic;
    const piln = u.termination?.paymentInLieu || 0;
    const total = slip.net + leaveEncash + piln;
    return {
      title: "Full & Final Settlement Statement",
      refNo: `HR/FNF/${new Date().getFullYear()}/${u.id.slice(-4).toUpperCase()}`,
      structured: true,
      sections: [
        { h: "Employee", rows: [
          ["Name", u.name],
          ["Employee ID", u.id.toUpperCase()],
          ["Role", u.title],
          ["Department", DEPT_LABELS[u.department] || u.department],
          ["Date of joining", longDate(u.startDate)],
          ["Last working day", longDate(u.notice?.lastWorkingDay || u.termination?.lastWorkingDay)],
        ]},
        { h: "Earnings (final month)", rows: slip.earnings.map((e) => [e.name, inr(e.amount)]).concat([["Gross", inr(slip.gross)]]) },
        { h: "Statutory deductions", rows: slip.deductions.map((d) => [d.name, "−" + inr(d.amount)]).concat([["Total", "−" + inr(slip.totalDeductions)]]) },
        { h: "Settlement", rows: [
          ["Net of final month", inr(slip.net)],
          [`Leave encashment (${leaveEncashable} days × ${inr(dailyBasic)}/day)`, inr(leaveEncash)],
          piln ? ["Payment in lieu of notice", inr(piln)] : null,
          ["Total payable", inr(total)],
        ].filter(Boolean) },
      ],
      total,
    };
  },
};

Object.assign(window, {
  OFFBOARDING_STEPS, TERMINATION_STEPS, procedureFor, procedureProgress,
  toggleProcedureStep, setProcedureNote, docTemplates, longDate, todayLong,
});
