/* page-customers.jsx — IIFE-scoped; exports via window.
   Customers (03-ui §Customers rev2): ONE role-parameterised CustomersList for GA·CM·AM·OM.
   Full PII every role (no masking) · status active|inactive|archive · all-role multi-select
   + bulk Set-status (+GA Export) · 700px DetailDrawer with read|edit|create modes.
   OMRedemptions relocated to page-rewards.jsx. */
(function(){
const { useState, useMemo, useEffect, useRef } = React;

const STATUS_OPTS = [
  { value: "active",   label: "Active" },
  { value: "inactive", label: "Inactive" },
  { value: "archive",  label: "Archive" },
];

/** @spec CM-050 / AM-050 / GA-020 / OM-050 — Customers directory (all-tier CRU, full PII) */
function CustomersList({ role }) {
  if (!["GA", "CM", "AM", "OM"].includes(role)) return _notAuthorised;

  const canExport = role === "GA"; // only Export is GA-only; everything else is all-role
  const canScopeFilter = role === "GA" || role === "CM" || role === "AM"; // OM = status+search only
  // Best-available deep-link routes per role; unbuilt → Stub (accepted).
  const ordersRoute = { CM: "cm-orders", AM: "am-orders", OM: "om-orders-live", GA: "ga-orders" }[role];
  const loyaltyRoute = { CM: "cm-loyalty" }[role] || "loyalty"; // non-CM → unbuilt route resolves to Stub
  const redemptionsRoute = role === "OM" ? "om-redemptions" : "redemptions";

  const [searchQuery, setSearchQuery] = useState("");
  const [status, setStatus] = useState("");
  const [geo, setGeo] = useState({ countries: [] });
  const [sel, setSel] = useState({});
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [customers, setCustomers] = useState(() => CM_CUSTOMERS.map(c => ({ ...c })));
  const [drawerId, setDrawerId] = useState(null);
  const [mode, setMode] = useState("read"); // read | edit | create
  const [draft, setDraft] = useState(null);
  const [bulkStatus, setBulkStatus] = useState(""); // pending bulk Set-status value (opens confirm)

  const desc = {
    GA: "Consumers across all markets.",
    CM: "Consumers in your country.",
    AM: "Consumers in your area.",
    OM: "Consumers who order at your outlet.",
  }[role];

  // Baseline role scope. GA = all markets; CM/AM/OM = own country.
  // CM_CUSTOMERS carries only `country` — sub-country (area/outlet) scoping isn't representable here.
  const scopeCountry = role === "OM" ? (SB3_OUTLET_BY_ID[OM_OUTLET_ID] || {}).country_id
    : (role === "CM" || role === "AM") ? "PH"
    : null; // GA = unscoped
  const q = searchQuery.trim().toLowerCase();
  const rows = customers
    .filter(c => !scopeCountry || c.country === scopeCountry)
    .filter(c => !status || c.status === status)
    .filter(c => !canScopeFilter || !geo.countries || geo.countries.length === 0 || geo.countries.includes(c.country))
    .filter(c => !q || c.name.toLowerCase().includes(q) || (c.email || "").toLowerCase().includes(q) || (c.phone || "").toLowerCase().includes(q));

  const totalPages = Math.max(1, Math.ceil(rows.length / pageSize));
  const visibleRows = rows.slice((page - 1) * pageSize, page * pageSize);

  // ── Selection / bulk (ALL roles) ──────────────────────────────────────────
  const selectedIds = Object.keys(sel).filter(k => sel[k]);
  const onToggleSelected = (id) => {
    if (id === "all") {
      const allOn = rows.length > 0 && rows.every(r => sel[r.id]);
      const next = {};
      if (!allOn) rows.forEach(r => { next[r.id] = true; });
      setSel(next);
    } else {
      setSel(s => ({ ...s, [id]: !s[id] }));
    }
  };
  const doSetStatus = () => {
    const next = bulkStatus;
    setCustomers(cs => cs.map(c => selectedIds.includes(c.id) ? { ...c, status: next } : c));
    setSel({}); setBulkStatus("");
  };
  const doExport = () => { setSel({}); };

  const statusLabel = (v) => (STATUS_OPTS.find(o => o.value === v) || {}).label || v;
  const bulkActions = (
    <>
      <div style={{ minWidth: 170 }}>
        <Select value="" placeholder="Set status…" onChange={setBulkStatus} options={STATUS_OPTS}/>
      </div>
      {canExport && <Btn variant="secondary" size="sm" onClick={doExport}>Export</Btn>}
    </>
  );

  // ── Columns: identical for ALL roles (full parity) ──
  const columns = [
    { label: "Name",         sortable: true, sortKey: "name", render: r => <span style={{ ...T.primary() }}>{r.name}</span> },
    { label: "Email",        sortable: true, sortKey: "email", width: 190, render: r => _emailLink(r.email, { muted: true }) },
    { label: "Phone",        sortable: true, sortKey: "phone", width: 150, render: r => _phoneLink(r.phone, { muted: true }) },
    { label: "Country",      sortable: true, sortKey: "country", width: 90, render: r => <span style={{ ...T_MUTED }}>{(SB2_COUNTRY_BY_ID[r.country] || {}).flag || ""} {r.country}</span> },
    { label: "Loyalty pts",  sortable: true, sortKey: "loyalty_points_balance", width: 110, render: r => <span style={{ ...T.amount }}>{(r.loyalty_points_balance || 0).toLocaleString()}</span> },
    { label: "Orders",       sortable: true, sortKey: "orders_count", width: 90, render: r => <span style={{ ...T.amount }}>{(r.orders_count || 0).toLocaleString()}</span> },
    { label: "Member since", sortable: true, sortKey: "created_at", width: 120, render: r => <span style={{ ...T_MUTED }}>{_fmtDate(r.created_at, r.country)}</span> },
    { label: "Status",       width: 110, sortable: true, sortKey: "status", render: r => <StatusPill status={r.status} kind="customer"/> },
  ];

  // ── Drawer record (live, derived by id) + mode helpers ──
  const c = drawerId ? customers.find(x => x.id === drawerId) : null;
  const isCreate = mode === "create";
  const isEdit = mode === "edit";
  const isForm = isEdit || isCreate;
  const walletShown = c && c.country === "SG" && c.wallet_balance != null;

  const openRead = (r) => { setDrawerId(r.id); setMode("read"); setDraft(null); };
  const closeDrawer = () => { setDrawerId(null); setMode("read"); setDraft(null); };
  const startEdit = () => { setDraft({ ...c }); setMode("edit"); };
  const startCreate = () => {
    setDrawerId(null);
    setDraft({
      id: null, name: "", username: "", email: "", phone: "", birthday: "",
      country: scopeCountry || "PH", status: "active", loyalty_tier: "Bronze",
      loyalty_points_balance: 0, orders_count: 0, gifts: 0, redemptions: 0,
      created_at: "", first_order_at: "", last_order_at: "",
    });
    setMode("create");
  };
  const setD = (k, v) => setDraft(d => ({ ...d, [k]: v }));
  const saveForm = () => {
    if (isCreate) {
      const id = `cust_NEW_${Date.now()}`;
      const rec = { ...draft, id, created_at: draft.created_at || new Date().toISOString().slice(0, 10) };
      setCustomers(cs => [rec, ...cs]);
      setDrawerId(id); setMode("read"); setDraft(null);
    } else {
      setCustomers(cs => cs.map(x => x.id === draft.id ? { ...x, ...draft } : x));
      setMode("read"); setDraft(null);
    }
  };

  const deepLink = (route, filter) => () => { closeDrawer(); _go(route, { filter }); };

  const drawerTitle = isCreate ? "New Customer" : (c ? c.name : "");
  const drawerSubtitle = isCreate ? "" : (c && c.username ? `@${c.username}` : "");
  const drawerActions = isForm
    ? (<>
        <Btn variant="secondary" onClick={() => { if (isCreate) closeDrawer(); else { setMode("read"); setDraft(null); } }}>Cancel</Btn>
        <Btn variant="primary" onClick={saveForm}>Save</Btn>
      </>)
    : (<>
        <Btn variant="secondary" onClick={closeDrawer}>Close</Btn>
        <Btn variant="primary" onClick={startEdit}>Edit</Btn>
      </>);

  // Form fields shared by edit + create.
  const formFields = draft && (
    <>
      <FormSection title="General">
        <div className="row" style={{ gap: 16 }}>
          <div className="grow"><Field label="Name"><Input value={draft.name} onChange={v => setD("name", v)} placeholder="Full name"/></Field></div>
          <div className="grow"><Field label="Username"><Input value={draft.username} onChange={v => setD("username", v)} placeholder="handle"/></Field></div>
        </div>
        <Field label="Birthday"><DateField value={draft.birthday} onChange={v => setD("birthday", v)}/></Field>
      </FormSection>
      <FormSection title="Contact">
        <div className="row" style={{ gap: 16 }}>
          <div className="grow"><Field label="Email"><Input type="email" value={draft.email} onChange={v => setD("email", v)} placeholder="name@example.com"/></Field></div>
          <div className="grow"><Field label="Phone"><Input type="tel" value={draft.phone} onChange={v => setD("phone", v)} placeholder="+63 917 000 0000"/></Field></div>
        </div>
      </FormSection>
      <FormSection title="Account">
        <div className="row" style={{ gap: 16 }}>
          <div className="grow"><Field label="Country">
            <Select value={draft.country} onChange={v => setD("country", v)}
              disabled={!canScopeFilter}
              options={SB2_COUNTRIES.map(co => ({ value: co.country_id, label: `${co.flag} ${co.country_name}` }))}/>
          </Field></div>
          <div className="grow"><Field label="Status"><Select value={draft.status} onChange={v => setD("status", v)} options={STATUS_OPTS}/></Field></div>
        </div>
      </FormSection>
    </>
  );

  return (
    <div className="page-inner">
      <PageHead title="Customers" description={desc}
        actions={<><ExportButton role={role} variant="secondary" onClick={() => {}}/><Btn variant="primary" onClick={startCreate}>New customer</Btn></>}/>

      <FilterBar
        primaryFilter={{ key: "status", label: "Status", options: [
          { value: "", label: "All statuses" },
          ...STATUS_OPTS,
        ] }}
        primaryValue={{ status }}
        onPrimaryChange={(next) => { if (next.status !== undefined) setStatus(next.status); }}
        advancedFilters={canScopeFilter ? [
          { key: "geo", kind: "geoscope", label: "Network scope", role,
            countries: SB2_COUNTRIES.map(co => ({ value: co.country_id, label: `${co.flag} ${co.country_name}` })) },
        ] : []}
        advancedValues={canScopeFilter ? { geo } : {}}
        onAdvancedChange={(k, v) => { if (k === "geo") setGeo(v); }}
        onAdvancedReset={() => setGeo({ countries: [] })}
        onReset={() => { setStatus(""); setGeo({ countries: [] }); setSearchQuery(""); }}
        search={searchQuery}
        onSearch={setSearchQuery}
        searchPlaceholder="Search customers…"
      />

      <BulkBar selectedCount={selectedIds.length} onDeselect={() => setSel({})} actions={bulkActions}/>

      <Table
        columns={columns}
        rows={visibleRows}
        selected={sel}
        onToggleSelected={onToggleSelected}
        onRow={r => openRead(r)}
        emptyText="No customers match the current filter."/>

      <TableFooter page={page} totalPages={totalPages} onPage={setPage} count={pageSize} onCountChange={n => { setPageSize(n); setPage(1); }}/>

      <DetailDrawer
        open={isCreate || !!drawerId}
        onClose={closeDrawer}
        title={drawerTitle}
        subtitle={drawerSubtitle}
        actions={drawerActions}
      >
        {isForm && formFields}

        {!isForm && c && (
          <>
            <FormSection title="General">
              <KeyValueGrid columns={2} items={[
                { label: "Name",        value: c.name },
                { label: "Username",    value: c.username ? `@${c.username}` : "—" },
                { label: "Birthday",    value: c.birthday || "—" },
                { label: "First order", value: c.first_order_at || "—" },
              ]}/>
            </FormSection>

            <FormSection title="Contact">
              <KeyValueGrid columns={2} items={[
                { label: "Email", value: _emailLink(c.email) },
                { label: "Phone", value: _phoneLink(c.phone) },
              ]}/>
            </FormSection>

            <FormSection title="Account">
              <KeyValueGrid columns={2} items={[
                { label: "Country",      value: <span>{(SB2_COUNTRY_BY_ID[c.country] || {}).flag || ""} {(SB2_COUNTRY_BY_ID[c.country] || {}).country_name || c.country}</span> },
                { label: "Loyalty tier", value: <span className="chip">{c.loyalty_tier}</span> },
                { label: "Status",       value: <StatusPill status={c.status} kind="customer"/> },
                { label: "Member since", value: _fmtDate(c.created_at, c.country) },
                { label: "Last order",   value: c.last_order_at || "—" },
              ]}/>
            </FormSection>
          </>
        )}

        {/* Stats + Remarks: shown in READ and EDIT (always read-only); hidden only in CREATE (no record yet). */}
        {!isCreate && c && (
          <>
            <FormSection title="Activity">
              <div className="stat-panel stat-panel-snapshot">
                <div className="stat-panel-grid">
                  {walletShown && <StatCard label="Wallet" value={c.wallet_balance} sub="current balance" icon={<LIcon name="Wallet" size={16}/>}
                    onClick={deepLink("wallet", { customer_id: c.id, label: c.name })}/>}
                  <StatCard label="Orders" value={(c.orders_count || 0).toLocaleString()} sub="View this customer's orders"
                    icon={<LIcon name="ShoppingBag" size={16}/>}
                    onClick={deepLink(ordersRoute, { customer_id: c.id, label: c.name })}/>
                  <StatCard label="Loyalty Points" value={(c.loyalty_points_balance || 0).toLocaleString()} sub="View loyalty activity"
                    icon={<LIcon name="Star" size={16}/>}
                    onClick={deepLink(loyaltyRoute, { customer_id: c.id, label: c.name })}/>
                  <StatCard label="Gifts" value={(c.gifts || 0).toLocaleString()} sub="View gifts sent"
                    icon={<LIcon name="Gift" size={16}/>}
                    onClick={deepLink("purchases", { sender_id: c.id, label: c.name })}/>
                  <StatCard label="Redemptions" value={(c.redemptions || 0).toLocaleString()} sub="View redemptions"
                    icon={<LIcon name="Ticket" size={16}/>}
                    onClick={deepLink(redemptionsRoute, { customer_id: c.id, label: c.name })}/>
                </div>
              </div>
            </FormSection>

            <CustomerRemarks customerId={c.id} role={role}/>
          </>
        )}
      </DetailDrawer>

      <ConfirmModal
        open={!!bulkStatus}
        title={`Set ${selectedIds.length} customer${selectedIds.length === 1 ? "" : "s"} to ${statusLabel(bulkStatus)}?`}
        body={<>This updates the status of the selected customer{selectedIds.length === 1 ? "" : "s"} to {statusLabel(bulkStatus)}. Out-of-scope rows are excluded.</>}
        confirmLabel={`Set ${statusLabel(bulkStatus)}`}
        onCancel={() => setBulkStatus("")}
        onConfirm={doSetStatus}
      />
    </div>
  );
}

// Remarks sub-block — keeps _useRemarks (a hook) at a stable top level, not inside the drawer JSX.
function CustomerRemarks({ customerId, role }) {
  const [remarks, addRemark, editRemark, deleteRemark] = _useRemarks("customer", customerId, [
    { id: "rem_seed_1", content: "VIP customer — handles bulk orders for nearby office. Flagged in priority queue.", created_by_name: "Bea Lim (CM)", created_at: "2026-04-15 13:50" },
    { id: "rem_seed_2", content: "Prefers no-contact handoff at the counter.", created_by_name: "Ravi N. (OM)", created_at: "2026-04-20 11:02" },
  ]);
  return <RemarksSection entityType="customer" entityId={customerId} remarks={remarks} onAdd={addRemark} currentUser="you" onEdit={editRemark} onDelete={deleteRemark} role={role}/>;
}

// OMRedemptions relocated to page-rewards.jsx (Rewards module consolidation).

Object.assign(window, { CustomersList });
})();
