// Resident comms — multi-channel updates that close the loop with owners and
// tenants. AI-drafted, sent across SMS / email / owner portal / app, tracked.
const COMMS_THREADS = [
  { id: 'BC-3071', subj: 'Planned water shut-off — Thu 8am–11am', bldg: 'The Lumen', aud: 210, chans: ['message-square', 'mail', 'smartphone'],
    status: 'sending', statusLabel: 'Sending', sent: 188, opened: 0, time: 'now',
    body: 'Hi {first_name}, water will be off in {building} Thursday 8–11am for the roof works. Tanks will keep bathrooms running. Reply STOP to opt out.' },
  { id: 'BC-3068', subj: 'AGM reminder — 41 lots have not voted', bldg: 'Harbourview', aud: 41, chans: ['mail', 'smartphone'],
    status: 'auto', statusLabel: 'AI nudge', sent: 41, opened: 28, time: '2h',
    body: 'Hi {first_name}, the Harbourview AGM closes Thursday 6pm. Two motions still need your vote — it takes 30 seconds from your portal.' },
  { id: 'BC-3061', subj: 'Lift back in service — Level 7', bldg: 'Cove Apartments', aud: 64, chans: ['message-square'],
    status: 'resolved', statusLabel: 'Delivered', sent: 64, opened: 59, time: 'Yesterday',
    body: 'Good news — the Level 7 lift is back in service as of 4:10pm. Thanks for your patience while Otis completed the repair.' },
  { id: 'BC-3057', subj: 'Quarterly owner update — Q2 FY26', bldg: 'Parkside Gardens', aud: 96, chans: ['mail'],
    status: 'resolved', statusLabel: 'Delivered', sent: 96, opened: 71, time: '3 days',
    body: 'Your Q2 update is ready: budget on track, all routines current, two works completed. Full audit-ready report attached.' },
  { id: 'BC-3050', subj: 'Special levy — consultation open', bldg: 'Adelaide Central', aud: 120, chans: ['mail', 'smartphone'],
    status: 'info', statusLabel: 'Scheduled', sent: 0, opened: 0, time: 'Fri 9am',
    body: 'A special levy is proposed for the fire-safety remediation. Read the rationale and submit feedback before the committee meeting.' },
];
const CHAN_LABEL = { 'message-square': 'SMS', mail: 'Email', smartphone: 'App', megaphone: 'Portal' };

function CommsRow({ t, sel, onClick }) {
  return (
    <div className={`mini-row comms-row ${sel ? 'sel' : ''}`} onClick={onClick}>
      <div className="chan"><Icon name={t.chans[0]} /></div>
      <div className="tx">
        <div className="s">{t.subj}</div>
        <div className="b">{siteOf(t.bldg).short} · {t.aud} recipients · {t.chans.map(c => CHAN_LABEL[c]).join(' + ')}</div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 6 }}>
        <span className="tm">{t.time}</span>
        <TagFromStatus status={t.statusLabel} />
      </div>
    </div>
  );
}

function Composer({ t }) {
  const [chans, setChans] = React.useState(['message-square', 'mail', 'smartphone']);
  const toggle = c => setChans(p => p.includes(c) ? p.filter(x => x !== c) : [...p, c]);
  const pct = t.sent && t.aud ? Math.round((t.sent / t.aud) * 100) : 0;
  const openPct = t.opened && t.sent ? Math.round((t.opened / t.sent) * 100) : 0;
  return (
    <div className="comms-detail">
      <div className="cd-head">
        <div className="bldg">{t.id} · {siteOf(t.bldg).short} · {siteOf(t.bldg).sp}</div>
        <h2>{t.subj}</h2>
        <div className="row"><TagFromStatus status={t.statusLabel} /><span className="aud">{t.aud} recipients</span></div>
      </div>
      <div className="cd-body">
        <AiBlock title="Opsmera AI · drafted this message"
          body="I wrote this from the work order and the building's tone. It is personalised per recipient and reads at grade 6. You can edit before sending."
          basis="Residents who get an update within 24h are 70% less likely to log a follow-up call on this portfolio."
          actions={[['Use draft', 'check'], ['Rewrite', 'refresh-cw']]} />
        <div className="msg-card">
          <div className="msg-chans">
            {[['message-square', 'SMS'], ['mail', 'Email'], ['smartphone', 'App push'], ['megaphone', 'Owner portal']].map(([c, l]) => (
              <button key={c} className={`chan-toggle ${chans.includes(c) ? 'on' : ''}`} onClick={() => toggle(c)}>
                <Icon name={c} />{l}
              </button>
            ))}
          </div>
          <div className="msg-body">{t.body}</div>
          <div className="msg-vars">
            <span className="var">{'{first_name}'}</span><span className="var">{'{building}'}</span><span className="var">{'{lot}'}</span>
            <span className="msg-meta">Personalised · {chans.length} channels · ~{t.aud} sends</span>
          </div>
        </div>
        {t.sent > 0 && (
          <div className="deliver">
            <div className="dl-stat"><div className="n">{t.sent}</div><div className="l">Sent</div></div>
            <div className="dl-stat"><div className="n">{pct}%</div><div className="l">Delivered</div>
              <div className="bar"><i style={{ width: pct + '%', background: 'var(--mint-500)' }} /></div></div>
            <div className="dl-stat"><div className="n">{openPct || '—'}{openPct ? '%' : ''}</div><div className="l">Opened</div>
              <div className="bar"><i style={{ width: openPct + '%', background: '#5B9BF0' }} /></div></div>
            <div className="dl-stat"><div className="n">{Math.round(t.aud * 0.03)}</div><div className="l">Replies</div></div>
          </div>
        )}
      </div>
      <div className="cd-actions">
        <button className="btn btn-primary" onClick={() => act('Broadcast sent', { kind: 'resolved', sub: t.aud + ' recipients · ' + chans.length + ' channels' })}><Icon name="send" />Send to {t.aud}</button>
        <button className="btn btn-ghost" onClick={() => act('Saved as draft', { kind: 'info', icon: 'save' })}><Icon name="save" />Save draft</button>
        <button className="btn btn-ghost" onClick={() => act('Scheduled', { kind: 'info', icon: 'clock' })}><Icon name="clock" />Schedule</button>
      </div>
    </div>
  );
}

function Comms() {
  const [sel, setSel] = React.useState(COMMS_THREADS[0].id);
  const [showDetail, setShowDetail] = React.useState(false);
  const isMobile = useIsMobile(820);
  const t = COMMS_THREADS.find(x => x.id === sel);
  const pick = id => { setSel(id); setShowDetail(true); };
  return (
    <div className="view"><div className={`split ${showDetail ? 'show-detail' : ''}`}>
      <div className="split-list">
        <div className="in-toolbar">
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--fg-3)' }}>Resident comms</span>
          <button className="btn btn-primary btn-sm" style={{ marginLeft: 'auto' }} onClick={() => act('New broadcast', { kind: 'info', icon: 'plus', sub: 'AI will draft from a work order or topic' })}><Icon name="plus" />New</button>
        </div>
        <div style={{ padding: '14px 20px 4px' }}>
          <div className="stat-strip">
            <div className="s"><div className="n">1,284</div><div className="l">Sent / wk</div></div>
            <div className="s"><div className="n">71%</div><div className="l">Open rate</div></div>
            <div className="s"><div className="n">-38%</div><div className="l">Follow-up calls</div></div>
            <div className="s"><div className="n">4</div><div className="l">Channels</div></div>
          </div>
        </div>
        {COMMS_THREADS.map(x => <CommsRow key={x.id} t={x} sel={x.id === sel} onClick={() => pick(x.id)} />)}
      </div>
      <div className="split-detail">
        {isMobile && <button className="detail-back" onClick={() => setShowDetail(false)}><Icon name="arrow-left" />All comms</button>}
        <Composer t={t} />
      </div>
    </div></div>
  );
}
Object.assign(window, { Comms });
