// Local Users, franchise account directory for HQ / corporate users
// Lets corporate staff search, browse and mirror any franchise account view

const { useState: useStateLU } = React;

// ── Sample data, FreshNest franchise operators ──────────────────────────
const FRESHNEST_LOCAL_USERS = [
  { id: 1,  name: "Alicia Weber",     email: "aweber@westlake.freshnest.com",     role: "Local",           lastLoginRaw: new Date(2026, 0, 6),   lastLogin: "Jan 6, 2026",  enabled: true,  locationCount: 2, locations: "#746 Lenexa, KS",            initials: "AW" },
  { id: 2,  name: "Aaron Rogelstad",  email: "arogelstad@brentwood.freshnest.com", role: "Local",           lastLoginRaw: new Date(2025, 8, 8),   lastLogin: "Sep 8, 2025",  enabled: true,  locationCount: 1, locations: "#672 Brentwood, TN",          initials: "AR" },
  { id: 3,  name: "Boyd Hathaway",    email: "bhathaway@denver.freshnest.com",     role: "Local",           lastLoginRaw: new Date(2025, 6, 14),  lastLogin: "Jul 14, 2025", enabled: true,  locationCount: 6, locations: "#274 Denver, CO",             initials: "BH" },
  { id: 4,  name: "Darin Krum",       email: "dkrum@eastham.freshnest.com",        role: "Local",           lastLoginRaw: new Date(2026, 4, 27),  lastLogin: "May 27, 2026", enabled: true,  locationCount: 1, locations: "#689 Eastham, MA",            initials: "DK" },
  { id: 5,  name: "Lauren Reabold",   email: "lreabold@cleveland.freshnest.com",   role: "Local",           lastLoginRaw: new Date(2024, 0, 31),  lastLogin: "Jan 31, 2024", enabled: true,  locationCount: 1, locations: "#663 Cleveland, OH",          initials: "LR" },
  { id: 6,  name: "Alisa Coccari",    email: "acoccari@bonita.freshnest.com",      role: "Local",           lastLoginRaw: new Date(2026, 2, 2),   lastLogin: "Mar 2, 2026",  enabled: true,  locationCount: 9, locations: "#525 Bonita Springs, FL",     initials: "AC" },
  { id: 7,  name: "Darin Fleming",    email: "dfleming@shelby.freshnest.com",      role: "Local",           lastLoginRaw: new Date(2026, 5, 12),  lastLogin: "Jun 12, 2026", enabled: true,  locationCount: 1, locations: "#702 Shelby, OH",             initials: "DF" },
  { id: 8,  name: "Steve Modi",       email: "smodi@littlerock.freshnest.com",     role: "Local",           lastLoginRaw: new Date(2024, 11, 2),  lastLogin: "Dec 2, 2024",  enabled: true,  locationCount: 1, locations: "#668 Little Rock, AR",        initials: "SM" },
  { id: 9,  name: "Elena Nelson",     email: "enelson@minneapolis.freshnest.com",  role: "Local",           lastLoginRaw: new Date(2026, 5, 11),  lastLogin: "Jun 11, 2026", enabled: true,  locationCount: 2, locations: "#627 Minneapolis, MN",        initials: "EN" },
  { id: 10, name: "Bryan Andrejko",   email: "bandrejko@freshnest.com",            role: "Corporate-Local", lastLoginRaw: new Date(2021, 9, 29),  lastLogin: "Oct 29, 2021", enabled: true,  locationCount: 0, locations: "–",                          initials: "BA" },
  { id: 11, name: "Alicia Chen",      email: "alicia@freshnest.com",              role: "Local",           lastLoginRaw: new Date(2026, 5, 19),  lastLogin: "Jun 19, 2026", enabled: true,  locationCount: 4, locations: "#1042 Austin Downtown, TX",     initials: "AC" },
  { id: 12, name: "Jason Wu",         email: "jwu@portland.freshnest.com",         role: "Local",           lastLoginRaw: new Date(2026, 5, 5),   lastLogin: "Jun 5, 2026",  enabled: false, locationCount: 1, locations: "#388 Portland, OR",           initials: "JW" },
  { id: 13, name: "Carmen Ibarra",    email: "cibarra@phoenix.freshnest.com",      role: "Local",           lastLoginRaw: new Date(2026, 4, 18),  lastLogin: "May 18, 2026", enabled: true,  locationCount: 4, locations: "#219 Phoenix, AZ",            initials: "CI" },
  { id: 14, name: "Reggie Thornton",  email: "rthornton@atlanta.freshnest.com",    role: "Local",           lastLoginRaw: new Date(2026, 5, 20),  lastLogin: "Jun 20, 2026", enabled: true,  locationCount: 1, locations: "#094 Atlanta, GA",            initials: "RT" },
  { id: 15, name: "Priya Anand",      email: "panand@chicago.freshnest.com",       role: "Local",           lastLoginRaw: new Date(2026, 5, 22),  lastLogin: "Jun 22, 2026", enabled: true,  locationCount: 2, locations: "#177 Chicago, IL",            initials: "PA" },
  { id: 16, name: "Marcus Bell",      email: "mbell@houston.freshnest.com",        role: "Local",           lastLoginRaw: new Date(2026, 5, 10),  lastLogin: "Jun 10, 2026", enabled: true,  locationCount: 5, locations: "#332 Houston, TX",            initials: "MB" },
  { id: 17, name: "Tanya Volkov",     email: "tvolkov@seattle.freshnest.com",      role: "Local",           lastLoginRaw: new Date(2026, 3, 14),  lastLogin: "Apr 14, 2026", enabled: true,  locationCount: 1, locations: "#413 Seattle, WA",            initials: "TV" },
  { id: 18, name: "Nadia Osei",       email: "nosei@nashville.freshnest.com",      role: "Local",           lastLoginRaw: new Date(2026, 5, 1),   lastLogin: "Jun 1, 2026",  enabled: true,  locationCount: 2, locations: "#581 Nashville, TN",          initials: "NO" },
  { id: 19, name: "Derek Paulson",    email: "dpaulson@boston.freshnest.com",      role: "Local",           lastLoginRaw: new Date(2025, 11, 8),  lastLogin: "Dec 8, 2025",  enabled: false, locationCount: 1, locations: "#229 Boston, MA",             initials: "DP" },
  { id: 20, name: "Isabel Ferreira",  email: "iferreira@miami.freshnest.com",      role: "Local",           lastLoginRaw: new Date(2026, 5, 21),  lastLogin: "Jun 21, 2026", enabled: true,  locationCount: 3, locations: "#768 Miami, FL",              initials: "IF" },
  { id: 21, name: "Chris Yamamoto",   email: "cyamamoto@sandiego.freshnest.com",   role: "Local",           lastLoginRaw: new Date(2026, 4, 30),  lastLogin: "May 30, 2026", enabled: true,  locationCount: 1, locations: "#839 San Diego, CA",          initials: "CY" },
  { id: 22, name: "Fatima Al-Hassan", email: "falhassan@dallas.freshnest.com",     role: "Local",           lastLoginRaw: new Date(2026, 5, 17),  lastLogin: "Jun 17, 2026", enabled: true,  locationCount: 4, locations: "#156 Dallas, TX",             initials: "FA" },
];

// Avatar color palette, cycles through brand slots
const AVATAR_COLORS = [
  { bg: 'rgba(0,29,85,0.09)',    fg: 'var(--la-brand-secondary-700,#001e40)' },
  { bg: 'rgba(242,128,32,0.10)', fg: 'var(--la-brand-primary-600,#b35f18)'  },
  { bg: 'rgba(13,138,138,0.10)',  fg: '#0a6666'                               },
  { bg: 'rgba(237,169,26,0.12)', fg: '#886805'                               },
];

function LocalUsersPage({ onMirror }) {
  const [search, setSearch] = useStateLU('');
  const [roleFilter, setRoleFilter] = useStateLU('all');
  const [sortCol, setSortCol] = useStateLU('lastLoginRaw');
  const [sortDir, setSortDir] = useStateLU('desc');
  const [pg, setPg] = useStateLU(1);
  const PER_PAGE = 12;

  const filtered = FRESHNEST_LOCAL_USERS.filter(u => {
    const q = search.toLowerCase();
    const matchQ = !q ||
      u.name.toLowerCase().includes(q) ||
      u.email.toLowerCase().includes(q) ||
      u.locations.toLowerCase().includes(q);
    const matchRole =
      roleFilter === 'all' ||
      (roleFilter === 'local' && u.role === 'Local') ||
      (roleFilter === 'corp'  && u.role === 'Corporate-Local');
    return matchQ && matchRole;
  });

  const sorted = [...filtered].sort((a, b) => {
    let va = a[sortCol], vb = b[sortCol];
    if (typeof va === 'string') { va = va.toLowerCase(); vb = vb.toLowerCase(); }
    if (va < vb) return sortDir === 'asc' ? -1 : 1;
    if (va > vb) return sortDir === 'asc' ?  1 : -1;
    return 0;
  });

  const totalPages = Math.max(1, Math.ceil(sorted.length / PER_PAGE));
  const rows = sorted.slice((pg - 1) * PER_PAGE, pg * PER_PAGE);

  function toggleSort(col) {
    if (sortCol === col) setSortDir(d => d === 'asc' ? 'desc' : 'asc');
    else { setSortCol(col); setSortDir('asc'); }
    setPg(1);
  }

  const SortInd = ({ col }) => {
    if (sortCol !== col) return <span style={{ opacity: 0.2, marginLeft: 3, fontSize: 10 }}>↕</span>;
    return <span style={{ marginLeft: 3, fontSize: 10, color: 'var(--la-brand-primary-500)' }}>{sortDir === 'asc' ? '↑' : '↓'}</span>;
  };

  const COL_STYLE = {
    padding: '10px 14px',
    fontSize: 10.5, fontWeight: 700,
    letterSpacing: '0.07em', textTransform: 'uppercase',
    color: 'var(--la-text-muted)',
    borderBottom: '1.5px solid var(--la-border-subtle)',
    whiteSpace: 'nowrap', userSelect: 'none',
    fontFamily: 'var(--la-font-ui)',
    background: 'var(--la-surface)',
  };

  return (
    <div className="page active">

      {/* ── Page header ───────────────────────────────────────────── */}
      <div className="page-header">
        <div>
          <div className="page-title">Local users</div>
          <div className="page-sub">
            {filtered.length} of {FRESHNEST_LOCAL_USERS.length} franchise accounts
            <span style={{ margin: '0 6px', opacity: 0.35 }}>·</span>
            mirror any view to assist on a call
          </div>
        </div>

        <div className="page-actions" style={{ gap: 8 }}>
          {/* Search */}
          <div style={{ position: 'relative' }}>
            <span style={{
              position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)',
              color: 'var(--la-text-muted)', pointerEvents: 'none', display: 'flex',
            }}>
              {Icon.search}
            </span>
            <input
              value={search}
              onChange={e => { setSearch(e.target.value); setPg(1); }}
              placeholder="Search by name, email, or location…"
              style={{
                paddingLeft: 34, paddingRight: 12, paddingTop: 8, paddingBottom: 8,
                fontSize: 13.5, fontFamily: 'var(--la-font-ui)',
                border: '1.5px solid var(--la-border-default)',
                borderRadius: 'var(--la-control-corner)', outline: 'none', width: 280,
                background: 'var(--la-surface-raised)', color: 'var(--la-text-body)',
                transition: 'border-color 180ms, box-shadow 180ms',
              }}
              onFocus={e => {
                e.target.style.borderColor = 'var(--la-brand-primary-400)';
                e.target.style.boxShadow = '0 0 0 3px rgba(242,128,32,0.14)';
              }}
              onBlur={e => {
                e.target.style.borderColor = 'var(--la-border-default)';
                e.target.style.boxShadow = 'none';
              }}
            />
          </div>

          {/* Role filter */}
          <div style={{ position: 'relative' }}>
            <select
              value={roleFilter}
              onChange={e => { setRoleFilter(e.target.value); setPg(1); }}
              style={{
                padding: '8px 30px 8px 12px', fontSize: 13.5,
                fontFamily: 'var(--la-font-ui)',
                border: '1.5px solid var(--la-border-default)',
                borderRadius: 'var(--la-control-corner)', outline: 'none',
                background: 'var(--la-surface-raised)', color: 'var(--la-text-body)',
                cursor: 'pointer', appearance: 'none', WebkitAppearance: 'none',
              }}
            >
              <option value="all">All roles</option>
              <option value="local">Local</option>
              <option value="corp">Corporate-Local</option>
            </select>
            <span style={{
              position: 'absolute', right: 10, top: '50%', transform: 'translateY(-50%)',
              pointerEvents: 'none', color: 'var(--la-text-muted)', fontSize: 11,
            }}>⌄</span>
          </div>

          {/* Export (demo, not wired to a real export) */}
          <button
            onClick={() => window.toast && window.toast('Export', 'Demo only, export isn’t wired up in this prototype.', 'info')}
            style={{
              display: 'inline-flex', alignItems: 'center', gap: 7,
              padding: '8px 16px', fontSize: 13.5, fontWeight: 700,
              fontFamily: 'var(--la-font-ui)',
              background: 'var(--la-brand-secondary-surface,#001e40)', color: '#fff',
              border: 'none', borderRadius: 'var(--la-control-corner)',
              cursor: 'pointer', whiteSpace: 'nowrap',
              transition: 'background 140ms, transform 100ms',
            }}
            onMouseEnter={e => { e.currentTarget.style.background = '#001132'; e.currentTarget.style.transform = 'translateY(-1px)'; }}
            onMouseLeave={e => { e.currentTarget.style.background = 'var(--la-brand-secondary-surface,#001e40)'; e.currentTarget.style.transform = 'none'; }}
          >
            <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="M7 10l5 5 5-5"/><path d="M12 15V3"/>
            </svg>
            Export
          </button>
        </div>
      </div>

      {/* ── Table ─────────────────────────────────────────────────── */}
      <div style={{
        background: 'var(--la-surface-raised)',
        border: '1px solid var(--la-border-subtle)',
        borderRadius: 'var(--la-container-corner)',
        overflow: 'hidden',
        boxShadow: 'var(--la-shadow-sm)',
      }}>
        <div style={{ overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 760 }}>

            <thead>
              <tr>
                {[
                  { col: 'name',          label: 'Name',             align: 'left',   w: '17%',   sortable: true  },
                  { col: 'email',         label: 'Email',            align: 'left',   w: '22%',   sortable: true  },
                  { col: 'role',          label: 'Role',             align: 'left',   w: '13%',   sortable: true  },
                  { col: 'lastLoginRaw',  label: 'Last login',       align: 'left',   w: '13%',   sortable: true  },
                  { col: 'enabled',       label: 'Enabled',          align: 'left',   w: '9%',    sortable: true  },
                  { col: 'locationCount', label: 'Loc. count',       align: 'center', w: '9%',    sortable: true  },
                  { col: 'locations',     label: 'Primary location', align: 'left',   w: 'auto',  sortable: false },
                  { col: null,            label: '',                  align: 'right',  w: '120px', sortable: false },
                ].map(({ col, label, align, w, sortable }) => (
                  <th key={col || 'action'} onClick={() => sortable && col && toggleSort(col)}
                    style={{ ...COL_STYLE, textAlign: align, width: w, cursor: sortable ? 'pointer' : 'default' }}>
                    {label}{sortable && col && <SortInd col={col}/>}
                  </th>
                ))}
              </tr>
            </thead>

            <tbody>
              {rows.length === 0 && (
                <tr>
                  <td colSpan={8} style={{
                    padding: '48px 20px', textAlign: 'center',
                    color: 'var(--la-text-muted)', fontSize: 14,
                    fontFamily: 'var(--la-font-ui)',
                  }}>
                    No users match your search.
                  </td>
                </tr>
              )}

              {rows.map((u, i) => {
                const av = AVATAR_COLORS[u.id % AVATAR_COLORS.length];
                return (
                  <tr key={u.id}
                    onClick={() => u.locationCount > 0 && onMirror(u)}
                    title={u.locationCount > 0 ? `Open ${u.name}'s local experience` : undefined}
                    style={{
                      borderBottom: i < rows.length - 1 ? '1px solid var(--la-border-subtle)' : 'none',
                      transition: 'background 100ms',
                      cursor: u.locationCount > 0 ? 'pointer' : 'default',
                    }}
                    onMouseEnter={e => e.currentTarget.style.background = 'var(--la-surface)'}
                    onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
                  >

                    {/* Name */}
                    <td style={{ padding: '11px 14px' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
                        <div style={{
                          width: 28, height: 28, borderRadius: '50%', flexShrink: 0,
                          background: av.bg, color: av.fg,
                          display: 'flex', alignItems: 'center', justifyContent: 'center',
                          fontSize: 10, fontWeight: 700, fontFamily: 'var(--la-font-ui)',
                          letterSpacing: '0.03em',
                        }}>{u.initials}</div>
                        <span style={{
                          fontSize: 13.5, fontWeight: 600,
                          color: 'var(--la-text-heading)',
                          fontFamily: 'var(--la-font-ui)', whiteSpace: 'nowrap',
                        }}>{u.name}</span>
                      </div>
                    </td>

                    {/* Email */}
                    <td style={{ padding: '11px 14px' }}>
                      <span style={{
                        fontSize: 13, color: 'var(--la-brand-secondary-600)',
                        fontFamily: 'var(--la-font-ui)',
                      }}>{u.email}</span>
                    </td>

                    {/* Role */}
                    <td style={{ padding: '11px 14px' }}>
                      <span style={{
                        display: 'inline-block', padding: '2px 9px', borderRadius: 999,
                        fontSize: 11, fontWeight: 700, fontFamily: 'var(--la-font-ui)',
                        background: u.role === 'Corporate-Local' ? 'rgba(237,169,26,0.13)' : 'rgba(0,29,85,0.07)',
                        color:      u.role === 'Corporate-Local' ? '#886805' : 'var(--la-brand-secondary-700)',
                      }}>{u.role}</span>
                    </td>

                    {/* Last login */}
                    <td style={{
                      padding: '11px 14px', fontSize: 13,
                      color: 'var(--la-text-body)', fontFamily: 'var(--la-font-ui)', whiteSpace: 'nowrap',
                    }}>{u.lastLogin}</td>

                    {/* Enabled */}
                    <td style={{ padding: '11px 14px' }}>
                      <span style={{
                        display: 'inline-flex', alignItems: 'center', gap: 5,
                        fontSize: 12.5, fontWeight: 600, fontFamily: 'var(--la-font-ui)',
                        color: u.enabled ? '#17743f' : 'var(--la-text-muted)',
                      }}>
                        <span style={{
                          width: 7, height: 7, borderRadius: '50%', flexShrink: 0,
                          background: u.enabled ? '#1f9d55' : 'var(--la-border-default)',
                          display: 'inline-block',
                        }}/>
                        {u.enabled ? 'Yes' : 'No'}
                      </span>
                    </td>

                    {/* Location count */}
                    <td style={{ padding: '11px 14px', textAlign: 'center' }}>
                      {u.locationCount > 0 ? (
                        <span style={{
                          fontSize: 13.5, fontWeight: 700, fontFamily: 'var(--la-font-ui)',
                          color: u.locationCount > 1
                            ? 'var(--la-brand-secondary-600)' : 'var(--la-text-body)',
                        }}>{u.locationCount}</span>
                      ) : (
                        <span style={{ color: 'var(--la-text-faint)', fontSize: 13 }}>–</span>
                      )}
                    </td>

                    {/* Primary location */}
                    <td style={{
                      padding: '11px 14px', fontSize: 12.5,
                      color: 'var(--la-text-muted)', fontFamily: 'var(--la-font-ui)',
                    }}>{u.locations}</td>

                    {/* Mirror action */}
                    <td style={{ padding: '11px 14px', textAlign: 'right' }}>
                      {u.locationCount > 0 && (
                        <button
                          onClick={(e) => { e.stopPropagation(); onMirror(u); }}
                          style={{
                            display: 'inline-flex', alignItems: 'center', gap: 5,
                            padding: '5px 13px', fontSize: 12, fontWeight: 700,
                            fontFamily: 'var(--la-font-ui)',
                            background: 'transparent',
                            border: '1.5px solid rgba(0,29,85,0.22)',
                            borderRadius: 999,
                            color: 'var(--la-brand-secondary-700)',
                            cursor: 'pointer', whiteSpace: 'nowrap',
                            transition: 'background 140ms, border-color 140ms, color 140ms',
                          }}
                          onMouseEnter={e => {
                            e.currentTarget.style.background = 'var(--la-brand-secondary-surface,#001e40)';
                            e.currentTarget.style.borderColor = 'var(--la-brand-secondary-surface,#001e40)';
                            e.currentTarget.style.color = '#fff';
                          }}
                          onMouseLeave={e => {
                            e.currentTarget.style.background = 'transparent';
                            e.currentTarget.style.borderColor = 'rgba(0,29,85,0.22)';
                            e.currentTarget.style.color = 'var(--la-brand-secondary-700)';
                          }}
                        >
                          <svg viewBox="0 0 24 24" width="11" height="11" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                            <path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7z"/>
                            <circle cx="12" cy="12" r="3"/>
                          </svg>
                          Mirror view
                        </button>
                      )}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

        {/* ── Pagination ─────────────────────────────────────────── */}
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          padding: '11px 16px',
          borderTop: '1px solid var(--la-border-subtle)',
          background: 'var(--la-surface)',
        }}>
          <div style={{
            fontSize: 12.5, color: 'var(--la-text-muted)',
            fontFamily: 'var(--la-font-ui)',
          }}>
            Items per page: <strong style={{ color: 'var(--la-text-body)' }}>{PER_PAGE}</strong>
            <span style={{ margin: '0 8px', opacity: 0.35 }}>·</span>
            {sorted.length === 0 ? '0' : `${(pg - 1) * PER_PAGE + 1}–${Math.min(pg * PER_PAGE, sorted.length)}`} of {sorted.length}
          </div>
          <div style={{ display: 'flex', gap: 3 }}>
            {[
              { lbl: '⟨⟨', act: () => setPg(1),              dis: pg <= 1           },
              { lbl: '‹',   act: () => setPg(p => p - 1),    dis: pg <= 1           },
              { lbl: '›',   act: () => setPg(p => p + 1),    dis: pg >= totalPages  },
              { lbl: '⟩⟩', act: () => setPg(totalPages),     dis: pg >= totalPages  },
            ].map(b => (
              <button key={b.lbl} onClick={b.act} disabled={b.dis} style={{
                width: 28, height: 28, borderRadius: 6,
                border: '1px solid var(--la-border-subtle)',
                background: b.dis ? 'transparent' : 'var(--la-surface-raised)',
                color: b.dis ? 'var(--la-text-faint)' : 'var(--la-text-body)',
                cursor: b.dis ? 'default' : 'pointer',
                fontSize: 12, fontWeight: 700,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>{b.lbl}</button>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

window.LocalUsersPage = LocalUsersPage;
window.FRESHNEST_LOCAL_USERS = FRESHNEST_LOCAL_USERS;
