/* ========================================================================
   CUSTOM FILTERS — Settings → Custom Filters
   List view (table of system/custom filters) + detail view (Details +
   Filter options on the left, per-option criteria builder on the right).
   ======================================================================== */

/* ---- modal state (create / edit) --------------------------------------- */
let cfModalMode = null;      // null | 'create' | 'edit'
let cfModalFilterId = null;
function openCreateCustomFilter() { cfModalMode = 'create'; cfModalFilterId = null; notify(); }
function openEditCustomFilter(id) { cfModalMode = 'edit'; cfModalFilterId = id; notify(); }
function closeCustomFilterModal() { cfModalMode = null; cfModalFilterId = null; notify(); }

/* ---- header action: "Create new" (list view only) ---------------------- */
function CustomFilterHeaderActions() {
  useAppState();
  if (state.page !== 'custom-filters' || state.customFilterId) return null;
  return (
    <button
      className="btn btn-primary btn-lg cf-create-new"
      type="button"
      onClick={openCreateCustomFilter}
    >
      <Icon name="plus" size={16} />
      Create new
    </button>
  );
}

/* ---- Create / Edit Filter modal ---------------------------------------- */
function CustomFilterModal() {
  useAppState();
  if (!cfModalMode) return null;
  return <CustomFilterModalBody key={cfModalMode + ':' + (cfModalFilterId || 'new')} />;
}

function CustomFilterModalBody() {
  const editing = cfModalMode === 'edit';
  const existing = editing ? customFilterById(cfModalFilterId) : null;
  const [title, setTitle] = React.useState(existing ? existing.title : '');
  const [key, setKey] = React.useState(existing ? existing.key : '');
  const [vis, setVis] = React.useState(existing ? existing.visibility : 'private');
  const nameRef = React.useRef(null);

  React.useEffect(() => { if (nameRef.current) nameRef.current.focus(); }, []);
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') closeCustomFilterModal(); };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, []);

  const canSave = title.trim().length > 0 && key.trim().length > 0;

  const doSave = () => {
    if (!canSave) return;
    if (editing) {
      updateCustomFilter(cfModalFilterId, { title, key, visibility: vis });
      closeCustomFilterModal();
      showToast({ message: `“${title.trim()}” updated`, icon: 'check' });
    } else {
      const f = addCustomFilter({ title, key, visibility: vis });
      closeCustomFilterModal();
      openCustomFilter(f.id);
      showToast({ message: `“${f.title}” created`, icon: 'filter' });
    }
  };

  return (
    <div className="modal-overlay" onMouseDown={(e) => { if (e.target === e.currentTarget) closeCustomFilterModal(); }}>
      <div className="modal" role="dialog" aria-labelledby="cf-modal-title">
        <div className="modal-header">
          <div className="modal-title" id="cf-modal-title">{editing ? 'Edit Filter' : 'Create Custom Filter'}</div>
          <button className="modal-close" aria-label="Close" onClick={closeCustomFilterModal}>×</button>
        </div>
        <div className="modal-body">
          <div className="modal-field">
            <label className="modal-field-label" htmlFor="cf-name-input">Filter Name</label>
            <div className="modal-combo-wrap">
              <input
                ref={nameRef}
                className="modal-input" id="cf-name-input" type="text" autoComplete="off"
                placeholder="e.g. Buying Stage"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); doSave(); } }}
              />
            </div>
          </div>
          <div className="modal-field">
            <label className="modal-field-label" htmlFor="cf-key-input">CRM key</label>
            <div className="modal-combo-wrap">
              <input
                className="modal-input cf-modal-key" id="cf-key-input" type="text" autoComplete="off"
                placeholder="e.g. buying_stage"
                value={key}
                onChange={(e) => setKey(cfSanitizeKey(e.target.value))}
                onKeyDown={(e) => {
                  if (e.key === ' ') e.preventDefault();
                  if (e.key === 'Enter') { e.preventDefault(); doSave(); }
                }}
              />
            </div>
            <p className="cf-modal-help">Key written to your CRM. No spaces — use underscores.</p>
          </div>
          <div className="modal-field">
            <span className="modal-field-label">Sharing</span>
            <div className="cf-share-toggle">
              {[['private', 'Private', 'lock'], ['shared', 'Shared with Company', 'users']].map(([v, label, icon]) => (
                <button
                  key={v} type="button"
                  className={cx('cf-share-btn', vis === v && 'cf-share-btn--on')}
                  onClick={() => setVis(v)}
                >
                  <Icon name={icon} size={15} /> {label}
                </button>
              ))}
            </div>
          </div>
        </div>
        <div className="modal-footer">
          <button className="btn-modal" onClick={closeCustomFilterModal}>Cancel</button>
          <button className="btn-modal btn-modal-primary" disabled={!canSave} onClick={doSave}>Save</button>
        </div>
      </div>
    </div>
  );
}

/* ---- list row “more actions” menu (custom filters only) ----------------- */
function CustomFilterRowMenu({ filter }) {
  const [open, setOpen] = React.useState(false);
  const [pos, setPos] = React.useState(null);
  const btnRef = React.useRef(null);
  const menuRef = React.useRef(null);

  React.useEffect(() => {
    if (!open) return;
    const onDown = (e) => {
      if (menuRef.current && menuRef.current.contains(e.target)) return;
      if (btnRef.current && btnRef.current.contains(e.target)) return;
      setOpen(false);
    };
    const onScroll = () => setOpen(false);
    document.addEventListener('mousedown', onDown);
    window.addEventListener('scroll', onScroll, true);
    return () => {
      document.removeEventListener('mousedown', onDown);
      window.removeEventListener('scroll', onScroll, true);
    };
  }, [open]);

  const toggle = (e) => {
    e.stopPropagation();
    if (open) { setOpen(false); return; }
    const r = btnRef.current.getBoundingClientRect();
    setPos({ top: r.bottom + 6, right: Math.max(8, window.innerWidth - r.right) });
    setOpen(true);
  };

  return (
    <React.Fragment>
      <button ref={btnRef} className="cf-row-menu" type="button" aria-label="More actions" onClick={toggle}>
        <Icon name="ellipsis" size={18} />
      </button>
      {open ? (
        <div
          ref={menuRef} className="cf-menu"
          style={{ position: 'fixed', top: pos.top, right: pos.right, zIndex: 1000 }}
          onClick={(e) => e.stopPropagation()}
        >
          <button className="cf-menu-item" type="button"
            onClick={(e) => { e.stopPropagation(); setOpen(false); openEditCustomFilter(filter.id); }}>
            <Icon name="settings" size={15} /> Settings
          </button>
          <button className="cf-menu-item cf-menu-item--danger" type="button"
            onClick={(e) => {
              e.stopPropagation(); setOpen(false);
              deleteCustomFilter(filter.id);
              showToast({ message: `Deleted “${filter.title}”`, icon: 'trash-2' });
            }}>
            <Icon name="trash-2" size={15} /> Delete
          </button>
        </div>
      ) : null}
    </React.Fragment>
  );
}

/* ---- list view --------------------------------------------------------- */
function CustomFiltersList() {
  useAppState();
  const [sort, setSort] = React.useState({ col: 'name', dir: 'asc' });
  const [expanded, setExpanded] = React.useState(() => new Set());
  const toggleExpand = (id) => setExpanded(prev => {
    const nx = new Set(prev);
    if (nx.has(id)) nx.delete(id); else nx.add(id);
    return nx;
  });
  const openOption = (filterId, optId) => {
    state.customFilterId = filterId;
    state.customFilterOptionId = optId;
    if (state.page !== 'custom-filters') switchPage('custom-filters'); else notify();
  };

  const dirFor = (col) => (sort.col === col ? sort.dir : null);
  const toggleSort = (col) => setSort(s => ({
    col,
    dir: s.col === col && s.dir === 'asc' ? 'desc' : 'asc',
  }));

  const rows = CUSTOM_FILTERS.slice().sort((a, b) => {
    const dir = sort.dir === 'asc' ? 1 : -1;
    if (sort.col === 'items') return (a.options.length - b.options.length) * dir;
    if (sort.col === 'type') return a.type.localeCompare(b.type) * dir;
    if (sort.col === 'key') return a.key.localeCompare(b.key) * dir;
    return a.title.localeCompare(b.title) * dir;
  });

  const SortHead = ({ col, label }) => {
    const d = dirFor(col);
    return (
      <button className="cf-th" type="button" onClick={() => toggleSort(col)}>
        {label}
        <Icon
          name={d === 'asc' ? 'arrow-down' : d === 'desc' ? 'arrow-up' : 'arrow-down'}
          size={15}
          className={cx('cf-th-arrow', !d && 'cf-th-arrow--idle')}
        />
      </button>
    );
  };

  return (
    <div className="cf-scroll">
      <div className="cf-page">
        <div className="cf-page-head">
          <h1 className="cf-page-title">Custom filters</h1>
          <p className="cf-page-sub">Combine multiple data filters and access them from the dashboard</p>
        </div>

        <div className="cf-table card">
          <div className="cf-table-head">
            <div className="cf-col-name"><SortHead col="name" label="Name" /></div>
            <div className="cf-col-type"><SortHead col="type" label="Type" /></div>
            <div className="cf-col-key"><SortHead col="key" label="CRM key" /></div>
            <div className="cf-col-items"><SortHead col="items" label="Items" /></div>
            <div className="cf-col-menu" />
          </div>
          {rows.map(f => {
            const open = expanded.has(f.id);
            const opts = f.options.slice().sort((a, b) => a.value.localeCompare(b.value, undefined, { sensitivity: 'base' }));
            const hasOpts = opts.length > 0;
            return (
              <React.Fragment key={f.id}>
                <div className={cx('cf-row', open && 'cf-row--expanded')} onClick={() => openCustomFilter(f.id)}>
                  <div className="cf-col-name">
                    <span className="cf-row-name">
                      {hasOpts ? (
                        <button
                          className={cx('cf-row-expand', open && 'open')}
                          type="button"
                          aria-label={open ? 'Collapse' : 'Expand'}
                          onClick={(e) => { e.stopPropagation(); toggleExpand(f.id); }}
                        >
                          <Icon name="chevron-right" size={16} />
                        </button>
                      ) : <span className="cf-expand-spacer" />}
                      <Icon name="building-2" size={17} className="cf-row-icon" />
                      <span className="cf-row-label">{f.title}</span>
                      <Icon name="chevron-right" size={16} className="cf-row-chev" />
                    </span>
                  </div>
                  <div className="cf-col-type">
                    <span className="badge neutral cf-type-badge">{f.type}</span>
                  </div>
                  <div className="cf-col-key">
                    <span className="cf-key-code">{f.key}</span>
                  </div>
                  <div className="cf-col-items">
                    <span className="cf-items-count">{f.options.length}</span>
                  </div>
                  <div className="cf-col-menu">
                    {f.systemLocked ? null : <CustomFilterRowMenu filter={f} />}
                  </div>
                </div>
                {open ? opts.map(opt => (
                  <div
                    className="cf-row cf-row--child"
                    key={opt.id}
                    onClick={(e) => { e.stopPropagation(); openOption(f.id, opt.id); }}
                  >
                    <div className="cf-col-name">
                      <span className="cf-row-name cf-child-name">
                        <span className="cf-child-rail" aria-hidden="true"></span>
                        <span className="cf-child-label">{opt.value}</span>
                      </span>
                    </div>
                    <div className="cf-col-type"></div>
                    <div className="cf-col-key">
                      <span className="cf-child-meta">{cfFormatCount(opt.contactsFound)} contacts · {cfFormatCount(opt.accountsFound)} accounts</span>
                    </div>
                    <div className="cf-col-items"></div>
                    <div className="cf-col-menu">
                      <Icon name="chevron-right" size={16} className="cf-row-chev" />
                    </div>
                  </div>
                )) : null}
              </React.Fragment>
            );
          })}
        </div>
      </div>
    </div>
  );
}

/* ---- detail: filter-options nav (floating left panel) ------------------ */
function CustomFilterOptionsNav({ filter }) {
  useAppState();
  const opts = filter.options.slice().sort((a, b) => a.value.localeCompare(b.value, undefined, { sensitivity: 'base' }));
  return (
    <div className="records-nav" id="records-nav">
      <button className="rn-back" type="button" onClick={openCustomFiltersList}>
        <Icon name="arrow-left" size={14} />
        <span className="rn-back-label">Back to Custom filters</span>
      </button>
      <div className="rn-head">
        <span className="rn-head-title">Filter options</span>
        <span className="rn-head-count">{filter.options.length} options</span>
      </div>
      <button className="rn-create" type="button"
        onClick={() => showToast({ message: 'Create a new filter option', icon: 'plus' })}>
        <Icon name="plus" size={15} />
        Create new option
      </button>
      <div className="rn-list">
        {opts.length === 0 ? <div className="rn-empty">No options yet.</div> : null}
        {opts.map(opt => (
          <button
            key={opt.id}
            className={cx('rn-item', state.customFilterOptionId === opt.id && 'active')}
            type="button"
            onClick={() => { state.customFilterOptionId = opt.id; notify(); }}
          >
            <span className="rn-item-body">
              <span className="rn-item-name">{opt.value}</span>
              <span className="rn-item-meta">{cfFormatCount(opt.contactsFound)} contacts · {cfFormatCount(opt.accountsFound)} accounts</span>
            </span>
          </button>
        ))}
      </div>
    </div>
  );
}

/* ---- detail: head (title + locked Key / CRM field) --------------------- */
function CustomFilterDetailHead({ filter, option }) {
  const locked = filter.systemLocked;
  const editable = !!option && !locked;
  return (
    <div className="detail-head cf-detail-head">
      <div className="detail-head-text">
        <div className="detail-record-name-row">
          {editable ? (
            <h1 className="detail-record-name" contentEditable spellCheck={false} suppressContentEditableWarning
              onBlur={(e) => { const v = e.currentTarget.textContent.trim(); if (!v) { e.currentTarget.textContent = option.value; return; } option.value = v; notify(); }}
              onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); e.currentTarget.blur(); } }}>
              {option.value}</h1>
          ) : (
            <h1 className="detail-record-name">{option ? option.value : filter.title}</h1>
          )}
        </div>
      </div>
    </div>
  );
}

/* ---- detail: criteria row (alphabetical value chips) ------------------- */
function CriteriaRow({ option, row, canDelete }) {
  const [draft, setDraft] = React.useState('');
  const inputRef = React.useRef(null);
  const fields = CF_FIELDS[option.entity] || CF_FIELDS.contacts;
  const hasValues = row.values.length > 0;
  const sorted = row.values.slice().sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'base' }));

  const addChip = (raw) => {
    const v = raw.trim();
    if (!v) return;
    if (!row.values.includes(v)) row.values.push(v);
    setDraft('');
    notify();
  };

  return (
    <div className="cf-criteria-row">
      <div className="cf-criteria-controls">
        <div className="cf-select-wrap cf-select-field">
          <select className="cf-select" value={fields.includes(row.field) ? row.field : fields[0]}
            onChange={(e) => { row.field = e.target.value; notify(); }}>
            {fields.map(f => <option key={f} value={f}>{f}</option>)}
          </select>
          <Icon name="chevron-down" size={16} className="cf-select-chev" />
        </div>
        <div className="cf-select-wrap cf-select-op">
          <select className="cf-select" value={row.op}
            onChange={(e) => { row.op = e.target.value; notify(); }}>
            {CF_OPERATORS.map(o => <option key={o} value={o}>{o}</option>)}
          </select>
          <Icon name="chevron-down" size={16} className="cf-select-chev" />
        </div>
        <button className="cf-trash" type="button" aria-label="Remove filter" disabled={!canDelete}
          onClick={() => {
            if (!canDelete) return;
            option.rows = option.rows.filter(r => r.id !== row.id);
            notify();
          }}>
          <Icon name="trash-2" size={18} />
        </button>
      </div>

      <div className="cf-chipbox cf-chipbox--grid"
        onClick={(e) => { if (!e.target.closest('button') && e.target.tagName !== 'INPUT') inputRef.current && inputRef.current.focus(); }}>
        {hasValues ? (
          <div className="cf-chipgrid">
            {sorted.map(v => (
              <span className="cf-chip" key={v}>
                <span className="cf-chip-label">{v}</span>
                <button className="cf-chip-x" type="button" aria-label={`Remove ${v}`}
                  onClick={() => { row.values = row.values.filter(x => x !== v); notify(); }}>
                  <Icon name="x" size={13} />
                </button>
              </span>
            ))}
          </div>
        ) : null}
        <div className="cf-chip-inputrow">
          <input
            ref={inputRef} className="cf-chip-input" type="text" value={draft}
            placeholder={hasValues ? 'Add another value…' : 'Add a value…'}
            onChange={(e) => setDraft(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === 'Enter' || e.key === ',') { e.preventDefault(); addChip(draft); }
              else if (e.key === 'Backspace' && !draft && row.values.length) {
                row.values.pop(); notify();
              }
            }}
            onBlur={() => addChip(draft)}
          />
          {hasValues ? (
            <button className="cf-chipbox-clear" type="button" aria-label="Clear all values"
              onClick={() => { row.values = []; notify(); }}>
              <Icon name="x" size={14} />
            </button>
          ) : null}
        </div>
      </div>
    </div>
  );
}

/* ---- detail: option settings (work-area body) -------------------------- */
function CustomFilterOptionPane({ filter, option }) {
  useAppState();

  const addRow = () => {
    const fields = CF_FIELDS[option.entity] || CF_FIELDS.contacts;
    option.rows.push({ id: cfRowId(), field: fields[0], op: 'Contains', values: [] });
    notify();
  };

  return (
    <React.Fragment>
      <section className="cf-section">
        <h2 className="cf-section-title">Settings</h2>
        <p className="cf-help cf-section-sub">These are the Contact or Account criteria used to match records in our database.</p>

        <div className="cf-field">
          <div className="cf-filters-head">
            <div className="cf-filter-type">
              <span className="cf-filter-type-label">Filter type:</span>
              <div className="entity-switch">
              {['contacts', 'accounts'].map(ent => (
                <button
                  key={ent}
                  className={cx(option.entity === ent && 'active')}
                  type="button"
                  onClick={() => { option.entity = ent; notify(); }}
                >
                  {ent === 'contacts' ? 'Contacts' : 'Accounts'}
                </button>
              ))}
              </div>
            </div>
          </div>

          <div className="cf-criteria-card">
            {option.rows.map((row, i) => (
              <React.Fragment key={row.id}>
                <CriteriaRow option={option} row={row} canDelete={option.rows.length > 1} />
                <div className="cf-connector">
                  <button className="cf-add-dot" type="button" aria-label="Add filter" onClick={addRow}>
                    <Icon name="plus" size={15} />
                  </button>
                  {i < option.rows.length - 1 ? (
                    <div className="cf-joiner">
                      {['AND', 'OR'].map(j => (
                        <button
                          key={j}
                          className={cx('cf-joiner-btn', option.join === j && 'cf-joiner-btn--on')}
                          type="button"
                          onClick={() => { option.join = j; notify(); }}
                        >{j}</button>
                      ))}
                    </div>
                  ) : null}
                </div>
              </React.Fragment>
            ))}
          </div>

          <button className="cf-add-filter" type="button" onClick={addRow}>
            <Icon name="plus" size={16} />
            Add a filter
          </button>
        </div>
      </section>

      <div className="cf-option-footer">
        <span className="cf-match-count">
          <Icon name="users" size={17} />
          <strong>{cfFormatCount(option.entity === 'accounts' ? option.accountsFound : option.contactsFound)}</strong>
          {' '}{option.entity === 'accounts' ? 'Accounts' : 'Contacts'} meet criteria
        </span>
        <div className="cf-footer-actions">
          <label className="cf-default-toggle">
            <input
              type="radio" checked={!!option.isDefault} readOnly
              onClick={() => {
                const next = !option.isDefault;
                filter.options.forEach(o => { o.isDefault = false; });
                option.isDefault = next;
                notify();
              }}
            />
            <span className="cf-default-dot" />
            <span>Make Organization Default</span>
          </label>
          <button
            className="btn cf-delete-item" type="button"
            onClick={() => {
              filter.options = filter.options.filter(o => o.id !== option.id);
              state.customFilterOptionId = null;
              notify();
              showToast({ message: `Deleted “${option.value}”`, icon: 'trash-2' });
            }}
          >Delete item</button>
          <button
            className="btn cf-save-item" type="button"
            onClick={() => showToast({ message: `“${option.value}” saved`, icon: 'check' })}
          >Save Item</button>
        </div>
      </div>
    </React.Fragment>
  );
}

/* ---- detail view (3-column detail shell) ------------------------------- */
function CustomFilterDetail({ filter }) {
  useAppState();
  const option = customFilterOption(filter, state.customFilterOptionId);
  return (
    <div className="body">
      <div className="floating-widget-spacer">
        <div className="floating-widget">
          <CustomFilterOptionsNav filter={filter} />
        </div>
      </div>
      <div className="content-panel">
        <div id="work-area">
          <div className="cf-detail-scope" data-role="detail">
            <CustomFilterDetailHead filter={filter} option={option} />
            {option ? (
              <CustomFilterOptionPane filter={filter} option={option} />
            ) : filter.options.length === 0 ? (
              <div className="cf-options-empty">
                <span className="cf-options-empty-ico"><Icon name="list-plus" size={24} /></span>
                <strong>No filter options yet</strong>
                <p>Filter options are the selectable values that appear in your filter dropdown. Create your first one to get started.</p>
                <button className="btn btn-primary cf-options-empty-btn" type="button"
                  onClick={() => showToast({ message: 'Create a new filter option', icon: 'plus' })}>
                  <Icon name="plus" size={15} />
                  Create first option
                </button>
              </div>
            ) : (
              <div className="pv-empty">
                <span className="pv-empty-ico"><Icon name="mouse-pointer-click" size={26} /></span>
                <strong>Pick a filter option</strong>
                <p>Choose an option from the panel on the left to view and edit its matching criteria.</p>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---- page root --------------------------------------------------------- */
function CustomFiltersPage() {
  useAppState();
  const filter = state.customFilterId ? customFilterById(state.customFilterId) : null;
  return (
    <React.Fragment>
      {filter ? (
        <CustomFilterDetail filter={filter} />
      ) : (
        <div className="body cf-body"><CustomFiltersList /></div>
      )}
      <CustomFilterModal />
    </React.Fragment>
  );
}

/* ---- breadcrumbs ------------------------------------------------------- */
function CustomFiltersBreadcrumbs() {
  useAppState();
  const filter = state.customFilterId ? customFilterById(state.customFilterId) : null;
  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">Settings</span>
      <Icon name="chevron-right" className="breadcrumb-sep" size={14} />
      {filter ? (
        <React.Fragment>
          <button className="breadcrumb-link" type="button" onClick={openCustomFiltersList}>Custom filters</button>
          <Icon name="chevron-right" className="breadcrumb-sep" size={14} />
          <span className="breadcrumb-item current">{filter.title}</span>
        </React.Fragment>
      ) : (
        <span className="breadcrumb-item current">Custom filters</span>
      )}
    </div>
  );
}

window.PAGES['custom-filters'] = CustomFiltersPage;
window.PAGE_BREADCRUMBS = window.PAGE_BREADCRUMBS || {};
window.PAGE_BREADCRUMBS['custom-filters'] = CustomFiltersBreadcrumbs;
window.PAGE_HEADER_ACTIONS = window.PAGE_HEADER_ACTIONS || {};
window.PAGE_HEADER_ACTIONS['custom-filters'] = CustomFilterHeaderActions;
window.PAGE_NO_ASK_AI = window.PAGE_NO_ASK_AI || {};
window.PAGE_NO_ASK_AI['custom-filters'] = true;

Object.assign(window, { CustomFiltersPage, CustomFiltersBreadcrumbs, CustomFilterHeaderActions, openCreateCustomFilter, openEditCustomFilter, closeCustomFilterModal });
