/* C5 Website and Brief experience. Customer mounting remains disabled. */
(function (root) {
  const {useState, useRef, useEffect} = React;
  const client = root.ClicklyxWebsites, copy = client.copy;
  function useIcons(dependencies) {
    useEffect(() => {if (root.lucide && root.lucide.createIcons) root.lucide.createIcons();}, dependencies);
  }
  function useKnowledgePages(enabled) {
    const [pages, setPages] = useState([]), [websiteId, setWebsiteId] = useState(null);
    const lease = useRef(0), retryBusy = useRef(false);
    const activeSite = useRef(null), activeWorkspace = useRef(null);
    const pageLease = useRef(0), pageOrigin = useRef(null);
    const detailsRef = useRef(null), successRef = useRef(false);
    const [load, setLoad] = useState({status:'idle'});
    const close = () => {lease.current += 1; pageLease.current += 1; pageOrigin.current = null; activeSite.current = null; setWebsiteId(null); setLoad({status:'idle'});};
    const open = async (id, success, details) => {
      const version = ++lease.current;
      let requestOrigin;
      const samePage = activeSite.current === id && pageOrigin.current && root.ClicklyxWebsiteContext.isCurrent(pageOrigin.current);
      if (activeSite.current !== id) {pageLease.current += 1; pageOrigin.current = null;}
      const pageVersion = pageLease.current;
      activeSite.current = id;
      detailsRef.current = details || null;
      successRef.current = !!success;
      if (!samePage) {setWebsiteId(null); setLoad({status:'loading', id});}
      try {
        requestOrigin = root.ClicklyxWebsiteContext.capture();
        activeWorkspace.current = requestOrigin.workspaceId;
        const result = await root.ClicklyxWebsiteContext.getContext(id);
        if (version !== lease.current || !root.ClicklyxWebsiteContext.isCurrent(requestOrigin)) return;
        if (result.context.mode !== 'strict') {setWebsiteId(null);setLoad({status:'error',id,retryable:false});return;}
        // Refreshing the same page updates permissions, but must not invalidate
        // its pending Knowledge reads or discard its unsaved form state.
        // Navigation and identity/epoch changes still invalidate the origin.
        const origin = pageOrigin.current && root.ClicklyxWebsiteContext.isCurrent(pageOrigin.current)
          ? pageOrigin.current
          : root.ClicklyxWebsiteContext.capturePage(id, () => pageVersion === pageLease.current);
        pageOrigin.current = origin;
        activeWorkspace.current = origin.workspaceId;
        const family = JSON.stringify([origin.userId, origin.sessionId, origin.workspaceId, id]);
        const page = {family, site:result.website, origin, success:!!success, details:detailsRef.current};
        setPages(current => [...current.filter(item => item.family !== family), page]);
        setWebsiteId(id);
        setLoad({status:'ready',id});
      } catch (error) {if (version === lease.current && (!requestOrigin || root.ClicklyxWebsiteContext.isCurrent(requestOrigin))) {
        setWebsiteId(null); setLoad({status:'error',id,retryable:client.retryable(error)});
      }}
    };
    useEffect(() => {
      if (!enabled) return undefined;
      const changed = () => {close(); setPages([]);};
      root.addEventListener('ranklyx:workspace-switching', changed);
      const unlisten = root.ClicklyxWebsiteContext.subscribe(() => {
        const liveWorkspace = root.ClicklyxWebsiteContext.inspect().workspaceId;
        const ids=new Set(root.ClicklyxWebsiteContext.inspect().websites.map(site => site.id));
        setPages(current => current.filter(page => page.origin.workspaceId === liveWorkspace && ids.has(page.site.id)));
        if (activeWorkspace.current !== liveWorkspace) close();
        else if (activeSite.current) open(activeSite.current, successRef.current, detailsRef.current);
      });
      return () => {lease.current += 1; pageLease.current += 1; unlisten(); root.removeEventListener('ranklyx:workspace-switching', changed);};
    }, [enabled]);
    return {pages, websiteId, open, close, load, retry:() => {
      if(!retryBusy.current && load.status==='error' && load.retryable && activeSite.current && activeWorkspace.current===root.ClicklyxWebsiteContext.inspect().workspaceId){
        retryBusy.current=true;open(activeSite.current,successRef.current,detailsRef.current).finally(()=>{retryBusy.current=false;});
      }
    }};
  }
  function useWebsites(enabled) {
    const [state, setState] = useState({status:'loading', websites:[], administrator:false});
    const sequence = useRef(0);
    const identity = () => {const value=root.ClicklyxWebsiteContext.inspect();return JSON.stringify([value.userId,value.sessionId,value.workspaceId]);};
    const key = identity();
    const [revision, revise] = useState(0);
    const refresh = result => {
      if (result && result.origin && root.ClicklyxWebsiteContext.isCurrent(result.origin)) {
        sequence.current += 1; setState({...result, status:'ready', identity:identity()});
      } else revise(value => value + 1);
    };
    useEffect(() => {
      if (!enabled) return undefined;
      const version = ++sequence.current;
      setState(current => current.identity === key && current.origin && root.ClicklyxWebsiteContext.isCurrent(current.origin)
        ? {...current, status:'refreshing'} : {status:'loading', websites:[], administrator:false});
      client.overview().then(result => {
        if (version === sequence.current && key === identity() && root.ClicklyxWebsiteContext.isCurrent(result.origin))
          setState({...result, status:'ready', identity:key});
      }).catch(error => {
        if (version === sequence.current && key === identity()) setState({status:'error', websites:[], administrator:false, identity:key,retryable:client.retryable(error)});
      });
      return () => {sequence.current += 1;};
    }, [enabled, key, revision]);
    useEffect(() => {
      if (!enabled) return undefined;
      const invalidate = () => {sequence.current += 1; setState({status:'loading',websites:[],administrator:false}); refresh();};
      root.addEventListener('ranklyx:workspace-switching', invalidate);
      root.addEventListener('ranklyx:workspace-changed', invalidate);
      // Chromium can emit window focus while moving focus within the document.
      // Only an actual window departure/return requires a background refresh.
      let away = false;
      const blur = event => {if (event.target === root) away = true;};
      const focus = event => {if (event.target === root && away) {away = false; refresh();}};
      root.addEventListener('blur', blur);
      root.addEventListener('focus', focus);
      return () => {
        root.removeEventListener('ranklyx:workspace-switching', invalidate);
        root.removeEventListener('ranklyx:workspace-changed', invalidate);
        root.removeEventListener('blur', blur);
        root.removeEventListener('focus', focus);
      };
    }, [enabled]);
    const current = state.identity === key && (state.status === 'error' || state.origin && root.ClicklyxWebsiteContext.isCurrent(state.origin));
    return {state:enabled && current ? state : {status:'loading',websites:[],administrator:false}, refresh};
  }
  function WebsiteLoadError({knowledge, retryable, onRetry}) {
    const blocked='The requested operation is unavailable.'; // Existing authorization contract copy.
    return <section className="c5-load-error"><p role="alert">{retryable ? (knowledge ? copy.knowledgeError : copy.overviewError) : blocked}</p>
      {retryable && <button type="button" className="rl-btn rl-btn--secondary" onClick={onRetry}>{copy.retry}</button>}</section>;
  }
  function KnowledgeLoadState({load,onRetry}) {
    return <main className="rl-page c5-websites" aria-busy={load.status==='loading'}>{load.status==='error' && <WebsiteLoadError knowledge retryable={load.retryable} onRetry={onRetry} />}</main>;
  }
  function WebsitesSidebar({state, active, websiteId, onNavigate}) {
    const [open, setOpen] = useState(active === 'websites' || active === 'website-knowledge');
    // Background Website revalidation changes rows, not these fixed icons.
    // Repainting globally here would also replace the active editor's icons.
    useIcons([open, active]);
    useEffect(() => {if (active === 'websites' || active === 'website-knowledge') setOpen(true);}, [active]);
    return <div className="rl-nav__group">
      <button type="button" className="rl-nav__item rl-nav__parent" aria-expanded={open} aria-controls="c5-websites-nav" onClick={() => setOpen(value => !value)}>
        <i data-lucide="globe" /><span>{copy.navigation}</span><i data-lucide="chevron-down" className={`rl-nav__chevron ${open ? 'rl-nav__chevron--open' : ''}`} />
      </button>
      {open && <div id="c5-websites-nav" className="rl-nav__sub" role="group" aria-label={copy.navigation}>
        <button type="button" className={`rl-nav__child ${active === 'websites' ? 'rl-nav__child--active' : ''}`} aria-current={active === 'websites' ? 'page' : undefined} onClick={() => onNavigate('websites')}><span className="rl-nav__childdot" /><span>{copy.all}</span></button>
        {state.websites.map(site => <button type="button" key={site.id} className={`rl-nav__child ${active === 'website-knowledge' && websiteId === site.id ? 'rl-nav__child--active' : ''}`} aria-current={active === 'website-knowledge' && websiteId === site.id ? 'page' : undefined} onClick={() => onNavigate('website-knowledge', {websiteId:site.id})}>
          <span className="rl-nav__childdot" /><span>{client.domain(site)}</span>{!site.canWrite && <span className="c5-readonly">{copy.readonly}</span>}
        </button>)}
      </div>}
    </div>;
  }
  function HomeWebsites({state, onNavigate}) {
    useIcons([state]);
    return <section className="rl-home-panel"><div className="rl-home-panel__head"><h2>{copy.navigation}</h2><button type="button" className="rl-btn rl-btn--ghost" onClick={() => onNavigate('websites')}>{copy.viewAll}</button></div>
      <div className="rl-home-knowledge">{state.websites.map(site => <button type="button" key={site.id} onClick={() => onNavigate('website-knowledge', {websiteId:site.id})}><span>{client.domain(site)}</span>{!site.canWrite && <span>{copy.readonly}</span>}<i data-lucide="arrow-right" /></button>)}</div>
    </section>;
  }
  function AddWebsite({state, onClose, onSuccess, onPlans, refresh}) {
    const unfunded = state.funding === 'unfunded';
    const dialog = useRef(null), input = useRef(null), live = useRef(true), submitted = useRef(null);
    const [value, setValue] = useState(''), [error, setError] = useState(''), [busy, setBusy] = useState(false);
    const [limit, setLimit] = useState(state.usage && state.usage.count >= state.usage.limit ? state.usage.limit : null);
    const origin = useRef(state.origin);
    useEffect(() => {
      const previous = document.activeElement;
      (input.current || dialog.current).focus();
      live.current = true;
      return () => {live.current = false; if (previous && previous.isConnected) previous.focus();};
    }, []);
    const current = () => live.current && root.ClicklyxWebsiteContext.isCurrent(origin.current);
    const submit = async event => {
      event.preventDefault(); if (busy || unfunded || !current()) return;
      const url = client.domainUrl(value);
      if (!url) {setError(copy.invalid); input.current.focus(); return;}
      if (!submitted.current || submitted.current.url !== url) submitted.current = {url, id:root.crypto.randomUUID()};
      setBusy(true); setError('');
      try {
        const website = await client.create(value, submitted.current.id, origin.current);
        if (current()) onSuccess(website);
      } catch (cause) {
        if (!current()) return;
        if (cause.code === 'capacity_full') {
          // Fetch the current funded limit; never infer it from an attempted plan.
          try {const latest = await client.overview(); if (current() && latest.administrator) setLimit(latest.usage.limit);} catch (_) {if (current()) setError(copy.error);}
        } else {
          if (cause.code === 'duplicate_domain') submitted.current = null;
          setError(cause.code === 'invalid_domain' ? copy.invalid : cause.code === 'duplicate_domain' ? copy.duplicate : copy.error);
        }
      } finally {if (current()) setBusy(false);}
    };
    const keyboard = event => {
      if (event.key === 'Escape') {event.preventDefault(); onClose();}
      if (event.key === 'Tab') {
        const nodes = [...dialog.current.querySelectorAll('button:not(:disabled), input:not(:disabled), [tabindex="0"]')];
        const first = nodes[0], last = nodes[nodes.length - 1];
        if (event.shiftKey && (document.activeElement === first || document.activeElement === dialog.current)) {event.preventDefault(); last.focus();}
        else if (!event.shiftKey && (document.activeElement === last || document.activeElement === dialog.current)) {event.preventDefault(); first.focus();}
      }
    };
    return <div className="c5-modal-backdrop"><section ref={dialog} className="c5-modal" role="dialog" aria-modal="true" aria-labelledby="c5-add-title" aria-describedby="c5-add-description" tabIndex={-1} onKeyDown={keyboard} aria-busy={busy}>
      <h2 id="c5-add-title">{limit === null ? copy.add : copy.limitTitle}</h2><p id="c5-add-description">{unfunded ? copy.unfunded : limit === null ? copy.modalDescription : copy.limitDescription(limit)}</p>
      {!unfunded && limit === null ? <form onSubmit={submit} noValidate><label htmlFor="c5-domain">{copy.domain}</label><input ref={input} id="c5-domain" value={value} onChange={event => {setValue(event.target.value); setError('');}} placeholder={copy.placeholder} autoComplete="url" aria-invalid={!!error} aria-describedby={error ? 'c5-add-error' : undefined} disabled={busy} />
        {error && <p id="c5-add-error" role="alert">{error}</p>}<div className="c5-modal-actions"><button type="button" className="rl-btn rl-btn--secondary" onClick={onClose}>{copy.cancel}</button><button type="submit" className="rl-btn rl-btn--primary" disabled={busy}>{copy.add}</button></div>
      </form> : <><div role="alert">{error}</div><div className="c5-modal-actions"><button type="button" className="rl-btn rl-btn--secondary" onClick={onClose}>{copy.cancel}</button><button type="button" className="rl-btn rl-btn--primary" onClick={onPlans}>{copy.plans}</button></div></>}
    </section></div>;
  }
  function ReadOnlyHelp({onPlans}) {
    const text = client.selectionCopy;
    return <div className="c5-resource-help"><p>{text.readonly}</p><p>{text.reassurance}</p><button type="button" className="rl-btn rl-btn--secondary" onClick={onPlans}>{text.plans}</button></div>;
  }
  function SelectWebsites({state, action='resolve', onClose, onSuccess, refresh}) {
    const text = client.selectionCopy, dialog = useRef(null), live = useRef(true), origin = useRef(state.origin), submitted = useRef(null), pending = useRef(false);
    const planned=state.scheduledSelection, expanding=action==='expand', planning=action==='pending';
    const limit=planning ? planned.limit : state.usage.limit;
    const locked=expanding ? state.selection.websiteIds : [];
    const [ids, setIds] = useState(planning ? planned.websiteIds : locked), [busy, setBusy] = useState(false), [error, setError] = useState('');
    const lineage=useRef(planning ? [planned.commitmentId,planned.commitmentRevision].join(':') : null);
    const allowed=['ready','refreshing'].includes(state.status) && state.administrator && (planning ? planned && Date.parse(planned.effectiveAt)>Date.now()
      && lineage.current===[planned.commitmentId,planned.commitmentRevision].join(':') : state.selection.state===(expanding?'expansion':'unresolved'));
    const current = () => live.current && root.ClicklyxWebsiteContext.isCurrent(origin.current);
    useEffect(() => {
      const previous = document.activeElement; live.current = true; dialog.current.focus();
      return () => {live.current = false; if (previous && previous.isConnected) previous.focus(); else {const fallback = document.querySelector('.c5-page-head button'); if (fallback) fallback.focus();}};
    }, []);
    useEffect(() => {setIds(values => [...new Set([...locked,...values.filter(id => state.websites.some(site => site.id === id))])]);}, [state.websites,state.selection]);
    const submit = async event => {
      event.preventDefault();
      if (pending.current || !current() || !allowed || state.status!=='ready' || ids.length !== limit || locked.some(id=>!ids.includes(id))) return;
      const input = {action, websiteIds:[...ids].sort(), expectedRevision:Number(planning ? planned.revision : state.selection.revision),
        ...(planning ? {commitmentId:planned.commitmentId,commitmentRevision:planned.commitmentRevision} : {})};
      const fingerprint = JSON.stringify(input);
      if (!submitted.current || submitted.current.fingerprint !== fingerprint) submitted.current = {fingerprint, id:root.crypto.randomUUID()};
      pending.current = true; setBusy(true); setError(''); dialog.current.focus();
      try {
        const result = await client.submitSelection({...input, requestId:submitted.current.id}, origin.current);
        if (current()) onSuccess(result.current);
      } catch (_) {
        if (!current()) return;
        setError(text.error);
        // Reconcile only by reads. Keep the exact request identity after an
        // uncertain result; changed input/revision creates a fresh request.
        try {const latest = await client.overview(); if (current()) refresh(latest);} catch (_) {}
      } finally {pending.current = false; if (current()) setBusy(false);}
    };
    const keyboard = event => {
      if (event.key === 'Escape') {event.preventDefault(); if (!pending.current) onClose();}
      if (event.key === 'Tab') {
        if (pending.current) {event.preventDefault(); return;}
        const nodes = [...dialog.current.querySelectorAll('button:not(:disabled), input:not(:disabled)')];
        const first = nodes[0], last = nodes[nodes.length - 1];
        if (!first) {event.preventDefault(); return;}
        if (event.shiftKey && (document.activeElement === first || document.activeElement === dialog.current)) {event.preventDefault(); last.focus();}
        else if (!event.shiftKey && (document.activeElement === last || document.activeElement === dialog.current)) {event.preventDefault(); first.focus();}
      }
    };
    return <div className="c5-modal-backdrop"><section ref={dialog} className="c5-modal c5-selection-modal" role="dialog" aria-modal="true" aria-labelledby="c5-selection-title" aria-describedby="c5-selection-description" aria-busy={busy} tabIndex={-1} onKeyDown={keyboard}>
      <h2 id="c5-selection-title">{expanding ? client.expansionCopy.title : text.title}</h2><p id="c5-selection-description">{planning ? client.plannedCopy.description(limit,client.effectiveDate(planned.effectiveAt)) : expanding ? client.expansionCopy.description(state.selection.availableExpansionSlots) : text.description(limit)}</p>
      <form onSubmit={submit}><fieldset disabled={busy || !allowed}><legend>{expanding ? client.expansionCopy.title : text.title}</legend>{state.websites.filter(site=>!expanding || locked.includes(site.id) || !site.canWrite).map(site => <label key={site.id}><input type="checkbox" value={site.id} checked={ids.includes(site.id)} disabled={locked.includes(site.id) || !ids.includes(site.id) && ids.length >= limit}
        onChange={event => {setIds(values => event.target.checked ? [...values, site.id] : values.filter(id => id !== site.id)); setError('');}} /><span>{client.domain(site)}</span></label>)}</fieldset>
        <output aria-live="polite">{ids.length} / {limit}</output>{error && <p role="alert">{error}</p>}
        <div className="c5-modal-actions"><button type="button" className="rl-btn rl-btn--secondary" disabled={busy} onClick={() => {if (!pending.current) onClose();}}>{text.cancel}</button><button type="submit" className="rl-btn rl-btn--primary" disabled={busy || !allowed || state.status!=='ready' || ids.length !== limit}>{text.save}</button></div>
      </form>
    </section></div>;
  }
  function WebsitesOverview({state, refresh, onNavigate}) {
    const text = client.selectionCopy;
    const unfunded = state.funding === 'unfunded';
    const [adding, setAdding] = useState(false), [selecting, setSelecting] = useState(false), [notice, setNotice] = useState(null);
    const [deleting, setDeleting] = useState(null), [menu, setMenu] = useState(null), [deletedNotice, setDeletedNotice] = useState(null);
    const required = state.administrator && state.selection && state.selection.state === 'unresolved';
    const planned=state.administrator && state.scheduledSelection && Date.parse(state.scheduledSelection.effectiveAt)>Date.now() ? state.scheduledSelection : null;
    const expansion=state.administrator && state.selection?.state==='expansion' && state.selection.availableExpansionSlots>0
      && state.websites.filter(site=>!state.selection.websiteIds.includes(site.id) && !site.canWrite).length>=state.selection.availableExpansionSlots;
    const available=selecting==='pending' ? !!planned : selecting==='expand' ? expansion : required;
    useIcons([state, adding, selecting, menu, deleting]);
    useEffect(() => {if(!state.administrator || state.context?.canEditArticles === false){setMenu(null);setDeleting(null);}}, [state.administrator, state.context?.canEditArticles]);
    useEffect(() => {if (!state.administrator || unfunded || state.status==='error') setAdding(false); if (!available || state.status==='error') setSelecting(false);}, [state.administrator, unfunded, available,state.status]);
    useEffect(() => {
      if(selecting==='pending' && planned && selectingLineage.current!==planned.commitmentId+':'+planned.commitmentRevision)setSelecting(false);
    }, [planned,selecting]);
    const selectingLineage=useRef(null);
    const select=action=>{selectingLineage.current=planned ? planned.commitmentId+':'+planned.commitmentRevision : null;setSelecting(action);};
    useEffect(() => {
      if(!planned)return undefined;
      let timer;
      const boundary=Date.parse(planned.effectiveAt), wait=() => {
        const remaining=boundary-Date.now();
        if(remaining<=0)refresh();else timer=setTimeout(wait,Math.min(2147483647,remaining));
      };
      wait();return()=>clearTimeout(timer);
    },[planned?.effectiveAt]);
    return <main className="rl-page c5-websites" aria-busy={state.status === 'loading' || state.status === 'refreshing'}><div className="c5-overview-inner"><header className="c5-page-head"><div><h1>{copy.title}</h1><div className="c5-page-description"><p>{copy.description}</p>{state.administrator && (unfunded ? <span>{copy.readonly}</span> : <span>{state.usage.count} of {state.usage.limit} websites</span>)}</div></div>{state.administrator && !unfunded && <button type="button" className="rl-btn c5-add-website" onClick={() => setAdding(true)}><i data-lucide="plus" />{copy.add}</button>}</header>
      {state.status === 'ready' && !state.websites.length && <section className="c5-empty"><i data-lucide="globe" /><h2>{copy.empty}</h2><p>{unfunded ? copy.unfunded : state.administrator ? copy.emptyAdmin : copy.emptyMember}</p></section>}
      {state.status === 'ready' && unfunded && <section className="c5-resource-help">{!!state.websites.length && <p>{copy.unfunded}</p>}<button type="button" className="rl-btn rl-btn--secondary" onClick={() => onNavigate('settings', {section:'billing'})}>{copy.plans}</button></section>}
      {state.status==='error' && <WebsiteLoadError retryable={state.retryable} onRetry={()=>refresh()} />}
      {['ready','refreshing'].includes(state.status) && required && <section className="c5-selection-notice"><h2>{text.heading}</h2><p>{text.notice(state.usage.limit)}</p><div className="c5-selection-actions"><button type="button" className="rl-btn rl-btn--primary" onClick={() => select('resolve')}>{text.action}</button><button type="button" className="rl-btn rl-btn--secondary" onClick={() => onNavigate('settings', {section:'billing'})}>{text.plans}</button></div></section>}
      {['ready','refreshing'].includes(state.status) && planned && <section className="c5-selection-notice c5-planned-notice"><h2>{client.plannedCopy.heading}</h2><p>{client.plannedCopy.notice(planned.limit,client.effectiveDate(planned.effectiveAt))}</p><button type="button" className="rl-btn rl-btn--primary" onClick={()=>select('pending')}>{text.action}</button></section>}
      {['ready','refreshing'].includes(state.status) && expansion && <section className="c5-selection-notice c5-expansion-notice"><h2>{client.expansionCopy.heading}</h2><p>{state.selection.expansionReason==='deletion' ? client.expansionCopy.optional : client.expansionCopy.notice(state.usage.limit,state.selection.availableExpansionSlots)}</p><button type="button" className="rl-btn rl-btn--primary" onClick={()=>select('expand')}>{text.action}</button></section>}
      {notice && state.administrator && root.ClicklyxWebsiteContext.isCurrent(notice.origin)
        && (notice.action!=='pending' || planned && notice.commitmentId===planned.commitmentId && notice.commitmentRevision===planned.commitmentRevision)
        && <p role="status">{notice.action==='pending' ? client.plannedCopy.success : text.success}</p>}
      {deletedNotice && root.ClicklyxWebsiteContext.isCurrent(deletedNotice.origin) && <p role="status">{client.deletionCopy.success}</p>}
      {!!state.websites.length && <table className="c5-websites-table" aria-label={copy.navigation}><thead><tr><th scope="col">Website</th><th scope="col">Actions</th></tr></thead><tbody>{state.websites.map(site => <tr key={site.id}>
        <td><button type="button" className="c5-site-link" onClick={() => onNavigate('website-knowledge', {websiteId:site.id})}>{client.domain(site)}</button>{!site.canWrite && <span className="c5-readonly">{copy.readonly}</span>}</td>
        <td>{state.administrator && <div className="c5-site-management"><button type="button" className="c5-site-menu-button" data-site-menu={site.id} aria-label={client.deletionCopy.action+' '+client.domain(site)} aria-haspopup="menu" aria-expanded={menu===site.id} onClick={() => setMenu(menu===site.id?null:site.id)} onKeyDown={event => {if(event.key==='ArrowDown'){event.preventDefault();setMenu(site.id);}}}><i data-lucide="ellipsis" /></button>
          {menu===site.id && <WebsiteMenu site={site} allowed={state.status==='ready' && state.context?.canEditArticles===true} onClose={() => setMenu(null)} onDelete={() => {setMenu(null);setDeleting(site);}} />}
        </div>}</td>
      </tr>)}</tbody></table>}
      {state.administrator && state.context && state.context.canEditArticles === true && state.websites.some(site => !site.canWrite) && <ReadOnlyHelp onPlans={() => onNavigate('settings', {section:'billing'})} />}
      {selecting && available && <SelectWebsites key={selecting} action={selecting} state={state} refresh={refresh} onClose={() => setSelecting(false)} onSuccess={latest => {setSelecting(false); setNotice({origin:latest.origin,action:selecting,commitmentId:latest.scheduledSelection?.commitmentId,commitmentRevision:latest.scheduledSelection?.commitmentRevision}); refresh(latest);}} />}
      {adding && state.administrator && !unfunded && <AddWebsite state={state} refresh={refresh} onClose={() => setAdding(false)} onPlans={() => {setAdding(false); onNavigate('settings', {section:'billing'});}} onSuccess={website => {setAdding(false); refresh(); onNavigate('website-knowledge', {websiteId:website.id, success:true});}} />}
      {deleting && state.administrator && <DeleteWebsite site={deleting} state={state} onClose={() => setDeleting(null)} onSuccess={latest => {setDeleting(null);setDeletedNotice({origin:latest.origin});refresh(latest);}} />}
    </div></main>;
  }
  function WebsiteMenu({site,allowed,onClose,onDelete}) {
    const menu=useRef(null);
    useEffect(() => {menu.current.focus();const close=event => {if(!event.target.closest('.c5-site-management'))onClose();};document.addEventListener('pointerdown',close);return () => document.removeEventListener('pointerdown',close);}, []);
    return <div ref={menu} className="c5-site-menu" role="menu" tabIndex={-1} onKeyDown={event => {if(['Escape','Tab'].includes(event.key)){if(event.key==='Escape')event.preventDefault();const button=menu.current.parentElement.querySelector('button');onClose();button.focus();}else if(['ArrowDown','ArrowUp','Home','End'].includes(event.key)){event.preventDefault();menu.current.querySelector('button:not(:disabled)')?.focus();}}}>
      <button type="button" role="menuitem" disabled={!allowed} onClick={onDelete}>Delete website</button>
    </div>;
  }
  function DeleteWebsite({site,state,onClose,onSuccess}) {
    const text=client.deletionCopy,domain=client.domain(site),dialog=useRef(null),input=useRef(null),live=useRef(true),pending=useRef(false),origin=useRef(state.origin),requestId=useRef(root.crypto.randomUUID());
    const [value,setValue]=useState(''),[busy,setBusy]=useState(false),[error,setError]=useState('');
    const current=() => live.current && root.ClicklyxWebsiteContext.isCurrent(origin.current);
    useEffect(() => {const previous=document.querySelector('[data-site-menu="'+site.id+'"]');input.current.focus();return () => {live.current=false;if(previous?.isConnected)previous.focus();else document.querySelector('.c5-page-head button')?.focus();};}, []);
    useEffect(() => {if(!root.ClicklyxWebsiteContext.isCurrent(origin.current))onClose();}, [state]);
    const submit=async event => {
      event.preventDefault();if(pending.current||!current()||value!==domain||!state.administrator||state.context?.canEditArticles!==true)return;
      pending.current=true;setBusy(true);setError('');dialog.current.focus();
      try{const latest=await client.deleteWebsite(site.id,requestId.current,origin.current);if(current())onSuccess(latest);}
      catch(_){if(current())setError(text.error);}
      finally{if(current()){pending.current=false;setBusy(false);}}
    };
    const keyboard=event => {
      if(event.key==='Escape'){event.preventDefault();if(!pending.current)onClose();}
      if(event.key==='Tab'){
        event.preventDefault();if(pending.current)return;
        const nodes=[...dialog.current.querySelectorAll('input:not(:disabled),button:not(:disabled)')],index=nodes.indexOf(document.activeElement);
        nodes[(index+(event.shiftKey?-1:1)+nodes.length)%nodes.length]?.focus();
      }
    };
    return <div className="c5-modal-backdrop"><section ref={dialog} className="c5-modal" role="dialog" aria-modal="true" aria-labelledby="c5-delete-title" aria-describedby="c5-delete-warning c5-delete-knowledge c5-delete-articles c5-delete-capacity c5-delete-backup" aria-busy={busy} tabIndex={-1} onKeyDown={keyboard}>
      <h2 id="c5-delete-title">{text.title(domain)}</h2><p id="c5-delete-warning">{text.warning}</p><p id="c5-delete-knowledge">{text.knowledge}</p><p id="c5-delete-articles">{text.articles}</p><p id="c5-delete-capacity">{text.capacity}</p><p id="c5-delete-backup">{text.backup}</p>
      <form onSubmit={submit}><label htmlFor="c5-delete-domain">{text.label(domain)}</label><input id="c5-delete-domain" ref={input} value={value} disabled={busy} onChange={event => {setValue(event.target.value);setError('');}} autoComplete="off" spellCheck={false} aria-describedby={error?'c5-delete-error':undefined} />
        {error && <p id="c5-delete-error" role="alert">{error}</p>}<div className="c5-modal-actions"><button type="button" className="rl-btn rl-btn--secondary" disabled={busy} onClick={onClose}>{text.cancel}</button><button type="submit" className="rl-btn c5-delete-action" disabled={busy||value!==domain||state.context?.canEditArticles!==true}>{text.action}</button></div>
      </form>
    </section></div>;
  }
  function BriefWebsiteField({value, state, error, disabled, onChange, onAdd, SelectComponent=root.SelectInput}) {
    const text = client.briefCopy;
    return <div className="rl-field c5-brief-website"><label id="c5-brief-website-label" className="rl-field__label" htmlFor="c5-brief-website"><span>{text.label}</span><span className="req" aria-hidden="true">*</span></label>
      <SelectComponent id="c5-brief-website" labelledBy="c5-brief-website-label" required value={value || ''} placeholder={text.placeholder}
        disabled={disabled || state.status === 'loading' || state.status === 'error'} invalid={!!error} describedBy={error ? 'c5-brief-website-error' : undefined}
        onChange={onChange} options={[{value:'',label:text.placeholder},...state.websites.map(site=>({value:site.id,label:client.domain(site)+(!site.canWrite?' — '+text.readonly:''),disabled:!site.canWrite}))]} />
      {state.websites.some(site => site.id === value && !site.canWrite) && <p className="rl-field__hint">{text.readonlyExplanation}</p>}
      {state.status === 'ready' && !state.websites.length && <div className="rl-field__hint"><p>{state.funding === 'unfunded' ? copy.unfunded : state.administrator ? text.emptyAdmin : text.emptyMember}</p>{state.administrator && state.funding !== 'unfunded' && <button type="button" className="rl-btn rl-btn--secondary" onClick={onAdd}>{copy.add}</button>}</div>}
      {error && <p id="c5-brief-website-error" className="c5-brief-error" role="alert">{error}</p>}
    </div>;
  }
  function KnowledgePage({site, origin, success, details, onReturnToBrief, websites, onNavigate}) {
    const [tab, setTab] = useState(0), buttons = useRef([]);
    const sourceEnabled = root.ClicklyxWebsiteSources && root.ClicklyxWebsiteSources.enabled === true;
    const tabs = sourceEnabled ? [...copy.tabs, 'Website Knowledge'] : copy.tabs;
    const briefReturnContext = details && details.briefReturnContext;
    useEffect(() => {if (details && details.tab !== undefined) setTab(Number.isInteger(details.tab) && details.tab >= 0 && details.tab < tabs.length ? details.tab : 0);}, [details && details.tab, briefReturnContext && briefReturnContext.token]);
    const Context = root.ClicklyxKnowledgeAccess.getPageContext();
    const components = [root.BrandProfile, root.ProductKnowledge, root.BrandVoice, root.IcpKnowledge];
    const keyboard = (event, index) => {
      let next = index;
      if (event.key === 'ArrowRight') next = (index + 1) % tabs.length;
      else if (event.key === 'ArrowLeft') next = (index + tabs.length - 1) % tabs.length;
      else if (event.key === 'Home') next = 0;
      else if (event.key === 'End') next = tabs.length - 1;
      else return;
      event.preventDefault(); setTab(next); buttons.current[next].focus();
    };
    return <Context.Provider value={origin}><div className="rl-page c5-knowledge"><header className="c5-knowledge-head"><h1>{client.domain(site)}</h1>{!site.canWrite && <span className="c5-readonly">{copy.readonly}</span>}{success && <p role="status">{copy.success}</p>}</header>
      {origin && websites && websites.administrator && websites.origin && root.ClicklyxWebsiteContext.isCurrent(websites.origin)
        && websites.context && websites.context.canEditArticles === true && websites.websites.some(value => value.id === site.id && !value.canWrite)
        && <div className="c5-knowledge-resource-help"><ReadOnlyHelp onPlans={() => onNavigate('settings', {section:'billing'})} /></div>}
      <div className="c5-tabs" role="tablist" aria-label={client.domain(site)}>{tabs.map((label, index) => <button type="button" key={label} ref={node => {buttons.current[index] = node;}} id={'c5-tab-' + site.id + '-' + index} role="tab" aria-selected={index === tab} aria-controls={'c5-panel-' + site.id + '-' + index} tabIndex={index === tab ? 0 : -1} onClick={() => setTab(index)} onKeyDown={event => keyboard(event, index)}>{label}{index === 4 && <span className="wk-beta">Beta</span>}</button>)}</div>
      {components.map((Component, index) => <div key={index} role="tabpanel" id={'c5-panel-' + site.id + '-' + index} aria-labelledby={'c5-tab-' + site.id + '-' + index} hidden={index !== tab}>{Component && <Component briefReturnContext={briefReturnContext && details.tab === index ? briefReturnContext : undefined} onReturnToBrief={briefReturnContext && details.tab === index ? onReturnToBrief : undefined} />}</div>)}
      {sourceEnabled && <div role="tabpanel" id={'c5-panel-' + site.id + '-4'} aria-labelledby={'c5-tab-' + site.id + '-4'} hidden={tab !== 4}>
        {tab === 4 && origin && root.ClicklyxWebsiteContext.isCurrent(origin) && root.WebsiteKnowledge
          && <root.WebsiteKnowledge key={site.id + ':' + origin.epoch + ':' + origin.workspaceEpoch} site={site} origin={origin} />}
      </div>}
    </div></Context.Provider>;
  }
  root.ClicklyxWebsitesUI = {useWebsites, useKnowledgePages, WebsitesSidebar, HomeWebsites, WebsitesOverview, KnowledgePage, KnowledgeLoadState, BriefWebsiteField, AddWebsite, SelectWebsites, DeleteWebsite};
})(window);
