// T2 Falcon Admin — Wallet & Balance .Mng — "Show as Client" view
// Single-client perspective: client header + master wallet + nested org/user table + transfer drawer.
// Re-uses BalanceTransferDrawer + the same allocation seed + per-row Transfer button.

const { useState: useStateWC, useEffect: useEffectWC, useMemo: useMemoWC } = React;

const ClientWalletView = ({
  selectedNode,
  tree,
  walletType, setWalletType,           // 'single' | 'multiple'
  balanceType,           // 'node' | 'user'
  activeChannels,        // array of channel ids (only used when walletType === 'multiple')
  toggleChannel,         // (id) => void — flips a channel on/off
  allocations, setAllocations,
  userAllocs, setUserAllocs,
  savedAllocations, setSavedAllocations,
  rowOpen, setRowOpen,
  toggleRow,
  drawerFor, setDrawerFor,
  onConfirmTransfer,
  t,
  pushToast,
  onSwitchView,          // back to picker
}) => {
  const [currency, setCurrency] = useStateWC('SAR');
  // When currency is Points, the client picks which commchannel's rate card
  // drives the SAR→Points conversion — same control as the Falcon view.
  const [rateChannel, setRateChannel] = useStateWC('');   // no auto-default — user must pick (see Select placeholder)
  // Hover-path highlight (same as the Hierarchy tree): ids on the hovered row's
  // ancestor chain → teal rail highlight.
  const [wbcHoveredPath, setWbcHoveredPath] = useStateWC(null);
  // Mirror to global so RiyalMark (and the transfer drawer) can pick the
  // right glyph (SAR ﷼ vs Points "Pt") without prop-threading.
  useEffectWC(() => {
    if (typeof window !== 'undefined') window.__wbCurrency = currency;
  }, [currency]);
  // (Pagination state removed — same reasoning as the Falcon view: a
  // hierarchy tree has no meaningful definition of "pages".)

  // Client master totals (per-channel pools — realistic large-enterprise SAR)
  const masterChannelTotals = { whatsapp: 18_450_320.55, voice: 12_280_140.25, aichat: 9_820_000, sms: 6_540_220.75, email: 2_180_000 };

  // ------- Build display rows (recursive) -------
  const MAX_DEPTH = 20;
  const tableRows = useMemoWC(() => {
    if (!selectedNode) return [];
    const rows = [];
    const visit = (org, depth, ancestorsHasNext, isLastChild, parentPath) => {
      const kids = org.children || [];
      const users = (org.users || []).slice(0, 3);
      const canDescend = depth < MAX_DEPTH;
      const hasChildren = canDescend && (
        balanceType === 'user'
          ? (kids.length > 0 || users.length > 0)
          : kids.length > 0
      );
      const path = [...parentPath, org.id];   // root→self id chain (hover-path highlight)
      rows.push({
        id: org.id, depth, name: org.name, kind: 'org',
        isHeader: depth === 0, hasChildren, parentName: null,
        ancestorsHasNext, isLastChild,   // tree-rail metadata (see wbTreeRails)
        path,
      });
      if (!rowOpen[org.id] || !canDescend) return;
      // Sub-nodes + the node's own users as one ordered sibling list so each
      // user's connector elbows back to THIS node (disambiguates users sitting
      // directly under a node vs. under one of its sub-nodes).
      // depth 0 is the client HEADER (no rail of its own) → don't add a rail
      // column for it, or the vertical guide breaks through expanded sub-trees.
      const childAncestors = depth === 0 ? ancestorsHasNext : [...ancestorsHasNext, !isLastChild];
      const childItems = [
        ...kids.map(k => ({ type: 'org', node: k })),
        ...(balanceType === 'user' ? users.map((u, idx) => ({ type: 'user', u, idx })) : []),
      ];
      childItems.forEach((item, j) => {
        const childIsLast = j === childItems.length - 1;
        if (item.type === 'org') {
          visit(item.node, depth + 1, childAncestors, childIsLast, path);
        } else {
          const userRowId = `${org.id}::${item.u.id}`;
          rows.push({
            id: userRowId, depth: depth + 1,
            name: item.u.firstName || item.u.username, kind: 'user',
            orgId: org.id, userIdx: item.idx, hasChildren: false, parentName: org.name,
            ancestorsHasNext: childAncestors, isLastChild: childIsLast,
            path: [...path, userRowId],
          });
        }
      });
    };
    visit(selectedNode, 0, [], true, []);
    return rows;
  }, [selectedNode, balanceType, rowOpen]);

  const getAlloc = (row, key) => {
    if (row.kind === 'user') {
      const k = `${row.orgId}::${row.userIdx}`;
      const u = userAllocs[k] || seedUserAlloc(row.orgId, row.userIdx);
      return u[key] || 0;
    }
    return allocations[row.id]?.[key] || 0;
  };

  const openDrawer = (row) => setDrawerFor(row);

  const colsKey = walletType === 'single' ? 'single' : `multi-${activeChannels.length}`;

  return (
    <div className="page wbc-page-1col">
      <div className="content-panel">
        <div className="content-body wbc-content-body">
        {/* ---------- Client header ---------- */}
        <div className="wbc-client-row">
          <BrandLogo brand={selectedNode?.brand} size={36} />
          <span className="wbc-client-name">{selectedNode?.name}</span>

          <div className="wbc-header-controls">
            <div className="wbc-hc-field">
              <span className="wbc-hc-label">{t.wbWalletType}</span>
              <select className="wbc-master-type-select" value={walletType} onChange={(e) => setWalletType(e.target.value)}>
                <option value="single">{t.wbSingleWallet}</option>
                <option value="multiple">{t.wbMultipleWallets}</option>
              </select>
            </div>
            <button className="wbc-switch-view" onClick={onSwitchView} title={t.tplBackToPicker || 'Switch view'}>
              <IcArrowLeft size={13} stroke={1.8} />
              <span>{t.tplBackToPicker || 'Switch view'}</span>
            </button>
          </div>
        </div>

        {/* ---------- Master Wallet card ----------
            Grid layout in multiple-wallets mode: the columns MIRROR the
            allocation table's grid-template-columns exactly, so each active
            channel pill sits directly above its matching column header in the
            table. Inactive (unchecked) channel pills are tucked into the same
            grid cell as the Master Wallet info, on the far left — they don't
            steal a grid track because no table column exists for them. */}
        <div className={`wbc-master ${walletType === 'multiple' ? 'wbc-master-grid' : ''}`} data-cols={colsKey}>
          {/* Cell 1 (org-column position): Master Wallet info + inactive pills */}
          <div className="wbc-master-info-cell">
            <div className="wbc-master-left">
              <div className="wbc-master-label">{t.wbMasterWallet}</div>
              <div className="wbc-master-amount">
                {/* Master Wallet: always Riyal (matches the Falcon view) */}
                <RiyalMark size={20} currency="SAR" />
                <strong>{fmtTotal(48_756_318.4250)}</strong>
              </div>
            </div>
            {/* "Show All" link — restores every channel after the user has
                unchecked some from the table header. Only rendered when at
                least one channel is currently inactive. */}
            {walletType === 'multiple'
              && toggleChannel
              && activeChannels.length < WB_CHANNELS.length && (
              <button
                type="button"
                className="wbc-show-all-link"
                onClick={() => {
                  WB_CHANNELS.forEach(c => {
                    if (!activeChannels.includes(c.id)) toggleChannel(c.id);
                  });
                }}
              >
                {t.wbShowAll || 'Show All'}
              </button>
            )}
          </div>

          {/* Per-channel pills — plain label + amount. Checkbox now lives
              on the TABLE COLUMN HEADER (see below) so this strip stays
              clean. Active channels only, in their grid positions. */}
          {walletType === 'multiple' && activeChannels.map(chId => {
            const ch = WB_CHANNELS.find(c => c.id === chId);
            if (!ch) return null;
            return (
              <div key={ch.id} className="wbc-master-ch wbc-master-ch--col is-active">
                <span className="wbc-master-ch-head">
                  <span className="wbc-master-ch-label">{t[ch.label]}</span>
                </span>
                <span className="wbc-master-ch-amt">
                  <RiyalMark size={13} currency={currency} />
                  {fmtNum(masterChannelTotals[ch.id] || 0)}
                </span>
              </div>
            );
          })}

          {/* Cell N+2 (transfer-column position): Type dropdown + (Points only)
              the rate-card commchannel selector. */}
          <div className="wbc-master-controls">
            <div className="wbc-hc-field">
              <span className="wbc-hc-label">{t.wbType || 'Type'}</span>
              <select className="wbc-master-type-select" value={currency} onChange={(e) => setCurrency(e.target.value)}>
                <option value="SAR">{t.wbCurrencySAR}</option>
                <option value="Points">{t.wbCurrencyPoints}</option>
              </select>
            </div>
            {/* Points + SINGLE wallet → pick which comm-channel's rate card drives
                the conversion. Shown ONLY when more than one comm-channel is
                enabled (with a single channel there's nothing to choose). In
                multiple-wallet mode each channel carries its own rate. The DDL
                opens on a "Select" placeholder so nothing is converted on a
                default value until the user explicitly picks a channel. */}
            {walletType === 'single' && currency === 'Points' && activeChannels.length > 1 && (
              <div className="wbc-hc-field">
                <span className="wbc-hc-label">{t.wbRateCardChannel || 'Rate card channel'}</span>
                <select className="wbc-master-type-select" value={rateChannel} onChange={(e) => setRateChannel(e.target.value)}>
                  <option value="">{t.wbSelect || 'Select'}</option>
                  {WB_CHANNELS.filter(ch => activeChannels.includes(ch.id)).map(ch => (
                    <option key={ch.id} value={ch.id}>{t[ch.label]}</option>
                  ))}
                </select>
              </div>
            )}
          </div>
        </div>

        {/* ---------- Allocation table ---------- */}
        <div className="wbc-table-card">
          <div className="wbc-tr wbc-tr-head" data-cols={colsKey}>
            <div className="wbc-th wbc-th-org">{t.wbOrganizations}</div>
            {walletType === 'single' ? (
              <div className="wbc-th wbc-th-amt">{t.wbWallet}</div>
            ) : (
              activeChannels.map(chId => {
                const ch = WB_CHANNELS.find(c => c.id === chId);
                const isLast = activeChannels.length === 1;
                return (
                  <label key={chId}
                    className={`wbc-th wbc-th-amt wbc-th-check ${isLast ? 'is-locked' : ''}`}
                    title={isLast ? (t.wbAtLeastOneChannel || 'At least one channel must remain visible') : ''}>
                    <input
                      type="checkbox"
                      className="wbc-th-check-input"
                      checked={true}
                      disabled={isLast || !toggleChannel}
                      onChange={() => !isLast && toggleChannel && toggleChannel(ch.id)}
                    />
                    <span className="wbc-th-check-box" aria-hidden="true">
                      <svg width="11" height="11" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
                        <path d="m3.5 8.5 3 3 6-7" />
                      </svg>
                    </span>
                    <span className="wbc-th-name">{t[ch.label]}</span>
                  </label>
                );
              })
            )}
            <div className="wbc-th wbc-th-xfer">{t.wbTransfer}</div>
          </div>

          <div className="wbc-table-body">
            {/* Render the full tree — slicing by page would break the
                hierarchy (a child row could end up on a different "page"
                than its parent). */}
            {tableRows.map(row => {
              const isHeader = !!row.isHeader;
              // In user-based mode the wallet belongs to the USER, not the node.
              // Node rows render an empty cell (and no transfer) so the team
              // isn't shown a wallet at two levels at once.
              const hideValue = balanceType === 'user' && row.kind !== 'user';
              return (
                <div key={row.id}
                  className={`wbc-tr ${isHeader ? 'wbc-tr-header' : 'wbc-tr-child'} ${row.kind === 'user' ? 'wbc-tr-user' : ''} ${wbcHoveredPath && wbcHoveredPath.has(row.id) ? 'on-path' : ''}`}
                  data-cols={colsKey}
                  onMouseEnter={() => setWbcHoveredPath(new Set(row.path))}
                  onMouseLeave={() => setWbcHoveredPath(null)}>
                  <div className="wbc-td wbc-td-org">
                    {wbTreeRails(row)}
                    {row.kind === 'user' ? (
                      <span className="wbc-td-chev wbc-td-chev-spacer" />
                    ) : (
                      <button
                        className={`wbc-td-chev ${row.hasChildren ? '' : 'invisible'} ${rowOpen[row.id] ? 'open' : ''}`}
                        onClick={() => row.hasChildren && toggleRow(row.id)}>
                        <IcChevronRight size={12} stroke={2.4} />
                      </button>
                    )}
                    {row.kind === 'user' && <UserDot name={row.name} />}
                    <span className="wbc-td-name">{row.name}</span>
                  </div>

                  {(isHeader || hideValue) ? (
                    walletType === 'single' ? (
                      <div className="wbc-td wbc-td-amt wbc-td-amt-empty" />
                    ) : (
                      activeChannels.map(chId => <div key={chId} className="wbc-td wbc-td-amt wbc-td-amt-empty" />)
                    )
                  ) : (
                    walletType === 'single' ? (
                      <div className="wbc-td wbc-td-amt">
                        <span className="wbc-amount-inline">
                          <RiyalMark size={13} currency={currency} />
                          <span>{fmtNum(getAlloc(row, 'single'))}</span>
                        </span>
                      </div>
                    ) : (
                      activeChannels.map(chId => (
                        <div key={chId} className="wbc-td wbc-td-amt">
                          <span className="wbc-amount-inline">
                            <RiyalMark size={13} currency={currency} />
                            <span>{fmtNum(getAlloc(row, chId))}</span>
                          </span>
                        </div>
                      ))
                    )
                  )}

                  <div className="wbc-td wbc-td-xfer">
                    {!isHeader && !hideValue && (
                      <button className="wbc-xfer-btn" onClick={() => openDrawer(row)} title={t.wbTransfer}>
                        <TransferIcon size={15} />
                      </button>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
          {/* No pagination — the table is a hierarchy tree, "pages" don't
              have a sensible definition over expanded/collapsed branches. */}
        </div>
        </div>
      </div>

      {drawerFor && (
        <BalanceTransferDrawer
          source={drawerFor}
          rows={tableRows}
          masterName={selectedNode?.name}
          channels={walletType === 'multiple' ? activeChannels : null}
          walletType={walletType}
          balanceType={balanceType}
          noMaster={true}
          getAlloc={getAlloc}
          t={t}
          onClose={() => setDrawerFor(null)}
          onConfirm={onConfirmTransfer}
        />
      )}
    </div>
  );
};

// ---- Falcon / Client perspective picker for the Wallet page ----
const WbViewAsPicker = ({ t, onPick }) => (
  <div className="tpl-picker-page">
    <div className="tpl-picker-card">
      <div className="tpl-picker-head">
        <div>
          <h2>{t.wbPickerTitle}</h2>
          <p>{t.wbPickerSubtitle}</p>
        </div>
      </div>
      <div className="tpl-picker-grid">
        <button className="tpl-picker-tile falcon" onClick={() => onPick('falcon')}>
          <span className="ic-wrap"><T2Mark size={28} color="white" /></span>
          <span className="ttl">{t.wbShowAsFalcon}</span>
          <span className="dsc">{t.wbShowAsFalconDesc}</span>
          <span className="cta">{t.wbShowAsFalcon} <IcChevronRight size={14} stroke={2} /></span>
        </button>
        <button className="tpl-picker-tile client" onClick={() => onPick('client')}>
          <span className="ic-wrap"><IcBuildingS size={26} stroke={1.7} /></span>
          <span className="ttl">{t.wbShowAsClient}</span>
          <span className="dsc">{t.wbShowAsClientDesc}</span>
          <span className="cta">{t.wbShowAsClient} <IcChevronRight size={14} stroke={2} /></span>
        </button>
      </div>
    </div>
  </div>
);

window.ClientWalletView = ClientWalletView;
window.WbViewAsPicker = WbViewAsPicker;
