// Platform outreach is separate from customer SMS subscriptions.
Object.assign(DICT.ru, {
  'Workshop invitations':'Приглашения сервисов','Invite a workshop':'Пригласить сервис',
  'Create invitation':'Создать приглашение','Workshop name':'Название сервиса','Recipient phone':'Телефон получателя',
  'SMS language':'Язык SMS','Country':'Страна','Poland':'Польша','Belarus':'Беларусь',
  'Registration link':'Ссылка на регистрацию','Copy link':'Копировать ссылку','Link copied':'Ссылка скопирована',
  'Customer requests':'Запросы пользователей','Prepare invitation':'Подготовить приглашение',
  'No invitations yet':'Приглашений пока нет','Search by name or phone':'Поиск по названию или телефону',
  'Invitation history':'История контактов','No contacts recorded':'Контакты пока не записаны',
  'Send SMS':'Отправить SMS','Send one test SMS':'Отправить одну тестовую SMS','SMS preview':'Превью SMS',
  'Test send to my number':'Тестовая отправка на свой номер','Test recipient':'Номер для теста',
  'One segment required':'Допускается только один SMS-сегмент','SMS queued':'SMS поставлена в очередь',
  'Queued':'В очереди','Accepted by provider':'Принято SMS-провайдером','Retry scheduled':'Ожидает повторной попытки',
  'Failed':'Ошибка отправки','Cancelled':'Отменено','Manually recorded':'Записано вручную',
  'Record contact':'Записать контакт','Personal meeting':'Личная встреча','Email (manual record)':'Email (запись вручную)',
  'Contact note':'Комментарий о контакте','Email address':'Email получателя','Save contact':'Сохранить контакт',
  'This records a contact; it does not send an email.':'Это запись о контакте, письмо автоматически не отправляется.',
  'Provider acceptance does not confirm delivery to the phone.':'Принятие провайдером не подтверждает доставку на телефон.',
  'Invitation opened':'Был переход по ссылке','No link visits yet':'Переходов по ссылке пока нет',
  'Link visits can include automatic previews.':'Переход может быть автоматическим превью ссылки.',
  'Registration application':'Заявка на регистрацию','Open application':'Открыть заявку',
  'Link expires':'Ссылка действует до','Expired or already registered':'Ссылка истекла или заявка уже получена',
  'Latest 100 invitations. SMS, email and meeting history.':'Последние 100 приглашений. История SMS, email и личных встреч.',
  'Recipient or country is invalid. Ukraine is not supported.':'Проверьте номер и страну. Отправка в Украину отключена.',
  'Wait one minute before resending. Daily limit: 20 SMS per administrator.':'Повторная отправка — через минуту. Лимит: 20 SMS в день на администратора.',
  'Each send is recorded with its recipient, template and provider status.':'Каждая отправка сохраняется с получателем, текстом и статусом провайдера.',
  'Preview uses an example link; the saved invitation has its own link.':'В превью пример ссылки; после создания приглашение получит собственную ссылку.',
  'Creating...':'Создание...','Create':'Создать','Save':'Сохранить','Loading...':'Загрузка...',
  'View details':'Открыть','Close':'Закрыть','Attempts':'Попытки','Operator':'Оператор',
});
Object.assign(DICT.pl, {
  'Workshop invitations':'Zaproszenia warsztatów','Invite a workshop':'Zaproś warsztat','Create invitation':'Utwórz zaproszenie',
  'Workshop name':'Nazwa warsztatu','Recipient phone':'Telefon odbiorcy','SMS language':'Język SMS','Country':'Kraj',
  'Poland':'Polska','Belarus':'Białoruś','Registration link':'Link do rejestracji','Copy link':'Kopiuj link','Link copied':'Link skopiowany',
  'Customer requests':'Zgłoszenia klientów','Prepare invitation':'Przygotuj zaproszenie','No invitations yet':'Brak zaproszeń',
  'Search by name or phone':'Szukaj nazwy lub telefonu','Invitation history':'Historia kontaktów','No contacts recorded':'Brak zapisanych kontaktów',
  'Send SMS':'Wyślij SMS','Send one test SMS':'Wyślij jeden testowy SMS','SMS preview':'Podgląd SMS',
  'Test send to my number':'Test na mój numer','Test recipient':'Numer testowy','One segment required':'Dozwolony tylko jeden segment SMS',
  'SMS queued':'SMS w kolejce','Queued':'W kolejce','Accepted by provider':'Przyjęty przez operatora SMS','Retry scheduled':'Zaplanowano ponowną próbę',
  'Failed':'Błąd wysyłki','Cancelled':'Anulowano','Manually recorded':'Zapisano ręcznie','Record contact':'Zapisz kontakt',
  'Personal meeting':'Spotkanie osobiste','Email (manual record)':'Email (zapis ręczny)','Contact note':'Notatka kontaktu',
  'Email address':'Adres email','Save contact':'Zapisz kontakt','This records a contact; it does not send an email.':'Zapis kontaktu nie wysyła wiadomości email.',
  'Provider acceptance does not confirm delivery to the phone.':'Przyjęcie przez operatora nie potwierdza doręczenia na telefon.',
  'Invitation opened':'Otwarto link','No link visits yet':'Link nie był jeszcze otwierany','Link visits can include automatic previews.':'Otwarcia mogą obejmować automatyczne podglądy.',
  'Registration application':'Wniosek rejestracyjny','Open application':'Otwórz wniosek','Link expires':'Link ważny do',
  'Expired or already registered':'Link wygasł lub wniosek już otrzymano',
  'Latest 100 invitations. SMS, email and meeting history.':'Ostatnie 100 zaproszeń. Historia SMS, email i spotkań.',
  'Recipient or country is invalid. Ukraine is not supported.':'Sprawdź numer i kraj. Wysyłka do Ukrainy jest wyłączona.',
  'Wait one minute before resending. Daily limit: 20 SMS per administrator.':'Ponowna wysyłka po minucie. Limit: 20 SMS dziennie na administratora.',
  'Each send is recorded with its recipient, template and provider status.':'Każda wysyłka zapisuje odbiorcę, treść i status operatora.',
  'Preview uses an example link; the saved invitation has its own link.':'Podgląd zawiera przykładowy link. Zapisane zaproszenie ma własny link.',
  'View details':'Szczegóły','Close':'Zamknij','Attempts':'Próby','Operator':'Operator',
});

Object.assign(DICT.ru, {
  'Manage invitations and follow each workshop’s progress.':'Приглашайте сервисы и отслеживайте каждый контакт.','Partner network':'Партнёрская сеть',
  'Latest invitations':'Последние приглашения','Copy link failed':'Не удалось скопировать ссылку. Выделите её в поле и скопируйте вручную.','All invitations':'Все приглашения','Without records':'Без истории','Applications received':'С заявкой',
  'invitations':'приглашений','Overview':'Обзор','SMS message':'SMS','Contact history':'История',
  'Reset filters':'Сбросить фильтры','Create your first invitation to get a registration link and track contact history.':'Создайте первое приглашение: здесь появятся ссылка на регистрацию и история контактов.','Select an invitation':'Выберите приглашение','Select a workshop to see its link, messages and contact history.':'Здесь будут ссылка, сообщения и история контактов с сервисом.',
  'No matching invitations':'Ничего не найдено','Try a different name or phone number.':'Попробуйте другое название или номер телефона.',
  'Clear search':'Сбросить поиск','Back to invitations':'К приглашениям','Invitation details':'Детали приглашения',
  'Ready to invite':'Готово к отправке','Application received':'Заявка получена','Link expired':'Ссылка истекла',
  'Created':'Создано','Invitation language':'Язык приглашения','Latest contact':'Последний контакт',
  'Recent activity':'Последние события','View full history':'Вся история','No activity yet':'Контактов пока нет',
  'Copy registration link':'Копировать ссылку на регистрацию','Registration':'Регистрация',
  'Send an invitation or record your first meeting with this workshop.':'Отправьте приглашение или запишите результат встречи с сервисом.',
  'Test SMS':'Тестовая SMS','To workshop':'Сервису','Sending to':'Получатель',
  'Check the message on your own phone before sending it to the workshop.':'Проверьте сообщение на своём телефоне перед отправкой сервису.',
  'Message':'Сообщение','Sending...':'Отправка...','Contact saved':'Контакт сохранён',
  'Message and details':'Текст и подробности','Add contact':'Добавить контакт','Cancel':'Отмена',
  'Manual contact':'Контакт вручную','View application':'Открыть заявку','Link activity':'Переход по ссылке',
  'Use this link to register the workshop.':'По этой ссылке сервис сможет зарегистрироваться.',
});
Object.assign(DICT.pl, {
  'Manage invitations and follow each workshop’s progress.':'Zapraszaj warsztaty i śledź historię kontaktów.','Partner network':'Sieć partnerów',
  'Latest invitations':'Ostatnie zaproszenia','Copy link failed':'Nie udało się skopiować linku. Zaznacz go w polu i skopiuj ręcznie.','All invitations':'Wszystkie','Without records':'Bez historii','Applications received':'Ze zgłoszeniem',
  'invitations':'zaproszeń','Overview':'Przegląd','SMS message':'SMS','Contact history':'Historia',
  'Reset filters':'Wyczyść filtry','Create your first invitation to get a registration link and track contact history.':'Utwórz pierwsze zaproszenie, aby otrzymać link do rejestracji i śledzić historię kontaktów.','Select an invitation':'Wybierz zaproszenie','Select a workshop to see its link, messages and contact history.':'Tutaj zobaczysz link, wiadomości i historię kontaktu z warsztatem.',
  'No matching invitations':'Brak wyników','Try a different name or phone number.':'Spróbuj innej nazwy lub numeru telefonu.',
  'Clear search':'Wyczyść wyszukiwanie','Back to invitations':'Do zaproszeń','Invitation details':'Szczegóły zaproszenia',
  'Ready to invite':'Gotowe do wysłania','Application received':'Otrzymano zgłoszenie','Link expired':'Link wygasł',
  'Created':'Utworzono','Invitation language':'Język zaproszenia','Latest contact':'Ostatni kontakt',
  'Recent activity':'Ostatnia aktywność','View full history':'Cała historia','No activity yet':'Brak kontaktów',
  'Copy registration link':'Kopiuj link do rejestracji','Registration':'Rejestracja',
  'Send an invitation or record your first meeting with this workshop.':'Wyślij zaproszenie lub zapisz wynik spotkania z warsztatem.',
  'Test SMS':'Testowy SMS','To workshop':'Do warsztatu','Sending to':'Odbiorca',
  'Check the message on your own phone before sending it to the workshop.':'Sprawdź wiadomość na własnym telefonie przed wysłaniem do warsztatu.',
  'Message':'Wiadomość','Sending...':'Wysyłanie...','Contact saved':'Kontakt zapisany',
  'Message and details':'Treść i szczegóły','Add contact':'Dodaj kontakt','Cancel':'Anuluj',
  'Manual contact':'Kontakt ręczny','View application':'Otwórz zgłoszenie','Link activity':'Otwarcie linku',
  'Use this link to register the workshop.':'Ten link umożliwia rejestrację warsztatu.',
});

function OutreachIcon({name,size=16}) {
  if(name==='copy')return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><rect x="8" y="8" width="12" height="12" rx="2"/><path d="M16 8V4a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v11a1 1 0 0 0 1 1h4"/></svg>;
  return React.createElement(Icon[name]||Icon.mail,{size,'aria-hidden':true});
}
function outreachLanguage(code) { return ({pl:'Polski',ru:'Русский',uk:'Українська',en:'English'})[code]||code; }
function outreachContacts(item) { return [...(item.contacts||[])].sort((a,b)=>new Date(b.createdAt)-new Date(a.createdAt)); }
function outreachState(item) {
  if(item.applicationId)return {label:'Application received',tone:'success'};
  if(new Date(item.expiresAt)<=new Date())return {label:'Link expired',tone:'neutral'};
  const latest=outreachContacts(item)[0];
  if(!latest)return {label:'Ready to invite',tone:'neutral'};
  return {label:({queued:'Queued',accepted:'Accepted by provider',failed:'Failed',retrying:'Retry scheduled',cancelled:'Cancelled',recorded:'Manually recorded'})[latest.status]||latest.status,tone:latest.status==='failed'?'danger':['queued','retrying'].includes(latest.status)?'warning':'neutral'};
}
function OutreachState({item}) { const state=outreachState(item);return <Badge kind={state.tone} pip>{tx(state.label)}</Badge>; }
function outreachChannel(channel) { return channel==='sms'?'SMS':tx(channel==='email'?'Email (manual record)':'Personal meeting'); }

function WorkshopInvitationsView({go,lang,onLang}) {
  const [items,setItems]=React.useState([]),[requests,setRequests]=React.useState([]);
  const [loading,setLoading]=React.useState(true),[error,setError]=React.useState(''),[selected,setSelected]=React.useState('');
  const [draft,setDraft]=React.useState(null),[query,setQuery]=React.useState(''),[filter,setFilter]=React.useState('all');
  const rowRefs=React.useRef(new Map());
  const refresh=async()=>{try{const data=await api('/platform/workshop-invitations');setItems(data.items||[]);setRequests(data.requests||[]);setError('');}catch(e){setError(e.message);}finally{setLoading(false);}};
  React.useEffect(()=>{let active=true;const load=async()=>{if(active)await refresh();};load();const timer=setInterval(load,5000);return()=>{active=false;clearInterval(timer);};},[]);
  const update=item=>{setItems(list=>[item,...list.filter(i=>i.id!==item.id)]);setSelected(item.id);};
  const date=(value,short=false)=>value?new Date(value).toLocaleString(I18N.lang==='ru'?'ru-RU':I18N.lang==='pl'?'pl-PL':'en-GB',short?{day:'numeric',month:'short'}:{day:'numeric',month:'short',year:'numeric',hour:'2-digit',minute:'2-digit'}):'—';
  const status=c=>tx(({queued:'Queued',accepted:'Accepted by provider',failed:'Failed',retrying:'Retry scheduled',cancelled:'Cancelled',recorded:'Manually recorded'})[c.status]||c.status);
  const counts={all:items.length,uncontacted:items.filter(i=>!(i.contacts||[]).length&&!i.applicationId).length,applications:items.filter(i=>i.applicationId).length};
  const filtered=items.filter(i=>(filter==='all'||(filter==='applications'?!!i.applicationId:!(i.contacts||[]).length&&!i.applicationId))&&`${i.workshopName} ${i.phone||''}`.toLowerCase().includes(query.trim().toLowerCase()));
  const row=items.find(i=>i.id===selected);
  const close=()=>{const id=selected;setSelected('');requestAnimationFrame(()=>rowRefs.current.get(id)?.focus());};
  return <div className="outreach-page">
    <header className="outreach-header"><div><div className="outreach-eyebrow">Carfello · {tx('Partner network')}</div><h1>{tx('Workshop invitations')}</h1><p>{tx('Manage invitations and follow each workshop’s progress.')}</p></div><div className="outreach-actions"><AdLangSelect lang={lang} onLang={onLang}/><button className="btn btn-primary" onClick={()=>setDraft({})}><OutreachIcon name="plus"/>{tx('Invite a workshop')}</button></div></header>
    {error&&<div className="banner-warn outreach-error" role="alert"><span>{error}</span><button className="btn btn-ghost" onClick={refresh}>{tx('Retry')}</button></div>}
    {!!requests.length&&<details className="outreach-requests"><summary><OutreachIcon name="inbox"/>{tx('Customer requests')}<span className="outreach-count">{requests.length}</span><OutreachIcon name="chevD"/></summary>{requests.map(q=><div key={q.id} className="outreach-request"><span><strong>{q.workshopName}</strong><small>{q.phone||'—'} · {q.countryCode} · {date(q.createdAt)}</small></span><button className="btn btn-outline sm" onClick={()=>setDraft(q)}>{tx('Prepare invitation')}<OutreachIcon name="arrowR" size={14}/></button></div>)}</details>}
    <div className="outreach-toolbar"><div className="outreach-filters" aria-label={tx('Workshop invitations')}>{[['all','All invitations'],['uncontacted','Without records'],['applications','Applications received']].map(([key,label])=><button type="button" key={key} aria-pressed={filter===key} onClick={()=>{setFilter(key);setSelected('');}}>{tx(label)}<span>{counts[key]}</span></button>)}</div><label className="outreach-search"><OutreachIcon name="search"/><input aria-label={tx('Search by name or phone')} placeholder={tx('Search by name or phone')} value={query} onChange={e=>{setQuery(e.target.value);setSelected('');}}/>{query&&<button className="outreach-icon-button" aria-label={tx('Clear search')} onClick={()=>setQuery('')}><OutreachIcon name="x" size={14}/></button>}</label></div>
    {!loading&&!filtered.length?<section className="outreach-empty-state"><span className="outreach-empty-icon"><OutreachIcon name={items.length?'search':'userPlus'} size={26}/></span><h2>{tx(items.length?'No matching invitations':'No invitations yet')}</h2><p>{tx(items.length?'Try a different name or phone number.':'Create your first invitation to get a registration link and track contact history.')}</p><button className={'btn '+(items.length?'btn-outline':'btn-primary')} onClick={()=>{if(items.length){setQuery('');setFilter('all');setSelected('');}else setDraft({});}}>{tx(items.length?'Reset filters':'Invite a workshop')}</button></section>:<div className={'outreach-layout '+(row?'has-selection':'')}>
      <section className="outreach-index" aria-label={tx('All invitations')}><div className="outreach-list-head"><span>{tx('Latest invitations')}</span><span>{filtered.length} / {items.length}</span></div>
        {loading?<div className="outreach-list-placeholder">{tx('Loading...')}</div>:!filtered.length?<div className="outreach-list-placeholder"><OutreachIcon name="search" size={24}/><strong>{tx(items.length?'No matching invitations':'No invitations yet')}</strong><p>{tx(items.length?'Try a different name or phone number.':'Send an invitation or record your first meeting with this workshop.')}</p></div>:<div className="outreach-list">{filtered.map(i=>{const last=outreachContacts(i)[0];return <button type="button" ref={node=>node?rowRefs.current.set(i.id,node):rowRefs.current.delete(i.id)} key={i.id} className={'outreach-card '+(i.id===selected?'selected':'')} aria-pressed={i.id===selected} aria-controls="outreach-detail" onClick={()=>setSelected(i.id)}><span className="outreach-card-top"><strong>{i.workshopName}</strong><OutreachIcon name="chevR" size={15}/></span><span className="outreach-card-contact">{i.phone||'—'}<span>{i.countryCode} · {outreachLanguage(i.language)}</span></span><span className="outreach-card-bottom"><OutreachState item={i}/><small title={date(last?.createdAt||i.createdAt)}>{date(last?.createdAt||i.createdAt,true)}</small></span>{last&&<span className="outreach-card-channel"><OutreachIcon name={last.channel==='sms'?'chat':last.channel==='email'?'mail':'users'} size={12}/>{outreachChannel(last.channel)}{last.isTest&&<span>TEST</span>}</span>}</button>;})}</div>}
      </section>
      {row?<WorkshopInvitationDetail key={row.id} item={row} update={update} go={go} date={date} status={status} onClose={close}/>:<section className="outreach-detail-empty"><span className="outreach-empty-icon"><OutreachIcon name="mail" size={26}/></span><h2>{tx('Select an invitation')}</h2><p>{tx('Select a workshop to see its link, messages and contact history.')}</p></section>}
    </div>}
    {draft&&<CreateWorkshopInvitation initial={draft} onClose={()=>setDraft(null)} onCreated={item=>{update(item);setDraft(null);setFilter('all');setQuery('');setRequests(list=>list.filter(q=>q.id!==item.requestId));}}/>}
  </div>;
}

function CreateWorkshopInvitation({initial,onClose,onCreated}) {
  const [form,setForm]=React.useState({requestId:initial.id||'',workshopName:initial.workshopName||'',phone:initial.phone||'',countryCode:initial.countryCode==='BY'?'BY':'PL',language:initial.countryCode==='BY'?'ru':'pl'});
  const [preview,setPreview]=React.useState(null),[error,setError]=React.useState(''),[busy,setBusy]=React.useState(false);
  React.useEffect(()=>{let active=true;setPreview(null);api('/platform/workshop-invitations/preview',{method:'POST',body:JSON.stringify({language:form.language})}).then(p=>{if(active){setPreview(p);setError('');}}).catch(e=>{if(active)setError(e.message);});return()=>{active=false;};},[form.language]);
  const submit=async(e)=>{e.preventDefault();setBusy(true);setError('');try{onCreated(await api('/platform/workshop-invitations',{method:'POST',body:JSON.stringify(form)}));}catch(e){setError(e.status===422?tx('Recipient or country is invalid. Ukraine is not supported.'):e.message);}finally{setBusy(false);}};
  const field=key=>e=>setForm(f=>({...f,[key]:e.target.value}));
  return <Modal title={tx('Create invitation')} onClose={busy?()=>{}:onClose}><form className="outreach-form outreach-create" aria-label={tx('Create invitation')} onSubmit={submit}>
    <p className="outreach-help">{tx('Use this link to register the workshop.')}</p>
    <label>{tx('Workshop name')}<input className="input" required autoFocus maxLength={200} value={form.workshopName} onChange={field('workshopName')}/></label>
    <label>{tx('Recipient phone')}<input className="input" type="tel" required autoComplete="off" placeholder={form.countryCode==='BY'?'+375…':'+48…'} value={form.phone} onChange={field('phone')}/></label>
    <div className="outreach-fields"><label>{tx('Country')}<select className="input" value={form.countryCode} onChange={e=>setForm(f=>({...f,countryCode:e.target.value,language:e.target.value==='BY'?'ru':'pl'}))}><option value="PL">{tx('Poland')}</option><option value="BY">{tx('Belarus')}</option></select></label><label>{tx('SMS language')}<select className="input" value={form.language} onChange={field('language')}><option value="pl">Polski</option><option value="ru">Русский</option><option value="uk">Українська</option><option value="en">English</option></select></label></div>
    <SMSInvitationPreview preview={preview}/><p className="outreach-help">{tx('Preview uses an example link; the saved invitation has its own link.')}</p>
    {error&&<div role="alert" className="banner-warn">{error}</div>}<div className="outreach-form-footer"><button type="button" className="btn btn-ghost" onClick={onClose} disabled={busy}>{tx('Cancel')}</button><button className="btn btn-primary" disabled={busy||preview?.segments!==1}>{busy?tx('Creating...'):tx('Create invitation')}</button></div>
  </form></Modal>;
}

function SMSInvitationPreview({preview}) {return <section className="outreach-preview" aria-label={tx('SMS preview')}><div className="outreach-preview-head"><span><OutreachIcon name="chat" size={15}/>{tx('SMS preview')}</span>{preview&&<span className={preview.segments===1?'outreach-one':'outreach-over'}>{preview.segments} SMS</span>}</div><p>{preview?.body||tx('Loading...')}</p>{preview&&<div className="outreach-preview-foot"><span>{preview.units}/{preview.limit}</span><span>{preview.encoding}</span>{preview.segments!==1&&<strong className="outreach-over">{tx('One segment required')}</strong>}</div>}</section>;}

function OutreachHistory({contacts,date,status,compact=false}) {
  if(!contacts.length)return <div className="outreach-no-activity"><OutreachIcon name="history" size={20}/><div><strong>{tx('No activity yet')}</strong><p>{tx('Send an invitation or record your first meeting with this workshop.')}</p></div></div>;
  return <ol className="outreach-history">{contacts.slice(0,compact?3:contacts.length).map(c=><li key={c.id}><span className="outreach-event-icon"><OutreachIcon name={c.channel==='sms'?'chat':c.channel==='email'?'mail':'users'} size={15}/></span><div className="outreach-event"><div className="outreach-event-top"><strong>{outreachChannel(c.channel)}</strong>{c.isTest&&<span className="outreach-test-label">TEST</span>}<Badge kind={c.status==='failed'?'danger':['queued','retrying'].includes(c.status)?'warning':'neutral'}>{status(c)}</Badge></div><div className="outreach-event-meta"><time dateTime={c.createdAt}>{date(c.createdAt)}</time>{c.actorName&&<span>{c.actorName}</span>}</div>{!compact&&<><div className="outreach-event-recipient">{c.recipient}</div><details className="outreach-message-details"><summary>{tx('Message and details')}</summary><p>{c.body||'—'}</p>{c.channel==='sms'&&<small>{c.encoding} · {c.units} · {c.segments} SMS · {tx('Attempts')}: {c.attempts}{c.providerMessageId?' · ID: '+c.providerMessageId:''}{c.errorCode?' · '+c.errorCode:''}</small>}</details></>}</div></li>)}</ol>;
}

function WorkshopInvitationDetail({item,update,go,date,status,onClose}) {
  const [tab,setTab]=React.useState('overview'),[isTest,setIsTest]=React.useState(true),[recipient,setRecipient]=React.useState(''),[preview,setPreview]=React.useState(null),[busy,setBusy]=React.useState(false),[error,setError]=React.useState(''),[success,setSuccess]=React.useState('');
  const [manual,setManual]=React.useState({channel:'meeting',recipient:'',note:''}),[showManual,setShowManual]=React.useState(false);
  const key=React.useRef(null),title=React.useRef(null),tabRefs=React.useRef({}),contacts=outreachContacts(item);
  const switchTab=next=>{setTab(next);setError('');setSuccess('');requestAnimationFrame(()=>tabRefs.current[next]?.focus());};
  React.useEffect(()=>{title.current?.focus({preventScroll:true});},[]);
  React.useEffect(()=>{let active=true;setPreview(null);api('/platform/workshop-invitations/preview',{method:'POST',body:JSON.stringify({invitationId:item.id,language:item.language,isTest})}).then(p=>{if(active)setPreview(p);}).catch(e=>{if(active)setError(e.message);});return()=>{active=false;};},[item.id,item.language,isTest]);
  const send=async()=>{if(busy)return;setBusy(true);setError('');setSuccess('');if(!key.current)key.current=crypto.randomUUID();try{update(await api(`/platform/workshop-invitations/${item.id}/sms`,{method:'POST',body:JSON.stringify({idempotencyKey:key.current,isTest,testRecipient:isTest?recipient:''})}));key.current=null;setSuccess(tx('SMS queued'));}catch(e){setError(e.status===429?tx('Wait one minute before resending. Daily limit: 20 SMS per administrator.'):e.message);}finally{setBusy(false);}};
  const record=async(e)=>{e.preventDefault();setBusy(true);setError('');setSuccess('');try{update(await api(`/platform/workshop-invitations/${item.id}/contacts`,{method:'POST',body:JSON.stringify(manual)}));setManual(m=>({...m,note:''}));setShowManual(false);setSuccess(tx('Contact saved'));}catch(e){setError(e.message);}finally{setBusy(false);}};
  const copy=async()=>{try{await navigator.clipboard.writeText(item.registrationUrl);setSuccess(tx('Link copied'));setError('');}catch{setError(tx('Copy link failed'));}};
  const inactive=!!item.applicationId||new Date(item.expiresAt)<=new Date();
  return <section className="outreach-detail" id="outreach-detail" aria-label={tx('Invitation details')}>
    <header className="outreach-detail-header"><button className="outreach-back" onClick={onClose}><OutreachIcon name="chevR"/>{tx('Back to invitations')}</button><div className="outreach-detail-title"><span className="outreach-workshop-icon"><OutreachIcon name="wrench" size={21}/></span><div><h2 ref={title} tabIndex={-1}>{item.workshopName}</h2><p>{item.phone||'—'}<span>·</span>{tx(item.countryCode==='BY'?'Belarus':'Poland')}<span>·</span>{outreachLanguage(item.language)}</p></div><button className="outreach-icon-button outreach-close" aria-label={tx('Close')} onClick={onClose} disabled={busy}><OutreachIcon name="x"/></button></div><div className="outreach-detail-status"><OutreachState item={item}/><span>{tx('Created')} {date(item.createdAt)}</span></div></header>
    <div className="outreach-tabs" role="tablist" aria-label={tx('Invitation details')}>{[['overview','Overview'],['sms','SMS message'],['history','Contact history']].map(([value,label])=><button key={value} id={'outreach-tab-'+value} role="tab" type="button" tabIndex={tab===value?0:-1} ref={node=>{tabRefs.current[value]=node;}} aria-selected={tab===value} aria-controls={'outreach-panel-'+value} onClick={()=>switchTab(value)} onKeyDown={e=>{const keys=['overview','sms','history'];const index=keys.indexOf(value);const next=e.key==='ArrowRight'?keys[(index+1)%3]:e.key==='ArrowLeft'?keys[(index+2)%3]:e.key==='Home'?keys[0]:e.key==='End'?keys[2]:null;if(next){e.preventDefault();switchTab(next);}}}>{tx(label)}{value==='history'&&<span>{contacts.length}</span>}</button>)}</div>
    <div className="outreach-detail-body" role="tabpanel" id={'outreach-panel-'+tab} aria-labelledby={'outreach-tab-'+tab}>
      {error&&<div role="alert" className="banner-warn outreach-notice">{error}</div>}{success&&<div role="status" className="outreach-success"><OutreachIcon name="checkCircle"/>{success}</div>}
      {tab==='overview'&&<><section className="outreach-link-card"><div className="outreach-section-heading"><h3>{tx('Registration link')}</h3><OutreachIcon name="globe"/></div><p className="outreach-help">{tx('Use this link to register the workshop.')}</p><div className="outreach-link"><input className="input" aria-label={tx('Registration link')} readOnly value={item.registrationUrl}/><button className="btn btn-outline" onClick={copy} aria-label={tx('Copy registration link')}><OutreachIcon name="copy" size={14}/>{tx('Copy link')}</button></div><div className="outreach-link-foot"><OutreachIcon name="clock" size={13}/>{tx('Link expires')}: {date(item.expiresAt)}</div></section>
      <dl className="outreach-facts"><div><dt>{tx('Invitation language')}</dt><dd>{outreachLanguage(item.language)}</dd></div><div><dt>{tx('Link activity')}</dt><dd>{item.openedAt?date(item.openedAt):tx('No link visits yet')}</dd></div></dl>
      {item.openedAt&&<p className="outreach-help">{tx('Link visits can include automatic previews.')}</p>}
      {item.applicationId&&<div className="outreach-application"><OutreachIcon name="checkCircle"/><div><strong>{tx('Application received')}</strong><span>{tx(APPLICATION_LABELS[item.applicationStatus]||item.applicationStatus)}</span></div><button className="btn btn-outline sm" onClick={()=>go('application',{id:item.applicationId})}>{tx('View application')}<OutreachIcon name="arrowR" size={14}/></button></div>}
      <div className="outreach-section-heading outreach-activity-heading"><h3>{tx('Recent activity')}</h3><button className="btn btn-ghost sm" onClick={()=>switchTab('history')}>{tx('View full history')}<OutreachIcon name="arrowR" size={14}/></button></div><OutreachHistory compact contacts={contacts} date={date} status={status}/><div className="outreach-overview-actions"><button className="btn btn-primary" onClick={()=>switchTab('sms')} disabled={inactive}><OutreachIcon name="chat"/>{tx('Send SMS')}</button><button className="btn btn-outline" onClick={()=>{switchTab('history');setShowManual(true);}}><OutreachIcon name="plus"/>{tx('Record contact')}</button></div></>}
      {tab==='sms'&&<div className="outreach-send"><div className="outreach-send-mode" role="group" aria-label={tx('Sending to')}><button type="button" aria-pressed={isTest} onClick={()=>{setIsTest(true);key.current=null;setSuccess('');}}>{tx('Test SMS')}</button><button type="button" aria-pressed={!isTest} onClick={()=>{setIsTest(false);key.current=null;setSuccess('');}}>{tx('To workshop')}</button></div><p className="outreach-help">{tx(isTest?'Check the message on your own phone before sending it to the workshop.':'Each send is recorded with its recipient, template and provider status.')}</p>
      {isTest?<label>{tx('Test recipient')}<input className="input" type="tel" value={recipient} onChange={e=>{setRecipient(e.target.value);key.current=null;}} placeholder="+48… / +375…" autoComplete="off"/></label>:<div className="outreach-recipient"><OutreachIcon name="user"/><span><small>{tx('Sending to')}</small><strong>{item.phone}</strong></span></div>}
      <SMSInvitationPreview preview={preview}/>{inactive&&<p className="outreach-help">{tx('Expired or already registered')}</p>}<div className="outreach-send-footer"><button className="btn btn-primary" onClick={send} disabled={busy||inactive||preview?.segments!==1||(isTest&&!recipient.trim())}><OutreachIcon name="chat"/>{busy?tx('Sending...'):tx(isTest?'Send one test SMS':'Send SMS')}</button><small>{tx('Each send is recorded with its recipient, template and provider status.')}</small></div></div>}
      {tab==='history'&&<><div className="outreach-section-heading"><h3>{tx('Invitation history')}</h3><button className="btn btn-outline sm" onClick={()=>setShowManual(!showManual)}><OutreachIcon name="plus" size={14}/>{tx('Add contact')}</button></div><p className="outreach-help">{tx('Provider acceptance does not confirm delivery to the phone.')}</p>
      {showManual&&<form onSubmit={record} className="outreach-form outreach-manual"><div className="outreach-section-heading"><h3>{tx('Manual contact')}</h3><button type="button" className="outreach-icon-button" aria-label={tx('Close')} onClick={()=>setShowManual(false)}><OutreachIcon name="x" size={15}/></button></div><select aria-label={tx('Record contact')} className="input" value={manual.channel} onChange={e=>setManual(m=>({...m,channel:e.target.value}))}><option value="meeting">{tx('Personal meeting')}</option><option value="email">{tx('Email (manual record)')}</option></select>{manual.channel==='email'&&<label>{tx('Email address')}<input className="input" type="email" value={manual.recipient} onChange={e=>setManual(m=>({...m,recipient:e.target.value}))}/></label>}<label>{tx('Contact note')}<textarea className="input" required maxLength={2000} value={manual.note} onChange={e=>setManual(m=>({...m,note:e.target.value}))}/></label>{manual.channel==='email'&&<small className="outreach-help">{tx('This records a contact; it does not send an email.')}</small>}<div className="outreach-form-footer"><button type="button" className="btn btn-ghost" disabled={busy} onClick={()=>setShowManual(false)}>{tx('Cancel')}</button><button className="btn btn-primary" disabled={busy}>{tx('Save contact')}</button></div></form>}
      <OutreachHistory contacts={contacts} date={date} status={status}/></>}
    </div>
  </section>;
}
