/* Selective reuse of approved Lane 2 visual controls; C7 controller follows. */
(function(root){
  'use strict';
  const {useEffect,useMemo,useRef,useState}=React;
  const WEBSITE_PAGE_LIMIT=300, DISCOVERED_PAGE_SIZE=25;
  const CATEGORY_OPTIONS = Object.freeze([
    { value: 'blog', label: 'Blog' },
    { value: 'product_feature', label: 'Product & feature' },
    { value: 'solution_use_case', label: 'Solution & use case' },
    { value: 'case_study', label: 'Case study' },
    { value: 'pricing', label: 'Pricing' },
    { value: 'resource_documentation', label: 'Documentation' },
    { value: 'other', label: 'Other' }
  ].map(Object.freeze));
  /* Website discovery pagination helpers: pure and deterministic for focused tests. */
  function paginateRows(rows, requestedPage, pageSize = DISCOVERED_PAGE_SIZE) {
    const safePageSize = Math.max(1, Math.floor(pageSize));
    const totalPages = Math.max(1, Math.ceil(rows.length / safePageSize));
    const page = Math.min(totalPages, Math.max(1, Math.floor(requestedPage) || 1));
    const start = (page - 1) * safePageSize;
    return { page, totalPages, rows: rows.slice(start, start + safePageSize) };
  }

  function getPaginationItems(currentPage, totalPages) {
    if (totalPages <= 7) return Array.from({ length: totalPages }, (_, index) => index + 1);
    if (currentPage <= 4) return [1, 2, 3, 4, 5, 'ellipsis-right', totalPages];
    if (currentPage >= totalPages - 3) {
      return [1, 'ellipsis-left', totalPages - 4, totalPages - 3, totalPages - 2, totalPages - 1, totalPages];
    }
    return [1, 'ellipsis-left', currentPage - 1, currentPage, currentPage + 1, 'ellipsis-right', totalPages];
  }

  function getVisibleSelectionState(selectedIds, visibleIds) {
    const selectedSet = new Set(selectedIds);
    const selectedCount = visibleIds.filter((id) => selectedSet.has(id)).length;
    return {
      selectedCount,
      checked: visibleIds.length > 0 && selectedCount === visibleIds.length,
      indeterminate: selectedCount > 0 && selectedCount < visibleIds.length
    };
  }

  function toggleVisibleSelection(selectedIds, visibleIds) {
    const visibleState = getVisibleSelectionState(selectedIds, visibleIds);
    const visibleSet = new Set(visibleIds);
    if (visibleState.checked) return selectedIds.filter((id) => !visibleSet.has(id));
    return Array.from(new Set(selectedIds.concat(visibleIds)));
  }

  /* End Website discovery pagination helpers. */

  function categoryLabel(value) {
    const match = CATEGORY_OPTIONS.find((option) => option.value === value);
    return match ? match.label : 'Other';
  }

  function categoryTone(value) {
    return CATEGORY_OPTIONS.some((option) => option.value === value) ? value : 'other';
  }

  function CategoryDot({ category }) {
    return <span className={'wk-category-dot wk-category-dot--' + categoryTone(category)} aria-hidden="true"></span>;
  }

  function CategoryChip({ category }) {
    return (
      <span className="wk-category-chip">
        <CategoryDot category={category} />
        <span>{categoryLabel(category)}</span>
      </span>
    );
  }

  function CategoryMenuItems({ value, onSelect, showSelection = true }) {
    return CATEGORY_OPTIONS.map((option) => {
      const selected = showSelection && value === option.value;
      return (
        <button
          key={option.value}
          type="button"
          role={showSelection ? 'menuitemradio' : 'menuitem'}
          aria-checked={showSelection ? selected : undefined}
          className={'wk-tool-menu-item ' + (selected ? 'wk-tool-menu-item--active' : '')}
          onClick={() => onSelect(option.value)}>
          <CategoryDot category={option.value} />
          <span>{option.label}</span>
          {showSelection && <span className="wk-tool-menu-check" aria-hidden="true">{selected ? '✓' : ''}</span>}
        </button>
      );
    });
  }

  function CategoryDropdown({ id, value, label, onChange, disabled }) {
    const [open, setOpen] = useState(false);
    const dropdownRef = useRef(null);
    const triggerRef = useRef(null);
    const menuRef = useRef(null);

    useEffect(() => {
      if (!open) return undefined;
      function closeOnOutsideClick(event) {
        if (dropdownRef.current && !dropdownRef.current.contains(event.target)) setOpen(false);
      }
      function closeOnEscape(event) {
        if (event.key !== 'Escape') return;
        setOpen(false);
        if (triggerRef.current) triggerRef.current.focus();
      }
      document.addEventListener('mousedown', closeOnOutsideClick);
      document.addEventListener('keydown', closeOnEscape);
      return () => {
        document.removeEventListener('mousedown', closeOnOutsideClick);
        document.removeEventListener('keydown', closeOnEscape);
      };
    }, [open]);

    function focusMenuItem(position) {
      window.setTimeout(() => {
        if (!menuRef.current) return;
        const items = Array.from(menuRef.current.querySelectorAll('[role^="menuitem"]'));
        if (!items.length) return;
        const index = position === 'last' ? items.length - 1 : 0;
        items[index].focus();
      }, 0);
    }

    function handleMenuKeyDown(event) {
      const items = Array.from(menuRef.current ? menuRef.current.querySelectorAll('[role^="menuitem"]') : []);
      const currentIndex = items.indexOf(document.activeElement);
      let nextIndex = currentIndex;
      if (event.key === 'ArrowDown') nextIndex = currentIndex >= items.length - 1 ? 0 : currentIndex + 1;
      else if (event.key === 'ArrowUp') nextIndex = currentIndex <= 0 ? items.length - 1 : currentIndex - 1;
      else if (event.key === 'Home') nextIndex = 0;
      else if (event.key === 'End') nextIndex = items.length - 1;
      else return;
      event.preventDefault();
      if (items[nextIndex]) items[nextIndex].focus();
    }

    return (
      <div ref={dropdownRef} className="wk-category-dropdown">
        <button
          ref={triggerRef}
          disabled={disabled}
          id={id}
          type="button"
          className="wk-category-dropdown__trigger"
          aria-label={(label ? label + ': ' : 'Category: ') + categoryLabel(value)}
          aria-haspopup="menu"
          aria-expanded={open}
          aria-controls={id + '-menu'}
          onClick={() => setOpen((current) => !current)}
          onKeyDown={(event) => {
            if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return;
            event.preventDefault();
            setOpen(true);
            focusMenuItem(event.key === 'ArrowUp' ? 'last' : 'first');
          }}>
          <CategoryDot category={value} />
          <span>{categoryLabel(value)}</span>
          <i data-lucide="chevron-down" aria-hidden="true"></i>
        </button>
        {open &&
          <div
            ref={menuRef}
            id={id + '-menu'}
            className="wk-tool-popover wk-tool-popover--category wk-category-dropdown__menu"
            role="menu"
            aria-label={label}
            data-state="open"
            onKeyDown={handleMenuKeyDown}>
            <CategoryMenuItems
              value={value}
              onSelect={(category) => {
                onChange(category);
                setOpen(false);
                if (triggerRef.current) triggerRef.current.focus();
              }} />
          </div>
        }
      </div>
    );
  }

  function trapFocus(event, container) {
    if (event.key !== 'Tab' || !container) return;
    const focusable = Array.from(container.querySelectorAll(
      'button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [href], [tabindex]:not([tabindex="-1"])'
    )).filter((element) => element.getAttribute('aria-hidden') !== 'true');
    if (!focusable.length) return;
    const first = focusable[0];
    const last = focusable[focusable.length - 1];
    if (event.shiftKey && document.activeElement === first) {
      event.preventDefault();
      last.focus();
    } else if (!event.shiftKey && document.activeElement === last) {
      event.preventDefault();
      first.focus();
    }
  }

  function RemoveSelectedPagesModal({ open, count, dialogRef, confirmRef, onClose, onConfirm }) {
    if (!open) return null;
    return (
      <div className="wk-overlay wk-overlay--center wk-overlay--confirm" onMouseDown={onClose}>
        <div
          ref={dialogRef}
          className="wk-modal wk-modal--confirm"
          role="alertdialog"
          aria-modal="true"
          aria-labelledby="wk-bulk-remove-title"
          aria-describedby="wk-bulk-remove-description"
          onMouseDown={(event) => event.stopPropagation()}
          onKeyDown={(event) => trapFocus(event, dialogRef.current)}>
          <div className="wk-modal__head wk-modal__head--danger">
            <span className="wk-modal__icon" aria-hidden="true"><i data-lucide="trash-2"></i></span>
            <h2 id="wk-bulk-remove-title">Remove selected pages?</h2>
            <p id="wk-bulk-remove-description">Remove {count} selected {count === 1 ? 'page' : 'pages'} from Website Knowledge?</p>
          </div>
          <div className="wk-modal__actions">
            <button type="button" className="rl-btn rl-btn--secondary wk-compact-btn" onClick={onClose}>Cancel</button>
            <button ref={confirmRef} type="button" className="rl-btn wk-danger-button wk-compact-btn" onClick={onConfirm}>Remove pages</button>
          </div>
        </div>
      </div>
    );
  }

  function TableToolbar({
    countLabel, query, onQueryChange, category, onCategoryChange, searchLabel,
    selectedCount, bulkKind, onBulkCategory, onBulkStatus, onBulkRemove
  }) {
    const [openMenu, setOpenMenu] = useState('');
    const [searchOpen, setSearchOpen] = useState(false);
    const controlsRef = useRef(null);
    const searchInputRef = useRef(null);
    const toolbarKey = bulkKind === 'imported' ? 'imported' : 'discovered';

    useEffect(() => {
      if (!openMenu) return undefined;
      function closeOnOutsideClick(event) {
        if (controlsRef.current && !controlsRef.current.contains(event.target)) setOpenMenu('');
      }
      function closeOnEscape(event) {
        if (event.key === 'Escape') setOpenMenu('');
      }
      document.addEventListener('mousedown', closeOnOutsideClick);
      document.addEventListener('keydown', closeOnEscape);
      return () => {
        document.removeEventListener('mousedown', closeOnOutsideClick);
        document.removeEventListener('keydown', closeOnEscape);
      };
    }, [openMenu]);

    useEffect(() => {
      if (searchOpen && searchInputRef.current) searchInputRef.current.focus();
    }, [searchOpen]);

    useEffect(() => {
      if (selectedCount === 0 && (openMenu === 'bulk-category' || openMenu === 'bulk-status')) setOpenMenu('');
    }, [selectedCount, openMenu]);

    function toggleMenu(menu) {
      setOpenMenu((current) => current === menu ? '' : menu);
      setSearchOpen(false);
    }

    function toggleSearch() {
      setSearchOpen((open) => !open);
      setOpenMenu('');
    }

    return (
      <div className="wk-table-toolbar">
        <span className="wk-table-count" aria-live="polite">{selectedCount > 0 ? selectedCount + ' selected' : countLabel}</span>
        <div className="wk-table-controls" aria-label={toolbarKey + ' page tools'} ref={controlsRef}>
          {selectedCount > 0 &&
            <React.Fragment>
              <div className="wk-table-bulk-actions" aria-label="Bulk actions">
                <div className="wk-tool-wrap">
                  <button
                    type="button"
                    className={'wk-tool-button ' + (openMenu === 'bulk-category' ? 'wk-tool-button--active' : '')}
                    aria-label="Change category"
                    title="Change category"
                    aria-haspopup="menu"
                    aria-expanded={openMenu === 'bulk-category'}
                    aria-controls={'wk-' + toolbarKey + '-bulk-category-menu'}
                    onClick={() => toggleMenu('bulk-category')}>
                    <i data-lucide="tag"></i>
                    <span className="wk-tool-tooltip" role="tooltip">Change category</span>
                  </button>
                  {openMenu === 'bulk-category' &&
                    <div id={'wk-' + toolbarKey + '-bulk-category-menu'} className="wk-tool-popover wk-tool-popover--category" role="menu" aria-label="Change category" data-state="open">
                      <CategoryMenuItems
                        value=""
                        showSelection={false}
                        onSelect={(categoryValue) => {
                          onBulkCategory(categoryValue);
                          setOpenMenu('');
                        }} />
                    </div>
                  }
                </div>

                {bulkKind === 'imported' &&
                  <div className="wk-tool-wrap">
                    <button
                      type="button"
                      className={'wk-tool-button ' + (openMenu === 'bulk-status' ? 'wk-tool-button--active' : '')}
                      aria-label="Change status"
                      title="Change status"
                      aria-haspopup="menu"
                      aria-expanded={openMenu === 'bulk-status'}
                      aria-controls="wk-imported-bulk-status-menu"
                      onClick={() => toggleMenu('bulk-status')}>
                      <i data-lucide="circle-check"></i>
                      <span className="wk-tool-tooltip" role="tooltip">Change status</span>
                    </button>
                    {openMenu === 'bulk-status' &&
                      <div id="wk-imported-bulk-status-menu" className="wk-tool-popover wk-tool-popover--status" role="menu" aria-label="Change status" data-state="open">
                        <button type="button" role="menuitem" className="wk-tool-menu-item" onClick={() => { onBulkStatus('enabled'); setOpenMenu(''); }}>
                          <span className="wk-status-dot wk-status-dot--enabled" aria-hidden="true"></span><span>Enabled</span>
                        </button>
                        <button type="button" role="menuitem" className="wk-tool-menu-item" onClick={() => { onBulkStatus('disabled'); setOpenMenu(''); }}>
                          <span className="wk-status-dot wk-status-dot--disabled" aria-hidden="true"></span><span>Disabled</span>
                        </button>
                      </div>
                    }
                  </div>
                }

                {bulkKind === 'imported' &&
                  <button type="button" className="wk-tool-button wk-tool-button--danger" aria-label="Remove selected" title="Remove selected" onClick={() => { setOpenMenu(''); onBulkRemove(); }}>
                    <i data-lucide="trash-2"></i>
                    <span className="wk-tool-tooltip" role="tooltip">Remove selected</span>
                  </button>
                }
              </div>
              <span className="wk-tool-divider" aria-hidden="true"></span>
            </React.Fragment>
          }

          <div className="wk-tool-wrap">
            <button
              type="button"
              className={'wk-tool-button ' + (openMenu === 'filter' || category !== 'all' ? 'wk-tool-button--active' : '')}
              aria-label="Filter by category"
              title="Filter by category"
              aria-haspopup="menu"
              aria-expanded={openMenu === 'filter'}
              aria-controls={'wk-' + toolbarKey + '-filter-menu'}
              onClick={() => toggleMenu('filter')}>
              <i data-lucide="list-filter"></i>
              {category !== 'all' && <span className="wk-tool-badge">1</span>}
              <span className="wk-tool-tooltip" role="tooltip">Filter by category</span>
            </button>
            {openMenu === 'filter' &&
              <div id={'wk-' + toolbarKey + '-filter-menu'} className="wk-tool-popover wk-tool-popover--category" role="menu" aria-label="Filter by category" data-state="open">
                <button type="button" role="menuitemradio" aria-checked={category === 'all'} className={'wk-tool-menu-item ' + (category === 'all' ? 'wk-tool-menu-item--active' : '')} onClick={() => { onCategoryChange('all'); setOpenMenu(''); }}>
                  <i className="wk-tool-menu-icon" data-lucide="layers-3"></i>
                  <span>All categories</span><span className="wk-tool-menu-check">{category === 'all' ? '✓' : ''}</span>
                </button>
                {CATEGORY_OPTIONS.map((option) =>
                  <button key={option.value} type="button" role="menuitemradio" aria-checked={category === option.value} className={'wk-tool-menu-item ' + (category === option.value ? 'wk-tool-menu-item--active' : '')} onClick={() => { onCategoryChange(option.value); setOpenMenu(''); }}>
                    <CategoryDot category={option.value} />
                    <span>{option.label}</span><span className="wk-tool-menu-check">{category === option.value ? '✓' : ''}</span>
                  </button>
                )}
              </div>
            }
          </div>

          <div className={'wk-toolbar-search ' + (searchOpen ? 'wk-toolbar-search--open' : '')} data-state={searchOpen ? 'open' : 'closed'}>
            <label className="wk-toolbar-search__field" aria-hidden={!searchOpen}>
              <i data-lucide="search" aria-hidden="true"></i>
              <input
                ref={searchInputRef}
                type="search"
                tabIndex={searchOpen ? 0 : -1}
                value={query}
                onChange={(event) => onQueryChange(event.target.value)}
                onKeyDown={(event) => {
                  if (event.key !== 'Escape') return;
                  if (query) onQueryChange('');
                  else setSearchOpen(false);
                }}
                placeholder="Search pages"
                aria-label={searchLabel} />
              {query &&
                <button type="button" className="wk-toolbar-search__clear" tabIndex={searchOpen ? 0 : -1} aria-label="Clear search" onClick={() => onQueryChange('')}>
                  <i data-lucide="x"></i>
                </button>
              }
            </label>
            <button type="button" className={'wk-tool-button ' + (searchOpen || query ? 'wk-tool-button--active' : '')} aria-label="Search" title="Search" aria-expanded={searchOpen} onClick={toggleSearch}>
              <i data-lucide="search"></i>
              <span className="wk-tool-tooltip" role="tooltip">Search</span>
            </button>
          </div>
        </div>
      </div>
    );
  }


  const pageCount = count => count + (count === 1 ? ' page' : ' pages');
  const targetStatus = state => ({completed:'Complete',failed:'Failed',cancelled:'Cancelled',invalidated:'Cancelled',queued:'Ready to continue',processing:'Waiting for import result',uncertain:'Import status unknown'})[state];
  const targetError = code => ({
    page_fetch_or_extraction_failed:'The page could not be fetched or readable content could not be extracted.',
    website_source_provider_rejected:'The summary provider could not complete this request.',
    website_source_summary_invalid:'The summary response did not meet the required format.',
    website_source_provider_unavailable:'The summary service is unavailable.',
    website_source_content_invalid:'The page did not contain suitable readable content.',
    import_outcome_uncertain:'The import result could not be confirmed. It will not be retried automatically.'
  })[code] || 'This page could not be imported.';

  function summaryPreview(summary) {
    const segments = typeof Intl.Segmenter === 'function'
      ? Array.from(new Intl.Segmenter(undefined, {granularity:'grapheme'}).segment(summary), item => item.segment)
      : Array.from(summary);
    return segments.slice(0,80).join('') + (segments.length > 80 ? '…' : '');
  }

  function SummaryPopover({page}) {
    const [open,setOpen]=useState(false),[position,setPosition]=useState(null);
    const trigger=useRef(null),panel=useRef(null),showTimer=useRef(null),hideTimer=useRef(null),pinned=useRef(false);
    const summary=typeof page.summary==='string' ? page.summary : '';
    const id='wk-summary-'+page.id;
    const clearTimers=()=>{root.clearTimeout(showTimer.current);root.clearTimeout(hideTimer.current);showTimer.current=null;hideTimer.current=null;};
    const close=(restore=false)=>{clearTimers();pinned.current=false;setOpen(false);setPosition(null);if(restore)trigger.current?.focus();};
    const enter=()=>{root.clearTimeout(hideTimer.current);if(!open&&!showTimer.current)showTimer.current=root.setTimeout(()=>{showTimer.current=null;setOpen(true);},1000);};
    const leave=()=>{root.clearTimeout(showTimer.current);showTimer.current=null;if(!pinned.current)hideTimer.current=root.setTimeout(()=>{if(!panel.current?.contains(document.activeElement))close();},180);};
    useEffect(()=>()=>clearTimers(),[]);
    React.useLayoutEffect(()=>{
      if(!open)return;
      if(root.lucide)root.lucide.createIcons();
      const place=()=>{
        const r=trigger.current?.getBoundingClientRect(),p=panel.current;if(!r||!p)return;
        const width=Math.min(380,root.innerWidth-24),height=Math.min(p.getBoundingClientRect().height,root.innerHeight-24);
        const left=Math.max(12,Math.min(r.left,root.innerWidth-width-12));
        const top=r.bottom+8+height<=root.innerHeight-12?r.bottom+8:Math.max(12,r.top-height-8);
        setPosition({left,top,width});
      };
      place();root.addEventListener('resize',place);root.addEventListener('scroll',place,true);
      const outside=e=>{if(!trigger.current?.contains(e.target)&&!panel.current?.contains(e.target))close();};
      const escape=e=>{if(e.key==='Escape'){e.preventDefault();close(panel.current?.contains(document.activeElement)||document.activeElement===trigger.current);}};
      document.addEventListener('pointerdown',outside);document.addEventListener('keydown',escape);
      return()=>{root.removeEventListener('resize',place);root.removeEventListener('scroll',place,true);document.removeEventListener('pointerdown',outside);document.removeEventListener('keydown',escape);};
    },[open]);
    if(!summary.trim())return <span className="wk-muted-cell">—</span>;
    return <React.Fragment>
      <button ref={trigger} type="button" className="wk-summary-preview" aria-label={'Read summary for '+page.title}
        aria-haspopup="dialog" aria-expanded={open} aria-controls={open?id:undefined}
        onMouseEnter={enter} onMouseLeave={leave}
        onClick={event=>{clearTimers();if(open&&pinned.current){close();return;}pinned.current=true;setOpen(true);if(event.detail===0)root.setTimeout(()=>panel.current?.querySelector('button')?.focus(),0);}}>
        {summaryPreview(summary)}
      </button>
      {open&&ReactDOM.createPortal(<div ref={panel} id={id} role="dialog" aria-label={'Summary for '+page.title}
        className="wk-summary-popover" style={position||{visibility:'hidden',width:Math.min(380,root.innerWidth-24)}}
        onMouseEnter={()=>root.clearTimeout(hideTimer.current)} onMouseLeave={leave}
        onFocusCapture={()=>root.clearTimeout(hideTimer.current)}
        onBlurCapture={event=>{if(!event.currentTarget.contains(event.relatedTarget)&&!pinned.current)leave();}}>
        <button type="button" className="wk-icon-button wk-summary-close" aria-label="Close summary" onClick={()=>close(true)}><i data-lucide="x" aria-hidden="true"/></button>
        <p>{summary}</p>
      </div>,document.body)}
    </React.Fragment>;
  }

  function ImportResultsModal({targets,onClose}) {
    const dialog=useRef(null),closeButton=useRef(null);
    useEffect(()=>{
      const previous=document.activeElement;closeButton.current?.focus();
      if(root.lucide)root.lucide.createIcons();
      const escape=event=>{if(event.key==='Escape'){event.preventDefault();onClose();}};
      document.addEventListener('keydown',escape);
      return()=>{document.removeEventListener('keydown',escape);if(previous?.isConnected)previous.focus();};
    },[]);
    return ReactDOM.createPortal(<div className="wk-overlay wk-overlay--center" onMouseDown={onClose}>
      <section ref={dialog} role="dialog" aria-modal="true" aria-labelledby="wk-import-results-title"
        className="wk-modal wk-modal--results" onMouseDown={event=>event.stopPropagation()} onKeyDown={event=>trapFocus(event,dialog.current)}>
        <header className="wk-modal__head"><h2 id="wk-import-results-title">Import results</h2></header>
        <button ref={closeButton} type="button" className="wk-icon-button wk-modal__close" aria-label="Close import results" onClick={onClose}><i data-lucide="x" aria-hidden="true"/></button>
        <ul className="wk-results-list" aria-label="Page import outcomes" tabIndex="0">{targets.map(target=><li key={target.url}>
          <span className="wk-result-url">{target.url}</span><span className={'wk-result-state wk-result-state--'+target.state}>{targetStatus(target.state)}</span>
          {target.state==='failed'&&<p>{targetError(target.failureCode)}</p>}
        </li>)}</ul>
      </section>
    </div>,document.body);
  }

  function OperationFeedback({operation:o,data,view:v,successful,onContinue,onRetry,onCancel,writable,canCancel}) {
    const [dismissed,setDismissed]=useState(false),[hovered,setHovered]=useState(false),[focused,setFocused]=useState(false),[modal,setModal]=useState(false);
    const remaining=useRef(10000),container=useRef(null);
    useEffect(()=>{remaining.current=10000;setDismissed(false);},[successful]);
    useEffect(()=>{
      if(!successful||dismissed||hovered||focused||modal)return;
      const started=Date.now(),timer=root.setTimeout(()=>setDismissed(true),remaining.current);
      return()=>{root.clearTimeout(timer);remaining.current=Math.max(0,remaining.current-(Date.now()-started));};
    },[successful,dismissed,hovered,focused,modal]);
    if(dismissed)return null;
    const targets=data.importTargets.filter(t=>t.operationId===o.operationId);
    return <div ref={container} className="wk-operation" data-operation={o.operationId}
      onMouseEnter={event=>{if(container.current?.contains(event.target))setHovered(true);}} onMouseLeave={()=>setHovered(false)}
      onFocusCapture={()=>setFocused(true)} onBlurCapture={event=>{if(!event.currentTarget.contains(event.relatedTarget))setFocused(false);}}>
      {!successful&&<span className="wk-status" role="status">{o.kind==='scan'?'Scan: ':''}{v.status}</span>}
      {o.kind==='import'&&o.boundedImport&&<button type="button" className="wk-import-result" aria-haspopup="dialog" onClick={()=>setModal(true)}>
        <span aria-live="polite">{v.completed} of {pageCount(v.total)} imported · {v.failed} failed</span>
      </button>}
      {successful&&<button type="button" className="wk-icon-button wk-result-dismiss" aria-label="Dismiss import result" onClick={()=>setDismissed(true)}><i data-lucide="x" aria-hidden="true"/></button>}
      {v.uncertain&&<p>{o.kind==='scan'?"We couldn't confirm whether this scan finished. We won't retry it automatically.":"We couldn't confirm whether this page finished importing. We won't retry it automatically."}</p>}
      {v.canContinue&&<button type="button" className="rl-btn rl-btn--secondary wk-compact-btn" disabled={!writable} onClick={onContinue}>Continue import</button>}
      {v.canRetry&&<button type="button" className="rl-btn rl-btn--secondary wk-compact-btn" disabled={!writable} onClick={onRetry}>{o.kind==='scan'?'Retry scan':'Retry import'}</button>}
      {v.canCancel&&<button type="button" className="rl-btn rl-btn--secondary wk-compact-btn" disabled={!canCancel} onClick={onCancel}>{o.kind==='scan'?'Cancel scan':'Cancel import'}</button>}
      {modal&&<ImportResultsModal targets={targets} onClose={()=>{setHovered(container.current?.matches(':hover')||false);setModal(false);}}/>}
    </div>;
  }

  function ImportedPagesTable({
    website, rows, query, category, selectedIds, headerCheckboxRef,
    allVisibleSelected, onQueryChange, onCategoryChange, writable,
    onToggleAll, onToggleOne, onBulkCategory, onBulkStatus, onBulkRemove
  }) {
    return (
      <section className="wk-tab-panel" role="tabpanel" id="wk-imported-panel" aria-labelledby="wk-imported-tab">
        <TableToolbar
          countLabel={pageCount(website.importedCount)}
          query={query}
          onQueryChange={onQueryChange}
          category={category}
          onCategoryChange={onCategoryChange}
          searchLabel="Search imported pages"
          selectedCount={writable ? selectedIds.length : 0}
          bulkKind="imported"
          onBulkCategory={onBulkCategory}
          onBulkStatus={onBulkStatus}
          onBulkRemove={onBulkRemove} />
        <div className="wk-table-wrap">
          <table className="wk-table wk-table--imported">
            <thead>
              <tr>
                <th className="wk-checkbox-cell">
                  <input ref={headerCheckboxRef} type="checkbox" checked={allVisibleSelected} disabled={!writable || rows.length === 0} onChange={onToggleAll} aria-label="Select visible imported pages" />
                </th>
                <th>Page</th><th>Summary</th><th>Category</th><th>Status</th><th>Last refreshed</th>
              </tr>
            </thead>
            <tbody>
              {rows.map((page) =>
                <tr
                  key={page.id}
                  className={selectedIds.indexOf(page.id) >= 0 ? 'wk-table-row--selected' : ''}>
                  <td className="wk-checkbox-cell">
                    <input
                      type="checkbox"
                      checked={selectedIds.indexOf(page.id) >= 0}
                      disabled={!writable}
                      onChange={() => onToggleOne(page.id)}
                      aria-label={'Select ' + page.title} />
                  </td>
                  <td><span className="wk-page-cell__title">{page.title}</span><span className="wk-page-cell__url">{page.url}</span></td>
                  <td><SummaryPopover page={page}/></td>
                  <td><CategoryChip category={page.category} /></td>
                  <td><span className={'wk-availability wk-availability--' + page.availability}>{page.availability === 'enabled' ? 'Enabled' : page.availability === 'unavailable' ? 'Unavailable' : 'Disabled'}</span></td>
                  <td className="wk-muted-cell">{page.refreshed}</td>
                </tr>
              )}
              {rows.length === 0 && <tr className="wk-table-empty-row"><td colSpan="6">No imported pages match these filters.</td></tr>}
            </tbody>
          </table>
        </div>
      </section>
    );
  }

  function Pagination({ page, totalPages, onPageChange }) {
    if (totalPages <= 1) return null;
    const items = getPaginationItems(page, totalPages);
    return (
      <nav className="wk-pagination" aria-label="Discovered pages pagination">
        <button
          type="button"
          className="wk-pagination__nav"
          disabled={page === 1}
          onClick={() => onPageChange(page - 1)}>
          <i data-lucide="chevron-left" aria-hidden="true"></i><span>Previous</span>
        </button>
        <div className="wk-pagination__pages">
          {items.map((item) => typeof item === 'number' ?
            <button
              key={item}
              type="button"
              className={'wk-pagination__page ' + (item === page ? 'wk-pagination__page--current' : '')}
              aria-label={'Go to page ' + item}
              aria-current={item === page ? 'page' : undefined}
              onClick={() => onPageChange(item)}>{item}</button> :
            <span key={item} className="wk-pagination__ellipsis" aria-hidden="true">…</span>
          )}
        </div>
        <button
          type="button"
          className="wk-pagination__nav"
          disabled={page === totalPages}
          onClick={() => onPageChange(page + 1)}>
          <span>Next</span><i data-lucide="chevron-right" aria-hidden="true"></i>
        </button>
      </nav>
    );
  }

  function DiscoveredPagesTable({
    website, rows, query, category, selectedIds, headerCheckboxRef,
    allVisibleSelected, onQueryChange, onCategoryChange, onToggleAll,
    onToggleOne, onEditCategory, onBulkCategory, onImport, writable,
    page, totalPages, onPageChange
  }) {
    const remaining = Math.max(0, WEBSITE_PAGE_LIMIT - website.heldCount);
    const overCapacity = selectedIds.length > remaining;
    return (
      <section className="wk-tab-panel" role="tabpanel" id="wk-discovered-panel" aria-labelledby="wk-discovered-tab">
        {website.scanIncomplete &&
          <div className="wk-notice" role="status">
            <span className="wk-notice__icon" aria-hidden="true"><i data-lucide="info"></i></span>
            <div><strong>This scan is incomplete</strong><p>Some sitemap work could not be completed. The list below shows the pages found so far.</p></div>
          </div>
        }
        <TableToolbar
          countLabel={pageCount(website.discoveredCount) + ' found'}
          query={query}
          onQueryChange={onQueryChange}
          category={category}
          onCategoryChange={onCategoryChange}
          searchLabel="Search discovered pages"
          selectedCount={writable ? selectedIds.length : 0}
          bulkKind="discovered"
          onBulkCategory={onBulkCategory} />
        <div className="wk-table-wrap">
          <table className="wk-table wk-table--discovered">
            <thead>
              <tr>
                <th className="wk-checkbox-cell">
                  <input ref={headerCheckboxRef} type="checkbox" checked={allVisibleSelected} disabled={!writable || !rows.some((page) => page.importStatus === 'not_imported')} onChange={onToggleAll} aria-label="Select eligible visible pages" />
                </th>
                <th>Page URL</th>
                <th>Category</th>
                <th>Import status</th>
              </tr>
            </thead>
            <tbody>
              {rows.map((page) => {
                const selectable = page.importStatus === 'not_imported';
                return (
                  <tr key={page.id} className={selectedIds.indexOf(page.id) >= 0 ? 'wk-table-row--selected' : ''}>
                    <td className="wk-checkbox-cell">
                      <input
                        type="checkbox"
                        checked={selectedIds.indexOf(page.id) >= 0}
                        disabled={!writable || !selectable}
                        onClick={(event) => event.stopPropagation()}
                        onChange={() => onToggleOne(page.id)}
                        aria-label={'Select ' + page.url} />
                    </td>
                    <td><span className="wk-discovered-url">{page.url}</span></td>
                    <td>
                      <CategoryDropdown
                        disabled={!writable}
                        id={'wk-category-' + website.id + '-' + page.id}
                        value={page.category}
                        label={'Category for ' + page.url}
                        onChange={(value) => onEditCategory(page.id, value)} />
                    </td>
                    <td><span className={'wk-import-state wk-import-state--' + page.importStatus}>{{imported:'Already imported',not_imported:'Not imported',pending:'Ready to continue',processing:'Waiting for import result',uncertain:'Import status unknown'}[page.importStatus]}</span></td>
                  </tr>
                );
              })}
              {rows.length === 0 && <tr className="wk-table-empty-row"><td colSpan="4">No discovered pages match these filters.</td></tr>}
            </tbody>
          </table>
        </div>
        <Pagination page={page} totalPages={totalPages} onPageChange={onPageChange} />
        <div className="wk-selection-bar" aria-live="polite">
          <div>
            <strong>{selectedIds.length} selected</strong>
            <span>{pageCount(remaining)} remaining (of {WEBSITE_PAGE_LIMIT})</span>
            {overCapacity && <span className="wk-selection-error">Reduce the selection to fit the remaining capacity.</span>}
          </div>
          <button type="button" className="rl-btn rl-btn--primary wk-primary-button" disabled={!writable || selectedIds.length === 0 || overCapacity} onClick={onImport}>Import selected pages</button>
        </div>
      </section>
    );
  }

  // C7 owns data, holds and revisions. Navigation stops UI continuation;
  // it does not claim to cancel work already executing on the server.
  function WebsiteKnowledge({site,origin}) {
    const scope=root.ClicklyxWebsiteContext, sources=root.ClicklyxWebsiteSources;
    const access=root.ClicklyxKnowledgeAccess.useAccess();
    const transport=useMemo(()=>sources.forPage(origin),[origin]);
    const [data,setData]=useState(null),[error,setError]=useState(false),[loading,setLoading]=useState(true);
    const [busy,setBusy]=useState(false),[activeId,setActiveId]=useState(null),[scanning,setScanning]=useState(false);
    const [feedbackId,setFeedbackId]=useState(null);
    const [tab,setTab]=useState('imported'),[importedQuery,setImportedQuery]=useState(''),[importedCategory,setImportedCategory]=useState('all');
    const [discoveredQuery,setDiscoveredQuery]=useState(''),[discoveredCategory,setDiscoveredCategory]=useState('all'),[page,setPage]=useState(1);
    const [selectedImported,setSelectedImported]=useState([]),[selectedDiscovered,setSelectedDiscovered]=useState([]),[removeOpen,setRemoveOpen]=useState(false);
    const alive=useRef(true),sequence=useRef(0),pending=useRef(false),continueId=useRef(null),cancelPending=useRef(false);
    const importedHeader=useRef(null),discoveredHeader=useRef(null),dialog=useRef(null),confirm=useRef(null);
    const observedImports=useRef(null),verifiedOrigin=useRef(null);
    const current=()=>alive.current&&scope.isCurrent(origin);
    const permitted=()=>current()&&site.canWrite&&access.canMutate();
    const announce=v=>root.dispatchEvent(new CustomEvent('clicklyx:website-source-changed',{detail:{userId:origin.userId,sessionId:origin.sessionId,workspaceId:origin.workspaceId,websiteId:site.id,retainedCount:v.capacity.retained}}));
    async function read(){
      const version=++sequence.current;
      let value;
      try{value=await transport.read();}catch(error){if(current()&&version===sequence.current&&[401,403,404].includes(error.status)){setData(null);continueId.current=null;}throw error;}
      if(!current()||version!==sequence.current)return null;
      // Only completion observed in this visit is transient feedback. Stored
      // successful receipts remain durable but are not a results-history UI.
      const imports=value.operations.filter(o=>o.kind==='import'),latest=imports[0];
      if(latest&&observedImports.current){
        const prior=observedImports.current.get(latest.operationId);
        if(successfulImport(latest,value)&&prior&&prior!=='completed')setFeedbackId(latest.operationId);
        else if(!prior&&!successfulImport(latest,value))setFeedbackId(null);
      }
      observedImports.current=new Map(imports.map(o=>[o.operationId,o.state]));
      setData(value);setLoading(false);announce(value);return value;
    }
    async function reload(){setError(false);try{await read();}catch(_){if(current()){setLoading(false);setError(true);}}}
    useEffect(()=>{
      alive.current=true;observedImports.current=null;verifiedOrigin.current=null;setFeedbackId(null);setData(null);setLoading(true);reload();
      const refresh=()=>{if(current())reload();};root.addEventListener('focus',refresh);
      return()=>{alive.current=false;sequence.current++;continueId.current=null;root.removeEventListener('focus',refresh);};
    },[origin]);
    useEffect(()=>{if(root.lucide)root.lucide.createIcons();});
    async function run(action,importId){
      if(pending.current||!permitted())return;
      if(importId)setFeedbackId(null);
      pending.current=true;setBusy(true);setError(false);
      try{
        const result=await action();if(!current())return;
        let value=await read();
        if(importId){
          const id=importId(result);continueId.current=id;setActiveId(id);setFeedbackId(id);
          // Read before every step. A claimed target, uncertainty or CAS loss
          // ends this loop. Reopening the tab never starts it.
          while(current()&&permitted()&&continueId.current===id&&value){
            const operation=value.operations.find(o=>o.operationId===id);
            if(!operation||!sources.operationView(operation,value,true).canContinue)break;
            await transport.importAction(operation,'advance');
            if(!current()||continueId.current!==id)break;
            value=await read();
          }
        }
      }catch(_){if(current()){setError(true);try{await read();}catch(_) {}}}
      finally{continueId.current=null;pending.current=false;if(current()){setActiveId(null);setBusy(false);setScanning(false);}}
    }
    async function cancel(operation){
      if(cancelPending.current||!permitted())return;
      cancelPending.current=true;continueId.current=null;setError(false);
      try{
        const value=await read();if(!current()||!value)return;
        const fresh=value.operations.find(o=>o.operationId===operation.operationId);
        if(!fresh||!sources.operationView(fresh,value,false).canCancel)return;
        if(fresh.kind==='scan')await transport.scanAction(fresh,'cancel');else await transport.importAction(fresh,'cancel');
        if(current())await read();
      }catch(_){if(current()){setError(true);try{await read();}catch(_) {}}}
      finally{cancelPending.current=false;}
    }
    const writable=site.canWrite&&access.canMutate()&&!busy;
    useEffect(()=>{if(writable)verifiedOrigin.current=origin;},[writable,origin]);
    const workspaceAccess=root.ClicklyxWorkspaceAccess?.getState();
    // Presentation only: the original disabled condition and action guard stay
    // authoritative while a same-Website projection is being reverified.
    const checkingAccess=!!data&&!error&&!busy&&site.canWrite&&current()&&verifiedOrigin.current===origin
      &&scope.inspect().mode===null&&workspaceAccess?.workspaceId===origin.workspaceId
      &&workspaceAccess.status==='full'&&workspaceAccess.canMutateWorkspaceContent===true&&!workspaceAccess.errorCode;
    const heldUrls=new Map();
    (data?.importTargets||[]).forEach(t=>{if(['queued','processing','uncertain'].includes(t.state)){
      const prior=heldUrls.get(t.url);if(!prior||t.state==='uncertain'||t.state==='processing'&&prior!=='uncertain')heldUrls.set(t.url,t.state);
    }});
    const date=value=>new Intl.DateTimeFormat('en-US',{year:'numeric',month:'short',day:'numeric',timeZone:'UTC'}).format(new Date(value));
    const imported=(data?.pages||[]).map(p=>({...p,url:p.normalized_url,title:p.title||p.normalized_url,category:p.category_override||p.category,availability:p.availability==='available'?'enabled':p.availability,refreshed:date(p.updated_at)}));
    const retained=new Set(imported.map(p=>p.url));
    const discovered=(data?.candidates||[]).map(p=>({...p,id:p.normalized_url,url:p.normalized_url,category:p.category_override||p.category,
      importStatus:retained.has(p.normalized_url)?'imported':({queued:'pending',processing:'processing',uncertain:'uncertain'})[heldUrls.get(p.normalized_url)]||'not_imported'}));
    const filter=(rows,query,category)=>rows.filter(p=>(!query.trim()||(p.title+' '+p.url).toLowerCase().includes(query.trim().toLowerCase()))&&(category==='all'||p.category===category));
    const importedRows=filter(imported,importedQuery,importedCategory),discoveredRows=filter(discovered,discoveredQuery,discoveredCategory);
    const pagination=paginateRows(discoveredRows,page);
    const importedIds=importedRows.map(p=>p.id),eligible=pagination.rows.filter(p=>p.importStatus==='not_imported').map(p=>p.id);
    const importedSelection=getVisibleSelectionState(selectedImported,importedIds),discoveredSelection=getVisibleSelectionState(selectedDiscovered,eligible);
    const candidateIdentity=data?.candidates[0]?.scan_id||'';
    useEffect(()=>{setSelectedDiscovered([]);setPage(1);},[candidateIdentity]);
    useEffect(()=>{
      const ids=new Set(imported.map(p=>p.id));setSelectedImported(values=>values.filter(id=>ids.has(id)));
      const urls=new Set(discovered.filter(p=>p.importStatus==='not_imported').map(p=>p.id));setSelectedDiscovered(values=>values.filter(id=>urls.has(id)));
    },[data]);
    useEffect(()=>{if(importedHeader.current)importedHeader.current.indeterminate=importedSelection.indeterminate;if(discoveredHeader.current)discoveredHeader.current.indeterminate=discoveredSelection.indeterminate;});
    useEffect(()=>{
      if(!removeOpen)return;
      const previous=document.activeElement;confirm.current?.focus();
      const escape=event=>{if(event.key==='Escape'&&!pending.current)setRemoveOpen(false);};
      document.addEventListener('keydown',escape);return()=>{document.removeEventListener('keydown',escape);if(previous?.isConnected)previous.focus();};
    },[removeOpen]);
    async function bulk(kind,ids,patch){
      const chosen=(kind==='imported'?data.pages:data.candidates).filter(p=>ids.includes(kind==='imported'?p.id:p.normalized_url));
      await run(async()=>{for(const p of chosen){if(!permitted())break;
        if(kind==='imported')await transport.page(p,patch);else await transport.category(p,patch.categoryOverride);
      }});
    }
    function importSelection(refresh){
      const rows=refresh?imported.filter(p=>selectedImported.includes(p.id)&&!heldUrls.has(p.url)):discovered.filter(p=>selectedDiscovered.includes(p.id)&&p.importStatus==='not_imported');
      if(!rows.length||!refresh&&rows.length>300-data.capacity.held)return;
      const urls=rows.map(p=>p.url).sort(),scanId=refresh?null:rows[0].scan_id;
      if(!refresh&&rows.some(p=>p.scan_id!==scanId))return;
      run(()=>transport.importPages(root.crypto.randomUUID(),scanId,urls),result=>result.operation.operationId);
    }
    const scans=data?.operations.filter(o=>o.kind==='scan')||[],latestScan=scans[0];
    const blockedScan=scans.some(o=>['queued','processing','uncertain'].includes(o.state)),acceptedScan=scans.find(o=>o.state==='completed');
    function successfulImport(operation,value){
      const v=sources.operationView(operation,value,false);
      return operation.kind==='import'&&operation.state==='completed'&&v.total>0&&v.completed===v.total&&v.failed===0&&!v.uncertain;
    }
    const shownOperations=data?.operations.filter(o=>o.kind==='scan'?o===latestScan&&o.state!=='completed'
      :successfulImport(o,data)?o.operationId===feedbackId
      :o===data.operations.find(p=>p.kind==='import')||['queued','processing','uncertain','failed'].includes(o.state)||sources.operationView(o,data,false).failed>0)||[];
    const website={id:site.id,importedCount:imported.length,heldCount:data?.capacity.held||0,discoveredCount:discovered.length,scanIncomplete:acceptedScan?.complete===false};
    const toggle=(setter,id)=>{if(writable)setter(values=>values.includes(id)?values.filter(v=>v!==id):[...values,id]);};
    const keyboard=event=>{if(['ArrowRight','ArrowLeft','Home','End'].includes(event.key)){event.preventDefault();const next=event.key==='Home'?'imported':event.key==='End'?'discovered':tab==='imported'?'discovered':'imported';setTab(next);document.getElementById('wk-'+next+'-tab')?.focus();}};
    return <section className="wk-feature" aria-busy={loading}>
      <header className="wk-management-header"><div className="wk-management-header__main"><div className="wk-management-title-row"><h2>Website Knowledge</h2></div>
        {data&&<p><strong>{imported.length} of 300 pages imported</strong> · {acceptedScan?.finishedAt?'Last scanned '+date(acceptedScan.finishedAt):'Not scanned yet'}</p>}</div>
        <button type="button" className={'rl-btn rl-btn--primary wk-primary-button wk-management-scan-button'+(checkingAccess&&!blockedScan?' wk-management-scan-button--checking':'')} aria-busy={scanning||checkingAccess} disabled={!writable||!data||blockedScan} onClick={()=>{if(!permitted()||pending.current)return;setScanning(true);run(()=>transport.scan(root.crypto.randomUUID()));}}><i data-lucide={scanning||checkingAccess?'loader-2':'scan-search'} className={scanning||checkingAccess?'wk-spin':''}/><span>{scanning?'Scanning...':checkingAccess&&!blockedScan?'Checking access…':'Scan for new pages'}</span></button>
      </header>
      {error&&<div className="c5-load-error"><p role="alert">The requested operation is unavailable.</p><button type="button" className="rl-btn rl-btn--secondary" onClick={reload}>{root.ClicklyxWebsites.copy.retry}</button></div>}
      {data&&<React.Fragment>
        {shownOperations.map(o=><OperationFeedback key={o.operationId} operation={o} data={data} view={sources.operationView(o,data,activeId===o.operationId)} successful={successfulImport(o,data)} writable={writable} canCancel={site.canWrite&&access.canMutate()}
          onContinue={()=>run(async()=>({operation:o}),()=>o.operationId)}
          onRetry={()=>run(()=>o.kind==='scan'?(o.state==='queued'?transport.scan(o.operationId):transport.scanAction(o,'retry')):transport.importAction(o,'retry'),o.kind==='import'?result=>result.operation.operationId:null)} onCancel={()=>cancel(o)}/>)}
        <div className="wk-tabs" role="tablist" aria-label="Website pages" onKeyDown={keyboard}>{['imported','discovered'].map(value=><button key={value} id={'wk-'+value+'-tab'} type="button" role="tab" tabIndex={tab===value?0:-1} aria-selected={tab===value} aria-controls={'wk-'+value+'-panel'} className={'wk-tab'+(tab===value?' wk-tab--active':'')} onClick={()=>setTab(value)}>{value==='imported'?'Imported pages':'Discovered pages'}</button>)}</div>
        {tab==='imported'?<React.Fragment><ImportedPagesTable website={website} rows={importedRows} query={importedQuery} category={importedCategory} selectedIds={selectedImported} headerCheckboxRef={importedHeader} allVisibleSelected={importedSelection.checked} writable={writable}
          onQueryChange={setImportedQuery} onCategoryChange={setImportedCategory} onToggleAll={()=>writable&&setSelectedImported(values=>toggleVisibleSelection(values,importedIds))} onToggleOne={id=>toggle(setSelectedImported,id)}
          onBulkCategory={category=>bulk('imported',selectedImported,{categoryOverride:category})} onBulkStatus={value=>bulk('imported',selectedImported,{availability:value==='enabled'?'available':'disabled'})} onBulkRemove={()=>writable&&setRemoveOpen(true)}/>
          {!!selectedImported.length&&<div className="wk-selection-bar"><button type="button" className="rl-btn rl-btn--secondary wk-compact-btn" disabled={!writable||imported.filter(p=>selectedImported.includes(p.id)).some(p=>heldUrls.has(p.url))} onClick={()=>importSelection(true)}>Refresh selected pages</button></div>}</React.Fragment>
          :<DiscoveredPagesTable website={website} rows={pagination.rows} query={discoveredQuery} category={discoveredCategory} selectedIds={selectedDiscovered} headerCheckboxRef={discoveredHeader} allVisibleSelected={discoveredSelection.checked} writable={writable}
            onQueryChange={value=>{setDiscoveredQuery(value);setPage(1);}} onCategoryChange={value=>{setDiscoveredCategory(value);setPage(1);}} onToggleAll={()=>writable&&setSelectedDiscovered(values=>toggleVisibleSelection(values,eligible))} onToggleOne={id=>toggle(setSelectedDiscovered,id)}
            onEditCategory={(id,category)=>bulk('discovered',[id],{categoryOverride:category})} onBulkCategory={category=>bulk('discovered',selectedDiscovered,{categoryOverride:category})} onImport={()=>importSelection(false)} page={pagination.page} totalPages={pagination.totalPages} onPageChange={setPage}/>
        }
        <RemoveSelectedPagesModal open={removeOpen} count={selectedImported.length} dialogRef={dialog} confirmRef={confirm} onClose={()=>{if(!pending.current)setRemoveOpen(false);}} onConfirm={()=>{if(pending.current||!permitted())return;setRemoveOpen(false);const rows=data.pages.filter(p=>selectedImported.includes(p.id));run(async()=>{for(const p of rows){if(!permitted())break;await transport.remove(p);}});}}/>
      </React.Fragment>}
    </section>;
  }
  root.WebsiteKnowledge=WebsiteKnowledge;
})(window);
