// screen_company.jsx — company profile, user lifecycle and enterprise onboarding
(function () {
  const { useState, useEffect } = React;
  const h = React.createElement;
  window.Screens = window.Screens || {};
  const LEVEL_TONE = { owner: "green", manager: "blue", operator: "amber", viewer: "neutral" };
  const STATUS_TONE = { Active: "green", Invited: "amber", Suspended: "neutral", Removed: "red" };

  function initials(name) {
    return String(name || "?").split(/\s+/).map((p) => p[0]).join("").slice(0, 2).toUpperCase();
  }
  function userCounts(users) {
    return {
      active: users.filter((u) => u.status === "Active").length,
      invited: users.filter((u) => u.status === "Invited").length,
      suspended: users.filter((u) => u.status === "Suspended").length,
      owners: users.filter((u) => u.level === "owner" && u.status === "Active").length,
    };
  }

  function UserModal({ ctx, user, onClose }) {
    const { Modal, Button, Segmented } = window;
    const canAccess = ctx.can("manageCompanyAccess");
    const [name, setName] = useState(user ? user.name : "");
    const [email, setEmail] = useState(user ? user.email : "");
    const [department, setDepartment] = useState(user ? (user.department || "") : "");
    const [level, setLevel] = useState(user ? (user.level || "viewer") : "viewer");
    const [status, setStatus] = useState(user ? (user.status || "Invited") : "Invited");
    function field(label, body, key) {
      return h("label", { "data-company-modal-field-wrap": key || "", style: { display: "grid", gap: 6, fontSize: 12, fontWeight: 700, color: "var(--text-dim)" } }, label, body);
    }
    function save() {
      let saved = false;
      if (user) {
        saved = ctx.updateCompanyUser(user.id, {
          name, email, department,
          level: canAccess ? level : user.level,
          status: canAccess ? status : user.status,
        });
      } else {
        saved = ctx.createCompanyUser({ name, email, department, level });
      }
      if (saved) onClose();
    }
    return h(Modal, {
      "data-company-modal": user ? "edit-user" : "invite-user",
      "data-company-user-id": user ? user.id : "",
      title: user ? "Edit team member" : "Invite team member",
      sub: "Sample demo only — no real invitation is sent.",
      icon: "users",
      width: 560,
      onClose,
      footer: [
        h(Button, { key: "cancel", variant: "ghost", "data-company-action": "modal-cancel", "data-company-user-id": user ? user.id : "", onClick: onClose }, "Cancel"),
        h(Button, { key: "save", variant: "primary", "data-company-action": user ? "save-user" : "create-user", "data-company-user-id": user ? user.id : "", onClick: save }, user ? "Save changes" : "Send invite"),
      ],
    },
      h("div", { style: { display: "grid", gap: 13 } },
        field("Full name", h("input", { className: "field", value: name, "data-company-field": "name", onChange: (e) => setName(e.target.value), placeholder: "Ada Chan" }), "name"),
        field("Work email", h("input", { className: "field", value: email, "data-company-field": "email", onChange: (e) => setEmail(e.target.value), placeholder: "ada@company.com.hk" }), "email"),
        field("Department", h("input", { className: "field", value: department, "data-company-field": "department", onChange: (e) => setDepartment(e.target.value), placeholder: "Operations" }), "department"),
        field("Access level", h(Segmented, { value: level, onChange: setLevel, options: ctx.LEVELS.map((l) => ({ value: l.id, label: l.label, attrs: { "data-company-field": "level", "data-company-level-option": l.id, "data-company-active": l.id === level ? "true" : "false" } })) }), "level"),
        !canAccess && h("div", { style: { fontSize: 12, color: "var(--amber)", lineHeight: 1.45 } }, "Managers can invite Operators and Viewers. Owner approval is required before access levels change."),
        user && field("Status", h(Segmented, { value: status, onChange: setStatus, options: ["Active", "Invited", "Suspended"].map((s) => ({ value: s, label: s, attrs: { "data-company-field": "status", "data-company-status-option": s, "data-company-active": s === status ? "true" : "false" } })) }), "status")));
  }

  function ProfileCard({ ctx, profile, active }) {
    const { Card, CardHead, Button } = window;
    const [draft, setDraft] = useState(Object.assign({}, profile));
    const canManage = ctx.can("manageCompanyUsers");
    function input(key, label) {
      return h("label", { style: { display: "grid", gap: 6, fontSize: 12, fontWeight: 700, color: "var(--text-dim)" } },
        label,
        h("input", { className: "field", value: draft[key] || "", disabled: !canManage, title: canManage ? "" : ctx.denyReason("manageCompanyUsers"), "data-company-profile-field": key,
          onChange: (e) => setDraft((d) => Object.assign({}, d, { [key]: e.target.value })) }));
    }
    return h(Card, { id: "company-section-profile", "data-company-section": "profile", className: active ? "onboard-hl" : "" },
      h(CardHead, { title: "Company profile", sub: "Company details for this demo workspace.", icon: "settings",
        right: h(Button, { sm: true, variant: "primary", disabled: !canManage, title: canManage ? "" : ctx.denyReason("manageCompanyUsers"), "data-company-action": "save-profile",
          onClick: () => ctx.updateCompanyProfile(draft) }, "Save profile") }),
      h("div", { style: { padding: 18, display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(190px,1fr))", gap: 13 } },
        input("name", "Company name"),
        input("workspace", "Workspace name"),
        input("domain", "Email domain"),
        input("region", "Region"),
        input("industry", "Industry"),
        input("identityMode", "Sign-in method")));
  }

  function OnboardingCard({ ctx, profile, users, onInvite }) {
    const { Card, CardHead, Badge, Button } = window;
    const counts = userCounts(users);
    const canManageUsers = ctx.can("manageCompanyUsers");
    const inviteDenyReason = canManageUsers ? "" : ctx.denyReason("manageCompanyUsers");
    const connected = (ctx.office.connectors || []).some((c) => c.status === "已連接");
    const hired = (ctx.office.roles || []).some((r) => r.hired);
    const stamped = !!((ctx.office.kpi || {}).approved);
    const steps = [
      { id: "profile", label: "Company profile", done: !!(profile.name && profile.domain), next: "Confirm workspace identity", go: "company", arg: "profile" },
      { id: "invite", label: "Invite team members", done: counts.active + counts.invited >= 3, next: "Add an owner, manager and operator", go: "company", arg: "invite" },
      { id: "access", label: "Set access levels", done: counts.owners >= 1 && users.some((u) => u.level === "manager"), next: "Keep one active owner", go: "company", arg: "users" },
      { id: "sources", label: "Connect files", done: connected, next: "Connect Drive or email", go: "connectors" },
      { id: "activation", label: "First employee and approval", done: hired && stamped, next: "Give, review and approve one task", go: "employees" },
    ];
    function openStep(s) {
      if (s.id === "invite" && !canManageUsers) return;
      if (s.id === "invite" && onInvite) onInvite();
      ctx.openPage(s.go, s.arg);
    }
    function renderStep(s, i) {
      const disabled = s.id === "invite" && !canManageUsers;
      return h("button", { key: s.id, "data-company-onboarding-step": s.id, "data-company-onboarding-page": s.go, "data-company-onboarding-target": s.arg || s.go, "data-company-onboarding-done": s.done ? "true" : "false", "data-company-onboarding-disabled": disabled ? "true" : "false", disabled, title: disabled ? inviteDenyReason : "", onClick: () => openStep(s), className: "row gap10",
        style: { width: "100%", textAlign: "left", border: "1px solid var(--border)", borderRadius: 10, background: s.done ? "var(--green-soft)" : "var(--bg-3)", padding: 12, fontFamily: "var(--font)", cursor: disabled ? "not-allowed" : "pointer", opacity: disabled ? 0.72 : 1 } },
        h("span", { style: { width: 26, height: 26, borderRadius: 8, display: "grid", placeItems: "center", background: s.done ? "var(--green)" : "var(--bg-2)", color: s.done ? "#fff" : "var(--text-dim)", fontWeight: 800, flex: "none" } }, s.done ? h(window.Icon, { name: "check", size: 14 }) : i + 1),
        h("span", { className: "grow", style: { minWidth: 0 } },
          h("b", { style: { display: "block", fontSize: 13.5 } }, s.label),
          h("span", { style: { display: "block", marginTop: 2, fontSize: 12.5, color: "var(--text-dim)" } }, s.done ? "Ready" : s.next)),
        h(window.Icon, { name: "chevRight", size: 14, color: "var(--text-faint)" }));
    }
    const done = steps.filter((s) => s.done).length;
    return h(Card, null,
      h(CardHead, { title: "Setup checklist", sub: done + " of " + steps.length + " steps ready", icon: "sparkle",
        right: h(Badge, { tone: done === steps.length ? "green" : "amber" }, profile.rolloutStage === "Pilot setup" ? "Setup in progress" : (profile.rolloutStage || "Setup in progress")) }),
      h("div", { style: { padding: 16, display: "grid", gap: 10 } },
        steps.map(renderStep),
        h("div", { style: { padding: 12, borderRadius: 10, background: "var(--blue-soft)", border: "1px solid rgba(47,127,224,.18)", color: "var(--blue-deep)", fontSize: 12.5, lineHeight: 1.55 } },
          "Advanced sign-in is shown as a demo only. No real accounts are created.")));
  }

  function UsersTable({ ctx, users, onEdit, active }) {
    const { Card, CardHead, Badge, Button, Segmented } = window;
    const [filter, setFilter] = useState("All");
    const [confirmRemove, setConfirmRemove] = useState(null);
    const rows = filter === "All" ? users : users.filter((u) => u.status === filter);
    return h(Card, { id: "company-section-users", "data-company-section": "users", className: active ? "onboard-hl" : "" },
      h(CardHead, { title: "Team members", sub: rows.length + " shown", icon: "users",
        right: h("div", { className: "row gap8 wrap" },
          h(Segmented, { value: filter, onChange: setFilter, options: ["All", "Active", "Invited", "Suspended", "Removed"].map((s) => ({ value: s, label: s, attrs: { "data-company-filter": s, "data-company-filter-active": s === filter ? "true" : "false" } })) }),
          h(Button, { sm: true, variant: "primary", icon: "plus", disabled: !ctx.can("manageCompanyUsers"), title: ctx.can("manageCompanyUsers") ? "" : ctx.denyReason("manageCompanyUsers"), "data-company-action": "invite-user", onClick: () => onEdit(null) }, "Invite member")) }),
      h("div", { style: { overflowX: "auto" } },
        h("table", { className: "tbl", "data-company-users-table": "true", "data-company-filter-current": filter, "data-company-visible-count": String(rows.length) },
          h("thead", null, h("tr", null, ["Team member", "Department", "Access", "Status", "Setup", "Last seen", "Actions"].map((c, i) => h("th", { key: i, style: i === 6 ? { textAlign: "right" } : null }, c)))),
          h("tbody", null, rows.map((u) => {
            const canAccess = ctx.can("manageCompanyAccess");
            return h("tr", { key: u.id, "data-company-user-row": u.id, "data-company-user-email": u.email || "", "data-company-user-level": u.level || "", "data-company-user-status": u.status || "", "data-company-user-removed": u.status === "Removed" ? "true" : "false" },
              h("td", null, h("div", { className: "row gap10" },
                h("span", { style: { width: 32, height: 32, borderRadius: 9, background: "var(--bg-3)", border: "1px solid var(--border)", display: "grid", placeItems: "center", color: "var(--text-dim)", fontWeight: 800, fontSize: 11, flex: "none" } }, initials(u.name)),
                h("span", { style: { minWidth: 0 } }, h("b", { style: { display: "block", fontSize: 13 } }, u.name), h("span", { style: { display: "block", fontSize: 12, color: "var(--text-faint)" } }, u.email)))),
              h("td", { className: "dim", style: { fontSize: 12.5 } }, u.department || "General"),
              h("td", null, h(Badge, { tone: LEVEL_TONE[u.level] || "neutral" }, ctx.LEVEL_LABEL[u.level] || u.level)),
              h("td", null, h(Badge, { tone: STATUS_TONE[u.status] || "neutral" }, u.status || "Invited")),
              h("td", { className: "dim", style: { fontSize: 12.5 } }, u.onboarding || "Pending"),
              h("td", { className: "dim", style: { fontSize: 12.5, whiteSpace: "nowrap" } }, u.lastSeen || "Not yet"),
              h("td", { style: { textAlign: "right" } }, h("div", { className: "row gap6", style: { justifyContent: "flex-end", flexWrap: "wrap" } },
                h(Button, { sm: true, "data-company-action": "edit-user", "data-company-user-id": u.id, onClick: () => onEdit(u), disabled: !ctx.can("manageCompanyUsers"), title: ctx.can("manageCompanyUsers") ? "" : ctx.denyReason("manageCompanyUsers") }, "Edit"),
                u.status === "Invited" && h(Button, { sm: true, variant: "ghost", "data-company-action": "resend-invite", "data-company-user-id": u.id, onClick: () => ctx.resendCompanyInvite(u.id), disabled: !ctx.can("manageCompanyUsers"), title: ctx.can("manageCompanyUsers") ? "" : ctx.denyReason("manageCompanyUsers") }, "Resend"),
                u.status === "Active" && h(Button, { sm: true, variant: "ghost", "data-company-action": "suspend-user", "data-company-user-id": u.id, disabled: !canAccess, title: canAccess ? "" : ctx.denyReason("manageCompanyAccess"), onClick: () => ctx.deactivateCompanyUser(u.id) }, "Suspend"),
                u.status === "Suspended" && h(Button, { sm: true, variant: "ghost", "data-company-action": "reactivate-user", "data-company-user-id": u.id, disabled: !canAccess, title: canAccess ? "" : ctx.denyReason("manageCompanyAccess"), onClick: () => ctx.reactivateCompanyUser(u.id) }, "Reactivate"),
                u.status !== "Removed" && h(Button, { sm: true, variant: "ghost", "data-company-action": confirmRemove === u.id ? "confirm-remove-user" : "remove-user", "data-company-user-id": u.id, disabled: !canAccess, title: canAccess ? "" : ctx.denyReason("manageCompanyAccess"),
                  onClick: () => { if (confirmRemove === u.id) { ctx.deleteCompanyUser(u.id); setConfirmRemove(null); } else setConfirmRemove(u.id); } }, confirmRemove === u.id ? "Confirm remove" : "Remove"))));
          })))));
  }

  function Company({ ctx }) {
    const { PageHeader, Card, KPI, Badge, Button } = window;
    const profile = ctx.office.companyProfile || { name: ctx.office.company || ctx.client, workspace: ctx.client, domain: "demo.local", region: "Hong Kong", identityMode: "Email invitations", rolloutStage: "Pilot setup" };
    const users = (ctx.office.companyUsers && ctx.office.companyUsers.length) ? ctx.office.companyUsers : ctx.team;
    const counts = userCounts(users);
    const [modalUser, setModalUser] = useState(false);
    const canManageUsers = ctx.can("manageCompanyUsers");
    useEffect(() => {
      if (ctx.pageArg === "invite") {
        setModalUser(canManageUsers ? null : false);
        return;
      }
      if (ctx.pageArg !== "profile" && ctx.pageArg !== "users") return;
      const section = ctx.pageArg;
      const t = window.setTimeout(() => {
        const el = document.getElementById("company-section-" + section);
        if (el && el.scrollIntoView) el.scrollIntoView({ block: "center", behavior: "smooth" });
      }, 80);
      return () => window.clearTimeout(t);
    }, [ctx.pageArg, canManageUsers]);
    return h("div", { "data-company-root": "true", "data-company-arg": ctx.pageArg || "", "data-company-active-users": String(counts.active), "data-company-invited-users": String(counts.invited), "data-company-suspended-users": String(counts.suspended), "data-company-active-owners": String(counts.owners) },
      h(PageHeader, { eyebrow: "Company", title: "Company & Team", icon: "users",
        sub: "Manage company details, invite people and choose what each person can do.",
        right: [
          h(Badge, { key: "mode", tone: "blue" }, profile.identityMode || "Email invitations"),
          h(Button, { key: "settings", sm: true, "data-company-action": "open-settings", onClick: () => ctx.openPage("settings") }, "Settings"),
        ] }),
      h("div", { style: { display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(180px,1fr))", gap: 14, marginBottom: 16 } },
        h(KPI, { data: { tone: "green", icon: "users", v: counts.active, l: "Active members", sub: counts.invited + " invited" } }),
        h(KPI, { data: { tone: "amber", icon: "shield", v: counts.owners, l: "Active owners", sub: "Minimum one required" } }),
        h(KPI, { data: { tone: "blue", icon: "mail", v: counts.invited, l: "Open invitations", sub: "Mock email only" } }),
        h(KPI, { data: { tone: "violet", icon: "lock", v: counts.suspended, l: "Suspended members", sub: "Access paused" } })),
      h("div", { style: { display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(320px,1fr))", gap: 16, alignItems: "start", marginBottom: 16 } },
        h(ProfileCard, { ctx, profile, active: ctx.pageArg === "profile" }),
        h(OnboardingCard, { ctx, profile, users, onInvite: () => setModalUser(null) })),
      h(UsersTable, { ctx, users, active: ctx.pageArg === "users", onEdit: (u) => setModalUser(u || null) }),
      modalUser !== false && h(UserModal, { ctx, user: modalUser, onClose: () => setModalUser(false) }));
  }

  window.Screens.company = Company;
})();
