/* ========================================================================
   TERRITORIES — Company → Territories (admin). Named ownership patches
   defined with the shared filter panel; live overlap detection; user →
   territory assignment table. Port of js/13-territories.js.
   ======================================================================== */

/* ---- overlap math --------------------------------------------------------- */
function _terrAcctKey(a) { return a.accountId || a.name; }
function territoryAccountSet(filters) {
  const ids = new Set();
  const active = (filters || []).filter(isFilterComplete);
  if (!active.length) return ids;
  applyFilters(ACCOUNTS, active, 'accounts').forEach(a => ids.add(_terrAcctKey(a)));
  return ids;
}
function setOverlapCount(a, b) {
  let n = 0;
  const [small, big] = a.size <= b.size ? [a, b] : [b, a];
  small.forEach(k => { if (big.has(k)) n++; });
  return n;
}
function territoryEditorHideField(f) {
  if (f.id === 'account.territory') return true;
  return f.group !== 'Account' && f.group !== 'Location';
}
function salesforceOn() { return !!(window.TWEAKS && window.TWEAKS.salesforceIntegrated); }

/* ---- manual assignment stores --------------------------------------------- */
var TERRITORY_USER_ASSIGNMENTS = {};
var TERRITORY_MANUAL = {};
function manualTerritoryFilters(userId) {
  if (salesforceOn()) return null;
  const f = TERRITORY_MANUAL[userId];
  return (f && f.length) ? f : null;
}
function setManualTerritory(userId, filters) {
  if (filters && filters.length) TERRITORY_MANUAL[userId] = filters;
  else delete TERRITORY_MANUAL[userId];
}
function userOwnsTerritory(userId) {
  return territoriesForUser(userId).length > 0 || !!manualTerritoryFilters(userId);
}
function assignmentUsers() { return [ADMIN_USER, ...TEAM_MEMBERS]; }
function territoriesForUser(userId) {
  if (salesforceOn()) {
    const u = assignmentUsers().find(x => x.id === userId);
    if (!u) return [];
    return TERRITORIES.filter(t => t.owner && t.owner === u.name).map(t => t.id);
  }
  return (TERRITORY_USER_ASSIGNMENTS[userId] || []).filter(id => territoryById(id));
}
function toggleUserTerritory(userId, terrId) {
  const cur = TERRITORY_USER_ASSIGNMENTS[userId] || (TERRITORY_USER_ASSIGNMENTS[userId] = []);
  const i = cur.indexOf(terrId);
  if (i >= 0) cur.splice(i, 1); else cur.push(terrId);
}
function userAvatarColor(u) {
  if (u.id === ADMIN_USER.id) return 'var(--ps-primary-500)';
  const palette = ['#805cb7', '#43825c', '#3e4ccc', '#847b2b'];
  let h = 0; for (const c of u.id) h = (h * 31 + c.charCodeAt(0)) | 0;
  return palette[Math.abs(h) % palette.length];
}

/* ---- editor state ----------------------------------------------------------- */
var terrEdit = null;   // { id: 'new'|territoryId, name, panel }
function startNewTerritory() { openTerritoryEditor('new', '', []); }
function startEditTerritory(id) {
  const t = territoryById(id);
  if (!t) return;
  openTerritoryEditor(id, t.name, t.filters || []);
}
function openTerritoryEditor(id, name, filters) {
  const panel = {
    state: {
      entity: 'accounts',
      filters: (filters || []).map(f => ({ id: uid(), fieldId: f.fieldId, op: f.op, value: deepClone(f.value) })),
      openFieldId: null,
      editorAnchor: null,
    },
    opts: { hideField: territoryEditorHideField },
    afterMutation() {},
  };
  window.activeFilterPanel = panel;
  terrEdit = { id, name, panel };
  notify();
}
function teardownTerritoryEditor() {
  if (!terrEdit) return;
  window.activeFilterPanel = null;
  terrEdit = null;
}
function cancelTerritoryEdit() { teardownTerritoryEditor(); notify(); }
function saveTerritoryEdit() {
  if (!terrEdit) return;
  const name = (terrEdit.name || '').trim();
  const filters = terrEdit.panel.state.filters.filter(isFilterComplete);
  if (!name || !filters.length) return;
  const stamped = filters.map(f => ({ fieldId: f.fieldId, op: f.op, value: deepClone(f.value) }));
  const wasNew = terrEdit.id === 'new';
  if (wasNew) {
    TERRITORIES.push({ id: 't-' + Math.random().toString(36).slice(2, 7), name, owner: '', filters: stamped, _spec: null });
  } else {
    const t = territoryById(terrEdit.id);
    if (t) { t.name = name; t.filters = stamped; t._spec = null; }
  }
  syncTerritoryFieldOptions();
  teardownTerritoryEditor();
  notify();
  showToast({ message: wasNew ? `Territory \u201c${name}\u201d created` : `Territory \u201c${name}\u201d updated`, icon: 'land-plot' });
}

/* ---- editor modal -------------------------------------------------------------- */
function TerritoryEditModal() {
  useAppState();
  if (!terrEdit) return null;
  const isNew = terrEdit.id === 'new';
  const filters = terrEdit.panel.state.filters.filter(isFilterComplete);
  const nameOK = !!(terrEdit.name || '').trim();
  const canSave = nameOK && filters.length > 0;

  let flag;
  if (!filters.length) {
    flag = (
      <div className="terr-flag muted">
        <Icon name="filter" size={14} />
        <span>Add one or more filters below to define which accounts this territory owns.</span>
      </div>
    );
  } else {
    const draftSet = territoryAccountSet(filters);
    const overlaps = TERRITORIES
      .filter(t => t.id !== terrEdit.id)
      .map(t => ({ t, n: setOverlapCount(draftSet, territoryAccountSet(t.filters)) }))
      .filter(o => o.n > 0)
      .sort((a, b) => b.n - a.n);
    if (overlaps.length) {
      const total = overlaps.reduce((s, o) => s + o.n, 0);
      flag = (
        <div className="terr-flag warn">
          <Icon name="triangle-alert" size={14} />
          <div>
            <strong>Overlaps {overlaps.length} existing territor{overlaps.length === 1 ? 'y' : 'ies'}</strong>
            {' '}— {total} account{total === 1 ? '' : 's'} would be owned twice.
            <ul className="terr-flag-list">
              {overlaps.slice(0, 4).map(o => (
                <li key={o.t.id}><span className="tfl-name">{o.t.name}</span> <span className="tfl-count">{o.n} shared</span></li>
              ))}
              {overlaps.length > 4 ? <li><span className="tfl-count">+{overlaps.length - 4} more…</span></li> : null}
            </ul>
          </div>
        </div>
      );
    } else {
      flag = (
        <div className="terr-flag ok">
          <Icon name="check-check" size={14} />
          <span>No overlap — these accounts aren't claimed by any other territory.</span>
        </div>
      );
    }
  }

  return (
    <div className="modal-overlay terr-edit-overlay" role="dialog" aria-modal="true"
      onMouseDown={(e) => { if (e.target === e.currentTarget) cancelTerritoryEdit(); }}>
      <div className="modal terr-modal">
        <div className="modal-header">
          <div className="modal-title">{isNew ? 'New territory' : 'Edit territory'}</div>
          <button className="modal-close" type="button" aria-label="Close" onClick={cancelTerritoryEdit}>×</button>
        </div>
        <div className="modal-body terr-modal-body">
          <div className="modal-field">
            <label className="modal-field-label" htmlFor="terr-name">Territory name</label>
            <div className="modal-combo-wrap">
              <input className="modal-input" id="terr-name" type="text" autoComplete="off" autoFocus
                placeholder="e.g. Pacific Northwest K-12"
                value={terrEdit.name}
                onChange={(e) => { terrEdit.name = e.target.value; notify(); }}
                onKeyDown={(e) => { if (e.key === 'Escape') cancelTerritoryEdit(); }} />
            </div>
          </div>
          <div className="terr-help">Pick the accounts this territory owns using account &amp; location filters. The match count and any overlap with existing territories update as you go.</div>
          <div className="terr-overlap">{flag}</div>
          <div className="modal-field">
            <span className="modal-field-label">Filters</span>
            <div className="terr-panel-slot">
              {filters.length ? (
                <div className="qs-chips" style={{ gap: 8, padding: '4px 0 8px' }}>
                  {filters.map(f => <FilterChip f={f} key={f.id} />)}
                </div>
              ) : null}
              <FieldList panel={terrEdit.panel} />
            </div>
          </div>
        </div>
        <div className="modal-footer">
          <button className="btn-modal" type="button" onClick={cancelTerritoryEdit}>Cancel</button>
          <button className="btn-modal btn-modal-primary" type="button" disabled={!canSave} onClick={saveTerritoryEdit}>
            {isNew ? 'Create territory' : 'Save changes'}
          </button>
        </div>
      </div>
    </div>
  );
}

/* ---- user assignments card -------------------------------------------------------- */
function UserAssignmentsCard() {
  useAppState();
  const [openFor, setOpenFor] = React.useState(null);
  const sfOn = salesforceOn();
  React.useEffect(() => {
    if (openFor === null) return;
    const onDown = (e) => {
      if (e.target.closest('.uat-edit')) return;
      setOpenFor(null);
    };
    document.addEventListener('mousedown', onDown);
    return () => document.removeEventListener('mousedown', onDown);
  }, [openFor]);
  return (
    <AgentCardSection icon="users" title="User assignments" cardClass="uat-card"
      titleExtra={sfOn ? <span className="uat-sync-tag"><Icon name="cloud" size={12} />Synced from Salesforce</span> : null}
      bodyRaw={
        <div className="uat-wrap">
          <p className="uat-intro">{sfOn
            ? 'Each rep\u2019s territories are assigned automatically from Salesforce account ownership and can\u2019t be edited here.'
            : 'Assign each team member to one or more territories. A territory can be shared by multiple reps.'}</p>
          <table className="uat">
            <thead>
              <tr><th>User</th><th>Role</th><th>Assigned territories</th></tr>
            </thead>
            <tbody>
              {assignmentUsers().map(u => {
                const tids = territoriesForUser(u.id);
                const open = openFor === u.id;
                return (
                  <tr className="uat-row" key={u.id}>
                    <td className="uat-c-user">
                      <div className="uat-user">
                        <span className="uat-av" style={{ background: userAvatarColor(u) }}>{u.initials}</span>
                        <span className="uat-user-text">
                          <span className="uat-name">{u.name}</span>
                          <span className="uat-email">{u.email}</span>
                        </span>
                      </div>
                    </td>
                    <td className="uat-c-role"><span className="uat-role">{u.title}</span></td>
                    <td className="uat-c-terr">
                      <div className="uat-terr-inner">
                        <div className="uat-chips">
                          {tids.map(id => {
                            const t = territoryById(id);
                            return <span className="uat-chip" key={id}><Icon name="map-pin" size={12} />{t ? t.name : id}</span>;
                          })}
                          {manualTerritoryFilters(u.id) ? (
                            <span className="uat-chip uat-chip-manual" title="Defined by the user on their Account page">
                              <Icon name="user-round-pen" size={12} />Manually set
                            </span>
                          ) : null}
                          {(!tids.length && !manualTerritoryFilters(u.id)) ? (
                            <span className="uat-none">{sfOn ? 'No territory in Salesforce' : 'Unassigned'}</span>
                          ) : null}
                        </div>
                        {!sfOn ? (
                          <div className={cx('uat-edit', open && 'open')}>
                            <button className="uat-edit-btn" type="button" aria-expanded={open}
                              onClick={(e) => { e.stopPropagation(); setOpenFor(open ? null : u.id); }}>
                              <Icon name={tids.length ? 'pencil' : 'plus'} size={13} />{tids.length ? 'Edit' : 'Assign'}
                            </button>
                            {open ? (
                              <div className="uat-pop" onMouseDown={(e) => e.stopPropagation()}>
                                <div className="uat-pop-head">Assign territories</div>
                                {TERRITORIES.length ? (
                                  <div className="uat-pop-list">
                                    {TERRITORIES.map(t => {
                                      const on = new Set(territoriesForUser(u.id)).has(t.id);
                                      const n = territoryAccountSet(t.filters).size;
                                      return (
                                        <label className={cx('uat-pop-row', on && 'on')} key={t.id}>
                                          <input type="checkbox" checked={on}
                                            onChange={() => { toggleUserTerritory(u.id, t.id); notify(); }} />
                                          <span className="uat-pop-name">{t.name}</span>
                                          <span className="uat-pop-count" title={`${n} account${n === 1 ? '' : 's'}`}>{n}</span>
                                        </label>
                                      );
                                    })}
                                  </div>
                                ) : (
                                  <div className="uat-pop-empty">No territories yet. Create one above, then assign it here.</div>
                                )}
                              </div>
                            ) : null}
                          </div>
                        ) : null}
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      } />
  );
}

/* ---- the page ----------------------------------------------------------------------- */
function TerritoriesPage() {
  useAppState();
  const sfOn = salesforceOn();
  const sets = TERRITORIES.map(t => ({ t, set: territoryAccountSet(t.filters) }));
  return (
    <div className="body">
      <div className="content-panel">
        <div id="work-area">
          <div data-role="agent">
            <div className="agent-work terr-page">
              <div className="detail-head">
                <div className="detail-head-text">
                  <div className="detail-record-name-row">
                    <h1 className="detail-record-name">Territories</h1>
                  </div>
                  <p className="terr-intro">Carve your accounts into named ownership patches. Define each territory with filters — Pursuit flags any overlap so two reps never own the same account.</p>
                  {!sfOn ? <p className="terr-intro terr-intro-sf">Integrate your Salesforce instance to automatically manage your territories.</p> : null}
                  {sfOn ? (
                    <div className="terr-sync-note"><Icon name="cloud" size={14} /><span>Synced from <strong>Salesforce</strong> — territories are managed in Salesforce and can't be added here.</span></div>
                  ) : null}
                </div>
                {!sfOn ? (
                  <button className="btn-secondary-cta terr-sf-connect" type="button"
                    onClick={() => {
                      if (typeof setSalesforceIntegration === 'function') setSalesforceIntegration(true);
                      showToast({ message: 'Salesforce integrated — territories are now synced', icon: 'cloud' });
                    }}>
                    <span className="icon-frame"><Icon name="cloud" size={16} /></span>
                    Integrate Salesforce
                  </button>
                ) : null}
              </div>
              {(!sfOn && !TERRITORIES.length) ? (
                <p className="terr-empty-hint">No territories yet. Create one to start dividing up your accounts.</p>
              ) : null}
              <div className="agent-index-grid terr-grid">
                {sets.map(({ t, set }) => {
                  const overlapNames = sets
                    .filter(s => s.t.id !== t.id && setOverlapCount(set, s.set) > 0)
                    .map(s => s.t.name);
                  return (
                    <button className="agent-index-card terr-card" type="button" key={t.id} onClick={() => startEditTerritory(t.id)}>
                      <div className="terr-card-top">
                        <h3 className="terr-card-title">{t.name}</h3>
                        {overlapNames.length ? (
                          <span className="terr-overlap-badge">
                            <Icon name="triangle-alert" size={12} />
                            Overlaps with {overlapNames[0]}{overlapNames.length > 1 ? ` +${overlapNames.length - 1}` : ''}
                          </span>
                        ) : null}
                      </div>
                      <div className="terr-card-chips">
                        {(t.filters || []).length ? (
                          <div className="qs-chips" style={{ gap: 8 }}>
                            {(t.filters || []).map((f, i) => <AgentFilterChip f={f} key={i} />)}
                          </div>
                        ) : (
                          <div className="qs-meta" style={{ padding: '6px 2px' }}>No filters set.</div>
                        )}
                      </div>
                    </button>
                  );
                })}
                {!sfOn ? (
                  <button className="agent-index-new" type="button" onClick={startNewTerritory}>
                    <span className="aix-new-icon"><Icon name="plus" size={16} /></span>
                    <span className="aix-new-text">
                      <strong>New territory</strong>
                      <span>Define a new ownership patch</span>
                    </span>
                  </button>
                ) : null}
              </div>
              <UserAssignmentsCard />
            </div>
          </div>
        </div>
      </div>
      <TerritoryEditModal />
    </div>
  );
}
function TerritoriesBreadcrumbs() {
  return (
    <div className="breadcrumbs">
      <img src={(window.__resources&&window.__resources.logoColor)||"react/assets/logo-color.svg"} alt="Pursuit" width="14" height="17" />
      <Icon name="chevron-right" className="breadcrumb-sep" size={14} />
      <span className="breadcrumb-item">Company</span>
      <Icon name="chevron-right" className="breadcrumb-sep" size={14} />
      <span className="breadcrumb-item current">Territories</span>
    </div>
  );
}

window.PAGES.territories = TerritoriesPage;
window.PAGE_BREADCRUMBS = window.PAGE_BREADCRUMBS || {};
window.PAGE_BREADCRUMBS.territories = TerritoriesBreadcrumbs;
Object.assign(window, {
  TerritoriesPage, TerritoriesBreadcrumbs, TerritoryEditModal,
  territoryAccountSet, setOverlapCount, salesforceOn,
  manualTerritoryFilters, setManualTerritory, userOwnsTerritory,
  territoriesForUser, toggleUserTerritory, teardownTerritoryEditor,
  startNewTerritory, startEditTerritory, TERRITORY_MANUAL, TERRITORY_USER_ASSIGNMENTS,
});
