// society-page.jsx — Society detail page (route: 'society' with payload {acronym})
// Wired from Directory · Societies tab. Visual vocabulary borrowed from recording-page.

// ---- Real-world reference URLs and contact emails for the major societies
const SOCIETY_URLS = {
  ASCAP:'https://www.ascap.com', BMI:'https://www.bmi.com', SESAC:'https://www.sesac.com',
  GMR:'https://globalmusicrights.com', HFA:'https://www.harryfox.com', MLC:'https://www.themlc.com',
  PRS:'https://www.prsformusic.com', MCPS:'https://www.prsformusic.com/about-us/mcps',
  GEMA:'https://www.gema.de', SACEM:'https://www.sacem.fr', SIAE:'https://www.siae.it', SGAE:'https://www.sgae.es',
  STIM:'https://www.stim.se', BUMA:'https://www.bumastemra.nl', SUISA:'https://www.suisa.ch', SOZA:'https://www.soza.sk',
  SOCAN:'https://www.socan.com', CMRRA:'https://www.cmrra.ca', SACVEN:'https://www.sacven.org',
  JASRAC:'https://www.jasrac.or.jp', APRA:'https://www.apraamcos.com.au', CASH:'https://www.cash.org.hk', MCSC:'http://www.mcsc.com.cn',
  SAMRO:'https://www.samro.org.za',
  SX:'https://www.soundexchange.com', PPL:'https://www.ppluk.com', GVL:'https://www.gvl.de', SCPP:'https://www.scpp.fr', PPCA:'https://www.ppca.com.au', ReSound:'https://www.resound.ca',
  ICE:'https://www.iceservices.com', MRI:'https://www.musicreports.com', MINT:'https://www.mintds.eu', Armonia:'https://www.armoniaonline.com', Latinautor:'https://www.latinautor.com',
};
const SOCIETY_EMAILS = {
  ASCAP:'memberservices@ascap.com', BMI:'memberservices@bmi.com', SESAC:'memberinfo@sesac.com',
  PRS:'memberservices@prsformusic.com', GEMA:'kundenservice@gema.de', SACEM:'contact@sacem.fr',
  SOCAN:'memberservices@socan.com', APRA:'memberservices@apraamcos.com.au', JASRAC:'info@jasrac.or.jp',
  MLC:'memberservices@themlc.com', HFA:'clientservices@harryfox.com',
};

function ScreenSociety({ go, payload }) {
  const code = payload?.acronym || payload?.code || payload;
  const all = (typeof SOCIETIES !== 'undefined' ? SOCIETIES : []);
  const soc = all.find(s => s.acronym === code) || all[0];
  const [editing, setEditing] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  // ── Inline edit mode (in-page editing, mirrors work-detail pattern) ──
  const [editMode, setEditMode] = React.useState(false);
  const [patches, setPatches] = React.useState({});
  const commit = (k, v) => {
    setPatches(p => ({ ...p, [k]: v }));
    window.dispatchEvent(new CustomEvent('astro-toast',{detail:{msg:`Saved · ${k}`,tone:'ok'}}));
  };
  if (!soc) {
    return (
      <div style={{padding:'80px 0',textAlign:'center'}}>
        <div className="ff-mono upper" style={{fontSize:11,letterSpacing:'.12em',color:'var(--ink-3)',marginBottom:14}}>SOCIETY NOT FOUND</div>
        <Btn variant="secondary" onClick={()=>go('directory')}>Back to directory</Btn>
      </div>
    );
  }

  const toast = (msg, tone='ok') => window.dispatchEvent(new CustomEvent('astro-toast',{detail:{msg,tone}}));

  // Effective values — merge in any inline edits
  const eff = { ...soc, ...patches };
  const defaultEmail   = SOCIETY_EMAILS[soc.acronym] || `registrations@${soc.acronym.toLowerCase()}.org`;
  const defaultWebsite = SOCIETY_URLS[soc.acronym] || `https://www.${soc.acronym.toLowerCase()}.com`;
  const effEmail   = patches.email   ?? defaultEmail;
  const effWebsite = patches.website ?? defaultWebsite;
  const effPhone   = patches.phone   ?? '';
  const effAddress = patches.address ?? soc.territory;

  // ── Derived deterministic stats (per-society, stable across renders)
  // Hash code → seeded numbers so each society reads differently
  const hash = code.split('').reduce((a,c)=>((a<<5)-a + c.charCodeAt(0))|0, 0);
  const seed = (n) => Math.abs(Math.sin(hash + n*13.7)) ;

  const kindLabel = {PRO:'Performing rights', MRO:'Mechanical rights', NRO:'Neighboring rights', CMO:'Combined / collective management', HUB:'Multi-society admin · licensing hub'}[soc.kind];
  const kindColor = soc.kind === 'PRO' ? '#0a4a8c' : soc.kind === 'MRO' ? '#9b6a18' : soc.kind === 'NRO' ? '#0f6e3a' : soc.kind === 'HUB' ? '#a04432' : '#5a3d6e';

  const ackTone = (n) => n >= 99 ? '#0f6e3a' : n >= 95 ? '#0a4a8c' : n >= 90 ? '#9b6a18' : '#a04432';

  // Synthetic operational numbers
  const worksRegistered = Math.round(820 + seed(1)*4200);
  const claimsOpen      = Math.round(seed(2)*14);
  const claimsResolved  = Math.round(120 + seed(3)*340);
  const ytdEarnings     = Math.round(8200 + seed(4)*92000);
  const lastQuarterEarnings = Math.round(ytdEarnings * (0.18 + seed(5)*0.12));

  // 12-month ack-rate spark — anchor on current ackRate, +/- 3pts
  const sparkAck = Array.from({length:12}, (_,i)=> {
    const drift = (Math.sin(hash*0.3 + i*0.6) * 1.6 + (i-6)*0.05);
    return Math.max(70, Math.min(100, soc.ackRate + drift));
  });

  // Recent CWR transmissions to this society
  const baseTxn = (typeof TXN !== 'undefined' ? TXN : []).filter(t => t.recv === code);
  const txns = baseTxn.length ? baseTxn : [
    {id:`CWR-2026-0418-${code}A`, file:`CW260418${code}.V21`, count: Math.round(80+seed(7)*180), status:'acknowledged', sent:'14:22', ack:'14:48'},
    {id:`CWR-2026-0411-${code}B`, file:`CW260411${code}.V21`, count: Math.round(60+seed(8)*140), status:'acknowledged', sent:'10:08', ack:'10:39'},
    {id:`CWR-2026-0404-${code}C`, file:`CW260404${code}.V21`, count: Math.round(40+seed(9)*120), status: seed(10)>0.7 ? 'rejected':'acknowledged', sent:'09:14', ack:'10:02'},
  ];

  // Top works registered with this society (synthetic — pulls real WORKS titles if available)
  const topWorks = (typeof WORKS !== 'undefined' ? WORKS : []).slice(0, 8).map((w, i) => ({
    work: w,
    royalty: Math.round((0.4 + seed(20+i)) * 12000) / 100,
    pct: Math.round((seed(30+i)*40 + 25)),
  }));

  // ── helpers ──
  const Stat = ({label, value, sub, tone}) => (
    <div style={{padding:'18px 18px',borderRight:'1px solid var(--rule)'}}>
      <div className="ff-mono upper" style={{fontSize:9,letterSpacing:'.14em',color:'var(--ink-3)',fontWeight:500}}>{label}</div>
      <div className="ff-display num" style={{fontSize:32,fontWeight:600,letterSpacing:'-0.025em',marginTop:8,color: tone || 'var(--ink)'}}>{value}</div>
      {sub && <div className="ff-mono" style={{fontSize:11,color:'var(--ink-3)',marginTop:4}}>{sub}</div>}
    </div>
  );

  const StatusPill = ({status}) => {
    const map = {
      acknowledged: {bg:'oklch(0.94 0.06 140)', fg:'#0f6e3a', label:'ACK'},
      submitted:    {bg:'oklch(0.95 0.04 250)', fg:'#0a4a8c', label:'SUBMITTED'},
      rejected:     {bg:'oklch(0.93 0.08 25)',  fg:'#a04432', label:'REJECTED'},
    };
    const s = map[status] || map.submitted;
    return <span className="ff-mono upper" style={{fontSize:9,letterSpacing:'.1em',padding:'3px 7px',background:s.bg,color:s.fg,fontWeight:600}}>{s.label}</span>;
  };

  return (
    <div>
      {/* Title block */}
      <div style={{display:'grid',gridTemplateColumns:'1fr 360px',gap:48,alignItems:'end',marginBottom:24}}>
        <div>
          <button onClick={()=>go('directory')} className="ff-mono upper" style={{fontSize:10,color:'var(--ink-3)',marginBottom:14,display:'inline-flex',alignItems:'center',gap:6,background:'transparent',border:0,cursor:'pointer'}}>
            <Ic.Left width={12} height={12}/> Directory / Societies
          </button>
          <div className="ff-mono upper" style={{fontSize:10,color:'var(--ink-3)',marginBottom:8,letterSpacing:'.14em'}}>SOCIETY · {eff.country} · {eff.territory}</div>
          <div style={{display:'flex',alignItems:'flex-start',gap:24}}>
            <span style={{width:18,height:'clamp(48px,7vw,108px)',background:kindColor,marginTop:8,flexShrink:0}}/>
            {editMode && window.InlineText ? (
              <window.InlineText
                as="h1"
                value={eff.acronym}
                onCommit={(v)=>commit('acronym', v)}
                className="heading-swap ff-display"
                style={{fontSize:'clamp(48px,7vw,108px)',fontWeight:700,letterSpacing:'-0.05em',lineHeight:0.9,margin:0,display:'inline-block'}}
              />
            ) : (
              <h1 className="heading-swap ff-display" style={{fontSize:'clamp(48px,7vw,108px)',fontWeight:700,letterSpacing:'-0.05em',lineHeight:0.9,margin:0}}>{eff.acronym}</h1>
            )}
          </div>
          <div style={{marginTop:16,fontSize:18,color:'var(--ink)',fontWeight:500,letterSpacing:'-0.005em',maxWidth:680,lineHeight:1.3}}>
            {editMode && window.InlineText ? (
              <window.InlineText value={eff.name} onCommit={(v)=>commit('name', v)} multiline placeholder="Full name"/>
            ) : eff.name}
          </div>

          <div style={{display:'flex',gap:10,marginTop:18,flexWrap:'wrap',alignItems:'center'}}>
            <Pill tone="soft">{eff.kind} · {kindLabel}</Pill>
            <Pill>{eff.cwrAck}</Pill>
            {eff.kind !== 'HUB' && <Pill tone="soft">{(eff.members||0).toLocaleString()} members</Pill>}
            <Pill tone={eff.ackRate >= 95 ? 'ok' : eff.ackRate >= 90 ? 'soft' : 'danger'} dot>{eff.ackRate}% ack rate</Pill>
            <Pill tone="soft">last sent {eff.lastSent}</Pill>
          </div>
        </div>
        <div style={{display:'flex',flexDirection:'column',gap:10,alignItems:'flex-end'}}>
          <Btn variant="accent" icon={<Ic.Send/>} onClick={()=>setSending(true)}>Send CWR file</Btn>
          <Btn variant="secondary" icon={<Ic.Bar/>} onClick={()=>go('analytics')}>Royalty report</Btn>
          <Btn variant={editMode ? 'accent' : 'ghost'} icon={editMode ? <Ic.Check/> : <Ic.Edit/>} onClick={()=>{
            if (editMode) { setEditMode(false); toast('Done editing', 'ok'); }
            else { setEditMode(true); toast('Editing — click any field to change it'); }
          }}>{editMode ? 'Done editing' : 'Edit society'}</Btn>
          {window.DetailDelete && (
            <window.DetailDelete kind="party" record={{ id: soc.acronym, ...soc }} title={soc.name || soc.acronym} subtitle={`Society · ${soc.acronym}`} onDeleted={() => go && go('directory', { tab: 'societies' })} />
          )}
          <Btn variant="ghost" icon={<Ic.Ext/>} onClick={()=>{ const url = SOCIETY_URLS[soc.acronym] || `https://www.google.com/search?q=${encodeURIComponent(soc.name)}`; window.open(url, '_blank', 'noopener,noreferrer'); toast(`Opening ${soc.acronym} website →`); }}>Society website</Btn>
        </div>
      </div>

      {/* AT A GLANCE — stats strip */}
      <div style={{borderTop:'1px solid var(--rule)',borderBottom:'1px solid var(--rule)',display:'grid',gridTemplateColumns:'repeat(5, 1fr)',marginBottom:48}}>
        <Stat label="Works registered"  value={worksRegistered.toLocaleString()} sub="active in CWR feed"/>
        <Stat label="Royalties YTD"     value={`$${ytdEarnings.toLocaleString()}`} sub={`Last Q · $${lastQuarterEarnings.toLocaleString()}`}/>
        <Stat label="Ack rate · 12mo"   value={`${soc.ackRate}%`} tone={ackTone(soc.ackRate)} sub={`avg ${(sparkAck.reduce((a,b)=>a+b,0)/sparkAck.length).toFixed(1)}%`}/>
        <Stat label="Open claims"       value={claimsOpen} tone={claimsOpen>5?'#a04432':'var(--ink)'} sub={`${claimsResolved} resolved YTD`}/>
        <div style={{padding:'18px 18px'}}>
          <div className="ff-mono upper" style={{fontSize:9,letterSpacing:'.14em',color:'var(--ink-3)',fontWeight:500}}>Ack rate · trend</div>
          <svg viewBox="0 0 200 60" preserveAspectRatio="none" style={{width:'100%',height:54,marginTop:8,display:'block'}}>
            {(() => {
              const min = Math.min(...sparkAck) - 1;
              const max = Math.max(...sparkAck) + 1;
              const xs = sparkAck.map((v,i)=>[i*(200/(sparkAck.length-1)), 60 - ((v-min)/(max-min))*54]);
              const d = xs.map(([x,y],i)=>(i?'L':'M')+x.toFixed(1)+','+y.toFixed(1)).join(' ');
              return <>
                <path d={d} fill="none" stroke={ackTone(soc.ackRate)} strokeWidth={1.5}/>
                <circle cx={xs[xs.length-1][0]} cy={xs[xs.length-1][1]} r={2.5} fill={ackTone(soc.ackRate)}/>
              </>;
            })()}
          </svg>
        </div>
      </div>

      {/* Two-col body */}
      <div style={{display:'grid',gridTemplateColumns:'1fr 360px',gap:48}}>
        {/* LEFT */}
        <div>
          {/* RECENT TRANSMISSIONS */}
          <Section num="01" action={
            <button onClick={()=>go('cwr')} className="ff-mono upper" style={{fontSize:10,letterSpacing:'.06em',padding:'5px 10px',background:'transparent',color:'var(--ink-2)',border:'1px solid var(--rule)',cursor:'pointer'}}>
              All transmissions →
            </button>
          }>Recent CWR transmissions</Section>
          <div style={{borderLeft:'1px solid var(--rule)',borderTop:'1px solid var(--rule)'}}>
            <div className="ff-mono upper" style={{display:'grid',gridTemplateColumns:'1fr 220px 80px 100px 110px',fontSize:9,letterSpacing:'.1em',color:'var(--ink-3)',fontWeight:500,borderBottom:'1px solid var(--rule)',background:'var(--bg-2)'}}>
              <div style={{padding:'10px 14px',borderRight:'1px solid var(--rule)'}}>FILE</div>
              <div style={{padding:'10px 14px',borderRight:'1px solid var(--rule)'}}>TRANSMISSION ID</div>
              <div style={{padding:'10px 14px',borderRight:'1px solid var(--rule)',textAlign:'right'}}>WORKS</div>
              <div style={{padding:'10px 14px',borderRight:'1px solid var(--rule)'}}>STATUS</div>
              <div style={{padding:'10px 14px',borderRight:'1px solid var(--rule)',textAlign:'right'}}>SENT · ACK</div>
            </div>
            {txns.map((t,i)=>(
              <button key={i} onClick={()=>go('cwr')}
                style={{display:'grid',gridTemplateColumns:'1fr 220px 80px 100px 110px',gap:0,width:'100%',background:'transparent',border:0,borderBottom:'1px solid var(--rule)',cursor:'pointer',textAlign:'left',padding:0,fontFamily:'inherit',color:'inherit'}}
                onMouseEnter={e=>e.currentTarget.style.background='var(--bg-2)'}
                onMouseLeave={e=>e.currentTarget.style.background='transparent'}>
                <div className="ff-mono" style={{padding:'12px 14px',borderRight:'1px solid var(--rule)',fontSize:12,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{t.file}</div>
                <div className="ff-mono" style={{padding:'12px 14px',borderRight:'1px solid var(--rule)',fontSize:11,color:'var(--ink-3)'}}>{t.id}</div>
                <div className="ff-mono num" style={{padding:'12px 14px',borderRight:'1px solid var(--rule)',fontSize:12,textAlign:'right'}}>{t.count}</div>
                <div style={{padding:'12px 14px',borderRight:'1px solid var(--rule)'}}><StatusPill status={t.status}/></div>
                <div className="ff-mono num" style={{padding:'12px 14px',borderRight:'1px solid var(--rule)',fontSize:11,color:'var(--ink-3)',textAlign:'right'}}>{t.sent} · {t.ack}</div>
              </button>
            ))}
          </div>

          {/* TOP WORKS */}
          <div style={{height:48}}/>
          <Section num="02" action={
            <button onClick={()=>go('analytics')} className="ff-mono upper" style={{fontSize:10,letterSpacing:'.06em',padding:'5px 10px',background:'transparent',color:'var(--ink-2)',border:'1px solid var(--rule)',cursor:'pointer'}}>
              Royalty report →
            </button>
          }>Top works · {soc.acronym} earnings · 12mo</Section>
          <div className="ff-mono" style={{fontSize:11,color:'var(--ink-3)',marginBottom:10,lineHeight:1.5}}>
            Works registered with {soc.acronym} ranked by collected royalties. Click a row to open the work detail.
          </div>
          <div style={{borderTop:'1px solid var(--rule)'}}>
            {topWorks.map(({work, royalty, pct}, i) => (
              <button key={work.id} onClick={()=>go('work', work)}
                style={{display:'grid',gridTemplateColumns:'30px 1fr 100px 80px',gap:14,width:'100%',background:'transparent',border:0,borderBottom:'1px solid var(--rule-soft)',padding:'12px 0',cursor:'pointer',textAlign:'left',color:'inherit',fontFamily:'inherit',alignItems:'center'}}
                onMouseEnter={e=>e.currentTarget.style.background='var(--bg-2)'}
                onMouseLeave={e=>e.currentTarget.style.background='transparent'}>
                <span className="ff-display num" style={{fontSize:14,color:'var(--ink-4)',fontWeight:600}}>{String(i+1).padStart(2,'0')}</span>
                <div style={{minWidth:0}}>
                  <div style={{fontSize:13,fontWeight:500,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{work.title}</div>
                  <div className="ff-mono" style={{fontSize:10,color:'var(--ink-3)',marginTop:2}}>{work.iswc} · {work.writers?.[0]?.name || '—'}</div>
                </div>
                <div className="ff-mono num" style={{fontSize:13,fontWeight:600,textAlign:'right'}}>${royalty.toLocaleString()}</div>
                <div className="ff-mono num" style={{fontSize:11,color:'var(--ink-3)',textAlign:'right'}}>{pct}%</div>
              </button>
            ))}
          </div>
        </div>

        {/* RIGHT — sidebar */}
        <div>
          <Section num="·">Identity</Section>
          <div style={{borderTop:'1px solid var(--rule)'}}>
            <DetailRow label="Acronym" value={eff.acronym} editable={editMode} onCommit={(v)=>commit('acronym', v)}/>
            <DetailRow label="CISAC code" value={`0${(58 + (Math.abs(hash)%40)).toString().padStart(2,'0')}`}/>
            <DetailRow label="IPI prefix" value={eff.ipiPrefix}/>
            <DetailRow label="Country" value={eff.country} editable={editMode} onCommit={(v)=>commit('country', v)}/>
            <DetailRow label="Territory" value={eff.territory} editable={editMode} onCommit={(v)=>commit('territory', v)}/>
            <DetailRow label="Kind" value={editMode ? eff.kind : `${eff.kind} — ${kindLabel}`} editable={editMode} kind="select" options={['PRO','MRO','NRO','CMO','HUB']} onCommit={(v)=>commit('kind', v)}/>
            <DetailRow label="CWR support" value={eff.cwrAck} editable={editMode} kind="select" options={['CWR 2.1','CWR 2.2','CWR 3.0','CWR 3.1','CWR 2.1, 3.0','None — manual only']} onCommit={(v)=>commit('cwrAck', v)}/>
          </div>

          <div style={{height:32}}/>
          <Section num="·">Contact</Section>
          <div style={{borderTop:'1px solid var(--rule)'}}>
            <DetailRow label="Email"   value={effEmail}   editable={editMode} onCommit={(v)=>commit('email', v)}   mono/>
            <DetailRow label="Website" value={effWebsite.replace(/^https?:\/\//,'')} editable={editMode} onCommit={(v)=>commit('website', v.startsWith('http')?v:`https://${v}`)} mono/>
            <DetailRow label="Phone"   value={effPhone || '—'} editable={editMode} onCommit={(v)=>commit('phone', v)} mono/>
            <DetailRow label="Address" value={effAddress} editable={editMode} onCommit={(v)=>commit('address', v)} mono/>
          </div>

          <div style={{height:32}}/>
          <Section num="·">Operations</Section>
          <div style={{borderTop:'1px solid var(--rule)'}}>
            <DetailRow label="Last sent" value={soc.lastSent} mono/>
            <DetailRow label="Avg ack time" value={`${(2 + seed(11)*8).toFixed(1)}h`} mono/>
            <DetailRow label="Connection" value="OK" tone="#0f6e3a"/>
            <DetailRow label="Schedule" value="Weekly · Fridays 14:00 UTC"/>
          </div>
        </div>
      </div>

      {editing && (
        <AddSocietyModal
          onClose={()=>setEditing(false)}
          initial={{
            acronym: soc.acronym,
            name: soc.name,
            country: soc.country,
            territory: soc.territory,
            kind: soc.kind,
            cwrAck: soc.cwrAck,
            cisac: `0${(58 + (Math.abs(hash)%40)).toString().padStart(2,'0')}`,
            email: SOCIETY_EMAILS[soc.acronym] || `registrations@${soc.acronym.toLowerCase()}.org`,
            website: SOCIETY_URLS[soc.acronym] || `https://www.${soc.acronym.toLowerCase()}.com`,
            address: soc.territory,
          }}
        />
      )}
      {sending && <SendCWRModal soc={soc} onClose={()=>setSending(false)} go={go}/>}
    </div>
  );
}

function SendCWRModal({ soc, onClose, go }) {
  const [pickedFormat, setPickedFormat] = React.useState(
    (soc.cwrAck||'').includes('3.0') ? '3.0' : '2.1'
  );
  const [scope, setScope] = React.useState('queued'); // 'queued' | 'all' | 'modified'
  const [scheduling, setScheduling] = React.useState(false);
  const queuedCount = 12 + (Math.abs(soc.acronym.charCodeAt(0))%9);
  const allCount = soc.kind==='HUB' ? 1240 : Math.max(80, Math.round((soc.members||5000)/120));
  const modifiedCount = Math.max(3, Math.round(queuedCount*0.4));
  const count = scope==='queued' ? queuedCount : scope==='all' ? allCount : modifiedCount;
  const fileName = `CW${new Date().toISOString().slice(2,10).replace(/-/g,'')}${soc.acronym}.V${pickedFormat.replace('.','')}`;
  const formatsAvailable = (soc.cwrAck||'').includes(',')
    ? ['2.1','3.0']
    : (soc.cwrAck||'').includes('3.0') ? ['3.0']
    : (soc.cwrAck||'').includes('2.1') ? ['2.1'] : [];

  const send = (now) => {
    const verb = now ? 'queued for immediate transmission' : 'scheduled for next batch (Fri 14:00 UTC)';
    window.dispatchEvent(new CustomEvent('astro-toast',{detail:{msg:`${fileName} · ${count} works · ${verb}`,tone:'ok'}}));
    onClose();
    if (now) window.setTimeout(()=>go('cwr'), 200);
  };

  return (
    <div onClick={onClose} style={{position:'fixed',inset:0,background:'rgba(0,0,0,.4)',zIndex:1000,display:'flex',alignItems:'center',justifyContent:'center',padding:24}}>
      <div onClick={e=>e.stopPropagation()} style={{background:'var(--bg)',width:'min(560px,100%)',border:'1px solid var(--rule)',padding:0,maxHeight:'90vh',overflow:'auto'}}>
        <div style={{padding:'18px 22px',borderBottom:'1px solid var(--rule)',display:'flex',justifyContent:'space-between',alignItems:'center'}}>
          <div>
            <div className="ff-mono upper" style={{fontSize:9,color:'var(--ink-3)',letterSpacing:'.12em'}}>CWR · NEW TRANSMISSION</div>
            <div className="heading-swap ff-display" style={{fontSize:24,fontWeight:600,letterSpacing:'-0.03em',marginTop:4}}>Send to {soc.acronym}</div>
          </div>
          <button onClick={onClose} className="ff-mono" style={{background:'transparent',border:0,fontSize:18,cursor:'pointer',color:'var(--ink-3)',padding:4}}>✕</button>
        </div>

        <div style={{padding:'22px',display:'grid',gap:18}}>
          {formatsAvailable.length === 0 ? (
            <div style={{padding:'18px',background:'oklch(0.95 0.04 50)',border:'1px solid oklch(0.85 0.08 50)',color:'#7a4413'}}>
              <div className="ff-mono upper" style={{fontSize:10,letterSpacing:'.12em',fontWeight:600,marginBottom:6}}>NOT CWR-COMPATIBLE</div>
              <div style={{fontSize:13,lineHeight:1.5}}>{soc.acronym} accepts <b>{soc.cwrAck}</b> deliveries only. Generate the appropriate manifest from the analytics report instead.</div>
            </div>
          ) : (
            <>
              <div>
                <div className="ff-mono upper" style={{fontSize:9,letterSpacing:'.12em',color:'var(--ink-3)',fontWeight:500,marginBottom:8}}>Works to include</div>
                <div style={{display:'grid',gridTemplateColumns:'1fr 1fr 1fr',border:'1px solid var(--rule)'}}>
                  {[
                    {v:'queued', l:'Queued', n:queuedCount, sub:'unsent works'},
                    {v:'modified', l:'Modified', n:modifiedCount, sub:'changed since last send'},
                    {v:'all', l:'Full re-sync', n:allCount, sub:'every active work'},
                  ].map(({v,l,n,sub},i)=>(
                    <button key={v} onClick={()=>setScope(v)}
                      style={{padding:'12px 14px',background: scope===v ? 'var(--ink)' : 'transparent',color: scope===v ? 'var(--bg)' : 'var(--ink)',border:0,borderRight: i<2 ? '1px solid var(--rule)':'0',cursor:'pointer',textAlign:'left'}}>
                      <div className="ff-mono upper" style={{fontSize:9,letterSpacing:'.1em',fontWeight:600,opacity: scope===v ? 1 : 0.7}}>{l}</div>
                      <div className="ff-display num" style={{fontSize:24,fontWeight:600,marginTop:4,letterSpacing:'-0.02em'}}>{n.toLocaleString()}</div>
                      <div className="ff-mono" style={{fontSize:10,opacity:.7,marginTop:2}}>{sub}</div>
                    </button>
                  ))}
                </div>
              </div>

              <div>
                <div className="ff-mono upper" style={{fontSize:9,letterSpacing:'.12em',color:'var(--ink-3)',fontWeight:500,marginBottom:8}}>CWR format</div>
                <div style={{display:'flex',gap:0,border:'1px solid var(--rule)',width:'fit-content'}}>
                  {formatsAvailable.map((f,i)=>(
                    <button key={f} onClick={()=>setPickedFormat(f)} className="ff-mono upper"
                      style={{padding:'8px 16px',fontSize:10,letterSpacing:'.1em',fontWeight:500,
                        background: pickedFormat===f ? 'var(--ink)' : 'transparent',
                        color: pickedFormat===f ? 'var(--bg)' : 'var(--ink-2)',
                        border:0,borderRight:i<formatsAvailable.length-1 ? '1px solid var(--rule)':'0',cursor:'pointer'}}>
                      CWR {f}
                    </button>
                  ))}
                </div>
              </div>

              <div style={{padding:'14px',background:'var(--bg-2)',border:'1px solid var(--rule)',display:'grid',gap:6}}>
                <div className="ff-mono upper" style={{fontSize:9,letterSpacing:'.12em',color:'var(--ink-3)',fontWeight:500}}>Preview</div>
                <div className="ff-mono" style={{fontSize:13,fontWeight:600}}>{fileName}</div>
                <div className="ff-mono" style={{fontSize:11,color:'var(--ink-2)',lineHeight:1.5}}>
                  {count.toLocaleString()} {count===1?'work':'works'} · destined for {soc.acronym} ({soc.territory})<br/>
                  Estimated ack: ~{(2 + Math.random()*4).toFixed(1)}h based on {soc.acronym}&#39;s {soc.ackRate}% rate
                </div>
              </div>
            </>
          )}
        </div>

        <div style={{padding:'14px 22px',borderTop:'1px solid var(--rule)',display:'flex',justifyContent:'flex-end',gap:8,background:'var(--bg-2)'}}>
          <button onClick={onClose} className="ff-mono upper" style={{padding:'8px 14px',fontSize:10,letterSpacing:'.1em',fontWeight:500,background:'transparent',border:'1px solid var(--rule)',cursor:'pointer',color:'var(--ink-2)'}}>Cancel</button>
          {formatsAvailable.length > 0 && (
            <>
              <button onClick={()=>send(false)} className="ff-mono upper" style={{padding:'8px 14px',fontSize:10,letterSpacing:'.1em',fontWeight:500,background:'transparent',border:'1px solid var(--ink)',cursor:'pointer',color:'var(--ink)'}}>Schedule</button>
              <button onClick={()=>send(true)} className="ff-mono upper" style={{padding:'8px 14px',fontSize:10,letterSpacing:'.1em',fontWeight:500,background:'var(--ink)',color:'var(--bg)',border:0,cursor:'pointer'}}>Send now</button>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

function DetailRow({label, value, mono, tone, editable, onCommit, kind='text', options}) {
  const renderValue = () => {
    if (editable && window.InlineText) {
      if (kind === 'select' && options && window.InlineSelect) {
        return <window.InlineSelect value={value} options={options} onCommit={onCommit}/>;
      }
      return <window.InlineText value={String(value ?? '')} onCommit={onCommit} className={mono ? 'ff-mono' : ''} style={{fontSize:12,color:'var(--ink)'}}/>;
    }
    return <span className={mono ? 'ff-mono' : ''} style={{fontSize:12,color: tone || 'var(--ink)',fontWeight: tone ? 600 : 400,wordBreak:'break-word'}}>{value}</span>;
  };
  return (
    <div style={{display:'grid',gridTemplateColumns:'130px 1fr',gap:12,padding:'10px 0',borderBottom:'1px solid var(--rule-soft)',alignItems:'baseline'}}>
      <span className="ff-mono upper" style={{fontSize:9,letterSpacing:'.12em',color:'var(--ink-3)',fontWeight:500}}>{label}</span>
      {renderValue()}
    </div>
  );
}

Object.assign(window, { ScreenSociety });
