// UsageCosts.jsx — honest task activity and sample allowance view under Value
(function () {
  const h = React.createElement;
  const { Card, CardHead, EmptyHint, PageHeader, ProgressBar, Segmented } = window;

  const MONTH_EN = { 1: "January", 2: "February", 3: "March", 4: "April", 5: "May", 6: "June", 7: "July", 8: "August", 9: "September", 10: "October", 11: "November", 12: "December" };
  const WEEK_EN = { "本週": "This week", "上週": "Last week" };

  function monthText(value) {
    const match = String(value || "").match(/^(\d{4})\s*年\s*(\d{1,2})\s*月$/);
    return match ? MONTH_EN[Number(match[2])] + " " + match[1] : String(value || "");
  }

  function RoiViewSwitch({ ctx, active }) {
    return h(Segmented, {
      className: "roi-view-switch",
      ariaLabel: "Value views",
      value: active,
      onChange: (value) => ctx.openPage("roi", value === "usage" ? "usage" : null),
      options: [
        { value: "value", label: "Value", attrs: { "data-roi-view-option": "value", "data-roi-view-active": active === "value" ? "true" : "false" } },
        { value: "usage", label: "Tasks & costs", attrs: { "data-roi-view-option": "usage", "data-roi-view-active": active === "usage" ? "true" : "false" } },
      ],
    });
  }

  function nonNegative(value) {
    const number = Number(value);
    return Number.isFinite(number) ? Math.max(0, number) : 0;
  }

  function formatCopy(key, values) {
    if (window.I18N && window.I18N.format) return window.I18N.format(key, values);
    return key.replace(/\{([A-Za-z0-9_]+)\}/g, (token, name) => Object.prototype.hasOwnProperty.call(values || {}, name) ? values[name] : token);
  }

  function localCopy(value) {
    return window.I18N && window.I18N.t ? window.I18N.t(value) : value;
  }

  function UsageCosts({ ctx }) {
    const office = ctx.office;
    const k = office.kpi || {};
    const day0 = !!(office.onboarding && office.onboarding.day0);
    const activeRoles = day0 ? [] : (office.roles || []).filter((role) => role.hired);
    const paidRoles = activeRoles.filter((role) => !role.hired.trial);
    const paidEmployeeCount = paidRoles.length;
    const usage = office.ops && office.ops.usage;
    const billing = office.ops && office.ops.billing;
    // The allowance belongs to the billing period, not to each current employee.
    // Day-0 deliberately uses its zeroed KPI overlay because OFFICE.ops is retained.
    const used = nonNegative(!day0 && usage && usage.actions != null ? usage.actions : k.quotaUsed);
    const total = nonNegative(usage && usage.actionsQuota != null ? usage.actionsQuota : k.quotaTotal);
    const remaining = Math.max(0, total - used);
    const extraTasks = total > 0 ? Math.max(0, used - total) : 0;
    const extraRate = nonNegative(billing && billing.overage != null ? billing.overage : k.overage);
    const extraCharge = extraTasks * extraRate;
    const allowancePercent = total > 0 ? Math.min(100, Math.round(used / total * 100)) : 0;
    const weekly = Array.isArray(k.weeklyTasks) && k.weeklyTasks.length ? k.weeklyTasks.map(nonNegative) : [0];
    const maxWeekly = Math.max.apply(null, weekly) || 1;
    const scheduled = activeRoles.flatMap((role) => (role.skills || [])
      .filter((task) => task.enabled && task.routine)
      .map((task) => ({ role, task: window.skillCopy ? window.skillCopy(role.id, task, "name") : task.name, routine: task.routine })));
    const period = usage && usage.periodStart && usage.periodEnd ? usage.periodStart + " – " + usage.periodEnd : monthText(k.month);
    const usedMessage = total > 0
      ? formatCopy("{used} of {total} tasks used", { used: used.toLocaleString(), total: total.toLocaleString() })
      : formatCopy("{count} tasks used", { count: used.toLocaleString() });
    const remainingMessage = formatCopy("{count} tasks left", { count: remaining.toLocaleString() });
    const extraTasksMessage = formatCopy("{count} extra tasks", { count: extraTasks.toLocaleString() });
    const extraRateMessage = formatCopy("{price} per extra task", { price: "HK$" + extraRate.toFixed(2) });
    function scheduledRow(item, index) {
      const employee = window.officeRoleName ? window.officeRoleName(item.role, item.role.id) : (item.role.title || item.role.short || item.role.id);
      return h("li", {
        key: item.role.id + ":" + index,
        className: "row between wrap usage-scheduled-row",
        style: { gap: 10, padding: "10px 0", borderBottom: index === scheduled.length - 1 ? "none" : "1px solid var(--border)" },
      },
        h("div", { className: "row gap10", style: { minWidth: 0 } },
          h(window.Face, { role: item.role, size: 22, variant: "head" }),
          h("div", { style: { minWidth: 0 } },
            h("strong", { style: { display: "block", fontSize: 13.5 } }, item.task),
            h("div", { className: "usage-scheduled-meta", style: { marginTop: 2, color: "var(--text-faint)", fontSize: 12 } },
              h("span", { className: "usage-scheduled-employee" }, employee),
              h("span", { "aria-hidden": "true" }, " · "),
              h("span", null, item.routine)))));
    }

    return h("div", {
      "data-roi-screen": "true",
      "data-roi-view": "usage",
      "data-usage-used": String(used),
      "data-usage-total": String(total),
      "data-usage-remaining": String(remaining),
      "data-usage-paid-employees": String(paidEmployeeCount),
      "data-usage-extra-tasks": String(extraTasks),
      "data-usage-extra-charge": extraCharge.toFixed(2),
      className: "usage-costs",
    },
      h(PageHeader, {
        eyebrow: "Value",
        title: h("span", null, "Tasks & costs — ", h("span", null, monthText(k.month))),
        sub: "See what is included and any extra cost.",
        right: h(RoiViewSwitch, { ctx, active: "usage" }),
      }),
      h(Card, { className: "usage-summary", style: { padding: 20, marginBottom: 16, minHeight: 210 }, "data-usage-summary": "true" },
        h("div", { className: "two-col", style: { marginBottom: 0, alignItems: "stretch" } },
          h("section", { "aria-labelledby": "usage-included-title", style: { minWidth: 0 } },
            h("h2", { id: "usage-included-title", className: "usage-section-title eyebrow", style: { margin: "0 0 8px", fontSize: 11, lineHeight: 1.2 } }, "Included tasks"),
            h("div", { className: "row wrap", style: { alignItems: "baseline", gap: 7, marginBottom: 10 } },
              h("strong", { className: "mono usage-used-message", style: { fontSize: 30, lineHeight: 1 } }, usedMessage)),
            total > 0 && h(ProgressBar, { className: "usage-progress", value: allowancePercent, tone: allowancePercent >= 90 ? "amber" : "green", height: 9, ariaLabel: "Tasks used", style: { marginTop: 0 } }),
            h("div", { className: "row between wrap usage-summary-meta", style: { gap: 8, marginTop: 10, color: "var(--text-dim)", fontSize: 12.5 } },
              total > 0 && h("span", null, remainingMessage),
              h("span", { className: "mono", style: { color: "var(--text-faint)", marginLeft: total > 0 ? 0 : "auto" } }, period))),
          h("section", { "aria-labelledby": "usage-extra-title", style: { padding: 16, borderRadius: 12, background: "var(--bg-3)", border: "1px solid var(--border)" } },
            h("h2", { id: "usage-extra-title", className: "usage-section-title", style: { margin: 0, color: "var(--text-faint)", fontSize: 11.5, fontWeight: 700, letterSpacing: ".04em", textTransform: "uppercase" } }, "Estimated extra cost"),
            extraCharge > 0
              ? h("div", { className: "mono usage-extra-amount", style: { fontSize: 27, fontWeight: 700, marginTop: 7, color: "var(--amber)" } }, "HK$" + extraCharge.toFixed(2))
              : h("div", { className: "usage-extra-none", style: { fontSize: 27, fontWeight: 700, marginTop: 7, color: "var(--green)" } }, "No extra cost"),
            extraTasks > 0 && h("div", { className: "usage-extra-detail", style: { color: "var(--text-dim)", fontSize: 12.5, marginTop: 10 } }, extraTasksMessage),
            h("div", { className: "usage-extra-detail", style: { color: "var(--text-dim)", fontSize: 12.5, marginTop: 5 } }, extraRateMessage),
            h("div", { className: "usage-sample-note", style: { color: "var(--text-faint)", fontSize: 11.5, marginTop: 10, lineHeight: 1.45 } }, "Sample only — this is not a bill.")))),
      h("div", { className: "two-col usage-detail-grid" },
        h(Card, null,
          h(CardHead, { title: "Tasks by week", icon: "activity", headingLevel: 2 }),
          h("ul", { className: "bars usage-weekly-chart", "data-usage-weekly-chart": "true", "aria-label": "Tasks by week", tabIndex: 0, style: { height: 190, margin: 0, padding: "20px 18px 0", listStyle: "none" } }, weekly.map((value, index) => {
            const label = WEEK_EN[(k.weeks && k.weeks[index]) || ""] || ((k.weeks && k.weeks[index]) || "");
            const accessibleLabel = formatCopy("{week}: {count} tasks", { week: localCopy(label), count: value.toLocaleString() });
            return h("li", { key: index, className: "bar-col", style: { listStyle: "none" } },
              h("span", { className: "sr-only" }, accessibleLabel),
              h("span", { className: "mono usage-bar-value", "aria-hidden": "true", style: { fontSize: 10.5, color: "var(--text-dim)" } }, value),
              h("div", { className: "bar usage-bar-fill" + (index === weekly.length - 1 ? " current" : ""), style: { height: (value / maxWeekly * 100) + "%", background: index === weekly.length - 1 ? "var(--blue)" : "#b9d6f5" }, "aria-hidden": "true" }),
              h("span", { className: "bar-l", "aria-hidden": "true" }, label));
          }))),
        h(Card, { "data-usage-scheduled": String(scheduled.length) },
          h(CardHead, {
            title: "Scheduled tasks",
            icon: "clock",
            headingLevel: 2,
          }),
          scheduled.length === 0
            ? h(EmptyHint, { icon: "clock", text: "No scheduled tasks yet." })
            : h("ul", { className: "usage-scheduled-list", style: { margin: 0, padding: "6px 16px 12px", listStyle: "none" } }, scheduled.map(scheduledRow)))),
      h("div", { className: "rule-banner", style: { marginBottom: 0 } },
        h("div", { className: "row between wrap", style: { gap: 12 } },
          h("div", null,
            h("strong", null, "How tasks are counted"),
            h("div", { style: { marginTop: 3, color: "var(--text-dim)" } }, "A task counts when work reaches My Desk."))))
    );
  }

  Object.assign(window, { UsageCosts, RoiViewSwitch });
})();
