/* social-app.jsx: Clubcraft Social, ported from Plan Social (Social Media Planner/app.jsx). Same UI; the data seam is
   window.useSocialStore (social-store.jsx). AI drafting and images are live; publishing is wired in a later release. */
(function () {
const SD        = window.SocialData;
const note = (detail) => window.dispatchEvent(new CustomEvent('cc-error', { detail }));
const DAY_NAMES = SD.DAY_NAMES || ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];

/* Optional per-pillar reference questionnaire — blank is a no-op for AI generation */
const blankQuestionnaire = () => ({ facts:'', hook:'', subEntities:'', cta:'', toneNote:'', deadline:'', avoid:'', sourceDocIds:[] });
const TIMING_TAGS = [['early','Early'],['mid','Mid'],['near','Near event'],['spread','Spread']];

/* Club-level brand kit (clubs/{clubId}.brandKit) — set once, reused by every campaign.
   Multi-tenant: each club document carries its own kit. */
const blankBrandKit = () => ({ logoUrl:'', logoName:'', primaryColor:'#17458F', secondaryColor:'#F7A81B', toneWords:'', standardHashtags:'', signOff:'', avoidWords:'' });

/* Per-campaign branding — most campaigns just inherit the club brand kit (primary:'club').
   An event with its own identity can flip primary:'event' and describe in usageNote where
   the club brand should still appear, rather than the app encoding placement rules itself. */
const blankBranding = () => ({ primary:'club', eventLogoUrl:'', eventLogoName:'', eventPrimaryColor:'', eventSecondaryColor:'', usageNote:'' });

/* Default draft for a campaign's closing/sign-off message — pre-fills Setup so
   every campaign starts from the same proven shape (sponsor thanks → CTA with
   date → hashtags) instead of a blank box. Only used while cfg.signOffMessage
   is still empty; once a campaign saves its own version this is never shown
   again for that campaign. Known facts (event name, standard hashtags) are
   interpolated in; anything still unconfirmed stays a bracketed placeholder
   for a human to fill in — never guessed. */
const defaultSignOffMessage = (cfg, clubBrandKit) => {
  const eventName = (cfg && cfg.eventName) || '[Event name]';
  const tags = ((clubBrandKit && clubBrandKit.standardHashtags) || '').trim();
  return `Thank you to our sponsors [name sponsors once confirmed]. Together, we're building a healthier, more connected community.\n\nMark your calendars for ${eventName} [event date] and be part of something special! 🏃‍♀️🏃‍♂️🚶‍♀️\n\n${tags ? tags + ' ' : ''}[add relevant hashtags]`;
};

const QUESTIONNAIRE_KEYS = ['facts','hook','subEntities','cta','toneNote','deadline','avoid'];
const qFilledCount = q => QUESTIONNAIRE_KEYS.filter(k => (q && q[k] || '').trim()).length;

/* Which of a week's two angles a given post actually uses — the SAME rule
   generatePost() applies when building the AI payload (alternate by day-order
   position once a second angle exists), so the topic shown in Post Brief
   never disagrees with the topic that post was actually generated from.
   Before this existed, every post row displayed w.topicAndAngle only, so two
   posts in one week always showed the identical heading even when the second
   one had been (or would be) generated from topicAndAngle2 — reading as
   duplicate content to whoever's scanning the list, even once the drafted
   captions themselves genuinely differed. */
const postAngle = (w, weekPosts, postId) => {
  if (!w) return '';
  /* Extra posts (added beyond Setup's preferred days) can carry their own topic. */
  const own = (weekPosts||[]).find(x=>x.id===postId);
  if (own && own.extra && (own.topic||'').trim()) return own.topic;
  const hasAlt = !!(w.topicAndAngle2 && w.topicAndAngle2.trim());
  if (!hasAlt) return w.topicAndAngle || '';
  /* Alternate across the regular (Setup-day) posts only. Counting extras shifted
     the pairing whenever an extra fell before them (e.g. a Saturday extra made
     Sunday take angle 2 and Wednesday angle 1). */
  const sorted = (weekPosts||[]).filter(x=>!x.extra).sort((a,b)=>a.dayOffset-b.dayOffset);
  const idx = sorted.findIndex(x=>x.id===postId);
  return (idx>=0 && idx%2===1) ? w.topicAndAngle2 : w.topicAndAngle;
};

/* Reference doc freshness — uploaded files are treated as fixed snapshots (no check needed);
   link-only rows should carry a dated "verifiedDate" that's re-checked periodically. */
const STALE_DAYS = 180;
function docFreshness(r) {
  if (r.docUrl) return null;
  if (!r.url)   return null;
  if (!r.verifiedDate) return { level:'warn', text:'Add a checked-on date' };
  const days = (Date.now() - new Date(r.verifiedDate).getTime()) / 86400000;
  if (days > STALE_DAYS) return { level:'warn', text:`Checked ${r.verifiedDate} — verify it's still current` };
  return { level:'ok', text:`Checked ${r.verifiedDate}` };
}

/* Setup readiness — an honest self-check, not a gate. Shared by the Setup modal's
   small-print strip and the full Setup Guide page, so both always agree. */
const READINESS_CHECKS = [
  { key:'briefing',   label:'More info reads like a briefing',
    done: d => (d.moreInfo||'').trim().length > 60 },
  { key:'beneficiaries', label:'Beneficiaries described',
    done: d => (d.beneficiaries||[]).length===0 || d.beneficiaries.every(b=>(b.about||'').trim()) },
  { key:'sponsors',   label:'Sponsors described',
    done: d => (d.sponsors||[]).length===0 || d.sponsors.every(s=>(s.about||'').trim()) },
  { key:'refDoc',     label:'A reference document added',
    done: d => (d.referenceDocs||[]).length>0 || (d.moreInfoDocs||[]).length>0 },
  { key:'docsDated',  label:'Link-only docs are dated',
    done: d => (d.referenceDocs||[]).every(r=>!docFreshness(r) || docFreshness(r).level==='ok') },
  { key:'pillars',    label:'Key pillars are grounded',
    done: d => (d.pillars||[]).length===0 || d.pillars.some(p=>qFilledCount(p.questionnaire||{})>0) },
];
function computeReadiness(d) {
  const readiness = READINESS_CHECKS.map(c => ({ key:c.key, label:c.label, done: c.done(d||{}) }));
  return { readiness, readyCount: readiness.filter(r=>r.done).length };
}

/* Managed image storage: every organisation gets 2 GB included; extra storage is added in blocks
   by Delivio (imageStorage.extraBytes on the club document). See docs/image-storage-design.md. */
/* Time zone for post times: the club's own zone unless the campaign sets another. The Auto-Publish Cron reads campaign.config.timeZone. */
/* Short zone name right now, e.g. "AEDT" (falls back to the IANA id). */
function _tzAbbr(tz) {
  try {
    const parts = new Intl.DateTimeFormat(CCIntl.locale(), { timeZone: tz || CCIntl.timezone(), timeZoneName: 'short' }).formatToParts(new Date());
    const n = parts.find(x => x.type === 'timeZoneName');
    return n ? n.value : (tz || CCIntl.timezone());
  } catch (e) { return tz || CCIntl.timezone(); }
}
const INCLUDED_BYTES = 2 * 1024 * 1024 * 1024;
const _allowanceBytes = settings => INCLUDED_BYTES + Math.max(0, Number((settings||{}).extraBytes) || 0);

/* Resize a blob to 1200×630 (Facebook optimal) using canvas cover-fit crop */
function _resizeForFacebook(blob) {
  const W = 1200, H = 630;
  return new Promise((resolve, reject) => {
    const img = new Image();
    const url = URL.createObjectURL(blob);
    img.onload = () => {
      URL.revokeObjectURL(url);
      const canvas = document.createElement('canvas');
      canvas.width = W; canvas.height = H;
      const ctx = canvas.getContext('2d');
      const srcRatio = img.width / img.height;
      const tgtRatio = W / H;
      let sx, sy, sw, sh;
      if (srcRatio > tgtRatio) {
        sh = img.height; sw = sh * tgtRatio; sx = (img.width - sw) / 2; sy = 0;
      } else {
        sw = img.width; sh = sw / tgtRatio; sx = 0; sy = (img.height - sh) / 2;
      }
      ctx.drawImage(img, sx, sy, sw, sh, 0, 0, W, H);
      canvas.toBlob(b => b ? resolve(b) : reject(new Error('Canvas resize failed')), 'image/jpeg', 0.90);
    };
    img.onerror = () => { URL.revokeObjectURL(url); reject(new Error('Image load failed')); };
    img.src = url;
  });
}

/* Quota is enforced by the server (it refuses an upload or a picture when storage is full) and never deletes anything:
   an image a queued post points at must not disappear. */

/* True when the URL loads as an image in this browser (no CORS needed). Used before a post is approved
   for auto-publish, and by the Image Library health check. */
function _checkImageUrl(url, timeoutMs) {
  return new Promise(resolve => {
    if (!url || !/^https?:\/\//i.test(url)) return resolve(false);
    const img = new Image();
    const t = setTimeout(() => { img.src = ''; resolve(false); }, timeoutMs || 15000);
    img.onload  = () => { clearTimeout(t); resolve(img.naturalWidth > 0); };
    img.onerror = () => { clearTimeout(t); resolve(false); };
    img.referrerPolicy = 'no-referrer';
    img.src = url;
  });
}

/* Friendly name for where an image is hosted, so a stray third-party link stands out. */
function _imageHost(url) {
  let h = '';
  try { h = new URL(url).hostname.toLowerCase(); } catch(e) { return {label:'Unknown', trusted:false}; }
  if (h.endsWith('firebasestorage.googleapis.com') || h.endsWith('firebasestorage.app')) return {label:'Plansocial storage', trusted:true};
  if (h.endsWith('zohostratus.com.au') || h.endsWith('zohostratus.com'))                    return {label:'Plansocial storage', trusted:true};
  if (h.endsWith('campaign-image.com'))                                                       return {label:'Zoho Campaigns library (unreliable)', trusted:false};
  if (h.endsWith('canva.com') || h.endsWith('googleusercontent.com') || h.endsWith('drive.google.com')) return {label:h+' (may expire)', trusted:false};
  return {label:h, trusted:true};
}

/* (The server records every stored picture itself.) */

/* Clubcraft API for the image helpers below (the same call the store uses, for the club the member is acting in). */
const _api = (method, path, body) => window.ClubcraftApi.call(method, path, body, { club: window.CC_ACTIVE_CLUB });

/* Resize a logo to fit 400px, keeping its transparency (PNG), or JPEG if that is still too big. */
function _resizeLogo(blob) {
  const MAX = 400;
  return new Promise((resolve, reject) => {
    const img = new Image();
    const url = URL.createObjectURL(blob);
    img.onload = () => {
      URL.revokeObjectURL(url);
      const k = Math.min(1, MAX / Math.max(img.width || MAX, img.height || MAX));
      const canvas = document.createElement('canvas');
      canvas.width = Math.max(1, Math.round((img.width || MAX) * k)); canvas.height = Math.max(1, Math.round((img.height || MAX) * k));
      canvas.getContext('2d').drawImage(img, 0, 0, canvas.width, canvas.height);
      canvas.toBlob(b => {
        if (b && b.size <= 450000) return resolve(b);
        canvas.toBlob(j => j ? resolve(j) : reject(new Error('Canvas resize failed')), 'image/jpeg', 0.88);
      }, 'image/png');
    };
    img.onerror = () => { URL.revokeObjectURL(url); reject(new Error('That file could not be read as a picture')); };
    img.src = url;
  });
}

/* Store a picture for this campaign. The server checks the bytes, the member's role and the club's storage allowance, keeps the file in
   the public image bucket (so Facebook and Instagram can fetch it) and lists it in the Image Library. Returns { url, id, bytes }. */
async function _storeImage(blob, o) {
  const data = await _blobToBase64(blob);
  try {
    const r = await _api('POST', '/club/social/' + o.campaignId + '/images', { kind: o.kind || 'post', postId: o.postId || '', name: o.filename || '', data });
    window.dispatchEvent(new Event('cc-images-changed'));
    return { url: r.url, id: r.id, bytes: r.bytes };
  } catch (e) {
    if (e && e.data && e.data.code === 'storage_full') throw new Error('STORAGE_FULL');
    throw e;
  }
}

/* The club's brand-kit logo (club admins only; it belongs to no campaign). */
async function _uploadClubLogo(file) {
  const blob = await _resizeLogo(file);
  const r = await _api('POST', '/club/social/images', { name: file.name || 'logo', data: await _blobToBase64(blob) });
  return r.url;
}

/* A logo for a campaign (event identity, a beneficiary or a sponsor). */
async function _uploadCampaignLogo(campaignId, file) {
  if (!campaignId) throw new Error('Save the campaign first, then add the logo.');
  const blob = await _resizeLogo(file);
  return (await _storeImage(blob, { campaignId, kind: 'logo', filename: file.name })).url;
}

/* Delete one stored picture (the server refuses while a post of the campaign still uses it). */
async function _deleteStoredImage(img) {
  await _api('DELETE', '/club/social/' + img.campaignId + '/images/' + img.id);
  window.dispatchEvent(new Event('cc-images-changed'));
}

/* A readable message for a failed picture call. */
const _imgError = (err, fallback) => (err && err.message === 'STORAGE_FULL') ? 'Image storage is full. Delete pictures you no longer need in the Image Library, or ask Delivio to add storage.' : ((err && err.message) || fallback);

/* Convert a blob to a base64 string (no data: prefix) for the Drive-backup webhook */
function _blobToBase64(blob) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(String(reader.result).split(',')[1] || '');
    reader.onerror = reject;
    reader.readAsDataURL(blob);
  });
}

/* ── date helpers ─────────────────────────────────────────────────────────── */
const DAYS   = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
const MONTHS = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
function parseDate(s)  { const [y,m,d] = s.split('-').map(Number); return new Date(y,m-1,d); }
function addDays(d,n)  { const x=new Date(d); x.setDate(x.getDate()+n); return x; }
function fmt(d)        { return `${DAYS[d.getDay()]} ${d.getDate()} ${MONTHS[d.getMonth()]} ${d.getFullYear()}`; }
function fmtShort(d)   { return `${d.getDate()} ${MONTHS[d.getMonth()]}`; }
/* Local calendar-day string (not toISOString(), which shifts the day across the UTC boundary). */
function ymd(d)        { return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`; }
function isoWeek(date) {
  const d = new Date(Date.UTC(date.getFullYear(),date.getMonth(),date.getDate()));
  const dn = (d.getUTCDay()+6)%7;
  d.setUTCDate(d.getUTCDate()-dn+3);
  const ft = new Date(Date.UTC(d.getUTCFullYear(),0,4));
  return 1+Math.round(((d-ft)/86400000-3+((ft.getUTCDay()+6)%7))/7);
}

/* Retired 'queued' status (was a workaround for Meta's 30-day scheduling
   limit, no longer relevant now that publishing is immediate) — any post
   still carrying it from before the migration is treated as 'ready'. */
function _hydratePost(p, postBusy) {
  const status = p.status === 'queued' ? 'ready' : p.status;
  return { ...p, ...(postBusy[p.id]||{}), status };
}

/* Which platforms a post publishes to — falls back to the campaign's
   configured platforms for posts created before per-post selection existed. */
function postPlatforms(p, cfg) {
  return p.platforms || { facebook: !!(cfg&&cfg.facebookPageId), instagram: !!(cfg&&cfg.instagramAccountId) };
}

const PENDING_ACTION_LABELS = { publish:'Instant Publish', posted:'Mark Posted', approveForAutoPublish:'Approve for Auto-Publish' };
const POSTED_VIA_LABELS = {
  instant: {label:'Instant Published', color:'#1D6FC4', bg:'#E3EEFC'},
  auto:    {label:'Auto-Published',    color:'#15803D', bg:'#E3F5E9'},
  manual:  {label:'Marked Posted',     color:'#5C6880', bg:'#EDF1F7'},
};

/* ── small SVG icons ─────────────────────────────────────────────────────── */
function SpinIcon({sz=13,light=false}) {
  return <svg width={sz} height={sz} viewBox="0 0 24 24" style={{animation:'spin .8s linear infinite'}}>
    <circle cx="12" cy="12" r="9" fill="none" stroke={light?'rgba(255,255,255,.3)':'rgba(138,90,5,.25)'} strokeWidth="3"/>
    <path d="M21 12a9 9 0 0 0-9-9" fill="none" stroke={light?'#fff':'currentColor'} strokeWidth="3" strokeLinecap="round"/>
  </svg>;
}
function StarIcon({sz=13}) { return <svg width={sz} height={sz} viewBox="0 0 24 24" fill="currentColor"><path d="M12 2l1.6 5.2L19 9l-5.4 1.8L12 16l-1.6-5.2L5 9l5.4-1.8z"/></svg>; }
function ChevronIcon({deg=0,sz=13,color='#A6B0C4'}) {
  return <svg width={sz} height={sz} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2.4" style={{transform:`rotate(${deg}deg)`,transition:'transform .18s'}}><path d="M9 18l6-6-6-6"/></svg>;
}
function GearIcon({sz=19}) {
  return <svg width={sz} height={sz} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>;
}
function SlidersIcon({sz=18}) { return <svg width={sz} height={sz} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M4 6h6M14 6h6M4 12h13M21 12h-2M4 18h9M17 18h3"/><circle cx="12" cy="6" r="2"/><circle cx="19" cy="12" r="2"/><circle cx="15" cy="18" r="2"/></svg>; }
function XIcon({sz=17}) { return <svg width={sz} height={sz} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2"><path d="M18 6L6 18M6 6l12 12"/></svg>; }
function PlusIcon({sz=13}) { return <svg width={sz} height={sz} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4"><path d="M12 5v14M5 12h14"/></svg>; }
function TrashIcon({sz=15}) { return <svg width={sz} height={sz} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2m2 0v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"/></svg>; }
function FilterIcon({sz=15}) { return <svg width={sz} height={sz} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M22 3H2l8 9.46V19l4 2v-8.54z"/></svg>; }
function CopyIcon({sz=13}) { return <svg width={sz} height={sz} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h10"/></svg>; }
function CheckIcon({sz=13,color='#15803D'}) { return <svg width={sz} height={sz} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2.6"><path d="M20 6L9 17l-5-5"/></svg>; }
function LinkIcon({sz=13}) { return <svg width={sz} height={sz} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>; }
function CalIcon({sz=15}) { return <svg width={sz} height={sz} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/></svg>; }
function FacebookIcon({sz=15}) { return <svg width={sz} height={sz} viewBox="0 0 24 24" fill="currentColor"><path d="M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z"/></svg>; }
function InstagramIcon({sz=15}) { return <svg width={sz} height={sz} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="2" y="2" width="20" height="20" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r="1" fill="currentColor" stroke="none"/></svg>; }
function RefreshIcon({sz=13}) { return <svg width={sz} height={sz} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M23 4v6h-6"/><path d="M1 20v-6h6"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>; }
function UploadIcon({sz=13}) { return <svg width={sz} height={sz} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M17 8l-5-5-5 5M12 3v12"/></svg>; }
function DownloadIcon({sz=13}) { return <svg width={sz} height={sz} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3"/></svg>; }
function PaperclipIcon({sz=12}) { return <svg width={sz} height={sz} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg>; }
function PhotosIcon({sz=15}) { return <svg width={sz} height={sz} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="2" y="6" width="20" height="16" rx="2"/><circle cx="9" cy="12" r="2"/><path d="m22 16-5-5-3 3-2-2-5 5"/></svg>; }
function PaletteIcon({sz=17}) { return <svg width={sz} height={sz} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M12 22a1 1 0 0 1-1-1 4 4 0 0 1 4-4h1.5a2.5 2.5 0 0 0 0-5H15a2 2 0 0 1-2-2 5 5 0 0 1 5-5c4 0 7 3.5 7 7.5 0 6-6 9.5-13 9.5Z"/><circle cx="6.5" cy="11.5" r="1.5" fill="currentColor" stroke="none"/><circle cx="9.5" cy="6.5" r="1.5" fill="currentColor" stroke="none"/><circle cx="15" cy="5.5" r="1.5" fill="currentColor" stroke="none"/></svg>; }
function BookIcon({sz=17}) { return <svg width={sz} height={sz} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2Z"/><path d="M9 7h8M9 11h5"/></svg>; }
function ShieldIcon({sz=17}) { return <svg width={sz} height={sz} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M12 2 4 5v6c0 5 3.4 8.7 8 11 4.6-2.3 8-6 8-11V5l-8-3Z"/><path d="m9 12 2 2 4-4"/></svg>; }

function CaptionEditor({value, readOnly, onSave, style}) {
  const [local, setLocal] = React.useState(value||'');
  React.useEffect(() => { setLocal(value||''); }, [value]);
  return (
    <textarea
      value={local}
      onChange={e => setLocal(e.target.value)}
      onBlur={() => { if (local !== (value||'')) onSave(local); }}
      readOnly={readOnly}
      placeholder="Write the Facebook caption, or hit Generate…"
      rows="7"
      style={style}
    />
  );
}

/* Textarea that edits locally and saves on blur or after a short pause. The live store writes the
   whole posts array on every change and only reflects it back after the Firestore round trip, which
   made controlled textareas jump the cursor to the end. External changes are only taken while the
   field is not focused, so typing is never overwritten. */
function BufferedTextarea({value, onSave, ...rest}) {
  const [local, setLocal] = React.useState(value || '');
  const focused = React.useRef(false);
  const timer   = React.useRef(null);
  const latest  = React.useRef({ local: value || '', value: value || '', onSave });
  latest.current.value  = value || '';
  latest.current.onSave = onSave;
  const flush = () => {
    clearTimeout(timer.current);
    const c = latest.current;
    if (c.local !== c.value) c.onSave(c.local);
  };
  React.useEffect(() => { if (!focused.current) { setLocal(value || ''); latest.current.local = value || ''; } }, [value]);
  React.useEffect(() => () => flush(), []);
  return (
    <textarea
      {...rest}
      value={local}
      onFocus={() => { focused.current = true; }}
      onChange={e => {
        const v = e.target.value;
        setLocal(v); latest.current.local = v;
        clearTimeout(timer.current);
        timer.current = setTimeout(flush, 1500);
      }}
      onBlur={() => { focused.current = false; flush(); }}
    />
  );
}

/* Read-only mock-up of how a post will look once published: a Facebook feed
   card (default) or an Instagram post. The page name and avatar come from the
   campaign's event branding when that leads, otherwise the club Brand Kit logo.
   Facebook collapses captions after a few lines behind "See more", and
   Instagram after about 125 characters, so both previews do the same. */
function PostPreviewModal({post, date, time, config, clubBrandKit, onClose}) {
  const cfg = config || {};
  const br  = cfg.branding || {};
  const bk  = clubBrandKit || {};
  const [mode, setMode] = React.useState('facebook');
  const [more, setMore] = React.useState(false);
  const caption = (post.draftCaption || '').trim();
  const img = post.generatedImageUrl || (/\.(png|jpe?g|gif|webp)(\?|$)/i.test(post.mediaFileLink||'') ? post.mediaFileLink : '');
  const avatar = (br.primary === 'event' && br.eventLogoUrl) ? br.eventLogoUrl : (bk.logoUrl || br.eventLogoUrl || '');
  const pageName = (cfg.eventName || 'Facebook Page').replace(/\s+\d{4}$/, '');
  const handle = (String(cfg.facebookPage||'').split('/').filter(Boolean).pop() || pageName.replace(/\s+/g,'')).toLowerCase();
  const fbCut = caption.split('\n').slice(0,5).join('\n').slice(0,320);
  const fbShort = !more && caption.length > fbCut.length;
  const igShort = !more && caption.length > 125;
  const igCut = caption.slice(0,125).replace(/\s+\S*$/,'');
  const hm = (time||'').split(':').map(Number);
  const clock = time ? `${(hm[0]%12)||12}:${String(hm[1]).padStart(2,'0')}${hm[0]<12?'am':'pm'}` : '';
  const when = date ? `${date.getDate()} ${MONTHS[date.getMonth()]}${clock?' at '+clock:''}` : '';
  const Avatar = ({sz}) => avatar
    ? <img src={avatar} alt="" style={{width:sz,height:sz,borderRadius:'50%',objectFit:'contain',background:'#fff',border:'1px solid #E4E6EB',flex:'none'}}/>
    : <div style={{width:sz,height:sz,borderRadius:'50%',background:'var(--b-primary)',color:'#fff',display:'grid',placeItems:'center',font:"800 13px 'Public Sans'",flex:'none'}}>{pageName.slice(0,1)}</div>;
  const tab = (id,label) => (
    <button key={id} onClick={()=>{setMode(id);setMore(false);}} style={{flex:1,background:mode===id?'var(--b-primary)':'#F0F4FA',color:mode===id?'#fff':'#6B7790',border:'1px solid '+(mode===id?'var(--b-primary)':'#D5DEF0'),borderRadius:8,padding:'6px 8px',font:"800 11.5px 'Public Sans'",cursor:'pointer'}}>{label}</button>
  );
  const sys = "-apple-system, 'Segoe UI', Helvetica, Arial, sans-serif";
  const seeMore = <span onClick={()=>setMore(true)} style={{color:'#65676B',fontWeight:600,cursor:'pointer'}}>{mode==='facebook'?'… See more':'… more'}</span>;
  return (
    <div onClick={onClose} style={{position:'fixed',inset:0,background:'rgba(17,27,50,.55)',zIndex:200,display:'flex',alignItems:'center',justifyContent:'center',padding:20}}>
      <div onClick={e=>e.stopPropagation()} style={{background:'#F0F2F5',borderRadius:16,width:'100%',maxWidth:520,maxHeight:'92vh',display:'flex',flexDirection:'column',boxShadow:'0 8px 48px color-mix(in srgb, var(--b-primary) 18%, transparent)',overflow:'hidden'}}>
        <div style={{background:'linear-gradient(135deg,var(--b-primary),var(--b-primary-deep))',padding:'14px 18px',display:'flex',alignItems:'center',gap:10}}>
          <span style={{font:"800 14px 'Public Sans'",color:'#fff',flex:1}}>Post Preview · Post {post.postNo}{when?' · '+when:''}</span>
          <button onClick={onClose} title="Close" style={{background:'none',border:'none',color:'#fff',cursor:'pointer',display:'flex'}}><XIcon sz={15}/></button>
        </div>
        <div style={{display:'flex',gap:6,padding:'12px 16px 0'}}>{tab('facebook','Facebook')}{tab('instagram','Instagram')}</div>
        <div style={{overflowY:'auto',padding:16}}>
          {!caption && <div style={{font:"600 12px 'Public Sans'",color:'#A6B0C4',marginBottom:10}}>No caption yet. Generate or write one to see it here.</div>}
          {mode==='facebook' ? (
            <div style={{background:'#fff',borderRadius:8,boxShadow:'0 1px 2px rgba(0,0,0,.2)',font:`400 15px/1.34 ${sys}`,color:'#050505'}}>
              <div style={{display:'flex',alignItems:'center',gap:8,padding:'12px 16px 0'}}>
                <Avatar sz={40}/>
                <div>
                  <div style={{fontWeight:600}}>{pageName}</div>
                  <div style={{font:`400 13px ${sys}`,color:'#65676B'}}>{when || 'Scheduled'} · 🌐</div>
                </div>
              </div>
              <div style={{padding:'10px 16px 12px',whiteSpace:'pre-wrap',wordBreak:'break-word'}}>{fbShort ? <>{fbCut}{seeMore}</> : caption}</div>
              {img && <img src={img} alt="" style={{width:'100%',display:'block',aspectRatio:'1200/630',objectFit:'cover'}}/>}
              <div style={{display:'flex',justifyContent:'space-around',borderTop:'1px solid #CED0D4',margin:'0 16px',padding:'6px 0',font:`600 14px ${sys}`,color:'#65676B'}}>
                <span>👍 Like</span><span>💬 Comment</span><span>↗ Share</span>
              </div>
            </div>
          ) : (
            <div style={{background:'#fff',borderRadius:8,border:'1px solid #DBDBDB',font:`400 14px/1.4 ${sys}`,color:'#000',maxWidth:360,margin:'0 auto'}}>
              <div style={{display:'flex',alignItems:'center',gap:10,padding:'10px 12px'}}>
                <Avatar sz={32}/><span style={{fontWeight:600}}>{handle}</span>
              </div>
              {img
                ? <img src={img} alt="" style={{width:'100%',display:'block',aspectRatio:'1.91/1',objectFit:'cover'}}/>
                : <div style={{aspectRatio:'1.91/1',background:'#EFEFEF',display:'grid',placeItems:'center',font:"600 12px 'Public Sans'",color:'#8E8E8E'}}>Instagram needs an image</div>}
              <div style={{padding:'8px 12px 0',fontSize:22,letterSpacing:6}}>♡ 💬 ➤</div>
              <div style={{padding:'6px 12px 12px',whiteSpace:'pre-wrap',wordBreak:'break-word'}}><span style={{fontWeight:600}}>{handle}</span> {igShort ? <>{igCut}{seeMore}</> : caption}</div>
              <div style={{padding:'0 12px 12px',font:`400 11px ${sys}`,color:'#8E8E8E',textTransform:'uppercase'}}>{when}</div>
            </div>
          )}
          <div style={{font:"500 11px/1.5 'Public Sans'",color:'#8A94A8',marginTop:10}}>Approximate preview. Links aren't clickable here, and on Instagram links in captions never are. Facebook and Instagram render the final layout.</div>
        </div>
      </div>
    </div>
  );
}

/* ── image style picker ──────────────────────────────────────────────────── */
const IMAGE_STYLES = [
  { id:'none',       label:'Original',      cat:'Everyday' },
  { id:'vibrant',    label:'Vibrant',       cat:'Everyday' },
  { id:'bw',         label:'B&W',           cat:'Everyday' },
  { id:'warm',       label:'Warm',          cat:'Everyday' },
  { id:'cool',       label:'Cool',          cat:'Everyday' },
  { id:'vintage',    label:'Vintage',       cat:'Moods' },
  { id:'minimal',    label:'Minimal',       cat:'Moods' },
  { id:'moody',      label:'Moody',         cat:'Moods' },
  { id:'airy',       label:'Bright & Airy', cat:'Moods' },
  { id:'neon',       label:'Neon',          cat:'Moods' },
  { id:'sketch',     label:'Sketch',        cat:'Creative' },
  { id:'popart',     label:'Pop Art',       cat:'Creative' },
  { id:'watercolor', label:'Watercolor',    cat:'Creative' },
  { id:'pixel',      label:'Pixel Art',     cat:'Creative' },
  { id:'anime',      label:'Anime',         cat:'Creative' },
];
const _IMG_CATS = { Everyday:'Everyday Classics', Moods:'Aesthetics & Moods', Creative:'Creative & Artistic' };

/* Landscape scene SVG — rendered once, CSS filter applied per style so tiles show real photo treatment */
const _SCENE_URL = (() => {
  const s = '<svg xmlns="http://www.w3.org/2000/svg" width="50" height="35" viewBox="0 0 50 35"><rect width="50" height="22" fill="#87CEEB"/><circle cx="41" cy="8" r="5" fill="#FFE566"/><rect y="22" width="50" height="13" fill="#5A9E54"/><ellipse cx="9" cy="23" rx="12" ry="5" fill="#4A8C45"/><ellipse cx="40" cy="24" rx="13" ry="4" fill="#3D7A39"/><rect x="27" y="14" width="2.5" height="9" fill="#5C3B1E"/><ellipse cx="28.3" cy="13" rx="5" ry="5" fill="#2D7A2D"/><ellipse cx="18" cy="18" rx="2.5" ry="2.5" fill="#D4956A"/><rect x="15.5" y="20" width="5" height="5" rx="1" fill="#C0624A"/></svg>';
  return `url("data:image/svg+xml;base64,${btoa(s)}")`;
})();

const _TILE_CFG = {
  none:       {},
  vibrant:    { filter:'saturate(2.5) contrast(1.1)' },
  bw:         { filter:'grayscale(1) contrast(1.2)' },
  warm:       { filter:'sepia(0.65) saturate(1.3) brightness(1.05)' },
  cool:       { filter:'hue-rotate(195deg) saturate(1.1) brightness(1.08)' },
  vintage:    { filter:'sepia(0.5) contrast(0.88) brightness(0.9) saturate(0.72)' },
  minimal:    { filter:'saturate(0.1) brightness(1.5) contrast(0.78)' },
  moody:      { filter:'brightness(0.45) contrast(1.5) saturate(0.6)' },
  airy:       { filter:'brightness(1.65) saturate(0.35) contrast(0.74)' },
  neon:       { filter:'saturate(4) hue-rotate(260deg) brightness(0.72) contrast(1.2)' },
  sketch:     { filter:'grayscale(1) contrast(8) brightness(1.1)' },
  popart:     { filter:'saturate(8) contrast(2.2)' },
  watercolor: { filter:'saturate(0.5) contrast(0.68) brightness(1.22)' },
  pixel:      { filter:'saturate(1.5) contrast(1.4)', backgroundSize:'10px 7px', backgroundRepeat:'repeat', imageRendering:'pixelated' },
  anime:      { filter:'saturate(2.1) contrast(1.4) brightness(1.08)' },
};

function ImageStylePicker({value, onChange, readOnly}) {
  return (
    <div>
      {['Everyday','Moods','Creative'].map(cat=>(
        <div key={cat} style={{marginBottom:7}}>
          <div style={{font:"700 9px 'Public Sans'",letterSpacing:'.04em',textTransform:'uppercase',color:'#B0B8C9',marginBottom:4}}>{_IMG_CATS[cat]}</div>
          <div style={{display:'flex',flexWrap:'wrap',gap:5}}>
            {IMAGE_STYLES.filter(s=>s.cat===cat).map(style=>{
              const sel=value===style.id;
              const cfg=_TILE_CFG[style.id]||{};
              return (
                <button key={style.id} title={style.label} onClick={()=>!readOnly&&onChange(style.id)}
                  style={{padding:0,border:`2px solid ${sel?'var(--b-primary)':'transparent'}`,borderRadius:7,cursor:readOnly?'default':'pointer',background:'none',outline:'none'}}>
                  <div style={{
                    width:50,height:35,borderRadius:5,overflow:'hidden',
                    backgroundImage:_SCENE_URL,
                    backgroundSize:cfg.backgroundSize||'cover',
                    backgroundRepeat:cfg.backgroundRepeat||'no-repeat',
                    imageRendering:cfg.imageRendering||'auto',
                    filter:cfg.filter||'none',
                    border:'1px solid rgba(0,0,0,.1)',
                  }}/>
                  <div style={{font:`${sel?800:600} 9px 'Public Sans'`,color:sel?'var(--b-primary)':'#6B7790',marginTop:2,textAlign:'center',width:54,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{style.label}</div>
                </button>
              );
            })}
          </div>
        </div>
      ))}
    </div>
  );
}

/* ── role badge colours ──────────────────────────────────────────────────── */
const ROLE_COLOR = {
  Read:   { color:'#5A6473', bg:'#EDF1F7' },
  Write:  { color:'#6D28D9', bg:'#EDE7FB' },
  Action: { color:'#B45309', bg:'#FCEEDA' },
  Admin:  { color:'var(--b-primary)', bg:'var(--b-wash)' },
};

/* ── StatusCells ─────────────────────────────────────────────────────────── */
function StatusCells({cells}) {
  return <>{cells.map(c=>(
    <span key={c.key} title={c.label} style={{display:'inline-flex',alignItems:'center',gap:5,padding:'3px 8px',borderRadius:7,font:"800 11px 'Public Sans'",color:c.color,background:c.bg}}>
      <span style={{width:6,height:6,borderRadius:'50%',background:c.dot}}/>
      {c.n}
    </span>
  ))}</>;
}

/* ── Sign-off strip ───────────────────────────────────────────────────────
   Multi-reviewer "recommend" marks on a post — Write/Action/Admin can each
   add their own {uid,name,note,ts} entry. Informational only: it never
   gates the Admin-only posting actions, it just surfaces who's reviewed it. */
function SignOffStrip({post, members, currentUserId, caps, onSetSignOff}) {
  const signOffs = post.signOffs || [];
  const mine = signOffs.find(x=>x.uid===currentUserId);
  const avatarChip = so => {
    const m = members.find(x=>x.id===so.uid);
    return <span key={so.uid} title={so.note ? `${so.name}: ${so.note}` : so.name} style={{width:23,height:23,borderRadius:'50%',display:'grid',placeItems:'center',font:"800 9.5px 'Public Sans'",color:'#fff',background:m?m.avatarColor:'#8A94A8',flex:'none'}}>{m?m.initials:'?'}</span>;
  };
  if (!caps.edit) {
    if (!signOffs.length) return null;
    return (
      <div style={{display:'flex',alignItems:'center',gap:6,flexWrap:'wrap'}}>
        <span style={{font:"800 10px 'Public Sans'",letterSpacing:'.06em',textTransform:'uppercase',color:'#8A94A8'}}>Recommended by</span>
        {signOffs.map(avatarChip)}
      </div>
    );
  }
  return (
    <div onClick={e=>e.stopPropagation()}>
      <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',gap:8,marginBottom:signOffs.length||mine?6:0}}>
        <span style={{font:"800 10px 'Public Sans'",letterSpacing:'.06em',textTransform:'uppercase',color:'#8A94A8'}}>Recommend to Admin</span>
        <button onClick={()=>onSetSignOff(post, !mine, mine?mine.note:'')} style={{display:'inline-flex',alignItems:'center',gap:5,border:'1px solid',borderColor:mine?'#BBE8C8':'#D9E1EE',background:mine?'#E3F5E9':'#F7F9FC',color:mine?'#15803D':'#5A6473',borderRadius:7,padding:'4px 9px',font:"800 11px 'Public Sans'",cursor:'pointer',flex:'none'}}>
          <CheckIcon sz={11} color={mine?'#15803D':'#9AA6BC'}/>{mine?'Recommended':'Recommend'}
        </button>
      </div>
      {signOffs.length>0 && <div style={{display:'flex',alignItems:'center',gap:6,flexWrap:'wrap',marginBottom:mine?6:0}}>{signOffs.map(avatarChip)}</div>}
      {mine && (
        <input value={mine.note||''} onChange={e=>onSetSignOff(post, true, e.target.value)} placeholder="Optional note for the Admin…" style={{width:'100%',border:'1px solid #D9E1EE',borderRadius:8,padding:'6px 9px',font:"500 12px 'Public Sans'",color:'#1A2942',outline:'none',boxSizing:'border-box'}}/>
      )}
    </div>
  );
}

/* ── Rotary logo ─────────────────────────────────────────────────────────── */
function RotaryLogo({sz=32}) {
  return null;
}
function _unusedRotaryLogo({sz=32}) {
  return <svg width={sz} height={sz} viewBox="0 0 100 100" aria-hidden="true" style={{flex:'none'}}>
    <mask id="smpw3">
      <rect width="100" height="100" fill="#000"/>
      <path d="M44.39,7.37 L47.18,1.08 L52.82,1.08 L55.61,7.37 L59.94,2.02 L65.39,3.48 L66.46,10.27 L72.02,6.22 L76.90,9.05 L76.18,15.89 L82.60,13.41 L86.59,17.40 L84.11,23.82 L90.95,23.10 L93.78,27.98 L89.73,33.54 L96.52,34.61 L97.98,40.06 L92.63,44.39 L98.92,47.18 L98.92,52.82 L92.63,55.61 L97.98,59.94 L96.52,65.39 L89.73,66.46 L93.78,72.02 L90.95,76.90 L84.11,76.18 L86.59,82.60 L82.60,86.59 L76.18,84.11 L76.90,90.95 L72.02,93.78 L66.46,89.73 L65.39,96.52 L59.94,97.98 L55.61,92.63 L52.82,98.92 L47.18,98.92 L44.39,92.63 L40.06,97.98 L34.61,96.52 L33.54,89.73 L27.98,93.78 L23.10,90.95 L23.82,84.11 L17.40,86.59 L13.41,82.60 L15.89,76.18 L9.05,76.90 L6.22,72.02 L10.27,66.46 L3.48,65.39 L2.02,59.94 L7.37,55.61 L1.08,52.82 L1.08,47.18 L7.37,44.39 L2.02,40.06 L3.48,34.61 L10.27,33.54 L6.22,27.98 L9.05,23.10 L15.89,23.82 L13.41,17.40 L17.40,13.41 L23.82,15.89 L23.10,9.05 L27.98,6.22 L33.54,10.27 L34.61,3.48 L40.06,2.02 L44.39,7.37 Z" fill="#fff"/>
      <circle cx="50" cy="50" r="33.5" fill="#000"/>
      <g fill="#fff">
        <rect x="45.6" y="14" width="8.8" height="72" rx="1.2"/>
        <rect x="45.6" y="14" width="8.8" height="72" rx="1.2" transform="rotate(60 50 50)"/>
        <rect x="45.6" y="14" width="8.8" height="72" rx="1.2" transform="rotate(120 50 50)"/>
      </g>
      <circle cx="50" cy="50" r="15" fill="#fff"/>
      <circle cx="50" cy="50" r="7.4" fill="#000"/>
      <rect x="47.7" y="34.5" width="4.6" height="9.5" rx="0.6" fill="#000"/>
    </mask>
    <rect width="100" height="100" fill="var(--b-accent)" mask="url(#smpw3)"/>
  </svg>;
}

/* ── App menu ────────────────────────────────────────────────────────────────
   Clubcraft's standard app menu (appmenu.jsx): the campaign switcher on top, the five working tabs, then the
   campaign and club actions that used to be buttons across the header. */
function AppHeader({state, actions, campaign, member, memberRole, caps, onSetup, onTeam, onSocials, onDeleteCampaign, onEventsImport, onPlanSocialImport, onBrandKit, onGuide, onShowImages, onNewCampaign, onApprovals, isAllCampaigns, mode, onSignOut, pendingConfirmCount}) {
  const M = window.CCAppMenu, I = window.CCMenuIcons;
  const rc = ROLE_COLOR[memberRole] || ROLE_COLOR.Read;
  const [campMenuOpen, setCampMenuOpen] = React.useState(false);
  const currentEntry = (state.campaignIndex||[]).find(c=>c.id===state.currentCampaignId);
  const currentLabel = isAllCampaigns ? 'All campaigns' : (currentEntry ? currentEntry.name : (campaign ? campaign.config.eventName : 'Select a campaign'));
  const selectCampaign = id => {
    actions.patch({currentCampaignId:id,tab:'planner',expanded:{},collapsed:{},filterStatus:'all',filterPillar:'all',filterWeek:'all'});
    setCampMenuOpen(false);
  };
  const sum = f => isAllCampaigns ? state.campaigns.reduce((n,c) => n+f(c), 0) : (campaign ? f(campaign) : 0);
  const totalWeeks  = sum(c => c.weeks.length);
  const totalPosts  = sum(c => c.posts.length);
  const readyCount  = sum(c => c.posts.filter(p=>p.status==='ready'||p.status==='queued').length);
  const postedCount = sum(c => c.posts.filter(p=>p.status==='posted').length);
  const tab = (key, label, icon, count) => ({ key, label, icon, count, onClick:()=>actions.patch({tab:key}) });
  /* The master calendar shows every post from every campaign; the plain Calendar item goes back to the campaign you were in. */
  const masterOn = isAllCampaigns && state.tab==='calendar';
  const openMaster = () => actions.patch(s=>({prevCampaignId: s.currentCampaignId==='all' ? s.prevCampaignId : s.currentCampaignId, currentCampaignId:'all', tab:'calendar'}));
  const openCalendar = () => actions.patch(s=>({tab:'calendar', ...(s.currentCampaignId==='all' ? {currentCampaignId: s.prevCampaignId || (s.campaigns[0]||{}).id || 'all'} : {})}));
  const one = !isAllCampaigns && caps.setup;
  const rowBtn = on => ({display:'block',width:'100%',textAlign:'left',border:'none',background:on?'var(--b-wash)':'transparent',color:on?'var(--b-primary-deep)':'var(--b-ink)',borderRadius:7,padding:'7px 9px',font:"600 13px 'Public Sans'",cursor:'pointer',whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'});

  const top = (
    <div>
      <button onClick={()=>setCampMenuOpen(o=>!o)} aria-expanded={campMenuOpen} style={{display:'flex',alignItems:'center',gap:8,width:'100%',border:'1px solid var(--b-line)',borderRadius:8,padding:'8px 10px',background:'var(--b-surface)',cursor:'pointer',textAlign:'left'}}>
        <span style={{flex:1,minWidth:0}}>
          <span style={{display:'block',font:"700 10px 'Public Sans'",color:'var(--b-muted)',textTransform:'uppercase',letterSpacing:'.06em'}}>Campaign</span>
          <span style={{display:'block',font:"700 13.5px 'Public Sans'",color:'var(--b-ink)',whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{currentLabel}</span>
        </span>
        <ChevronIcon deg={campMenuOpen?180:0} sz={11} color="var(--b-muted)"/>
      </button>
      {campMenuOpen && (
        <div style={{marginTop:4,border:'1px solid var(--b-line)',borderRadius:8,padding:4,background:'var(--b-surface)'}}>
          <button onClick={()=>selectCampaign('all')} style={rowBtn(state.currentCampaignId==='all')}>All campaigns</button>
          {(state.campaignIndex||[]).map(c=><button key={c.id} onClick={()=>selectCampaign(c.id)} style={rowBtn(state.currentCampaignId===c.id)}>{c.name}</button>)}
          <button onClick={()=>{ setCampMenuOpen(false); onNewCampaign(); }} style={{...rowBtn(false),display:'flex',alignItems:'center',gap:6,color:'var(--b-primary)',fontWeight:800,borderTop:'1px solid var(--b-line)',marginTop:3,borderRadius:0}}><PlusIcon sz={12}/> New campaign</button>
        </div>
      )}
      {!isAllCampaigns && campaign && (
        <div style={{marginTop:8,display:'flex',alignItems:'center',gap:8,padding:'0 2px'}}>
          <span style={{padding:'2px 8px',borderRadius:999,font:"800 10px/1.4 'Public Sans'",letterSpacing:'.05em',textTransform:'uppercase',color:state.isSocialSuperAdmin?'#fff':rc.color,background:state.isSocialSuperAdmin?'var(--b-accent)':rc.bg}}>{state.isSocialSuperAdmin?'Club admin':memberRole}</span>
          <span style={{font:"500 12px 'Public Sans'",color:'var(--b-muted)'}}>your role</span>
        </div>
      )}
    </div>
  );

  const groups = [
    { label:'Plan', items:[
      tab('planner','Week Planner',I.plan,totalWeeks), tab('posts','Post Brief',I.doc,totalPosts), tab('review','Ready to Post',I.check,readyCount),
      tab('history','Post History',I.history,postedCount),
      { key:'calendar', label:'Calendar', icon:I.calendar, count:isAllCampaigns?undefined:totalPosts, onClick:openCalendar },
      { key:'master', label:'Master calendar', icon:I.calendar, onClick:openMaster, hidden:state.campaigns.length<1, title:'Every planned post from every campaign, with its status' } ]},
    { label:'Campaign', items:[
      { key:'setup', label:'Setup', icon:I.setup, onClick:onSetup, hidden:!one, title:'Event details, branding, pillars and the week plan' },
      { key:'guide', label:'Setup guide', icon:I.guide, onClick:onGuide, hidden:!one, title:'Printable walkthrough with live readiness checks' },
      { key:'events', label:'Pull in from Events', icon:I.list, onClick:onEventsImport, hidden:!(!isAllCampaigns && caps.edit), title:'Add the promotion steps from an Events plan as draft posts' },
      /* shown again 2026-10-21 to bring over weeks and posts; hide it again (hidden:true) when the data is in */ { key:'psimport', label:'Import from Plan Social', icon:I.add, onClick:onPlanSocialImport, hidden:!one, title:'Bring a campaign\'s setup over from the Plan Social app (a file exported from it)' },
      { key:'delete', label:'Delete this campaign', icon:I.x||I.add, onClick:onDeleteCampaign, hidden:!(one && (!state.trial || state.platformAdmin) && (memberRole==='Admin' || state.isSocialSuperAdmin)), title:'Remove this campaign, its weeks, posts and stored pictures. This cannot be undone.' },
      { key:'team', label:'Team', icon:I.team, onClick:onTeam, hidden:!one, title:'Who works on this campaign, and what each person can do' },
      { key:'socials', label:'Socials', icon:['M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18z','M3 12h18M12 3c2.5 2.5 3.5 5.5 3.5 9s-1 6.5-3.5 9c-2.5-2.5-3.5-5.5-3.5-9s1-6.5 3.5-9z'], onClick:onSocials, hidden:!one, title:'The Facebook Page and Instagram account this campaign posts to' } ]},
    { label:'Club', items:[
      { key:'brand', label:'Brand kit', icon:I.palette, onClick:onBrandKit, hidden:!state.isSocialSuperAdmin, title:'Logo, colours and voice shared by every campaign' },
      { key:'images', label:'Image library', icon:I.images, onClick:onShowImages },
      { key:'approvals', label:'Approvals', icon:I.shield, onClick:onApprovals, hidden:!state.isSocialSuperAdmin, badge:state.pendingApprovals.length||null, title:'Approve or decline new campaigns' } ]}
  ];
  const foot = pendingConfirmCount > 0 ? <span style={{display:'inline-flex',alignItems:'center',gap:5,padding:'5px 10px',borderRadius:999,font:"800 11px 'Public Sans'",color:'#fff',background:'var(--b-accent)'}}>{pendingConfirmCount} awaiting you</span> : null;
  return <M title="Social" icon={["M18 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM6 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM18 22a3 3 0 1 0 0-6 3 3 0 0 0 0 6z","M8.6 13.5l6.8 4M15.4 6.5l-6.8 4"]} top={top} groups={groups} active={masterOn?'master':state.tab} foot={foot}/>;
}

/* Extra posts for one week — on top of the default posts that Setup's preferred
   days create. For peak moments (the days before a price deadline, the final days
   before the event). Each has its own day and, optionally, its own topic; Setup
   never deletes or re-dates them. Only an extra post with no caption yet can be removed. */
const WEEKDAY_SHORT = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']; /* indexed by Date.getDay() */
function ExtraPosts({w, posts, actions, caps, weekStartDate, compact}) {
  const extras = posts.filter(p=>p.weekId===w.id && p.extra).sort((a,b)=>a.dayOffset-b.dayOffset);
  const used = new Set(posts.filter(p=>p.weekId===w.id).map(p=>p.dayOffset));
  const firstFree = [0,1,2,3,4,5,6].find(d=>!used.has(d));
  const [day, setDay] = React.useState(firstFree === undefined ? 6 : firstFree);
  const dayLabel = off => { const d = addDays(weekStartDate, off); return `${WEEKDAY_SHORT[d.getDay()]} ${fmtShort(d)}`; };
  const sel = {border:'1px solid #D9E1EE',borderRadius:7,padding:'5px 6px',font:"600 11.5px 'Public Sans'",color:'#1A2942',background:'#fff',outline:'none'};
  const addBtn = <button onClick={()=>actions.addPost(w.id, Number(day))} disabled={!caps.edit}
      title="Add an extra post this week, on top of the default posting days set in Setup"
      style={{border:'1px dashed #9FB3D6',background:'#F5F8FC',color:'var(--b-primary)',borderRadius:8,padding:'5px 9px',font:"700 11.5px 'Public Sans'",cursor:caps.edit?'pointer':'default',opacity:caps.edit?1:.5}}>+ Add post</button>;
  if (compact) return (
    <div style={{display:'inline-flex',alignItems:'center',gap:5}}>
      <select value={day} onChange={e=>setDay(e.target.value)} disabled={!caps.edit} style={sel}>{[0,1,2,3,4,5,6].map(o=><option key={o} value={o}>{dayLabel(o)}</option>)}</select>
      {addBtn}
      {extras.length>0 && <span style={{font:"600 11px 'Public Sans'",color:'#6B7790'}}>+{extras.length} extra</span>}
    </div>
  );
  return (
    <div>
      <div style={{font:"800 9.5px 'Public Sans'",letterSpacing:'.05em',textTransform:'uppercase',color:'#9AA6BC',marginBottom:5}}>Extra posts</div>
      {extras.map(p=>{
        const canRemove = caps.edit && !(p.draftCaption||'').trim() && (p.status||'draft')==='draft';
        return (
          <div key={p.id} style={{border:'1px solid #E1E8F2',borderRadius:8,padding:7,marginBottom:6,background:'#FBFCFE'}}>
            <div style={{display:'flex',alignItems:'center',gap:6,marginBottom:5}}>
              <select value={p.dayOffset} onChange={e=>actions.updatePost(p.id,{dayOffset:Number(e.target.value)})} disabled={!caps.edit} style={sel}>
                {[0,1,2,3,4,5,6].map(o=><option key={o} value={o}>{dayLabel(o)}</option>)}
              </select>
              <div style={{flex:1}}/>
              {canRemove && <button onClick={()=>actions.removePost(p.id)} title="Remove this extra post" style={{border:'none',background:'none',color:'#B42318',font:"700 11px 'Public Sans'",cursor:'pointer'}}>Remove</button>}
            </div>
            <BufferedTextarea value={p.topic||''} onSave={v=>actions.updatePost(p.id,{topic:v})} readOnly={!caps.edit} rows="2"
              placeholder="Topic for this post (optional). Leave blank to use the week's angles."
              style={{width:'100%',border:'1px solid #E1E8F2',borderRadius:7,padding:'6px 8px',font:"500 12px/1.4 'Public Sans'",color:'#1A2942',background:'#fff',outline:'none'}}/>
          </div>
        );
      })}
      <div style={{display:'flex',alignItems:'center',gap:6}}>
        <select value={day} onChange={e=>setDay(e.target.value)} disabled={!caps.edit} style={sel}>{[0,1,2,3,4,5,6].map(o=><option key={o} value={o}>{dayLabel(o)}</option>)}</select>
        {addBtn}
      </div>
    </div>
  );
}

/* ── Week Planner tab ─────────────────────────────────────────────────────── */
function WeekPlannerTab({state, actions, caps, pillarById, weekNo, dateRange, statusCells, generateWeek, generateSecondAngle}) {
  const s = state;
  const start = parseDate(s.config.campaignStart);
  const isTable = s.plannerView==='table';
  const dragIdRef = React.useRef(null);
  const [dragOverId, setDragOverId] = React.useState(null);

  /* Drag a card onto another to swap its whole slot (topic, pillar, posts) into that
     position — dates/week number follow the slot, not the card, since both are just
     idx-derived (see weekStart in the parent). */
  const dropOnWeek = targetId => {
    const fromId = dragIdRef.current;
    dragIdRef.current = null;
    setDragOverId(null);
    if (!fromId || fromId === targetId) return;
    const ids = s.weeks.map(w => w.id);
    const from = ids.indexOf(fromId), to = ids.indexOf(targetId);
    if (from===-1 || to===-1) return;
    ids.splice(to, 0, ids.splice(from, 1)[0]);
    actions.reorderWeeks(ids);
  };

  const segBtn = (view, label) => {
    const active = s.plannerView===view;
    return <button onClick={()=>actions.patch({plannerView:view})} style={{border:'none',cursor:'pointer',borderRadius:8,padding:'7px 15px',font:"700 13px 'Public Sans'",background:active?'#fff':'transparent',color:active?'var(--b-primary)':'#6B7790',boxShadow:active?'0 1px 2px rgba(16,42,90,.12)':'none'}}>{label}</button>;
  };

  return (
    <div>
      <div style={{display:'flex',alignItems:'flex-end',justifyContent:'space-between',gap:16,marginBottom:18,flexWrap:'wrap'}}>
        <div>
          <h1 style={{margin:0,font:"800 23px/1.2 'Public Sans'",color:'var(--b-primary-deep)',letterSpacing:'-.01em'}}>Week Planner</h1>
          <p style={{margin:'5px 0 0',font:"500 13px 'Public Sans'",color:'#6B7790'}}>{s.weeks.length} weeks &nbsp;·&nbsp; {s.posts.length} posts{s.config.campaignStart ? <> &nbsp;·&nbsp; kicks off {fmt(start)}</> : <> &nbsp;·&nbsp; <span style={{color:'#B45309'}}>no start date set yet — add one in Setup</span></>}{!isTable && <> &nbsp;·&nbsp; <span style={{color:'#9AA6BC'}}>drag a card onto another to swap it into that week</span></>}</p>
        </div>
        <div style={{display:'inline-flex',background:'#E2E8F4',borderRadius:10,padding:3,gap:2}}>
          {segBtn('table','Table')}
          {segBtn('board','Board')}
        </div>
      </div>

      {isTable ? (
        <div style={{background:'#fff',border:'1px solid #E4EAF3',borderRadius:14,overflow:'hidden',boxShadow:'0 1px 3px rgba(16,42,90,.05)'}}>
          <div style={{display:'grid',gridTemplateColumns:'140px 120px 168px minmax(220px,1fr) 168px 140px 152px',background:'#F5F8FC',borderBottom:'1px solid #E4EAF3',font:"800 10.5px 'Public Sans'",letterSpacing:'.05em',textTransform:'uppercase',color:'#8A94A8'}}>
            {['Week','Dates','Pillar','Topic & Angle','Reference','Status','Action'].map(h=>(
              <div key={h} style={{padding:'11px 14px',textAlign:h==='Action'?'right':'left'}}>{h}</div>
            ))}
          </div>
          {s.weeks.map(w=>{
            const pil = pillarById(w.pillarId);
            return (
              <div key={w.id} className="hov-row" style={{display:'grid',gridTemplateColumns:'140px 120px 168px minmax(220px,1fr) 168px 140px 152px',borderBottom:'1px solid var(--b-bg)',alignItems:'center'}}>
                <div style={{padding:'12px 14px'}}>
                  <div style={{font:"800 13px 'Public Sans'",color:'var(--b-primary-deep)'}}>Week {weekNo(w)}</div>
                  {w._eventName && <span style={{display:'inline-block',padding:'2px 7px',borderRadius:999,font:"700 9.5px 'Public Sans'",color:'var(--b-primary)',background:'var(--b-wash)',marginTop:3,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis',maxWidth:120}}>{w._eventName}</span>}
                </div>
                <div style={{padding:'12px 14px',font:"600 12.5px 'Public Sans'",color:'#5C6880'}}>{dateRange(w)}</div>
                <div style={{padding:'8px 12px'}}>
                  <select value={w.pillarId} onChange={e=>actions.updateWeek(w.id,{pillarId:e.target.value})} disabled={!caps.edit} style={{width:'100%',border:'1px solid #DEE6F1',borderRadius:8,padding:'7px 8px',font:"600 12px 'Public Sans'",color:pil.color,background:pil.bg,outline:'none',cursor:caps.edit?'pointer':'default'}}>
                    {s.config.pillars.map(p=><option key={p.id} value={p.id} style={{background:'#fff',color:'#1A2942'}}>{p.label}</option>)}
                  </select>
                </div>
                <div style={{padding:'8px 12px'}}>
                  <input value={w.topicAndAngle} onChange={e=>actions.updateWeek(w.id,{topicAndAngle:e.target.value})} readOnly={!caps.edit} placeholder="Topic & angle…" style={{width:'100%',border:'1px solid #E1E8F2',borderRadius:8,padding:'8px 10px',font:"500 12.5px 'Public Sans'",color:'#1A2942',background:'#fff',outline:'none'}}/>
                </div>
                <div style={{padding:'8px 12px'}}>
                  <input value={w.referenceUrl} onChange={e=>actions.updateWeek(w.id,{referenceUrl:e.target.value})} readOnly={!caps.edit} placeholder="https://…" style={{width:'100%',border:'1px solid #E1E8F2',borderRadius:8,padding:'8px 10px',font:"500 12px 'Public Sans'",color:'var(--b-primary)',background:'#fff',outline:'none'}}/>
                </div>
                <div style={{padding:'10px 12px',display:'flex',flexWrap:'wrap',gap:5}}>
                  <StatusCells cells={statusCells(w.id)}/>
                  {!w._eventName && <ExtraPosts compact w={w} posts={s.posts} actions={actions} caps={caps} weekStartDate={addDays(parseDate(w._campaignStart||s.config.campaignStart||'2026-01-01'), w.idx*7)}/>}
                </div>
                <div style={{padding:'10px 14px',display:'flex',justifyContent:'flex-end'}}>
                  <button className="hov-generate" onClick={()=>generateWeek(w.id)} disabled={!caps.generate||!!w.generating} style={{display:'inline-flex',alignItems:'center',gap:6,background:'var(--b-accent)',color:'#3A2C05',border:'1px solid #E89A0A',borderRadius:9,padding:'8px 11px',font:"800 12px 'Public Sans'",cursor:'pointer',opacity:caps.generate?1:0.4}}>
                    {w.generating ? <><SpinIcon/><span>Working…</span></> : <><StarIcon/><span>Generate</span></>}
                  </button>
                </div>
              </div>
            );
          })}
        </div>
      ) : (
        <div className="sp-board-scroll" style={{display:'flex',gap:14}}>
          {s.weeks.map(w=>{
            const pil = pillarById(w.pillarId);
            const isDragOver = dragOverId === w.id;
            const wp = s.posts.filter(p=>p.weekId===w.id);
            return (
              <div key={w.id}
                draggable={caps.edit}
                onDragStart={e => { dragIdRef.current = w.id; e.dataTransfer.effectAllowed = 'move'; }}
                onDragOver={e => { if (caps.edit) { e.preventDefault(); if (dragOverId!==w.id) setDragOverId(w.id); } }}
                onDragLeave={() => setDragOverId(id => id===w.id ? null : id)}
                onDrop={e => { e.preventDefault(); dropOnWeek(w.id); }}
                onDragEnd={() => { dragIdRef.current = null; setDragOverId(null); }}
                style={{flex:'0 0 282px',background:'#fff',border:'1px solid '+(isDragOver?'var(--b-primary)':'#E4EAF3'),borderRadius:14,display:'flex',flexDirection:'column',boxShadow:isDragOver?'0 0 0 3px color-mix(in srgb, var(--b-primary) 18%, transparent)':'0 1px 3px rgba(16,42,90,.05)',overflow:'hidden',cursor:caps.edit?'grab':'default',transition:'box-shadow .12s,border-color .12s'}}>
                <div style={{padding:'13px 14px',borderBottom:'1px solid var(--b-bg)',display:'flex',alignItems:'center',justifyContent:'space-between',gap:8}}>
                  <div>
                    <div style={{font:"800 14px 'Public Sans'",color:'var(--b-primary-deep)'}}>Week {weekNo(w)}</div>
                    <div style={{font:"600 11.5px 'Public Sans'",color:'#9AA6BC'}}>{dateRange(w)}</div>
                    {w._eventName && <span style={{display:'inline-block',padding:'2px 7px',borderRadius:999,font:"700 9.5px 'Public Sans'",color:'var(--b-primary)',background:'var(--b-wash)',marginTop:3}}>{w._eventName}</span>}
                  </div>
                  <span style={{padding:'4px 9px',borderRadius:7,font:"800 11px 'Public Sans'",color:pil.color,background:pil.bg}}>{pil.label}</span>
                </div>
                <div style={{padding:'13px 14px',display:'flex',flexDirection:'column',gap:11,flex:1}}>
                  <div>
                    <div style={{font:"800 9.5px 'Public Sans'",letterSpacing:'.05em',textTransform:'uppercase',color:'#9AA6BC',marginBottom:5}}>Topic & Angle</div>
                    <BufferedTextarea value={w.topicAndAngle} onSave={v=>actions.updateWeek(w.id,{topicAndAngle:v})} readOnly={!caps.edit} placeholder="Topic & angle…" rows="3" style={{width:'100%',border:'1px solid #E1E8F2',borderRadius:8,padding:'8px 10px',font:"500 12.5px/1.45 'Public Sans'",color:'#1A2942',background:'#FBFCFE',outline:'none'}}/>
                  </div>
                  {wp.length > 1 && (
                    <div>
                      <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',gap:6,marginBottom:5}}>
                        <div style={{font:"800 9.5px 'Public Sans'",letterSpacing:'.05em',textTransform:'uppercase',color:'#9AA6BC'}}>2nd angle</div>
                        {caps.generate && (
                          <button onClick={()=>generateSecondAngle(w.id)} disabled={!!w.generating||!(w.topicAndAngle||'').trim()}
                            title="Generates a distinct second angle so alternate posts in this week don't read the same — leaves Topic & Angle and any drafted captions untouched"
                            style={{border:'none',background:'none',padding:0,font:"700 10.5px 'Public Sans'",color:'var(--b-primary)',cursor:'pointer',flex:'none',opacity:!(w.topicAndAngle||'').trim()?.5:1}}>
                            ✨ {w.generating?'Working…':'Generate'}
                          </button>
                        )}
                      </div>
                      {!(w.topicAndAngle2||'').trim() && (
                        <div style={{font:"600 10.5px 'Public Sans'",color:'#B45309',marginBottom:5}}>Not set — every post in this week will look alike</div>
                      )}
                      <BufferedTextarea value={w.topicAndAngle2||''} onSave={v=>actions.updateWeek(w.id,{topicAndAngle2:v})} readOnly={!caps.edit} placeholder="Optional — a distinct angle for alternate posts (2nd, 4th…). Leave blank and every post shares the angle above." rows="2" style={{width:'100%',border:'1px solid #E1E8F2',borderRadius:8,padding:'8px 10px',font:"500 12.5px/1.45 'Public Sans'",color:'#1A2942',background:'#FBFCFE',outline:'none'}}/>
                    </div>
                  )}
                  <div>
                    <div style={{font:"800 9.5px 'Public Sans'",letterSpacing:'.05em',textTransform:'uppercase',color:'#9AA6BC',marginBottom:5}}>Reference</div>
                    <input value={w.referenceUrl} onChange={e=>actions.updateWeek(w.id,{referenceUrl:e.target.value})} readOnly={!caps.edit} placeholder="https://…" style={{width:'100%',border:'1px solid #E1E8F2',borderRadius:8,padding:'7px 9px',font:"500 11.5px 'Public Sans'",color:'var(--b-primary)',background:'#FBFCFE',outline:'none'}}/>
                  </div>
                  <div style={{display:'flex',flexWrap:'wrap',gap:5}}>
                    <StatusCells cells={statusCells(w.id)}/>
                  </div>
                  {!w._eventName && <ExtraPosts w={w} posts={s.posts} actions={actions} caps={caps} weekStartDate={addDays(parseDate(w._campaignStart||s.config.campaignStart||'2026-01-01'), w.idx*7)}/>}
                </div>
                <div style={{padding:'12px 14px',borderTop:'1px solid var(--b-bg)'}}>
                  <button className="hov-generate" onClick={()=>generateWeek(w.id)} disabled={!caps.generate||!!w.generating} style={{width:'100%',display:'inline-flex',alignItems:'center',justifyContent:'center',gap:7,background:'var(--b-accent)',color:'#3A2C05',border:'1px solid #E89A0A',borderRadius:9,padding:9,font:"800 12.5px 'Public Sans'",cursor:'pointer',opacity:caps.generate?1:0.4}}>
                    {w.generating ? <><SpinIcon/><span>Generating…</span></> : <><StarIcon sz={14}/><span>Generate Week</span></>}
                  </button>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

/* ── Post Brief tab ───────────────────────────────────────────────────────── */
function PostBriefTab({state, actions, caps, pillarById, weekNo, dateRange, postDate, postsOf, statusCells, generatePost, advance, generateMediaBrief, generateImage, handleImageUpload, setSignOff, driveDestFor, setDriveDest, movePostToDate}) {
  const s = state;
  const [preview, setPreview] = React.useState(null);
  const weeks = s.weeks.filter(w => {
    if (s.filterWeek!=='all' && w.id!==s.filterWeek) return false;
    if (s.filterPillar!=='all' && w.pillarId!==s.filterPillar) return false;
    return postsOf(w.id).filter(p=>s.filterStatus==='all'||p.status===s.filterStatus).length > 0;
  });
  const filteredCount = weeks.reduce((n,w)=>n+postsOf(w.id).filter(p=>s.filterStatus==='all'||p.status===s.filterStatus).length, 0);

  const selStyle = {border:'1px solid #D9E1EE',borderRadius:8,padding:'7px 9px',font:"600 12.5px 'Public Sans'",color:'#1A2942',background:'#fff',outline:'none',cursor:'pointer'};

  return (
    <div>
      <div style={{marginBottom:14}}>
        <h1 style={{margin:0,font:"800 23px/1.2 'Public Sans'",color:'var(--b-primary-deep)',letterSpacing:'-.01em'}}>Post Brief</h1>
        <p style={{margin:'5px 0 0',font:"500 13px 'Public Sans'",color:'#6B7790'}}>One row per post · click a row to open the brief and edit the caption.</p>
      </div>
      <div style={{display:'flex',alignItems:'center',gap:10,flexWrap:'wrap',background:'#fff',border:'1px solid #E4EAF3',borderRadius:12,padding:'10px 12px',marginBottom:16,boxShadow:'0 1px 2px rgba(16,42,90,.04)'}}>
        <span style={{display:'inline-flex',alignItems:'center',gap:6,font:"800 11px 'Public Sans'",letterSpacing:'.04em',textTransform:'uppercase',color:'#8A94A8'}}><FilterIcon/>Filter</span>
        <select value={s.filterStatus} onChange={e=>actions.patch({filterStatus:e.target.value})} style={selStyle}>
          <option value="all">All statuses</option>
          {SD.STATUS_ORDER.map(k=><option key={k} value={k}>{SD.STATUS[k].label}</option>)}
        </select>
        <select value={s.filterPillar} onChange={e=>actions.patch({filterPillar:e.target.value})} style={selStyle}>
          <option value="all">All pillars</option>
          {s.config.pillars.map(p=><option key={p.id} value={p.id}>{p.label}</option>)}
        </select>
        <select value={s.filterWeek} onChange={e=>actions.patch({filterWeek:e.target.value})} style={selStyle}>
          <option value="all">All weeks</option>
          {s.weeks.map(w=><option key={w.id} value={w.id}>Week {weekNo(w)}{w._eventName?' · '+w._eventName:''}</option>)}
        </select>
        <div style={{flex:1}}/>
        <span style={{font:"700 12px 'Public Sans'",color:'#6B7790'}}>{filteredCount} of {s.posts.length} posts</span>
      </div>

      {preview && <PostPreviewModal post={s.posts.find(x=>x.id===preview.post.id)||preview.post} date={preview.date} time={(()=>{ const pp=s.posts.find(x=>x.id===preview.post.id)||preview.post; const c=(s.campaigns||[]).find(c=>c.posts.some(x=>x.id===pp.id)); return pp.postTime||(c&&c.config.defaultPostTime)||'19:30'; })()} config={s.config} clubBrandKit={s.clubBrandKit} onClose={()=>setPreview(null)}/>}

      {weeks.map(w=>{
        const pil = pillarById(w.pillarId);
        const wp  = postsOf(w.id).filter(p=>s.filterStatus==='all'||p.status===s.filterStatus);
        const open = !s.collapsed[w.id];
        return (
          <div key={w.id} style={{marginBottom:14,background:'#fff',border:'1px solid #E4EAF3',borderRadius:14,overflow:'hidden',boxShadow:'0 1px 3px rgba(16,42,90,.05)'}}>
            <button className="hov-collapse" onClick={()=>actions.patch(s=>({...s,collapsed:{...s.collapsed,[w.id]:!s.collapsed[w.id]}}))} style={{width:'100%',display:'flex',alignItems:'center',gap:12,padding:'13px 16px',background:'#F5F8FC',border:'none',borderBottom:'1px solid #E9EEF6',cursor:'pointer',textAlign:'left'}}>
              <ChevronIcon deg={open?90:0} color="#8A94A8" sz={14}/>
              <span style={{font:"800 14px 'Public Sans'",color:'var(--b-primary-deep)'}}>Week {weekNo(w)}</span>
              <span style={{font:"600 12px 'Public Sans'",color:'#9AA6BC'}}>{dateRange(w)}</span>
              <span style={{padding:'3px 9px',borderRadius:999,font:"800 11px 'Public Sans'",color:pil.color,background:pil.bg}}>{pil.label}</span>
              {w._eventName && <span style={{padding:'3px 9px',borderRadius:999,font:"700 10px 'Public Sans'",color:'var(--b-primary)',background:'var(--b-wash)'}}>{w._eventName}</span>}
              <div style={{flex:1}}/>
              <div style={{display:'flex',gap:5}}><StatusCells cells={statusCells(w.id)}/></div>
            </button>
            {open && (
              <div>
                {wp.map(p=>{
                  const st  = SD.STATUS[p.status];
                  const exp = !!s.expanded[p.id];
                  const preview = p.draftCaption ? p.draftCaption.slice(0,84)+(p.draftCaption.length>84?'…':'') : 'No caption yet — generate or write one.';
                  return (
                    <div key={p.id} style={{borderBottom:'1px solid #F0F3F9'}}>
                      <div className="hov-row" onClick={()=>actions.patch(s=>({...s,expanded:{...s.expanded,[p.id]:!s.expanded[p.id]}}))} style={{display:'grid',gridTemplateColumns:'64px 118px minmax(160px,1fr) 156px 150px 26px',gap:12,alignItems:'center',padding:'13px 16px',cursor:'pointer'}}>
                        <div style={{font:"800 13px 'Public Sans'",color:'var(--b-primary-deep)'}}>Post {p.postNo}</div>
                        <div style={{font:"600 12px 'Public Sans'",color:'#5C6880'}}>{fmt(postDate(w,p))}</div>
                        <div style={{minWidth:0}}>
                          <div style={{font:"700 12.5px 'Public Sans'",color:'#1A2942',whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{postAngle(w,wp,p.id)||'—'}</div>
                          <div style={{font:"500 11.5px 'Public Sans'",color:p.draftCaption?'#5C6880':'#A6B0C4',whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis',marginTop:2}}>{preview}</div>
                        </div>
                        <div><span style={{padding:'3px 9px',borderRadius:999,font:"800 11px 'Public Sans'",color:pil.color,background:pil.bg}}>{pil.label}</span></div>
                        <div>
                          <button className="hov-filter" onClick={e=>advance(e,p.id)}
                            title={p.status==='draft'?'Mark as Needs Edit':p.status==='needs'?'Mark as Ready to Post':p.status==='ready'?'Return to Needs Edit':st.label}
                            style={{display:'inline-flex',alignItems:'center',gap:6,padding:'5px 11px',borderRadius:999,border:'none',cursor:p.status==='posted'?'default':'pointer',font:"800 11.5px 'Public Sans'",color:st.color,background:st.bg}}>
                            <span style={{width:7,height:7,borderRadius:'50%',background:st.dot}}/>{st.label}
                          </button>
                        </div>
                        <div style={{display:'flex',justifyContent:'flex-end'}}><ChevronIcon deg={exp?90:0}/></div>
                      </div>
                      {exp && (
                        <div style={{padding:'6px 16px 18px',background:'#FBFCFE',display:'grid',gridTemplateColumns:'1fr 320px',gap:18,borderTop:'1px solid #F0F3F9'}}>
                          <div style={{margin:'6px 0 12px'}}>
                            <div style={{font:"800 10px 'Public Sans'",letterSpacing:'.06em',textTransform:'uppercase',color:'#8A94A8',marginBottom:6}}>Topic and angle</div>
                            {(() => {
                              const regular = wp.filter(x=>!x.extra).sort((a,b)=>a.dayOffset-b.dayOffset);
                              const second = !p.extra && (w.topicAndAngle2||'').trim() && regular.findIndex(x=>x.id===p.id)%2===1;
                              const val = p.extra ? (p.topic||'') : (second ? w.topicAndAngle2 : w.topicAndAngle) || '';
                              const save = v => p.extra ? actions.updatePost(p.id,{topic:v}) : actions.updateWeek(w.id, second ? {topicAndAngle2:v} : {topicAndAngle:v});
                              return <BufferedTextarea value={val} onSave={save} readOnly={!caps.edit} placeholder="What this post is about…" rows="2" style={{width:'100%',border:'1px solid #E1E8F2',borderRadius:10,padding:'9px 11px',font:"500 12.5px/1.5 'Public Sans'",color:'#26324A',background:'#fff',outline:'none'}}/>;
                            })()}
                            {!p.extra && wp.filter(x=>!x.extra).length>1 && !(w.topicAndAngle2||'').trim() && <div style={{font:"500 11px 'Public Sans'",color:'#9AA6BC',marginTop:4}}>This week's topic is shared by its posts. Add a second angle in the Week Planner to give each post its own.</div>}
                          </div>
                          <div>
                            <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',margin:'6px 0 7px'}}>
                              <span style={{font:"800 10px 'Public Sans'",letterSpacing:'.06em',textTransform:'uppercase',color:'#8A94A8'}}>Draft Caption</span>
                              <div style={{display:'flex',gap:6}}>
                              <button className="hov-filter" onClick={()=>setPreview({post:p,date:postDate(w,p)})} title="See how this post will look on Facebook and Instagram" style={{display:'inline-flex',alignItems:'center',gap:6,background:'#F0F4FA',color:'var(--b-primary)',border:'1px solid #D5DEF0',borderRadius:8,padding:'6px 11px',font:"800 11.5px 'Public Sans'",cursor:'pointer'}}>
                                <span>Preview</span>
                              </button>
                              <button className="hov-blue" onClick={()=>generatePost(p.id)} disabled={!caps.generate||!!p.generating} style={{display:'inline-flex',alignItems:'center',gap:6,background:'var(--b-primary)',color:'#fff',border:'none',borderRadius:8,padding:'6px 11px',font:"800 11.5px 'Public Sans'",cursor:'pointer',opacity:caps.generate?1:0.4}}>
                                {p.generating ? <><SpinIcon light/><span>Generating…</span></> : <><StarIcon sz={13}/><span>{p.status==='needs'?'Re-generate':p.draftCaption?'Regenerate':'Generate caption'}</span></>}
                              </button>
                              </div>
                            </div>
                            <CaptionEditor value={p.draftCaption} readOnly={!caps.edit} onSave={val=>actions.updatePost(p.id,{draftCaption:val})} style={{width:'100%',border:'1px solid #E1E8F2',borderRadius:10,padding:'11px 12px',font:"500 13px/1.55 'Public Sans'",color:'#26324A',background:'#fff',outline:'none',resize:'vertical'}}/>
                            <div style={{font:"600 11px 'Public Sans'",color:'#9AA6BC',marginTop:8}}>Last updated by {p.updatedBy||'—'}</div>
                            {(() => {
                              /* Post date moves the post like a Calendar drag (and locks it against Setup
                                 re-dating it); post time overrides the campaign's default time. */
                              const campId = w._campaignId || s.currentCampaignId;
                              const camp = (s.campaigns||[]).find(c=>c.id===campId);
                              const defTime = (camp && camp.config.defaultPostTime) || '19:30';
                              const locked = !caps.edit || p.status==='posted';
                              const inp = {border:'1px solid #E1E8F2',borderRadius:8,padding:'6px 9px',font:"600 12px 'Public Sans'",color:'#1A2942',background:'#fff',outline:'none'};
                              return (
                                <div style={{display:'flex',alignItems:'center',gap:10,flexWrap:'wrap',marginTop:12}}>
                                  <span style={{font:"800 10px 'Public Sans'",letterSpacing:'.06em',textTransform:'uppercase',color:'#8A94A8'}}>Post date</span>
                                  <input type="date" value={ymd(postDate(w,p))} disabled={locked}
                                    onChange={e=>{ if (e.target.value) movePostToDate(campId, p.id, parseDate(e.target.value)); }} style={inp}/>
                                  <span style={{font:"800 10px 'Public Sans'",letterSpacing:'.06em',textTransform:'uppercase',color:'#8A94A8'}}>Time</span>
                                  <input type="time" value={p.postTime||defTime} disabled={locked}
                                    onChange={e=>actions.updatePost(p.id,{postTime:e.target.value})} style={inp}/>
                                  <span style={{font:"700 11px 'Public Sans'",color:'#5C6880'}} title={(camp&&camp.config.timeZone)||CCIntl.timezone()}>{_tzAbbr(camp&&camp.config.timeZone)}</span>
                                  {(()=>{ const tz=(camp&&camp.config.timeZone)||CCIntl.timezone(), wf=CCIntl.workingFrom(tz); if(!wf) return null; const b=CCIntl.alsoTime(ymd(postDate(w,p)), p.postTime||defTime, tz); return b?<span style={{font:"700 11px 'Public Sans'",color:'#1E6E8C'}} title={CCIntl.t('working.field',{club:CCIntl.zoneName(tz),zone:CCIntl.zoneName(wf)})}>({b})</span>:null; })()}
                                  {p.postTime && !locked
                                    ? <button className="hov-filter" onClick={()=>actions.updatePost(p.id,{postTime:''})} style={{background:'none',border:'none',color:'var(--b-primary)',font:"700 11px 'Public Sans'",cursor:'pointer',padding:0}}>Use default ({defTime})</button>
                                    : <span style={{font:"500 11px 'Public Sans'",color:'#9AA6BC'}}>{p.postTime?'':'Campaign default'}</span>}
                                </div>
                              );
                            })()}
                          </div>
                          <div style={{display:'flex',flexDirection:'column',gap:14}}>
                            <div>
                              <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:6}}>
                                <span style={{font:"800 10px 'Public Sans'",letterSpacing:'.06em',textTransform:'uppercase',color:'#8A94A8'}}>Media Brief</span>
                                <div style={{display:'flex',gap:4}}>
                                  {caps.generate && <button className="hov-filter" onClick={()=>generateMediaBrief(p.id)} disabled={!!p.generatingBrief} style={{display:'inline-flex',alignItems:'center',gap:3,background:'#F0F4FA',color:'var(--b-primary)',border:'1px solid #D5DEF0',borderRadius:7,padding:'3px 8px',font:"800 10.5px 'Public Sans'",cursor:'pointer'}} title="Regenerate brief from caption">
                                    {p.generatingBrief?<SpinIcon sz={10}/>:<RefreshIcon sz={10}/>}<span>{p.generatingBrief?'…':'Regenerate'}</span>
                                  </button>}
                                  <button className="hov-filter" onClick={()=>{navigator.clipboard.writeText(p.mediaBrief||'');flash('Media brief copied');}} style={{display:'inline-flex',alignItems:'center',gap:3,background:'#F0F4FA',color:'#6B7790',border:'1px solid #D5DEF0',borderRadius:7,padding:'3px 8px',font:"800 10.5px 'Public Sans'",cursor:'pointer'}} title="Copy media brief">
                                    <CopyIcon sz={10}/><span>Copy</span>
                                  </button>
                                </div>
                              </div>
                              <BufferedTextarea value={p.mediaBrief} onSave={v=>actions.updatePost(p.id,{mediaBrief:v})} readOnly={!caps.edit} placeholder="Describe the photo / graphic to source…" rows="3" style={{width:'100%',border:'1px solid #E1E8F2',borderRadius:10,padding:'9px 11px',font:"500 12px/1.5 'Public Sans'",color:'#26324A',background:'#fff',outline:'none'}}/>
                            </div>
                            <div>
                              <div style={{font:"800 10px 'Public Sans'",letterSpacing:'.06em',textTransform:'uppercase',color:'#8A94A8',marginBottom:6}}>Image Style</div>
                              <ImageStylePicker value={p.imageStyle||'none'} onChange={s=>actions.updatePost(p.id,{imageStyle:s})} readOnly={!caps.edit}/>
                            </div>
                            <div>
                              <div style={{display:'flex',alignItems:'center',gap:6,marginBottom:8}}>
                                <span style={{font:"800 10px 'Public Sans'",letterSpacing:'.06em',textTransform:'uppercase',color:'#8A94A8'}}>Media</span>
                                <span style={{font:"500 10px 'Public Sans'",color:'#B0B8C9'}}>optional</span>
                              </div>
                              {p.generatedImageUrl && (
                                <div style={{position:'relative',marginBottom:8}}>
                                  <img src={p.generatedImageUrl} style={{width:'100%',aspectRatio:'1200/630',objectFit:'cover',borderRadius:8,border:'1px solid #E1E8F2',display:'block'}}/>
                                  {caps.edit && <button onClick={()=>actions.updatePost(p.id,{generatedImageUrl:'',mediaFileLink:''})} style={{position:'absolute',top:5,right:5,background:'rgba(0,0,0,.45)',border:'none',borderRadius:4,color:'#fff',cursor:'pointer',padding:'2px 5px',display:'flex',alignItems:'center',lineHeight:1}} title="Remove image"><XIcon sz={11}/></button>}
                                </div>
                              )}
                              <div style={{display:'flex',gap:6}}>
                                <button className="hov-blue" onClick={()=>generateImage(p.id)} disabled={!caps.generate||!!p.generatingImage} style={{flex:1,display:'inline-flex',alignItems:'center',justifyContent:'center',gap:5,background:'var(--b-primary)',color:'#fff',border:'none',borderRadius:8,padding:'7px 8px',font:"800 11px 'Public Sans'",cursor:'pointer',opacity:caps.generate?1:0.4}}>
                                  {p.generatingImage?<><SpinIcon light sz={11}/><span>Generating…</span></>:<><StarIcon sz={11}/><span>{p.generatedImageUrl?'Regenerate':'Generate image'}</span></>}
                                </button>
                                <label style={{flex:'0 0 auto',display:'inline-flex',alignItems:'center',justifyContent:'center',gap:5,background:'#F0F4FA',color:'var(--b-primary)',border:'1px solid #D5DEF0',borderRadius:8,padding:'7px 8px',font:"800 11px 'Public Sans'",cursor:caps.edit?'pointer':'default',opacity:caps.edit?1:0.4}}>
                                  {p.uploadingImage?<><SpinIcon sz={11}/><span>Uploading…</span></>:<><UploadIcon sz={11}/><span>Upload</span></>}
                                  <input type="file" accept="image/*" style={{display:'none'}} disabled={!caps.edit||!!p.uploadingImage} onChange={e=>handleImageUpload(p.id,e.target.files[0])}/>
                                </label>
                              </div>
                            </div>
                            <div>
                              <div style={{font:"800 10px 'Public Sans'",letterSpacing:'.06em',textTransform:'uppercase',color:'#8A94A8',marginBottom:6}}>Media File</div>
                              <div style={{display:'flex',gap:6,alignItems:'center'}}>
                                <input value={p.mediaFileLink||''} onChange={e=>actions.updatePost(p.id,{mediaFileLink:e.target.value})} readOnly={!caps.edit} placeholder="Drive / Canva URL or auto-filled from generated image" style={{flex:1,border:'1px solid #E1E8F2',borderRadius:9,padding:'8px 10px',font:"500 12px 'Public Sans'",color:'var(--b-primary)',background:'#fff',outline:'none'}}/>
                                {p.mediaFileLink && (
                                  <a href={p.mediaFileLink} target="_blank" rel="noreferrer" title="Open file" style={{flex:'none',width:34,height:34,display:'grid',placeItems:'center',border:'1px solid #D5DEF0',borderRadius:9,background:'#F0F4FA',color:'var(--b-primary)',textDecoration:'none'}}>
                                    <LinkIcon sz={14}/>
                                  </a>
                                )}
                              </div>
                            </div>
                            <div>
                              <div style={{font:"800 10px 'Public Sans'",letterSpacing:'.06em',textTransform:'uppercase',color:'#8A94A8',marginBottom:6}}>Reviewer Notes</div>
                              <BufferedTextarea value={p.reviewerNotes} onSave={v=>actions.updatePost(p.id,{reviewerNotes:v})} readOnly={!caps.edit} placeholder="Notes for the writer / next reviewer…" rows="3" style={{width:'100%',border:'1px solid #F1D9A8',borderRadius:10,padding:'9px 11px',font:"500 12px/1.5 'Public Sans'",color:'#7A5A14',background:'#FFFBF1',outline:'none'}}/>
                            </div>
                            <div>
                              <SignOffStrip post={p} members={state.members} currentUserId={state.currentUserId} caps={caps} onSetSignOff={setSignOff}/>
                            </div>
                          </div>
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        );
      })}
      {weeks.length===0 && <div style={{textAlign:'center',padding:'60px 20px',color:'#9AA6BC',font:"600 14px 'Public Sans'"}}>No posts match these filters.</div>}
    </div>
  );
}

/* ── Ready to Post tab ────────────────────────────────────────────────────── */
function ReadyToPostTab({state, actions, caps, weekNo, postDate, pillarById, copyCaption, copiedId, markPosted, sendBackId, setSendBackId, noteDrafts, setNoteDrafts, confirmSendBack, pushConfirmId, setPushConfirmId, onPublish, pushingId, setSignOff, isAdmin, declinePendingAction, approveConfirmId, setApproveConfirmId, onApproveForAutoPublish, approvingId, onRevokeAutoPublishApproval}) {
  const s = state;
  const ready = s.posts.filter(p=>p.status==='ready').map(p=>{
    const w = s.weeks.find(x=>x.id===p.weekId);
    return {p,w,t:w?postDate(w,p).getTime():0};
  }).filter(x=>x.w).sort((a,b)=>a.t-b.t);

  if (!ready.length) return (
    <div>
      <div style={{marginBottom:18}}>
        <h1 style={{margin:0,font:"800 23px/1.2 'Public Sans'",color:'var(--b-primary-deep)',letterSpacing:'-.01em'}}>Ready to Post</h1>
        <p style={{margin:'5px 0 0',font:"500 13px 'Public Sans'",color:'#6B7790'}}>Approved posts, sorted by suggested date.</p>
      </div>
      <div style={{textAlign:'center',padding:'70px 20px',background:'#fff',border:'1px dashed #D5DEEC',borderRadius:16}}>
        <div style={{font:"800 16px 'Public Sans'",color:'var(--b-primary-deep)',marginBottom:6}}>Nothing ready just yet</div>
        <div style={{font:"500 13px 'Public Sans'",color:'#6B7790'}}>Move a post to <b style={{color:'#15803D'}}>Ready to Post</b> in the Post Brief tab and it will appear here.</div>
      </div>
    </div>
  );

  return (
    <div>
      <div style={{marginBottom:18}}>
        <h1 style={{margin:0,font:"800 23px/1.2 'Public Sans'",color:'var(--b-primary-deep)',letterSpacing:'-.01em'}}>Ready to Post</h1>
        <p style={{margin:'5px 0 0',font:"500 13px 'Public Sans'",color:'#6B7790'}}>Approved posts, sorted by due date. Copy the caption, grab the media, then publish when it's due.</p>
      </div>
      <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fill,minmax(348px,1fr))',gap:16}}>
        {ready.map(({p,w})=>{
          const pil          = pillarById(w.pillarId);
          const sending      = sendBackId===p.id;
          const copied       = copiedId===p.id;
          const scheduled    = postDate(w, p);
          const daysUntil    = Math.round((scheduled.getTime() - Date.now()) / (1000 * 60 * 60 * 24));
          const isPushConfirm = pushConfirmId === p.id;
          const isApproveConfirm = approveConfirmId === p.id;
          const plats        = postPlatforms(p, s.config);
          const hasIg        = !!s.config.instagramAccountId;
          const anySelected  = plats.facebook || plats.instagram;
          const res          = p.publishResults;
          const dueBadge = daysUntil < 0
            ? {label:`Overdue ${Math.abs(daysUntil)}d`, color:'#B91C1C', bg:'#FEE2E2'}
            : daysUntil === 0
            ? {label:'Due today', color:'#B45309', bg:'#FCEEDA'}
            : {label:`In ${daysUntil}d`, color:'#5C6880', bg:'#EDF1F7'};
          return (
            <article key={p.id} style={{background:'#fff',border:'1px solid #E4EAF3',borderRadius:16,overflow:'hidden',boxShadow:'0 2px 10px rgba(16,42,90,.06)',display:'flex',flexDirection:'column'}}>
              <div style={{padding:'14px 16px',borderBottom:'1px solid var(--b-bg)',display:'flex',alignItems:'center',justifyContent:'space-between',gap:10}}>
                <div>
                  <div style={{font:"800 12.5px 'Public Sans'",color:'var(--b-primary-deep)'}}>{fmt(postDate(w,p))} &nbsp;·&nbsp; Week {weekNo(w)}, Post {p.postNo}</div>
                  {w._eventName && <div style={{font:"600 11px 'Public Sans'",color:'var(--b-primary)',marginTop:2}}>{w._eventName}</div>}
                </div>
                <div style={{display:'flex',gap:6,flexWrap:'wrap',justifyContent:'flex-end'}}>
                  <span style={{padding:'3px 9px',borderRadius:999,font:"800 11px 'Public Sans'",color:dueBadge.color,background:dueBadge.bg,whiteSpace:'nowrap'}}>{dueBadge.label}</span>
                  <span style={{padding:'3px 9px',borderRadius:999,font:"800 11px 'Public Sans'",color:pil.color,background:pil.bg,whiteSpace:'nowrap'}}>{pil.label}</span>
                </div>
              </div>
              <div style={{padding:'14px 16px',display:'flex',flexDirection:'column',gap:9}}>
                <div style={{display:'flex',alignItems:'center',justifyContent:'space-between'}}>
                  <span style={{font:"800 10px 'Public Sans'",letterSpacing:'.06em',textTransform:'uppercase',color:'#8A94A8'}}>Caption</span>
                  <button className="hov-outline" onClick={()=>copyCaption(p.id,p.draftCaption)} style={{display:'inline-flex',alignItems:'center',gap:6,border:'1px solid #D9E1EE',background:'#F7F9FC',borderRadius:8,padding:'5px 10px',font:"800 11.5px 'Public Sans'",color:'var(--b-primary)',cursor:'pointer'}}>
                    {copied ? <CheckIcon/> : <CopyIcon/>}
                    <span>{copied?'Copied':'Copy'}</span>
                  </button>
                </div>
                <div className="caption-body" style={{font:"500 13px/1.55 'Public Sans'",color:'#26324A'}}>{p.draftCaption}</div>
              </div>
              <div style={{padding:'12px 16px',borderTop:'1px solid var(--b-bg)',background:'#FAFBFE'}}>
                <div style={{font:"800 10px 'Public Sans'",letterSpacing:'.06em',textTransform:'uppercase',color:'#8A94A8',marginBottom:5}}>Media</div>
                <div style={{font:"500 12.5px/1.5 'Public Sans'",color:'#5C6880'}}>{p.mediaBrief||'No media brief.'}</div>
                {p.mediaFileLink && (
                  <a href={p.mediaFileLink} target="_blank" rel="noreferrer" style={{display:'inline-flex',alignItems:'center',gap:6,marginTop:8,font:"700 12px 'Public Sans'",color:'var(--b-primary)',textDecoration:'none',wordBreak:'break-all'}}>
                    <LinkIcon/><span>{p.mediaFileLink}</span>
                  </a>
                )}
              </div>
              <div style={{padding:'12px 16px',borderTop:'1px solid var(--b-bg)',display:'flex',alignItems:'center',gap:14,flexWrap:'wrap'}}>
                <span style={{font:"800 10px 'Public Sans'",letterSpacing:'.06em',textTransform:'uppercase',color:'#8A94A8'}}>Publish to</span>
                <label style={{display:'flex',alignItems:'center',gap:5,cursor:caps.edit?'pointer':'default',opacity:caps.edit?1:0.5}}>
                  <input type="checkbox" checked={plats.facebook} disabled={!caps.edit}
                    onChange={()=>actions.updatePost(p.id,{platforms:{...plats,facebook:!plats.facebook}})}/>
                  <FacebookIcon sz={13}/><span style={{font:"700 12px 'Public Sans'"}}>Facebook</span>
                </label>
                {hasIg && (
                  <label style={{display:'flex',alignItems:'center',gap:5,cursor:caps.edit?'pointer':'default',opacity:caps.edit?1:0.5}}>
                    <input type="checkbox" checked={plats.instagram} disabled={!caps.edit}
                      onChange={()=>actions.updatePost(p.id,{platforms:{...plats,instagram:!plats.instagram}})}/>
                    <InstagramIcon sz={13}/><span style={{font:"700 12px 'Public Sans'"}}>Instagram</span>
                  </label>
                )}
                <label style={{display:'flex',alignItems:'center',gap:5,opacity:0.35}} title="LinkedIn support is coming soon">
                  <input type="checkbox" disabled/>
                  <span style={{font:"700 12px 'Public Sans'"}}>LinkedIn</span>
                </label>
              </div>
              {anySelected && (
                <div style={{padding:'12px 16px',borderTop:'1px solid var(--b-bg)'}}>
                  <div style={{font:"800 10px 'Public Sans'",letterSpacing:'.06em',textTransform:'uppercase',color:'#8A94A8',marginBottom:7}}>Status</div>
                  {p.autoPublishApprovedAt ? (
                    <div style={{display:'flex',alignItems:'center',gap:8,flexWrap:'wrap'}}>
                      <span style={{display:'inline-flex',alignItems:'center',gap:6,padding:'7px 11px',borderRadius:8,background:'#E3F5E9',color:'#15803D',font:"800 11.5px 'Public Sans'"}}>
                        <CheckIcon sz={12}/>Done — approved, will auto-publish on {fmtShort(scheduled)}
                      </span>
                      {isAdmin && (
                        <button onClick={()=>onRevokeAutoPublishApproval(p.id)} style={{border:'none',background:'none',color:'#C0473F',font:"800 11.5px 'Public Sans'",cursor:'pointer'}}>
                          Revoke approval
                        </button>
                      )}
                    </div>
                  ) : (
                    <div style={{display:'flex',alignItems:'center',gap:8,flexWrap:'wrap'}}>
                      <span style={{display:'inline-flex',alignItems:'center',gap:6,padding:'7px 11px',borderRadius:8,background:'#FCEEDA',color:'#B45309',font:"800 11.5px 'Public Sans'"}}>
                        Needed — approve for auto-publish, or use Instant Publish below
                      </span>
                      <button className="hov-outline" onClick={()=>{ setApproveConfirmId(isApproveConfirm?null:p.id); setPushConfirmId(null); }} disabled={!caps.approve} style={{display:'inline-flex',alignItems:'center',gap:6,border:'1px solid #D9E1EE',background:'#F7F9FC',borderRadius:8,padding:'7px 11px',font:"800 11.5px 'Public Sans'",color:'var(--b-primary)',cursor:'pointer',opacity:caps.approve?1:0.4}}>
                        <ShieldIcon sz={13}/>Approve for Auto-Publish
                      </button>
                    </div>
                  )}
                </div>
              )}
              {res && (res.facebook || res.instagram) && (
                <div style={{padding:'10px 16px',borderTop:'1px solid var(--b-bg)',display:'flex',flexDirection:'column',gap:4}}>
                  {['facebook','instagram'].map(k => res[k] && res[k].selected && (
                    <div key={k} style={{font:"700 11.5px 'Public Sans'",color:res[k].ok?'#15803D':'#B91C1C',display:'flex',alignItems:'center',gap:6}}>
                      {res[k].ok ? <CheckIcon sz={12}/> : <XIcon sz={11}/>}
                      <span style={{textTransform:'capitalize'}}>{k}</span>
                      <span style={{color:'#8A94A8',fontWeight:500}}>{res[k].ok ? 'published' : (res[k].error||'failed')}</span>
                    </div>
                  ))}
                </div>
              )}
              <div style={{padding:'12px 16px'}}>
                <SignOffStrip post={p} members={state.members} currentUserId={state.currentUserId} caps={caps} onSetSignOff={setSignOff}/>
              </div>
              {isPushConfirm && (
                <div style={{padding:'12px 16px',borderTop:'1px solid var(--b-bg)',background:'#F0FDF4'}}>
                  <div style={{font:"700 12.5px 'Public Sans'",color:'#166534',marginBottom:8}}>
                    Instant Publish right now to <b>{[plats.facebook&&'Facebook',plats.instagram&&'Instagram'].filter(Boolean).join(' and ')||'…'}</b>? This publishes immediately — it doesn't wait for the due date.
                  </div>
                  <div style={{display:'flex',gap:8}}>
                    <button onClick={()=>onPublish(p.id)} disabled={pushingId===p.id||!anySelected} style={{flex:1,display:'inline-flex',alignItems:'center',justifyContent:'center',gap:6,background:'#1877F2',color:'#fff',border:'none',borderRadius:8,padding:8,font:"800 12px 'Public Sans'",cursor:'pointer',opacity:(pushingId===p.id||!anySelected)?0.6:1}}>
                      {pushingId===p.id ? <><SpinIcon light/>Publishing…</> : <>Confirm & Instant Publish</>}
                    </button>
                    <button onClick={()=>setPushConfirmId(null)} style={{background:'#fff',color:'#6B7790',border:'1px solid #E1E8F2',borderRadius:8,padding:'8px 14px',font:"800 12px 'Public Sans'",cursor:'pointer'}}>Cancel</button>
                  </div>
                </div>
              )}
              {isApproveConfirm && (
                <div style={{padding:'12px 16px',borderTop:'1px solid var(--b-bg)',background:'#F0FDF4'}}>
                  <div style={{font:"700 12.5px 'Public Sans'",color:'#166534',marginBottom:8}}>
                    Approve for auto-publish on <b>{fmt(scheduled)}</b>? Our cron will publish it automatically once it's due — no one needs to be present.
                  </div>
                  <div style={{display:'flex',gap:8}}>
                    <button onClick={()=>onApproveForAutoPublish(p.id)} disabled={approvingId===p.id} style={{flex:1,display:'inline-flex',alignItems:'center',justifyContent:'center',gap:6,background:'#15803D',color:'#fff',border:'none',borderRadius:8,padding:8,font:"800 12px 'Public Sans'",cursor:'pointer',opacity:approvingId===p.id?0.6:1}}>
                      {approvingId===p.id ? <><SpinIcon light/>Approving…</> : <>Confirm & Approve</>}
                    </button>
                    <button onClick={()=>setApproveConfirmId(null)} style={{background:'#fff',color:'#6B7790',border:'1px solid #E1E8F2',borderRadius:8,padding:'8px 14px',font:"800 12px 'Public Sans'",cursor:'pointer'}}>Cancel</button>
                  </div>
                </div>
              )}
              {sending && (
                <div style={{padding:'12px 16px',borderTop:'1px solid var(--b-bg)',background:'#FFFBF1'}}>
                  <div style={{font:"800 10px 'Public Sans'",letterSpacing:'.06em',textTransform:'uppercase',color:'#B45309',marginBottom:6}}>Note for the writer</div>
                  <textarea value={noteDrafts[p.id]||''} onChange={e=>setNoteDrafts(d=>({...d,[p.id]:e.target.value}))} placeholder="What needs changing?" rows="2" style={{width:'100%',border:'1px solid #F1D9A8',borderRadius:9,padding:'8px 10px',font:"500 12.5px/1.45 'Public Sans'",color:'#7A5A14',background:'#fff',outline:'none'}}/>
                  <div style={{display:'flex',gap:8,marginTop:8}}>
                    <button className="hov-filter" onClick={()=>confirmSendBack(p.id)} style={{flex:1,background:'#B45309',color:'#fff',border:'none',borderRadius:8,padding:8,font:"800 12px 'Public Sans'",cursor:'pointer'}}>Send back</button>
                    <button className="hov-outline" onClick={()=>setSendBackId(null)} style={{background:'#fff',color:'#6B7790',border:'1px solid #E1E8F2',borderRadius:8,padding:'8px 14px',font:"800 12px 'Public Sans'",cursor:'pointer'}}>Cancel</button>
                  </div>
                </div>
              )}
              {p.pendingAction && (
                <div style={{padding:'10px 16px',borderTop:'1px solid #F1D9A8',background:'#FFFBF1',display:'flex',alignItems:'center',justifyContent:'space-between',gap:8,flexWrap:'wrap'}}>
                  <span style={{font:"600 12px 'Public Sans'",color:'#7A5A14'}}>⏳ <b>{p.pendingAction.byName}</b> requested {PENDING_ACTION_LABELS[p.pendingAction.type]||'this action'} — {isAdmin?'confirm below':"awaiting your Admin's confirmation"}</span>
                  {isAdmin && <button onClick={()=>declinePendingAction(p.id)} style={{border:'none',background:'none',color:'#C0473F',font:"800 11.5px 'Public Sans'",cursor:'pointer'}}>Decline</button>}
                </div>
              )}
              <div style={{padding:'12px 16px',borderTop:'1px solid var(--b-bg)',display:'flex',gap:8,marginTop:'auto',flexWrap:'wrap'}}>
                <button onClick={()=>{ setPushConfirmId(isPushConfirm?null:p.id); setSendBackId(null); }} disabled={!caps.approve} title="Publishes immediately, right now — bypasses the auto-publish schedule" style={{flex:1,display:'inline-flex',alignItems:'center',justifyContent:'center',gap:6,background:'#1877F2',color:'#fff',border:'none',borderRadius:9,padding:9,font:"800 12.5px 'Public Sans'",cursor:'pointer',opacity:caps.approve?1:0.4}}>
                  {plats.facebook && <FacebookIcon sz={14}/>}{plats.instagram && <InstagramIcon sz={14}/>}
                  {p.pendingAction && isAdmin ? 'Confirm & Instant Publish' : 'Instant Publish'}
                </button>
                <button className="hov-green" onClick={()=>markPosted(p.id)} disabled={!caps.approve} style={{display:'inline-flex',alignItems:'center',gap:6,background:'#fff',color:'#15803D',border:'1px solid #BBE8C8',borderRadius:9,padding:'9px 12px',font:"800 12.5px 'Public Sans'",cursor:'pointer',opacity:caps.approve?1:0.4}}>
                  <CheckIcon sz={14}/>Posted
                </button>
                <button className="hov-amber" onClick={()=>{ setSendBackId(sending?null:p.id); setPushConfirmId(null); }} disabled={!caps.edit} style={{background:'#fff',color:'#B45309',border:'1px solid #F1D9A8',borderRadius:9,padding:'9px 14px',font:"800 12.5px 'Public Sans'",cursor:'pointer',opacity:caps.edit?1:0.4}}>Send Back</button>
              </div>
            </article>
          );
        })}
      </div>
    </div>
  );
}

/* ── Post History tab ─────────────────────────────────────────────────────── */
function PostHistoryTab({state, caps, weekNo, postDate, pillarById, copyCaption, copiedId, sendBackId, setSendBackId, noteDrafts, setNoteDrafts, confirmSendBack}) {
  const s = state;
  const posted = s.posts.filter(p=>p.status==='posted').map(p=>{
    const w = s.weeks.find(x=>x.id===p.weekId);
    return {p, w, t: w ? postDate(w,p).getTime() : 0};
  }).filter(x=>x.w).sort((a,b)=>b.t-a.t);

  if (!posted.length) return (
    <div>
      <h1 style={{margin:'0 0 6px',font:"800 23px/1.2 'Public Sans'",color:'var(--b-primary-deep)',letterSpacing:'-.01em'}}>Post History</h1>
      <p style={{margin:'0 0 18px',font:"500 13px 'Public Sans'",color:'#6B7790'}}>Posts that have been sent to Facebook.</p>
      <div style={{textAlign:'center',padding:'70px 20px',background:'#fff',border:'1px dashed #D5DEEC',borderRadius:16}}>
        <div style={{font:"800 16px 'Public Sans'",color:'var(--b-primary-deep)',marginBottom:6}}>No posts yet</div>
        <div style={{font:"500 13px 'Public Sans'",color:'#6B7790'}}>Posts marked as Posted will appear here.</div>
      </div>
    </div>
  );

  return (
    <div>
      <div style={{marginBottom:18}}>
        <h1 style={{margin:0,font:"800 23px/1.2 'Public Sans'",color:'var(--b-primary-deep)',letterSpacing:'-.01em'}}>Post History</h1>
        <p style={{margin:'5px 0 0',font:"500 13px 'Public Sans'",color:'#6B7790'}}>{posted.length} post{posted.length!==1?'s':''} sent to Facebook — most recent first. Use Send Back to recall a post for editing; delete it from Facebook manually first.</p>
      </div>
      <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fill,minmax(348px,1fr))',gap:16}}>
        {posted.map(({p,w})=>{
          const pil     = pillarById(w.pillarId);
          const sending = sendBackId===p.id;
          const copied  = copiedId===p.id;
          const via     = POSTED_VIA_LABELS[p.postedVia] || POSTED_VIA_LABELS.manual;
          const justPosted = p.postedAt && (Date.now() - new Date(p.postedAt).getTime()) < 24*60*60*1000;
          const res     = p.publishResults;
          return (
            <article key={p.id} style={{background:'#fff',border:justPosted?'1px solid #BBE8C8':'1px solid #E4EAF3',boxShadow:justPosted?'0 0 0 3px rgba(21,128,61,.12), 0 2px 10px rgba(16,42,90,.06)':'0 2px 10px rgba(16,42,90,.06)',borderRadius:16,overflow:'hidden',display:'flex',flexDirection:'column'}}>
              <div style={{padding:'14px 16px',borderBottom:'1px solid var(--b-bg)',display:'flex',alignItems:'center',justifyContent:'space-between',gap:10}}>
                <div>
                  <div style={{font:"800 12.5px 'Public Sans'",color:'var(--b-primary-deep)'}}>{fmt(postDate(w,p))} &nbsp;·&nbsp; Week {weekNo(w)}, Post {p.postNo}</div>
                  {w._eventName && <div style={{font:"600 11px 'Public Sans'",color:'var(--b-primary)',marginTop:2}}>{w._eventName}</div>}
                </div>
                <div style={{display:'flex',gap:6,flexWrap:'wrap',justifyContent:'flex-end'}}>
                  {justPosted && <span style={{padding:'3px 9px',borderRadius:999,font:"800 11px 'Public Sans'",color:'#15803D',background:'#E3F5E9',whiteSpace:'nowrap'}}>Just posted</span>}
                  <span style={{padding:'3px 9px',borderRadius:999,font:"800 11px 'Public Sans'",color:via.color,background:via.bg,whiteSpace:'nowrap'}}>{via.label}</span>
                  <span style={{padding:'3px 9px',borderRadius:999,font:"800 11px 'Public Sans'",color:pil.color,background:pil.bg,whiteSpace:'nowrap'}}>{pil.label}</span>
                </div>
              </div>
              {p.generatedImageUrl && (
                <img src={p.generatedImageUrl} style={{width:'100%',aspectRatio:'1200/630',objectFit:'cover',display:'block'}}/>
              )}
              {res && (res.facebook || res.instagram) && (
                <div style={{padding:'10px 16px',borderBottom:'1px solid var(--b-bg)',display:'flex',flexDirection:'column',gap:4,background:'#FAFBFE'}}>
                  {['facebook','instagram'].map(k => res[k] && res[k].selected && (
                    <div key={k} style={{font:"700 11.5px 'Public Sans'",color:res[k].ok?'#15803D':'#B91C1C',display:'flex',alignItems:'center',gap:6}}>
                      {res[k].ok ? <CheckIcon sz={12}/> : <XIcon sz={11}/>}
                      <span style={{textTransform:'capitalize'}}>{k}</span>
                      <span style={{color:'#8A94A8',fontWeight:500}}>{res[k].ok ? 'published' : (res[k].error||'failed')}</span>
                    </div>
                  ))}
                </div>
              )}
              <div style={{padding:'14px 16px',flex:1}}>
                <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:8}}>
                  <span style={{font:"800 10px 'Public Sans'",letterSpacing:'.06em',textTransform:'uppercase',color:'#8A94A8'}}>Caption</span>
                  <button className="hov-outline" onClick={()=>copyCaption(p.id,p.draftCaption)} style={{display:'inline-flex',alignItems:'center',gap:6,border:'1px solid #D9E1EE',background:'#F7F9FC',borderRadius:8,padding:'5px 10px',font:"800 11.5px 'Public Sans'",color:'var(--b-primary)',cursor:'pointer'}}>
                    {copied?<CheckIcon/>:<CopyIcon/>}<span>{copied?'Copied':'Copy'}</span>
                  </button>
                </div>
                <div className="caption-body" style={{font:"500 13px/1.55 'Public Sans'",color:'#26324A'}}>{p.draftCaption}</div>
                {p.mediaBrief && (
                  <div style={{marginTop:12,padding:'10px 12px',background:'#F5F8FC',borderRadius:9,border:'1px solid #E5EAF2'}}>
                    <div style={{font:"800 10px 'Public Sans'",letterSpacing:'.06em',textTransform:'uppercase',color:'#8A94A8',marginBottom:4}}>Media Brief</div>
                    <div style={{font:"500 12px/1.5 'Public Sans'",color:'#5C6880'}}>{p.mediaBrief}</div>
                  </div>
                )}
              </div>
              {sending && (
                <div style={{padding:'12px 16px',borderTop:'1px solid var(--b-bg)',background:'#FFFBF1'}}>
                  <div style={{padding:'8px 10px',background:'#FEF3C7',borderRadius:7,border:'1px solid #F1D9A8',font:"600 12px/1.4 'Public Sans'",color:'#92400E',marginBottom:8}}>
                    Remember to delete this post from Facebook before re-posting.
                  </div>
                  <div style={{font:"800 10px 'Public Sans'",letterSpacing:'.06em',textTransform:'uppercase',color:'#B45309',marginBottom:6}}>Note for the writer</div>
                  <textarea value={noteDrafts[p.id]||''} onChange={e=>setNoteDrafts(d=>({...d,[p.id]:e.target.value}))} placeholder="What needs changing?" rows={2} style={{width:'100%',border:'1px solid #F1D9A8',borderRadius:9,padding:'8px 10px',font:"500 12.5px/1.45 'Public Sans'",color:'#7A5A14',background:'#fff',outline:'none',boxSizing:'border-box'}}/>
                  <div style={{display:'flex',gap:8,marginTop:8}}>
                    <button className="hov-filter" onClick={()=>confirmSendBack(p.id)} style={{flex:1,background:'#B45309',color:'#fff',border:'none',borderRadius:8,padding:8,font:"800 12px 'Public Sans'",cursor:'pointer'}}>Send back</button>
                    <button className="hov-outline" onClick={()=>setSendBackId(null)} style={{background:'#fff',color:'#6B7790',border:'1px solid #E1E8F2',borderRadius:8,padding:'8px 14px',font:"800 12px 'Public Sans'",cursor:'pointer'}}>Cancel</button>
                  </div>
                </div>
              )}
              <div style={{padding:'12px 16px',borderTop:'1px solid var(--b-bg)',display:'flex',justifyContent:'flex-end',marginTop:'auto'}}>
                <button className="hov-amber" onClick={()=>setSendBackId(sending?null:p.id)} disabled={!caps.edit} style={{background:'#fff',color:'#B45309',border:'1px solid #F1D9A8',borderRadius:9,padding:'9px 14px',font:"800 12.5px 'Public Sans'",cursor:'pointer',opacity:caps.edit?1:0.4}}>Send Back</button>
              </div>
            </article>
          );
        })}
      </div>
    </div>
  );
}

/* ── Calendar View ────────────────────────────────────────────────────────── */
function CalendarView({campaigns, showAllCampaigns, caps, movePostToDate, pillarById, onSetup}) {
  const [dragDay, setDragDay] = React.useState(null);
  const dragRef = React.useRef(null);

  if (!campaigns || !campaigns.length) return null;
  const withWeeks = campaigns.filter(c => c.weeks && c.weeks.length > 0);
  const active = withWeeks.filter(c => /^\d{4}-\d{2}-\d{2}$/.test(c.config.campaignStart || ''));
  const undated = withWeeks.filter(c => !active.includes(c));
  if (!active.length && undated.length) return (
    <div style={{textAlign:'center',padding:'60px 20px',color:'#5A6473',font:"600 14px/1.6 'Public Sans'"}}>
      <div style={{font:"800 17px 'Public Sans'",color:'var(--b-primary-deep)',marginBottom:6}}>The calendar needs a start date</div>
      {undated.reduce((n,c)=>n+c.posts.length,0)} posts are planned but have no dates yet, because {showAllCampaigns?'these campaigns have':'this campaign has'} no start date.<br/>
      {caps.setup && !showAllCampaigns
        ? <button onClick={onSetup} style={{marginTop:14,background:'var(--b-primary)',color:'#fff',border:'none',borderRadius:9,padding:'10px 20px',font:"800 13px 'Public Sans'",cursor:'pointer'}}>Open Setup and choose a start date</button>
        : 'Ask the campaign admin to choose one in Setup.'}
    </div>
  );
  if (!active.length) return (
    <div style={{textAlign:'center',padding:'70px 20px',color:'#9AA6BC',font:"600 14px 'Public Sans'"}}>No weeks configured yet. Set up a campaign first.</div>
  );

  /* Date range */
  const allStartMs = active.map(c => parseDate(c.config.campaignStart).getTime());
  const allEndMs   = active.map(c => addDays(parseDate(c.config.campaignStart), c.weeks.length * 7 - 1).getTime());
  const rawStart   = new Date(Math.min(...allStartMs));
  const rawEnd     = new Date(Math.max(...allEndMs));

  /* Align to Mon–Sun week boundaries */
  const startDow = (rawStart.getDay() + 6) % 7;
  const calStart = addDays(rawStart, -startDow);
  const endDow   = (rawEnd.getDay() + 6) % 7;
  const calEnd   = addDays(rawEnd, 6 - endDow);

  /* Build week rows */
  const calWeeks = [];
  let cur = new Date(calStart.getTime());
  while (cur.getTime() <= calEnd.getTime()) {
    calWeeks.push(Array.from({length:7}, (_,i) => addDays(cur, i)));
    cur = addDays(cur, 7);
  }

  /* Posts scheduled on a given day */
  const postsForDay = (dayDate) => {
    const result = [];
    for (const c of active) {
      const camStart = parseDate(c.config.campaignStart);
      for (const w of c.weeks) {
        const wStart = addDays(camStart, w.idx * 7);
        for (const p of c.posts.filter(x => x.weekId === w.id)) {
          if (addDays(wStart, p.dayOffset).toDateString() === dayDate.toDateString()) {
            result.push({post:p, week:w, campaign:c});
          }
        }
      }
    }
    return result;
  };

  const isInAnyRange = (dayDate) => {
    const t = dayDate.getTime();
    return active.some(c => {
      const s = parseDate(c.config.campaignStart).getTime();
      const e = addDays(parseDate(c.config.campaignStart), c.weeks.length * 7 - 1).getTime();
      return t >= s && t <= e;
    });
  };

  const prefDays = !showAllCampaigns && active[0] ? (active[0].config.preferredDays || []) : [];
  const today    = new Date().toDateString();

  return (
    <div>
      <div style={{marginBottom:18}}>
        <h1 style={{margin:0,font:"800 23px/1.2 'Public Sans'",color:'var(--b-primary-deep)',letterSpacing:'-.01em'}}>{showAllCampaigns?'Master calendar':'Calendar'}</h1>
        <p style={{margin:'5px 0 0',font:"500 13px 'Public Sans'",color:'#6B7790'}}>
          {showAllCampaigns ? 'Every planned post from every campaign, with its status' : active[0].config.eventName}
          {!showAllCampaigns && caps.edit ? ' · drag posts to reschedule' : ' · read-only view'}
          {!showAllCampaigns && prefDays.length > 0 && ' · preferred days highlighted in blue'}
        </p>
      </div>

      {/* Status key: every post card shows its current state */}
      <div style={{display:'flex',flexWrap:'wrap',alignItems:'center',gap:14,marginBottom:12}}>
        {['draft','needs','ready','posted'].map(k => (
          <span key={k} style={{display:'inline-flex',alignItems:'center',gap:6,font:"700 11.5px 'Public Sans'",color:SD.STATUS[k].color}}>
            <span style={{width:9,height:9,borderRadius:'50%',background:SD.STATUS[k].dot}}/>{SD.STATUS[k].label}
          </span>
        ))}
        {undated.length>0 && <span style={{font:"600 11.5px 'Public Sans'",color:'#B45309'}}>{undated.length} campaign{undated.length===1?'':'s'} without a start date not shown</span>}
      </div>

      {/* Column headers (Mon–Sun) */}
      <div style={{display:'grid',gridTemplateColumns:'repeat(7,1fr)',gap:1,marginBottom:2}}>
        {DAY_NAMES.map((day,i) => {
          const isPref = prefDays.includes(i);
          return (
            <div key={day} style={{padding:'8px 10px',font:"700 11px 'Public Sans'",color:isPref?'var(--b-primary)':'#8A94A8',background:isPref?'#EEF3FC':'#F5F8FC',textAlign:'center',textTransform:'uppercase',letterSpacing:'.06em',borderRadius:i===0?'8px 0 0 0':i===6?'0 8px 0 0':0}}>
              {day}
            </div>
          );
        })}
      </div>

      {/* Calendar grid */}
      <div style={{border:'1px solid #E4EAF3',borderRadius:'0 0 14px 14px',overflow:'hidden',background:'#E4EAF3',display:'flex',flexDirection:'column',gap:1}}>
        {calWeeks.map((weekDays, wi) => {
          const mon = weekDays[0];
          const showMonthHdr = wi === 0 || mon.getMonth() !== calWeeks[wi-1][0].getMonth();
          return (
            <React.Fragment key={mon.toISOString()}>
              {showMonthHdr && (
                <div style={{padding:'8px 14px 5px',font:"800 11.5px 'Public Sans'",color:'var(--b-primary)',textTransform:'uppercase',letterSpacing:'.08em',background:'#F0F5FF',borderBottom:'1px solid #DDE5F4'}}>
                  {MONTHS[mon.getMonth()]} {mon.getFullYear()}
                </div>
              )}
              <div style={{display:'grid',gridTemplateColumns:'repeat(7,1fr)',gap:1,background:'#E4EAF3'}}>
                {weekDays.map((day, di) => {
                  const dayStr    = day.toDateString();
                  const dayPosts  = postsForDay(day);
                  const inRange   = isInAnyRange(day);
                  const isDragOver = dragDay === dayStr;
                  const isToday   = dayStr === today;
                  const isPref    = prefDays.includes(di);
                  const canDrop   = !showAllCampaigns && caps.edit && inRange;

                  return (
                    <div
                      key={dayStr}
                      onDragOver={e => { if (canDrop) { e.preventDefault(); setDragDay(dayStr); } }}
                      onDragLeave={e => { if (!e.currentTarget.contains(e.relatedTarget)) setDragDay(null); }}
                      onDrop={e => {
                        e.preventDefault();
                        if (dragRef.current && inRange) {
                          movePostToDate(dragRef.current.campaignId, dragRef.current.postId, day);
                          dragRef.current = null;
                        }
                        setDragDay(null);
                      }}
                      style={{
                        minHeight: 90,
                        padding: '6px 7px',
                        background: isDragOver ? '#D6E4FC'
                          : isToday ? '#FFFBF1'
                          : isPref && inRange ? '#FAFCFF'
                          : !inRange ? '#F4F6FA'
                          : '#fff',
                        transition: 'background .1s',
                        outline: isDragOver ? '2px solid #4B87E8' : 'none',
                        outlineOffset: '-2px',
                      }}
                    >
                      <div style={{font:"700 11px 'Public Sans'",color:isToday?'#B45309':!inRange?'#CDD4DF':'#8A94A8',marginBottom:4,display:'flex',alignItems:'center',gap:4}}>
                        <span>{day.getDate()}</span>
                        {isToday && <span style={{font:"700 9px 'Public Sans'",color:'#B45309',background:'#FEF3C7',padding:'1px 5px',borderRadius:4}}>Today</span>}
                        {isPref && inRange && !isToday && <span style={{marginLeft:'auto',width:5,height:5,borderRadius:'50%',background:'#93B5E8'}}/>}
                      </div>
                      <div style={{display:'flex',flexDirection:'column',gap:3}}>
                        {dayPosts.map(({post:p, week:w, campaign:c}) => {
                          const st     = SD.STATUS[p.status==='queued'?'ready':p.status];
                          const pil    = pillarById(w.pillarId);
                          const canDrag = !showAllCampaigns && caps.edit;
                          return (
                            <div
                              key={p.id}
                              draggable={canDrag}
                              onDragStart={e => {
                                if (!canDrag) { e.preventDefault(); return; }
                                dragRef.current = {postId:p.id, campaignId:c.id};
                                e.dataTransfer.effectAllowed = 'move';
                              }}
                              onDragEnd={() => { dragRef.current = null; setDragDay(null); }}
                              title={p.draftCaption || 'Draft — no caption yet'}
                              style={{padding:'4px 7px',borderRadius:6,background:st.bg,borderLeft:`3px solid ${pil.color}`,cursor:canDrag?'grab':'default',userSelect:'none'}}
                            >
                              <div style={{display:'flex',alignItems:'center',gap:4,marginBottom:1}}>
                                <span style={{width:5,height:5,borderRadius:'50%',background:st.dot,flex:'none'}}/>
                                <span style={{font:"800 10px 'Public Sans'",color:pil.color,flex:1,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{pil.label}</span>
                              </div>
                              <div style={{font:"800 9.5px 'Public Sans'",color:st.color,textTransform:'uppercase',letterSpacing:'.04em',marginBottom:1}}>{st.label}</div>
                              {!p.draftCaption && <div style={{font:"500 10.5px 'Public Sans'",color:'#8A94A8',fontStyle:'italic'}}>No caption yet</div>}
                              {p.draftCaption && (
                                <div style={{font:"500 10.5px/1.35 'Public Sans'",color:'#3D4A5C',display:'-webkit-box',WebkitLineClamp:2,WebkitBoxOrient:'vertical',overflow:'hidden'}}>
                                  {p.draftCaption}
                                </div>
                              )}
                              {showAllCampaigns && (
                                <div style={{font:"700 9px 'Public Sans'",color:'#6B7790',marginTop:2,textTransform:'uppercase',letterSpacing:'.04em',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{c.config.eventName}</div>
                              )}
                            </div>
                          );
                        })}
                      </div>
                    </div>
                  );
                })}
              </div>
            </React.Fragment>
          );
        })}
      </div>

      {!showAllCampaigns && caps.edit && (
        <p style={{textAlign:'center',marginTop:10,font:"500 11.5px 'Public Sans'",color:'#9AA6BC'}}>
          Drag a post card to any day to reschedule it.
        </p>
      )}
    </div>
  );
}

/* ── Setup modal ─────────────────────────────────────────────────────────── */
/* ── Image Library modal ─────────────────────────────────────────────────── */
const _fmtBytes = b => b>=1048576 ? (b/1048576).toFixed(1)+' MB' : b>=1024 ? Math.round(b/1024)+' KB' : b+' B';
const _fmtDate  = ts => {
  const d = typeof ts === 'number' && ts > 0 ? new Date(ts) : (ts?.toDate ? ts.toDate() : (ts?.seconds ? new Date(ts.seconds*1000) : null));
  return d ? d.toLocaleDateString(CCIntl.locale(),{day:'numeric',month:'short',year:'numeric'}) : '—';
};

function ImageLibraryModal({clubId, campaigns, settings, canManage, onSaveSettings, onClose}) {
  const [images,   setImages]   = React.useState(null);
  const [deleting, setDeleting] = React.useState({});
  const [health,   setHealth]   = React.useState({});   // image id -> 'checking' | 'ok' | 'broken'
  const [showSettings, setShowSettings] = React.useState(false);
  const [notice,   setNotice]   = React.useState('');
  const [usage, setUsage] = React.useState({usedBytes:0, allowedBytes:INCLUDED_BYTES});
  const allowance = usage.allowedBytes || _allowanceBytes(settings);
  /* URLs a post still points at: these images can't be deleted from the library */
  const usedUrls = new Set();
  (campaigns||[]).forEach(c => (c.posts||[]).forEach(p => { if (p.generatedImageUrl) usedUrls.add(p.generatedImageUrl); if (p.mediaFileLink) usedUrls.add(p.mediaFileLink); }));
  const checkOne = async img => {
    setHealth(h=>({...h,[img.id]:'checking'}));
    const ok = await _checkImageUrl(img.url);
    setHealth(h=>({...h,[img.id]:ok?'ok':'broken'}));
  };
  const checkAll = () => (images||[]).forEach(checkOne);

  React.useEffect(() => {
    _api('GET', '/club/social/images')
      .then(r => { setUsage({usedBytes:r.usedBytes||0, allowedBytes:r.allowedBytes||INCLUDED_BYTES});
        setImages((r.images||[]).map(i => ({id:i.id, url:i.url, filename:i.name, sizeBytes:i.bytes, campaignId:i.campaignId, uploadedAt:i.createdAt, kind:i.kind}))); })
      .catch(e => { setNotice((e && e.message) || 'The library could not be loaded'); setImages([]); });
  }, [clubId]);

  const totalBytes = usage.usedBytes;
  const pct        = Math.min(100,(totalBytes/allowance)*100);
  const camName    = id => (campaigns||[]).find(c=>c.id===id)?.config?.eventName||'';

  const doDelete = async img => {
    if (usedUrls.has(img.url)) { setNotice('That image is still used by a post. Change the post\'s image first, then delete it here.'); return; }
    if (!window.confirm('Delete this image? This cannot be undone.')) return;
    setDeleting(d=>({...d,[img.id]:true}));
    try {
      await _deleteStoredImage(img);
      setImages(imgs => imgs.filter(i=>i.id!==img.id));
      setUsage(u => ({...u, usedBytes: Math.max(0, u.usedBytes - (img.sizeBytes||0))}));
      setNotice('');
    } catch(e) { setNotice((e && e.message) || 'The picture could not be deleted'); }
    setDeleting(d=>({...d,[img.id]:false}));
  };

  const doDownload = img => {
    const a = document.createElement('a');
    a.href = img.url; a.download = img.filename||'image.jpg'; a.target='_blank'; a.click();
  };

  const barColor = pct>90?'#EF4444':pct>70?'#F59E0B':'var(--b-primary)';

  return (
    <div className="modal-overlay" style={{zIndex:60}}>
      <div style={{width:'100%',maxWidth:840,background:'#fff',borderRadius:18,boxShadow:'0 24px 60px rgba(22,40,70,.35)',overflow:'hidden',maxHeight:'90vh',display:'flex',flexDirection:'column'}}>

        {/* Header */}
        <div style={{padding:'16px 22px',borderTop:'3px solid var(--b-primary)',borderBottom:'1px solid var(--b-bg)',display:'flex',alignItems:'center',justifyContent:'space-between',flex:'none'}}>
          <div>
            <div style={{font:"800 17px 'Public Sans'",color:'var(--b-primary-deep)'}}>Image Library</div>
            <div style={{font:"500 12px 'Public Sans'",color:'#6B7790',marginTop:2}}>All generated and uploaded images stored for this club.</div>
          </div>
          <button className="hov-outline" onClick={onClose} style={{width:34,height:34,display:'grid',placeItems:'center',border:'none',background:'#F1F4F9',borderRadius:9,cursor:'pointer',color:'#5A6473'}}><XIcon/></button>
        </div>

        {/* Storage bar + Drive status */}
        <div style={{padding:'12px 22px',borderBottom:'1px solid var(--b-bg)',display:'flex',gap:18,alignItems:'center',flex:'none',background:'#FAFBFE'}}>
          <div style={{flex:1}}>
            <div style={{display:'flex',justifyContent:'space-between',marginBottom:5}}>
              <span style={{font:"600 12px 'Public Sans'",color:'#5A6473'}}>Storage used</span>
              <span style={{font:"700 12px 'Public Sans'",color:barColor}}>{_fmtBytes(totalBytes)} / {_fmtBytes(allowance)}</span>
            </div>
            <div style={{height:7,borderRadius:4,background:'#E5EAF2',overflow:'hidden'}}>
              <div style={{height:'100%',width:`${pct}%`,borderRadius:4,background:barColor,transition:'width .3s'}}/>
            </div>
            <div style={{font:"500 11px 'Public Sans'",color:'#9AA6BC',marginTop:4}}>Nothing is deleted automatically. When storage is full, new uploads are refused until space is freed or extra storage is added.</div>
            {notice && <div style={{font:"700 11.5px 'Public Sans'",color:'#B91C1C',marginTop:6}}>{notice}</div>}
          </div>
          <div style={{borderLeft:'1px solid #E5EAF2',paddingLeft:18,flex:'none',display:'flex',flexDirection:'column',gap:7,alignItems:'stretch'}}>
            <button onClick={checkAll} disabled={!images||!images.length} style={{border:'1px solid #D5DEF0',background:'#fff',color:'var(--b-primary)',borderRadius:8,padding:'7px 12px',font:"700 12px 'Public Sans'",cursor:'pointer'}}>Check all images load</button>
            {canManage && <button onClick={()=>setShowSettings(true)} style={{border:'1px solid var(--b-primary)',background:'var(--b-primary)',color:'#fff',borderRadius:8,padding:'7px 12px',font:"700 12px 'Public Sans'",cursor:'pointer'}}>Storage settings</button>}
          </div>
        </div>

        {/* Grid */}
        <div style={{overflowY:'auto',padding:'16px 22px',flex:1}}>
          {images===null ? (
            <div style={{textAlign:'center',padding:'48px 0',font:"500 14px 'Public Sans'",color:'#9AA6BC'}}>Loading…</div>
          ) : images.length===0 ? (
            <div style={{textAlign:'center',padding:'48px 0',font:"500 14px 'Public Sans'",color:'#9AA6BC'}}>No images stored yet — generate or upload images in the Post Brief tab.</div>
          ) : (
            <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fill,minmax(175px,1fr))',gap:12}}>
              {images.map(img=>(
                <div key={img.id} style={{border:'1px solid #E5EAF2',borderRadius:10,overflow:'hidden',background:'#F7F9FC'}}>
                  <div style={{height:120,background:'#DDE3EE',overflow:'hidden'}}>
                    <img src={img.url} alt={img.filename||'image'} style={{width:'100%',height:'100%',objectFit:'cover'}} onError={e=>{e.target.style.opacity=0;}}/>
                  </div>
                  <div style={{padding:'8px 10px'}}>
                    <div style={{font:"600 11.5px 'Public Sans'",color:'#1A2942',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}} title={img.filename}>{img.filename||'image.jpg'}</div>
                    <div style={{font:"500 10.5px 'Public Sans'",color:'#9AA6BC',marginTop:2}}>{_fmtDate(img.uploadedAt)}</div>
                    <div style={{font:"500 10.5px 'Public Sans'",color:'#9AA6BC'}}>{_fmtBytes(img.sizeBytes||0)}{camName(img.campaignId)?' · '+camName(img.campaignId):''}</div>
                    <div style={{font:"600 10.5px 'Public Sans'",marginTop:2,color:_imageHost(img.url).trusted?'#9AA6BC':'#B45309'}} title={img.url}>{_imageHost(img.url).label}{usedUrls.has(img.url)?' · in use':''}</div>
                    {health[img.id] && <div style={{font:"700 10.5px 'Public Sans'",marginTop:2,color:health[img.id]==='ok'?'#059669':health[img.id]==='broken'?'#B91C1C':'#9AA6BC'}}>{health[img.id]==='ok'?'Loads OK':health[img.id]==='broken'?'Does not load':'Checking…'}</div>}
                    <div style={{display:'flex',gap:6,marginTop:8}}>
                      <button onClick={()=>doDownload(img)} style={{flex:1,display:'inline-flex',alignItems:'center',justifyContent:'center',gap:4,border:'1px solid #D5DEF0',background:'#fff',color:'var(--b-primary)',borderRadius:7,padding:'5px 0',font:"700 10.5px 'Public Sans'",cursor:'pointer'}}><DownloadIcon sz={11}/>Save</button>
                      <button onClick={()=>doDelete(img)} disabled={!!deleting[img.id]} style={{flex:1,display:'inline-flex',alignItems:'center',justifyContent:'center',gap:4,border:'1px solid #F0D6D6',background:'#FFF5F5',color:'#C0473F',borderRadius:7,padding:'5px 0',font:"700 10.5px 'Public Sans'",cursor:'pointer',opacity:deleting[img.id]?0.5:1}}><TrashIcon sz={11}/>Delete</button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
      {showSettings && <ImageStorageModal settings={settings} usedBytes={totalBytes} onSave={st=>{onSaveSettings(st);setShowSettings(false);}} onClose={()=>setShowSettings(false)}/>}
    </div>
  );
}

/* ── Image Storage settings modal ────────────────────────────────────────
   Organisation-level (Admin only). Decides where this organisation's publishable
   images live. Managed storage (Catalyst Stratus) is the default; WordPress and
   link-only follow in later phases. See docs/image-storage-design.md. ───── */
function ImageStorageModal({settings, usedBytes, onSave, onClose}) {
  const st = settings || {};
  const [provider, setProvider] = React.useState(st.provider || 'managed');
  const allowance = _allowanceBytes(st);
  const pct = Math.min(100,(usedBytes/allowance)*100);
  const card = (id,title,desc,disabled) => (
    <label key={id} style={{display:'flex',gap:10,alignItems:'flex-start',border:'1px solid '+(provider===id?'var(--b-primary)':'#D9E1EE'),background:provider===id?'#F3F7FD':'#fff',borderRadius:10,padding:'11px 13px',cursor:disabled?'not-allowed':'pointer',opacity:disabled?0.55:1}}>
      <input type="radio" name="imgprov" checked={provider===id} disabled={disabled} onChange={()=>setProvider(id)} style={{marginTop:3}}/>
      <span><span style={{font:"800 13px 'Public Sans'",color:'var(--b-primary-deep)',display:'block'}}>{title}{disabled?' — coming soon':''}</span>
      <span style={{font:"500 12px/1.5 'Public Sans'",color:'#6B7790'}}>{desc}</span></span>
    </label>
  );
  return (
    <div className="modal-overlay" style={{zIndex:70}}>
      <div style={{width:'100%',maxWidth:540,background:'#fff',borderRadius:18,boxShadow:'0 24px 60px rgba(22,40,70,.35)',overflow:'hidden'}}>
        <div style={{padding:'16px 22px',borderTop:'3px solid var(--b-accent)',borderBottom:'1px solid var(--b-bg)',display:'flex',alignItems:'center',justifyContent:'space-between'}}>
          <div>
            <div style={{font:"800 17px 'Public Sans'",color:'var(--b-primary-deep)'}}>Image storage</div>
            <div style={{font:"500 12px 'Public Sans'",color:'#6B7790',marginTop:2}}>Where this organisation's post images are kept. Applies to every campaign and user.</div>
          </div>
          <button className="hov-outline" onClick={onClose} style={{width:34,height:34,display:'grid',placeItems:'center',border:'none',background:'#F1F4F9',borderRadius:9,cursor:'pointer',color:'#5A6473'}}><XIcon/></button>
        </div>
        <div style={{padding:'18px 22px',display:'flex',flexDirection:'column',gap:10}}>
          {card('managed','Plansocial managed storage','Nothing to set up. Includes '+_fmtBytes(INCLUDED_BYTES)+' per organisation; extra storage can be added in blocks.',false)}
          {card('wordpress','Your WordPress media library','Images are saved to your own website\'s uploads folder, so you keep them permanently.',true)}
          {card('link','Paste a link only','No uploads. Users paste a public image link, which is checked before a post can be approved.',true)}
          <div style={{marginTop:6}}>
            <div style={{display:'flex',justifyContent:'space-between',marginBottom:5}}>
              <span style={{font:"600 12px 'Public Sans'",color:'#5A6473'}}>Used</span>
              <span style={{font:"700 12px 'Public Sans'",color:'var(--b-primary)'}}>{_fmtBytes(usedBytes)} of {_fmtBytes(allowance)}{st.extraBytes?' (includes '+_fmtBytes(st.extraBytes)+' extra)':''}</span>
            </div>
            <div style={{height:7,borderRadius:4,background:'#E5EAF2',overflow:'hidden'}}><div style={{height:'100%',width:pct+'%',background:pct>90?'#EF4444':pct>70?'#F59E0B':'var(--b-primary)'}}/></div>
          </div>
        </div>
        <div style={{padding:'14px 22px',borderTop:'1px solid var(--b-bg)',display:'flex',justifyContent:'flex-end',gap:10,background:'#FAFBFE'}}>
          <button className="hov-outline" onClick={onClose} style={{background:'#fff',color:'#6B7790',border:'1px solid #D9E1EE',borderRadius:9,padding:'10px 18px',font:"800 13px 'Public Sans'",cursor:'pointer'}}>Cancel</button>
          <button className="hov-blue" onClick={()=>onSave({...st,provider})} style={{background:'var(--b-primary)',color:'#fff',border:'none',borderRadius:9,padding:'10px 22px',font:"800 13px 'Public Sans'",cursor:'pointer'}}>Save</button>
        </div>
      </div>
    </div>
  );
}

/* ── Brand Kit modal ──────────────────────────────────────────────────────
   Club-level identity — set once, reused by every campaign for this club.
   Multi-tenant: this is scoped to clubs/{clubId}, so each club gets its own
   kit with no shared state between clubs. Per-campaign overrides (an event
   with its own logo/colours) live in Setup § 2, not here. ────────────────── */
function BrandKitModal({draft, setDraft, onClose, onSave, clubId}) {
  const d = draft;
  const [logoBusy, setLogoBusy] = React.useState(false);
  const field = (key,e) => setDraft(dd=>({...dd,[key]:e.target.value}));

  const uploadLogo = async file => {
    if (!file) return;
    setLogoBusy(true);
    try {
      const url = await _uploadClubLogo(file);
      setDraft(dd=>({...dd,logoUrl:url,logoName:file.name}));
    } catch(e) { note(_imgError(e, 'The logo could not be uploaded')); }
    setLogoBusy(false);
  };

  const labelStyle = {display:'flex',flexDirection:'column',gap:5};
  const lblText    = {font:"700 11.5px 'Public Sans'",color:'#6B7790'};
  const inputStyle = {border:'1px solid #D9E1EE',borderRadius:8,padding:'9px 11px',font:"500 13px 'Public Sans'",color:'#1A2942',outline:'none',width:'100%'};
  const hint       = {font:"500 11.5px/1.5 'Public Sans'",color:'#9AA6BC',marginTop:5};

  return (
    <div className="modal-overlay" style={{zIndex:60}}>
      <div style={{width:'100%',maxWidth:560,background:'#fff',borderRadius:18,boxShadow:'0 24px 60px rgba(22,40,70,.35)',overflow:'hidden'}}>
        <div style={{padding:'18px 22px',borderTop:'3px solid var(--b-accent)',borderBottom:'1px solid var(--b-bg)',display:'flex',alignItems:'center',justifyContent:'space-between'}}>
          <div>
            <div style={{font:"800 18px 'Public Sans'",color:'var(--b-primary-deep)'}}>Club Brand Kit</div>
            <div style={{font:"500 12.5px 'Public Sans'",color:'#6B7790',marginTop:2}}>Set once, reused by every campaign for this club.</div>
          </div>
          <button className="hov-outline" onClick={onClose} style={{width:34,height:34,display:'grid',placeItems:'center',border:'none',background:'#F1F4F9',borderRadius:9,cursor:'pointer',color:'#5A6473'}}><XIcon/></button>
        </div>

        <div style={{padding:'20px 22px',maxHeight:'64vh',overflowY:'auto',display:'flex',flexDirection:'column',gap:18}}>

          <label style={labelStyle}>
            <span style={lblText}>Club logo</span>
            <div style={{display:'flex',alignItems:'center',gap:12}}>
              {d.logoUrl && <img src={d.logoUrl} alt="" style={{width:48,height:48,objectFit:'contain',border:'1px solid #E5EAF2',borderRadius:8,background:'#FAFBFE'}}/>}
              <label style={{display:'inline-flex',alignItems:'center',gap:6,cursor:'pointer',background:'#F0F4FA',border:'1px solid #D5DEF0',borderRadius:8,padding:'8px 12px',font:"700 12px 'Public Sans'",color:'var(--b-primary)'}}>
                <PaperclipIcon/>{logoBusy?'Uploading…':d.logoName?'Replace logo':'Upload logo'}
                <input type="file" accept="image/*" style={{display:'none'}} disabled={logoBusy} onChange={e=>uploadLogo(e.target.files[0])}/>
              </label>
              {d.logoName && !logoBusy && <span style={{font:"500 11.5px 'Public Sans'",color:'#5A6473'}}>{d.logoName}</span>}
            </div>
          </label>

          <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12}}>
            <label style={labelStyle}><span style={lblText}>Primary colour</span>
              <div style={{display:'flex',gap:8,alignItems:'center'}}>
                <input type="color" value={d.primaryColor||'#17458F'} onChange={e=>field('primaryColor',e)} style={{width:38,height:36,border:'1px solid #D9E1EE',borderRadius:7,padding:2,cursor:'pointer'}}/>
                <input value={d.primaryColor||''} onChange={e=>field('primaryColor',e)} style={inputStyle}/>
              </div>
            </label>
            <label style={labelStyle}><span style={lblText}>Secondary colour</span>
              <div style={{display:'flex',gap:8,alignItems:'center'}}>
                <input type="color" value={d.secondaryColor||'#F7A81B'} onChange={e=>field('secondaryColor',e)} style={{width:38,height:36,border:'1px solid #D9E1EE',borderRadius:7,padding:2,cursor:'pointer'}}/>
                <input value={d.secondaryColor||''} onChange={e=>field('secondaryColor',e)} style={inputStyle}/>
              </div>
            </label>
          </div>

          <label style={labelStyle}>
            <span style={lblText}>Tone of voice <span style={{fontWeight:500,color:'#9AA6BC',marginLeft:4}}>— 3 words is enough</span></span>
            <input value={d.toneWords||''} onChange={e=>field('toneWords',e)} placeholder="e.g. Warm, plain-spoken, community-run" style={inputStyle}/>
            <span style={hint}>Short enough to actually check a draft post against.</span>
          </label>

          <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12}}>
            <label style={labelStyle}><span style={lblText}>Standard hashtags</span>
              <input value={d.standardHashtags||''} onChange={e=>field('standardHashtags',e)} placeholder="#RotaryPeninsula" style={inputStyle}/>
            </label>
            <label style={labelStyle}><span style={lblText}>Standard sign-off</span>
              <input value={d.signOff||''} onChange={e=>field('signOff',e)} placeholder="— Rotary Peninsula 2.0" style={inputStyle}/>
            </label>
          </div>
          <div style={{...hint,marginTop:-10}}>Applied by default so it's not re-typed campaign to campaign — override per-campaign in Setup if a specific event needs something different.</div>

          <label style={labelStyle}>
            <span style={lblText}>Words &amp; phrases to avoid <span style={{fontWeight:500,color:'#9AA6BC',marginLeft:4}}>— club-wide, on top of anything a campaign adds</span></span>
            <textarea value={d.avoidWords||''} onChange={e=>field('avoidWords',e)} rows={2}
              placeholder="e.g. Never call a fun run a 'race'." style={{...inputStyle,resize:'vertical'}}/>
          </label>
        </div>

        <div style={{padding:'14px 22px',borderTop:'1px solid var(--b-bg)',display:'flex',justifyContent:'flex-end',gap:10,background:'#FAFBFE'}}>
          <button className="hov-outline" onClick={onClose} style={{background:'#fff',color:'#6B7790',border:'1px solid #D9E1EE',borderRadius:9,padding:'10px 18px',font:"800 13px 'Public Sans'",cursor:'pointer'}}>Cancel</button>
          <button className="hov-blue" onClick={onSave} style={{background:'var(--b-primary)',color:'#fff',border:'none',borderRadius:9,padding:'10px 22px',font:"800 13px 'Public Sans'",cursor:'pointer'}}>Save Brand Kit</button>
        </div>
      </div>
    </div>
  );
}

/* ── Setup Guide ──────────────────────────────────────────────────────────
   Printable walkthrough of the Setup screen, in the same order, with a live
   readiness checklist driven by the same computeReadiness() the Setup modal's
   strip uses — so the two never disagree. Print support: only the .guide-print
   subtree is visible under @media print (rule in social.css). ─────────────── */
const GUIDE_QUESTIONS = [
  ['A · Facts & figures',  'The exact numbers/dates that must be correct — and which document backs each one up.'],
  ['B · The hook',         'If a reader only remembers one sentence about this pillar, what should it be?'],
  ['C · Sub-entities',     'Does this pillar cover more than one thing (e.g. six beneficiaries)? List them, so one post covers one, not all six at once.'],
  ['D · Call to action',   'What do you want the reader to actually do — register, donate, RSVP, just follow along?'],
  ['E · Tone deviation',   'Only fill this in if this pillar should sound different from the rest — e.g. more playful for a prize announcement.'],
  ['F · Deadline / trigger','Any hard date this pillar is pinned to, like an early-bird cutoff.'],
  ['G · Off-limits',       "Anything not to say — an unconfirmed figure, a phrase your club dislikes, a past controversy."],
  ['H · Source documents', 'Tick which reference documents back this pillar up.'],
];
const GUIDE_AI_PROMPT = `You are helping me write a reference document for a community fundraising campaign run by a Rotary club. The document will be used by another AI to write accurate social media posts, so it must contain ONLY facts I actually give you below — do not add, guess, or infer any date, number, name or detail I haven't stated.

Subject: [name of the pillar, beneficiary, sponsor, or event detail this document is about]

Here is everything I know, in no particular order — some of it may be repeated or messy, that's fine:
[paste your raw notes, old flyer text, webpage copy, committee emails, etc. here]

Please turn this into a clear, well-organised reference document with:
- A one-paragraph plain-English summary
- Key facts and figures, each one exactly as I stated it
- Important dates or deadlines, if any
- Anything explicitly uncertain or still to be confirmed — list these separately, don't smooth over them

If something is unclear or missing that you'd expect a document like this to cover, list it as an open question for me at the end instead of filling it in yourself.`;

function PromptBox({text}) {
  const [copied, setCopied] = React.useState(false);
  const doCopy = () => {
    try { navigator.clipboard && navigator.clipboard.writeText(text); } catch(e) {}
    setCopied(true);
    setTimeout(()=>setCopied(false), 1800);
  };
  return (
    <div style={{position:'relative',background:'#1A2942',borderRadius:10,padding:'14px 16px',marginBottom:4}}>
      <button className="no-print" onClick={doCopy} style={{position:'absolute',top:10,right:10,display:'inline-flex',alignItems:'center',gap:5,background:copied?'#15803D':'rgba(255,255,255,.12)',color:'#fff',border:'none',borderRadius:7,padding:'5px 10px',font:"800 10.5px 'Public Sans'",cursor:'pointer'}}>
        <CopyIcon sz={11}/><span>{copied ? 'Copied!' : 'Copy'}</span>
      </button>
      <pre style={{margin:0,paddingRight:70,font:"13px/1.6 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace",color:'var(--b-wash)',whiteSpace:'pre-wrap',wordBreak:'break-word'}}>{text}</pre>
    </div>
  );
}

const GUIDE_PREP = [
  ['Your event’s "source of truth" document', 'A flyer, run sheet, sponsorship prospectus, or committee brief — whatever document in your club has the actual dates, prices and numbers on it. A PDF is better than a memory of a webpage.'],
  ['A one-paragraph plain-English description of the event', 'What it is, who runs it, why it exists. Write it like you’re explaining it to a neighbour, not a press release.'],
  ['Your beneficiary and sponsor lists, with one line on each', 'Not just names — what each one actually does, or what tier they sponsor at. This is the difference between a specific post and a generic one.'],
  ['Your club’s logo and brand colours', 'Set these once in the Club Brand Kit (palette icon in the header) — every campaign reuses them automatically.'],
  ['Your Facebook Page name (and Page ID, if posting automatically)', 'Ask whoever manages your club’s Facebook Page — the ID is a long number in Meta Business settings, not the Page’s web address.'],
];

function SetupGuideModal({config, clubBrandKit, onClose}) {
  const d = config || {};
  const { readiness, readyCount } = computeReadiness(d);
  const bk = clubBrandKit || {};

  const wrap    = {maxWidth:900,margin:'0 auto'};
  const card     = {background:'#FAFBFE',border:'1px solid #E5EAF2',borderRadius:12,padding:'18px 20px',marginBottom:12};
  const sectionS = {marginBottom:40};
  const secHead  = {display:'flex',alignItems:'baseline',gap:12,marginBottom:6};
  const secNum   = {font:"800 12px 'Public Sans'",color:'var(--b-primary)',background:'var(--b-wash)',borderRadius:7,padding:'4px 8px',flex:'none'};
  const h2       = {font:"800 21px 'Public Sans'",margin:0,color:'var(--b-primary-deep)'};
  const dek      = {font:"600 12.5px/1.55 'Public Sans'",color:'#6B7790',margin:'8px 0 16px',maxWidth:'70ch'};
  const h3       = {font:"800 13.5px 'Public Sans'",color:'#1A2942',margin:'0 0 7px'};
  const p        = {font:"400 14px/1.6 Georgia,serif",color:'#334158',margin:'0 0 8px'};
  const compare  = {display:'grid',gridTemplateColumns:'1fr 1fr',gap:10,marginTop:10};
  const exBase   = {borderRadius:9,padding:'11px 13px',font:"italic 13.5px/1.55 Georgia,serif"};
  const exTag    = {display:'block',font:"800 10px 'Public Sans'",letterSpacing:'.06em',textTransform:'uppercase',marginBottom:5,fontStyle:'normal'};
  const why      = {display:'flex',gap:9,alignItems:'flex-start',background:'#FCEEDA',border:'1px solid rgba(247,168,27,.35)',borderRadius:9,padding:'10px 13px',marginTop:10};

  return (
    <div className="modal-overlay" style={{zIndex:60,alignItems:'flex-start'}}>
      <div style={{width:'100%',maxWidth:980,background:'#fff',borderRadius:18,boxShadow:'0 24px 60px rgba(22,40,70,.35)',overflow:'hidden'}}>
        <div className="no-print" style={{padding:'16px 24px',borderTop:'3px solid var(--b-accent)',borderBottom:'1px solid var(--b-bg)',display:'flex',alignItems:'center',justifyContent:'space-between',position:'sticky',top:0,background:'#fff',zIndex:1}}>
          <div>
            <div style={{font:"800 18px 'Public Sans'",color:'var(--b-primary-deep)'}}>Campaign Setup Guide</div>
            <div style={{font:"500 12.5px 'Public Sans'",color:'#6B7790',marginTop:2}}>{d.eventName || 'This campaign'} — matches the Setup screen, section by section.</div>
          </div>
          <div style={{display:'flex',gap:10}}>
            <button className="hov-outline" onClick={()=>window.print()} style={{border:'1px solid #D9E1EE',background:'#fff',color:'var(--b-primary)',borderRadius:9,padding:'9px 16px',font:"800 12.5px 'Public Sans'",cursor:'pointer'}}>Print / Save as PDF</button>
            <button className="hov-outline" onClick={onClose} style={{width:34,height:34,display:'grid',placeItems:'center',border:'none',background:'#F1F4F9',borderRadius:9,cursor:'pointer',color:'#5A6473'}}><XIcon/></button>
          </div>
        </div>

        <div className="guide-print" style={{padding:'28px 30px 40px',maxHeight:'76vh',overflowY:'auto'}}>
          <div style={wrap}>

            <section style={sectionS}>
              <div style={secHead}><span style={secNum}>Before you start</span></div>
              <h2 style={h2}>Five things to have open in another tab</h2>
              <p style={dek}>Gathering these first means you fill in Setup once, rather than stopping halfway through to go and find them.</p>
              <div style={{...why,marginTop:0,marginBottom:16,background:'var(--b-wash)',border:'1px solid color-mix(in srgb, var(--b-primary) 25%, transparent)'}}>
                <span>⏱️</span>
                <p style={{...p,margin:0,font:"600 12.5px/1.6 'Public Sans'",color:'var(--b-primary)'}}>
                  This is the step that actually saves time. A Setup field filled from a real document rarely needs
                  touching again — one filled from memory usually does, the first time the AI drafts a post using a
                  "fact" that turns out to be wrong and someone has to notice, trace it back, and fix it. Fifteen
                  minutes here is the difference between filling in Setup once and re-opening it every week of the campaign.
                </p>
              </div>
              <div style={{display:'flex',flexDirection:'column',gap:8}}>
                {GUIDE_PREP.map(([t,desc])=>(
                  <label key={t} style={{display:'flex',gap:10,alignItems:'flex-start',...card,marginBottom:0,cursor:'pointer'}}>
                    <input type="checkbox" style={{marginTop:3,width:16,height:16,accentColor:'var(--b-primary)',flex:'none'}}/>
                    <div><div style={{font:"700 13px 'Public Sans'",color:'#1A2942',marginBottom:2}}>{t}</div><div style={{font:"400 13px/1.5 Georgia,serif",color:'#6B7790'}}>{desc}</div></div>
                  </label>
                ))}
              </div>
            </section>

            <section id="s1" style={sectionS}>
              <div style={secHead}><span style={secNum}>1</span><h2 style={h2}>Club &amp; Event</h2></div>
              <p style={dek}>The basics the AI reads before every single post — get this right and it pays off everywhere else.</p>
              <div style={card}>
                <h3 style={h3}>"More info" is the single most important box on this page</h3>
                <p style={p}>Don't just list facts — write the way you'd brief a new volunteer: what the event is, who's behind it, what tone to use, and anything that must never be said (e.g. an unconfirmed number, or calling a fun run a "race").</p>
                <div style={compare}>
                  <div style={{...exBase,background:'#FCEEDA',border:'1px dashed rgba(180,83,9,.4)'}}><span style={{...exTag,color:'#B45309'}}>Too thin</span>"Fun run in November raising money for charity."</div>
                  <div style={{...exBase,background:'#E3F5E9',border:'1px solid rgba(21,128,61,.35)'}}><span style={{...exTag,color:'#15803D'}}>Grounded</span>"Riverside Charity Fun Run - run by our club with a local sports club, 100% volunteer, all profit to community projects. Sunday 29 November at the riverside park. Tone: warm, plain-spoken, never corporate language."</div>
                </div>
                <div style={why}><span>💡</span><p style={{...p,margin:0,font:"600 12.5px/1.55 'Public Sans'",color:'#8A5A05'}}>If it isn't in this box (or a linked document), assume the AI will guess — and guesses are how wrong dates and invented statistics end up in a draft post.</p></div>
              </div>
            </section>

            <section id="s2" style={sectionS}>
              <div style={secHead}><span style={secNum}>2</span><h2 style={h2}>Beneficiaries &amp; Sponsors</h2></div>
              <p style={dek}>Where the money or effort actually goes — usually the emotional core of the campaign, so it's worth the extra minute per entry. Sponsors need their tier named correctly too, since that's usually a contractual promise, not a nicety.</p>
              <div style={card}>
                <p style={p}>The "about" box is what the AI quotes from when that beneficiary or sponsor comes up in a post. One name-dropped sentence isn't enough to write a good post from.</p>
                <div style={compare}>
                  <div style={{...exBase,background:'#FCEEDA',border:'1px dashed rgba(180,83,9,.4)'}}><span style={{...exTag,color:'#B45309'}}>Weak</span>"Great local charity."</div>
                  <div style={{...exBase,background:'#E3F5E9',border:'1px solid rgba(21,128,61,.35)'}}><span style={{...exTag,color:'#15803D'}}>Specific</span>"Mental health support — one of three charities entrants can choose to fundraise for at signup; also a beneficiary of overall event profits."</div>
                </div>
                <div style={why}><span>💡</span><p style={{...p,margin:0,font:"600 12.5px/1.55 'Public Sans'",color:'#8A5A05'}}>If a sponsorship tier isn't finalised yet, write that explicitly rather than leaving it blank — "tier to be confirmed" stops the AI inventing a Gold/Silver/Bronze structure that doesn't exist.</p></div>
              </div>
            </section>

            <section id="s3" style={sectionS}>
              <div style={secHead}><span style={secNum}>3</span><h2 style={h2}>Reference Documents</h2></div>
              <p style={dek}>This is where accuracy either holds up or falls apart — and the one section where a well-meaning shortcut causes the most damage.</p>
              <div style={{display:'flex',gap:9,alignItems:'flex-start',background:'#FCEEDA',border:'1px solid rgba(180,83,9,.35)',borderRadius:10,padding:'13px 15px',marginBottom:10}}>
                <span>⚠️</span>
                <div><div style={{font:"800 11px 'Public Sans'",textTransform:'uppercase',letterSpacing:'.04em',color:'#B45309',marginBottom:3}}>Websites go out of date — plan around it</div>
                <p style={{...p,margin:0}}>A link is only as accurate as the last time the page was updated. Early-bird pricing changes, sponsors are added, dates shift — and a linked page silently goes stale while your campaign is still running. The Planner has no way to know a page changed since you added the link.</p></div>
              </div>
              <div style={card}><h3 style={h3}>Prefer a document over a link</h3><p style={{...p,margin:0}}>Where you can, upload the actual document (event summary, run sheet, sponsorship pack) rather than pointing at a webpage. A PDF is a fixed snapshot — it can't change under you mid-campaign the way a live page can.</p></div>
              <div style={card}><h3 style={h3}>If it's a link, date it</h3><p style={{...p,margin:0}}>Use the Note field to record when you checked it and what's authoritative in it. The Setup screen tracks this for you — a link-only document without a "Checked on" date (or older than 180 days) shows a warning right on the row.</p></div>
              <div style={card}>
                <h3 style={h3}>Don't have a document yet? Use AI to draft one</h3>
                <p style={p}>If the facts only exist as scattered notes, old emails, a committee WhatsApp thread or a half-remembered conversation, an AI chat tool (ChatGPT, Claude, Gemini) can turn that mess into a clean one-page reference document in a couple of minutes — you just have to feed it only what you actually know, and tell it not to fill gaps itself.</p>
                <ul style={{...p,margin:'0 0 10px',paddingLeft:18}}>
                  <li style={{marginBottom:4}}>Paste in everything you have — old flyer text, a webpage, committee notes — even if it's messy or repeats itself. More raw material beats a tidy but incomplete summary.</li>
                  <li style={{marginBottom:4}}>Explicitly tell it not to invent anything. This is the single most important instruction — without it, AI tools fill gaps with plausible-sounding guesses.</li>
                  <li>Read the draft back against your own notes before uploading it. It's now a source-of-truth document for every future post — errors here get repeated all campaign, not just once.</li>
                </ul>
                <div style={{font:"800 10px 'Public Sans'",letterSpacing:'.06em',textTransform:'uppercase',color:'#8A94A8',marginBottom:6}}>Example script — copy, fill in the brackets, paste into any AI chat tool</div>
                <PromptBox text={GUIDE_AI_PROMPT}/>
                <div style={why}><span>💡</span><p style={{...p,margin:0,font:"600 12.5px/1.55 'Public Sans'",color:'#8A5A05'}}>Treat the result as a first draft, not a finished source. Once you're happy with it, upload it as a Reference Document like any other — it doesn't need to say "AI-drafted" anywhere, since by then a human (you) has checked it.</p></div>
              </div>
            </section>

            <section id="s4" style={sectionS}>
              <div style={secHead}><span style={secNum}>4</span><h2 style={h2}>Content Pillars &amp; the Reference Questionnaire</h2></div>
              <p style={dek}>Pillars are your topic categories. Every pillar can optionally carry a short questionnaire — this is the single biggest lever for accuracy, and the easiest section to skip by accident.</p>

              <div style={card}>
                <h3 style={h3}>What do we mean by "pillar"?</h3>
                <p style={p}>A pillar is a recurring theme your posts rotate through for the life of the campaign — not a single post, and not a post type (that's what Image Style is for). Each week is assigned one pillar, so over a multi-week campaign the same handful of pillars repeat in sequence, giving your Facebook page variety instead of the same angle every time. Most campaigns run well on somewhere between four and six pillars — few enough to keep each one recognisable, broad enough that each can carry several weeks of different posts without repeating itself.</p>
                <div style={compare}>
                  <div style={{...exBase,background:'#FCEEDA',border:'1px dashed rgba(180,83,9,.4)'}}><span style={{...exTag,color:'#B45309'}}>Too narrow</span>"Early-bird pricing ends Friday" — that's one post, not a theme it can rotate through for weeks.</div>
                  <div style={{...exBase,background:'#E3F5E9',border:'1px solid rgba(21,128,61,.35)'}}><span style={{...exTag,color:'#15803D'}}>A real pillar</span>"How to Get Involved" — covers registration, pricing, what to bring, team entries, on-the-day logistics: a dozen different posts, one clear theme.</div>
                </div>
                <p style={{...p,margin:'10px 0 0'}}>Typical Rotary event pillars: <b>About the Event</b>, <b>Meet the Beneficiaries</b>, <b>How to Get Involved</b>, <b>Volunteers &amp; Behind the Scenes</b>, <b>Sponsors &amp; Thanks</b>, <b>Countdown / Preparing for the Day</b>. Swap in whatever actually matches your event — these are a starting point, not a template to fill in exactly.</p>
              </div>

              <div style={card}>
                <h3 style={h3}>Before you start on a pillar: do you have a URL or document for it?</h3>
                <p style={{...p,margin:'0 0 10px'}}>Not every pillar needs its own source material — but the ones carrying specific facts do. For each pillar you're about to set up, check you have at least one of the two below before you start typing the questionnaire, not after.</p>
                <div style={{display:'flex',flexDirection:'column',gap:8}}>
                  {['A URL specific to this pillar — the actual page with the relevant facts, not just the event homepage','A document specific to this pillar — a run sheet, a beneficiary write-up, a sponsorship pack section'].map(t=>(
                    <label key={t} style={{display:'flex',gap:10,alignItems:'flex-start',cursor:'pointer'}}>
                      <input type="checkbox" style={{marginTop:3,width:16,height:16,accentColor:'var(--b-primary)',flex:'none'}}/>
                      <span style={{font:"400 13.5px/1.5 Georgia,serif",color:'#334158'}}>{t}</span>
                    </label>
                  ))}
                </div>
                <div style={why}><span>💡</span><p style={{...p,margin:0,font:"600 12.5px/1.55 'Public Sans'",color:'#8A5A05'}}>Have neither? That's fine — see "Don't have a document yet? Use AI to draft one" in §3 above before you fill in this pillar's questionnaire.</p></div>
              </div>

              <div style={card}>
                <h3 style={h3}>You don't need to fill this in for every pillar</h3>
                <p style={{...p,margin:0}}>Reserve it for pillars carrying real numbers, names or values that must stay correct — prize amounts, a beneficiary split, an entry fee table. A pillar like "Volunteers" or "Stories" usually runs fine on just a description.</p>
              </div>
              <div style={{...card,overflowX:'auto'}}>
                <h3 style={h3}>What each question is really asking</h3>
                <table style={{width:'100%',borderCollapse:'collapse',marginTop:8,font:"14px/1.5 Georgia,serif"}}>
                  <tbody>
                    {GUIDE_QUESTIONS.map(([k,desc])=>(
                      <tr key={k}>
                        <td style={{padding:'8px 12px 8px 0',borderBottom:'1px solid #E5EAF2',font:"800 12.5px 'Public Sans'",color:'var(--b-primary)',whiteSpace:'nowrap',verticalAlign:'top'}}>{k}</td>
                        <td style={{padding:'8px 0',borderBottom:'1px solid #E5EAF2',color:'#334158',verticalAlign:'top'}}>{desc}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </section>

            <section id="brand" style={sectionS}>
              <div style={secHead}><span style={secNum}>★</span><h2 style={h2}>Your Brand Kit</h2></div>
              <p style={dek}>Set once at the club level (palette icon in the header), reused by every campaign automatically — no need to re-enter your logo or colours each time.</p>
              <div style={{...card,display:'flex',alignItems:'center',gap:14}}>
                {bk.logoUrl
                  ? <img src={bk.logoUrl} alt="" style={{width:40,height:40,objectFit:'contain',border:'1px solid #E5EAF2',borderRadius:8,background:'#fff',flex:'none'}}/>
                  : <div style={{width:40,height:40,borderRadius:8,background:'var(--b-bg)',flex:'none'}}/>}
                <div style={{display:'flex',gap:6,flex:'none'}}>
                  <span style={{width:20,height:20,borderRadius:5,background:bk.primaryColor||'#17458F',border:'1px solid rgba(0,0,0,.08)'}}/>
                  <span style={{width:20,height:20,borderRadius:5,background:bk.secondaryColor||'#F7A81B',border:'1px solid rgba(0,0,0,.08)'}}/>
                </div>
                <div style={{font:"500 12.5px 'Public Sans'",color:'#6B7790'}}>
                  {bk.toneWords ? `Tone: "${bk.toneWords}"` : 'Not set up yet — open the palette icon in the header to add your logo, colours and tone of voice.'}
                </div>
              </div>
              <p style={{...p,marginTop:8}}>Most campaigns just inherit the club kit as-is. An event with its own identity (a named fun run with its own logo) can flip to "This event has its own branding" in Setup §2, and leave a note on exactly where the club's own logo should still appear.</p>
            </section>

            <section id="final" style={{background:'linear-gradient(155deg,var(--b-primary-deep) 0%,var(--b-primary) 100%)',borderRadius:16,padding:'26px 26px 30px',color:'#fff'}}>
              <div style={{...secHead,marginBottom:4}}><span style={{...secNum,background:'rgba(255,255,255,.16)',color:'#fff'}}>✓</span><h2 style={{...h2,color:'#fff'}}>Setup readiness — {readyCount}/{readiness.length}</h2></div>
              <p style={{...dek,color:'#C7D7F2'}}>Live for {d.eventName || 'this campaign'} — print this page once everything below is checked, or just eyeball it before you hit "Save &amp; rebuild."</p>
              <ul style={{listStyle:'none',margin:'14px 0 0',padding:0,display:'flex',flexDirection:'column',gap:9}}>
                {readiness.map(r=>(
                  <li key={r.key} style={{display:'flex',gap:10,alignItems:'flex-start',font:"600 14px/1.5 'Public Sans'"}}>
                    <span style={{flex:'none',width:18,height:18,borderRadius:5,border:'2px solid rgba(255,255,255,.5)',background:r.done?'var(--b-accent)':'transparent',display:'grid',placeItems:'center',marginTop:1,color:'var(--b-primary-deep)',font:"800 12px sans-serif"}}>{r.done ? '✓' : ''}</span>
                    <span style={{color:r.done?'#fff':'#C7D7F2'}}>{r.label}</span>
                  </li>
                ))}
              </ul>
            </section>

            <div style={{borderTop:'1px solid #E5EAF2',marginTop:36,paddingTop:16,font:"600 11.5px 'Public Sans'",color:'#9AA6BC',display:'flex',justifyContent:'space-between',flexWrap:'wrap',gap:8}}>
              <span>Social Media Planner — Campaign Setup Guide</span>
              <span>Mirrors the Setup screen exactly</span>
            </div>

          </div>
        </div>
      </div>
    </div>
  );
}

/* ── Setup modal ─────────────────────────────────────────────────────────── */
function SetupModal({draft, setDraft, clubBrandKit, onOpenBrandKit, onOpenGuide, onClose, onSave, onNewCampaign, clubId, campaignId, isSuperAdmin, callAI}) {
  const aiFetch = (u, opts) => callAI(JSON.parse(opts.body)).then(res => ({ json: () => Promise.resolve(res) })).catch(e => { note((e && e.message) || 'Drafting failed'); throw e; });
  const d = draft;
  const [docBusy, setDocBusy] = React.useState({});
  /* One-level undo for the AI campaign-closing refresh — holds the message text
     as it was immediately before the last AI overwrite, cleared once used (or
     replaced by a newer refresh). Not a full history, just a single safety net
     since the refresh is a full overwrite of hand-edited text. */
  const [signOffUndo, setSignOffUndo] = React.useState(null);

  const field    = (key,e) => setDraft(d=>({...d,[key]:e.target.value}));
  const rowField = (list,id,key,e) => { const v=e.target.value; setDraft(d=>({...d,[list]:d[list].map(r=>r.id===id?{...r,[key]:v}:r)})); };
  const addRow   = list => {
    const pre = list==='pillars'?'p_':(list==='sponsors'?'s':(list==='referenceDocs'?'rd':(list==='moreInfoDocs'?'mi':'b')));
    const id  = pre+Math.random().toString(36).slice(2,7);
    const row = list==='pillars'
      ? {id,label:'New Pillar',color:'var(--b-primary)',bg:'var(--b-wash)',description:'',timing:[],questionnaire:blankQuestionnaire()}
      : list==='referenceDocs'
        ? {id,name:'',url:'',docUrl:'',docName:'',pillarId:'',note:'',verifiedDate:''}
        : list==='moreInfoDocs'
          ? {id,name:'',docUrl:'',docName:''}
          : {id,name:'',url:'',about:'',docUrl:'',docName:'',logoUrl:'',logoName:''};
    setDraft(d=>({...d,[list]:[...(d[list]||[]),row]}));
  };
  /* Remove a source document entirely (not just untick it) — used by both the
     Reference Documents list and the pillar Sources checklist, so a doc deleted
     from either place doesn't leave a dangling id in some other pillar's
     sourceDocIds. */
  const removeSourceDoc = (list,docId) => setDraft(d=>({
    ...d,
    [list]: (d[list]||[]).filter(x=>x.id!==docId),
    pillars: d.pillars.map(p=>{
      const q = p.questionnaire||blankQuestionnaire();
      if (!(q.sourceDocIds||[]).includes(docId)) return p;
      return {...p, questionnaire:{...q, sourceDocIds:q.sourceDocIds.filter(x=>x!==docId)}};
    }),
  }));

  const brandField = (key,e) => { const v=e.target.value; setDraft(d=>({...d,branding:{...(d.branding||blankBranding()),[key]:v}})); };
  const setBrandPrimary = who => setDraft(d=>({...d,branding:{...(d.branding||blankBranding()),primary:who}}));
  const [eventLogoBusy, setEventLogoBusy] = React.useState(false);
  const uploadEventLogo = async file => {
    if (!file) return;
    setEventLogoBusy(true);
    try {
      const url = await _uploadCampaignLogo(campaignId, file);
      setDraft(dd=>({...dd,branding:{...(dd.branding||blankBranding()),eventLogoUrl:url,eventLogoName:file.name}}));
    } catch(e) { note(_imgError(e, 'The logo could not be uploaded')); }
    setEventLogoBusy(false);
  };

  const branding = d.branding || blankBranding();
  const { readiness, readyCount } = computeReadiness(d);

  const [expandedPillars, setExpandedPillars] = React.useState(new Set());
  const togglePillarExpand = id => setExpandedPillars(s=>{ const n=new Set(s); n.has(id)?n.delete(id):n.add(id); return n; });
  const togglePillarTiming = (pillarId,tag) => setDraft(d=>({...d,pillars:d.pillars.map(p=>{
    if (p.id!==pillarId) return p;
    const cur = p.timing||[];
    return {...p, timing: cur.includes(tag) ? cur.filter(t=>t!==tag) : [...cur,tag]};
  })}));
  const qField = (pillarId,key,e) => { const v=e.target.value; setDraft(d=>({...d,pillars:d.pillars.map(p=>p.id===pillarId?{...p,questionnaire:{...(p.questionnaire||blankQuestionnaire()),[key]:v}}:p)})); };
  const toggleSourceDoc = (pillarId,docId) => setDraft(d=>({...d,pillars:d.pillars.map(p=>{
    if (p.id!==pillarId) return p;
    const q = p.questionnaire || blankQuestionnaire();
    const cur = q.sourceDocIds||[];
    return {...p, questionnaire:{...q, sourceDocIds: cur.includes(docId) ? cur.filter(x=>x!==docId) : [...cur,docId]}};
  })}));
  /* Quick-add a URL or document straight from a pillar's questionnaire — creates a
     Section 5 referenceDocs row tagged to this pillar and auto-checks it, so you don't
     have to bounce up to Section 5 first. Returns the new id (generated synchronously,
     ahead of the setDraft functional update) so callers like the file-attach handler can
     immediately follow up with uploadDoc('referenceDocs', id, file). */
  const addPillarSourceDoc = (pillarId,fields) => {
    const id = 'rd'+Math.random().toString(36).slice(2,7);
    setDraft(d=>({
      ...d,
      referenceDocs:[...(d.referenceDocs||[]), {id, name:fields.name||'', url:fields.url||'', docUrl:fields.docUrl||'', docName:fields.docName||'', pillarId, note:'', verifiedDate:''}],
      pillars: d.pillars.map(p=>{
        if (p.id!==pillarId) return p;
        const q = p.questionnaire || blankQuestionnaire();
        return {...p, questionnaire:{...q, sourceDocIds:[...(q.sourceDocIds||[]), id]}};
      }),
    }));
    return id;
  };
  const [pillarUrlDraft, setPillarUrlDraft] = React.useState({});
  const draftQuestionnaire = async pillar => {
    const busyKey = `qgen_${pillar.id}`;
    setDraftBusy(b=>({...b,[busyKey]:true}));
    const q = pillar.questionnaire || blankQuestionnaire();
    const sourceDocs = [...(d.moreInfoDocs||[]), ...(d.referenceDocs||[])].filter(doc=>(q.sourceDocIds||[]).includes(doc.id)).map(doc=>({name:doc.name,url:doc.url||'',docUrl:doc.docUrl}));
    const _sf = window.SOCIAL_FIREBASE || {};
    const url = 'ai';
    if (!url) {
      setTimeout(()=>{ setDraftBusy(b=>({...b,[busyKey]:false})); }, 700);
      return;
    }
    try {
      const headers = {'Content-Type':'application/json'};
      if (_sf.webhookSecret) headers['x-webhook-secret']=_sf.webhookSecret;
      const res = await aiFetch(url, {method:'POST', headers, body: JSON.stringify({type:'draftText', target:'questionnaire', campaignName:d.eventName, name:pillar.label, sourceDocs})});
      const data = await res.json();
      if (data && typeof data==='object') {
        setDraft(dd=>({...dd,pillars:dd.pillars.map(p=>{
          if (p.id!==pillar.id) return p;
          const pq = p.questionnaire || blankQuestionnaire();
          return {...p, questionnaire:{...pq,
            facts:      data.facts      ?? pq.facts,
            hook:       data.hook       ?? pq.hook,
            subEntities:data.subEntities?? pq.subEntities,
            cta:        data.cta        ?? pq.cta,
            toneNote:   data.toneNote   ?? pq.toneNote,
            deadline:   data.deadline   ?? pq.deadline,
            avoid:      data.avoid      ?? pq.avoid,
          }};
        })}));
      }
    } catch(e) { console.error('Questionnaire draft failed:', e); }
    setDraftBusy(b=>({...b,[busyKey]:false}));
  };

  /* Draft short text from name + optional url/docUrl/sourceDocs via the AI webhook.
     Not fetched/read here — the client only sends the reference URLs. The n8n workflow's
     "Build Draft Text Prompt" node does the actual crawl/read (website HTML + PDF/image
     doc) for the 'about' target before calling Claude, so the model is grounded in real
     content rather than name-only guessing — same honesty convention as the rest of this
     app's prompts (no invented specifics; an unreachable source produces an honest
     placeholder, not a fabrication). */
  const [draftBusy, setDraftBusy] = React.useState({});
  const draftText = async (busyKey, target, payload, applyFn) => {
    setDraftBusy(b=>({...b,[busyKey]:true}));
    const _sf = window.SOCIAL_FIREBASE || {};
    const url = 'ai';
    if (!url) {
      setTimeout(()=>{
        setDraftBusy(b=>({...b,[busyKey]:false}));
        applyFn(target==='pillarDescription'
          ? `Covers ${payload.name || 'this pillar'} — drawing on ${(payload.sourceDocs||[]).map(x=>x.name).join(', ')||'the linked reference material'}. (Demo draft — configure an AI webhook for real generation.)`
          : target==='campaignClosing'
          ? `Thank you to our sponsors [name sponsors once confirmed]. Together, we're building a healthier, more connected community.\n\nMark your calendars for ${d.eventName||'[Event name]'} [event date] and be part of something special! 🏃‍♀️🏃‍♂️🚶‍♀️\n\n${payload.existingHashtags||''} [add relevant hashtags] (Demo draft — configure an AI webhook for real generation.)`
          : `${payload.name || 'This organisation'} — details drafted from ${payload.url||payload.docUrl||'the attached reference material'}. (Demo draft — configure an AI webhook for real generation.)`);
      }, 700);
      return;
    }
    try {
      const headers = {'Content-Type':'application/json'};
      if (_sf.webhookSecret) headers['x-webhook-secret']=_sf.webhookSecret;
      const res = await aiFetch(url, {method:'POST', headers, body: JSON.stringify({type:'draftText', target, campaignName:d.eventName, ...payload})});
      const data = await res.json();
      if (data.text) applyFn(data.text);
    } catch(e) { console.error('Draft text failed:', e); }
    setDraftBusy(b=>({...b,[busyKey]:false}));
  };
  const draftAbout = (list, row) => {
    const busyKey = `about_${list}_${row.id}`;
    draftText(busyKey, 'about', {name:row.name||'', existingText:row.about||'', url:row.url||'', docUrl:row.docUrl||'', entityType:list==='beneficiaries'?'beneficiary':'sponsor'},
      text => setDraft(dd=>({...dd,[list]:dd[list].map(r=>r.id===row.id?{...r,about:text}:r)})));
  };
  const draftPillarDescription = pillar => {
    const busyKey = `pdesc_${pillar.id}`;
    const q = pillar.questionnaire || blankQuestionnaire();
    const sourceDocs = [...(d.moreInfoDocs||[]), ...(d.referenceDocs||[])].filter(doc=>(q.sourceDocIds||[]).includes(doc.id)).map(doc=>({name:doc.name,url:doc.url||'',docUrl:doc.docUrl}));
    draftText(busyKey, 'pillarDescription', {name:pillar.label||'', existingText:pillar.description||'', sourceDocs},
      text => setDraft(dd=>({...dd,pillars:dd.pillars.map(p=>p.id===pillar.id?{...p,description:text}:p)})));
  };
  /* Full refresh of the campaign closing/sign-off block (sponsor thanks, CTA,
     hashtags) — grounded in the Facebook page, event website and reference
     documents rather than left to guesswork. This REPLACES the whole field
     (not just the hashtags), so the previous text is stashed for one-level
     undo before it's overwritten. */
  const draftCampaignClosing = () => {
    const busyKey = 'signoffRefresh';
    const docs = [...(d.moreInfoDocs||[]), ...(d.referenceDocs||[])]
      .filter(x=>x.url||x.docUrl).map(x=>({name:x.name||'', url:x.url||'', docUrl:x.docUrl||''}));
    const sponsors = (d.sponsors||[]).map(s=>typeof s==='string'?s:(s.name||'')).filter(Boolean);
    const prev = d.signOffMessage || '';
    draftText(busyKey, 'campaignClosing', {
      clubName: d.clubName||'', url: d.eventWebsite||'', facebookPage: d.facebookPage||'',
      facebookPageUrl: d.facebookPageUrl||'', docs, sponsors,
      existingHashtags: (clubBrandKit && clubBrandKit.standardHashtags) || '',
    }, text => {
      setSignOffUndo(prev);
      setDraft(dd=>({...dd, signOffMessage:text}));
    });
  };

  const _upload = async (path, file) => {
    if (path.indexOf('_logo_') < 0) { note('Uploading documents is coming in a later release. Paste a link to the document instead.'); throw new Error('DOCS_LATER'); }
    return _uploadCampaignLogo(campaignId, file);
  };

  const uploadDoc = async (list, rowId, file) => {
    if (!file) return;
    const key = `${list}_${rowId}`;
    setDocBusy(b=>({...b,[key]:true}));
    try {
      const url = await _upload(`social-context/${clubId}/${campaignId||'_'}/${list}/${rowId}_${file.name}`, file);
      setDraft(d=>({...d,[list]:d[list].map(r=>r.id===rowId?{...r,docUrl:url,docName:file.name}:r)}));
    } catch(e) { console.error('Doc upload:',e); }
    setDocBusy(b=>({...b,[key]:false}));
  };

  const rmDoc = (list, id) => setDraft(d=>({...d,[list]:d[list].map(r=>r.id===id?{...r,docUrl:'',docName:''}:r)}));
  const rmRow    = (list,id) => setDraft(d=>({...d,[list]:d[list].filter(r=>r.id!==id)}));

  /* Logo per beneficiary/sponsor — composited onto the AI-generated image
     when that entity is the subject of a post (see Build Image Prompt1 in
     the n8n workflow). Kept separate from uploadDoc's docUrl/docName, which
     is a reference document, not artwork. */
  const [logoRowBusy, setLogoRowBusy] = React.useState({});
  const uploadRowLogo = async (list, rowId, file) => {
    if (!file) return;
    const key = `${list}_${rowId}`;
    setLogoRowBusy(b=>({...b,[key]:true}));
    try {
      const url = await _upload(`social-context/${clubId}/${campaignId||'_'}/${list}/${rowId}_logo_${file.name}`, file);
      setDraft(d=>({...d,[list]:d[list].map(r=>r.id===rowId?{...r,logoUrl:url,logoName:file.name}:r)}));
    } catch(e) { note(_imgError(e, 'The logo could not be uploaded')); }
    setLogoRowBusy(b=>({...b,[key]:false}));
  };
  const rmRowLogo = (list, id) => setDraft(d=>({...d,[list]:d[list].map(r=>r.id===id?{...r,logoUrl:'',logoName:''}:r)}));
  const stepNum  = (key,delta,mn,mx) => setDraft(d=>{const v=Math.max(mn,Math.min(mx,(parseInt(d[key])||0)+delta));return{...d,[key]:v};});
  const toggleDay = i => setDraft(d => {
    const days = d.preferredDays || [];
    const next = days.includes(i) ? days.filter(x=>x!==i) : [...days,i].sort((a,b)=>a-b);
    return { ...d, preferredDays: next.length ? next : [i] };
  });
  const labelStyle = {display:'flex',flexDirection:'column',gap:5};
  const lblText    = {font:"700 11.5px 'Public Sans'",color:'#6B7790'};
  const inputStyle = {border:'1px solid #D9E1EE',borderRadius:8,padding:'9px 11px',font:"500 13px 'Public Sans'",color:'#1A2942',outline:'none',width:'100%'};
  const rowInput   = {border:'1px solid #D9E1EE',borderRadius:8,padding:'8px 10px',font:"500 12.5px 'Public Sans'",color:'#1A2942',outline:'none',width:'100%'};
  const sectionHdr = {font:"800 11px 'Public Sans'",letterSpacing:'.05em',textTransform:'uppercase',color:'var(--b-primary)',marginBottom:10};
  const rmBtn      = {width:34,height:34,display:'grid',placeItems:'center',border:'1px solid #F0D6D6',background:'#FCF3F3',borderRadius:8,cursor:'pointer',color:'#C0473F'};
  const addBtn     = {display:'inline-flex',alignItems:'center',gap:5,border:'1px solid #D9E1EE',background:'#F7F9FC',borderRadius:8,padding:'5px 10px',font:"800 11.5px 'Public Sans'",color:'var(--b-primary)',cursor:'pointer'};
  const stepper    = (key,mn,mx) => (
    <div style={{display:'inline-flex',alignItems:'center',border:'1px solid #D9E1EE',borderRadius:9,overflow:'hidden'}}>
      <button onClick={()=>stepNum(key,-1,mn,mx)} style={{width:38,height:38,border:'none',background:'#F5F8FC',cursor:'pointer',font:"800 18px 'Public Sans'",color:'var(--b-primary)'}}>-</button>
      <span style={{width:48,textAlign:'center',font:"800 15px 'Public Sans'",color:'var(--b-primary-deep)'}}>{d[key]}</span>
      <button onClick={()=>stepNum(key,+1,mn,mx)} style={{width:38,height:38,border:'none',background:'#F5F8FC',cursor:'pointer',font:"800 18px 'Public Sans'",color:'var(--b-primary)'}}>+</button>
    </div>
  );

  const prefDays = d.preferredDays || [];

  return (
    <div className="modal-overlay">
      <div style={{width:'100%',maxWidth:720,background:'#fff',borderRadius:18,boxShadow:'0 24px 60px rgba(22,40,70,.35)',overflow:'hidden'}}>
        <div style={{padding:'18px 22px',borderTop:'3px solid var(--b-accent)',borderBottom:'1px solid var(--b-bg)',display:'flex',alignItems:'center',justifyContent:'space-between'}}>
          <div>
            <div style={{font:"800 18px 'Public Sans'",color:'var(--b-primary-deep)'}}>Campaign Setup</div>
            <div style={{font:"500 12.5px 'Public Sans'",color:'#6B7790',marginTop:2}}>Configure this campaign — saving rebuilds the planner.</div>
          </div>
          <button className="hov-outline" onClick={onClose} style={{width:34,height:34,display:'grid',placeItems:'center',border:'none',background:'#F1F4F9',borderRadius:9,cursor:'pointer',color:'#5A6473'}}><XIcon/></button>
        </div>

        <div style={{padding:'11px 22px',borderBottom:'1px solid var(--b-bg)',display:'flex',alignItems:'center',gap:10,flexWrap:'wrap',background:'#FAFBFE'}}>
          <span style={{font:"800 11px 'Public Sans'",color:readyCount===readiness.length?'#15803D':'#B45309'}}>Setup readiness — {readyCount}/{readiness.length}</span>
          <div style={{display:'flex',alignItems:'center',gap:7,flexWrap:'wrap'}}>
            {readiness.map(r=>(
              <span key={r.key} title={r.label} style={{display:'inline-flex',alignItems:'center',gap:4,font:"600 10.5px 'Public Sans'",color:r.done?'#15803D':'#9AA6BC'}}>
                <span style={{width:6,height:6,borderRadius:'50%',background:r.done?'#22C55E':'#D9E1EE',flex:'none'}}/>{r.label}
              </span>
            ))}
          </div>
          <span style={{marginLeft:'auto',font:"500 11px 'Public Sans'",color:'#9AA6BC'}}>
            Recommended, not required —{' '}
            <button onClick={onOpenGuide} style={{border:'none',background:'none',padding:0,font:"700 11px 'Public Sans'",color:'var(--b-primary)',cursor:'pointer',textDecoration:'underline'}}>see the Setup Guide</button>
          </span>
        </div>

        <div style={{padding:'20px 22px',maxHeight:'64vh',overflowY:'auto',display:'flex',flexDirection:'column',gap:22}}>

          <div>
            <div style={sectionHdr}>1 · Club & Event</div>
            <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12}}>
              <label style={labelStyle}><span style={lblText}>Club name</span><input value={d.clubName} onChange={e=>field('clubName',e)} style={inputStyle}/></label>
              <label style={labelStyle}><span style={lblText}>Event / campaign name</span><input value={d.eventName} onChange={e=>field('eventName',e)} style={inputStyle}/></label>
              <label style={labelStyle}><span style={lblText}>Facebook page</span><input value={d.facebookPage} onChange={e=>field('facebookPage',e)} style={inputStyle}/></label>
              <label style={labelStyle}><span style={lblText}>Campaign start (Mon of Wk 1)</span><input type="date" value={d.campaignStart} onChange={e=>field('campaignStart',e)} style={inputStyle}/></label>
              <label style={{...labelStyle,gridColumn:'1/-1'}}>
                <span style={lblText}>Event website <span style={{fontWeight:500,color:'#9AA6BC',marginLeft:4}}>— optional</span></span>
                <input value={d.eventWebsite||''} onChange={e=>field('eventWebsite',e)} placeholder="https://yourevent.org.au/" style={{...inputStyle,color:'var(--b-primary)'}}/>
                <span style={{font:"500 11.5px 'Public Sans'",color:'#9AA6BC',marginTop:5,display:'block'}}>When set, this URL is sent to your webhook so N8N can scrape the page and align topic suggestions to your event content.</span>
              </label>
            </div>
            <div style={{marginTop:14,display:'flex',flexDirection:'column',gap:8}}>
              <label style={labelStyle}>
                <span style={lblText}>More info <span style={{fontWeight:500,color:'#9AA6BC',marginLeft:4}}>— background context for AI generation</span></span>
                <textarea value={d.moreInfo||''} onChange={e=>field('moreInfo',e)} rows={3}
                  placeholder="Campaign goals, key messages, tone of voice, important facts the AI should know…"
                  style={{...inputStyle,resize:'vertical',lineHeight:1.5}}/>
                <span style={{font:"500 11.5px/1.5 'Public Sans'",color:'#9AA6BC'}}>This is what grounds every AI-generated caption — write it like a briefing to a new volunteer, not a headline. If it isn't here or in a reference document, assume the AI will guess.</span>
              </label>
              <div style={{display:'flex',flexDirection:'column',gap:8}}>
                {(d.moreInfoDocs||[]).map(doc=>{
                  const docKey = `moreInfoDocs_${doc.id}`;
                  return (
                    <div key={doc.id} style={{display:'flex',alignItems:'center',gap:8,flexWrap:'wrap'}}>
                      <input value={doc.name} onChange={e=>rowField('moreInfoDocs',doc.id,'name',e)} placeholder="Document name" style={{...rowInput,flex:1,minWidth:160}}/>
                      <label style={{display:'inline-flex',alignItems:'center',gap:5,cursor:'pointer',background:'#F0F4FA',border:'1px solid #D5DEF0',borderRadius:7,padding:'5px 10px',font:"700 11px 'Public Sans'",color:'var(--b-primary)',flex:'none'}}>
                        <PaperclipIcon/>{docBusy[docKey]?'Uploading…':doc.docName?'Replace doc':'Attach doc'}
                        <input type="file" accept=".pdf,.doc,.docx,.txt" style={{display:'none'}} disabled={!!docBusy[docKey]} onChange={e=>uploadDoc('moreInfoDocs',doc.id,e.target.files[0])}/>
                      </label>
                      {doc.docName && !docBusy[docKey] && (
                        <a href={doc.docUrl} target="_blank" rel="noreferrer" style={{font:"500 11.5px 'Public Sans'",color:'var(--b-primary)',textDecoration:'none'}}>{doc.docName}</a>
                      )}
                      <button onClick={()=>removeSourceDoc('moreInfoDocs',doc.id)} style={{border:'none',background:'none',cursor:'pointer',color:'#C0473F',font:"800 14px 'Public Sans'",padding:0,lineHeight:1,flex:'none'}}>×</button>
                    </div>
                  );
                })}
                <button className="hov-outline" onClick={()=>addRow('moreInfoDocs')} style={{...addBtn,alignSelf:'flex-start'}}><PlusIcon/>Add doc</button>
              </div>
              <span style={{font:"500 11.5px/1.5 'Public Sans'",color:'#9AA6BC'}}>These are also selectable as Sources in each pillar's Reference Questionnaire below.</span>
              <label style={labelStyle}>
                <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',gap:8,flexWrap:'wrap'}}>
                  <span style={lblText}>Campaign closing / sign-off message <span style={{fontWeight:500,color:'#9AA6BC',marginLeft:4}}>— pre-filled with a default draft, edit for this campaign</span></span>
                  <div style={{display:'flex',alignItems:'center',gap:8}}>
                    {signOffUndo!==null && (
                      <button onClick={()=>{ setDraft(dd=>({...dd,signOffMessage:signOffUndo})); setSignOffUndo(null); }}
                        style={{border:'none',background:'none',padding:0,font:"700 11px 'Public Sans'",color:'var(--b-primary)',cursor:'pointer',textDecoration:'underline',flex:'none'}}>
                        Undo AI refresh
                      </button>
                    )}
                    <button onClick={draftCampaignClosing} disabled={!!draftBusy.signoffRefresh}
                      title="Checks the Facebook page, event website and reference documents to redraft this whole block, including hashtags — overwrites the current text below"
                      style={{display:'inline-flex',alignItems:'center',gap:5,border:'1px solid #D5DEF0',background:'#F0F4FA',borderRadius:7,padding:'6px 10px',font:"700 11px 'Public Sans'",color:'var(--b-primary)',cursor:draftBusy.signoffRefresh?'default':'pointer',opacity:draftBusy.signoffRefresh?.6:1,flex:'none',whiteSpace:'nowrap'}}>
                      ✨ {draftBusy.signoffRefresh?'Refreshing…':'Refresh with AI'}
                    </button>
                  </div>
                </div>
                <textarea value={d.signOffMessage||''} onChange={e=>field('signOffMessage',e)} rows={4}
                  style={{...inputStyle,resize:'vertical',lineHeight:1.5}}/>
                <span style={{font:"500 11.5px/1.5 'Public Sans'",color:'#9AA6BC'}}>Offered to the AI for posts where a closing message fits naturally — a campaign launch, countdown, or sponsor thank-you post — never forced into every post. Fill in the [bracketed] placeholders with confirmed sponsors and the actual event date; anything left bracketed is passed through as-is rather than guessed. "Refresh with AI" draws on the Facebook page, event website and reference documents above to redraft the whole block including hashtags — it overwrites whatever is currently in the box below (one-step undo available immediately after).</span>
              </label>
            </div>
          </div>

          <div>
            <div style={sectionHdr}>2 · Branding for This Event</div>
            <div style={{border:'1px solid #E5EAF2',borderRadius:10,padding:'12px',background:'#FAFBFE',display:'flex',alignItems:'center',gap:12,marginBottom:12}}>
              {clubBrandKit && clubBrandKit.logoUrl
                ? <img src={clubBrandKit.logoUrl} alt="" style={{width:36,height:36,objectFit:'contain',border:'1px solid #E5EAF2',borderRadius:7,background:'#fff',flex:'none'}}/>
                : <div style={{width:36,height:36,borderRadius:7,background:'var(--b-bg)',flex:'none'}}/>}
              <div style={{display:'flex',gap:6,flex:'none'}}>
                <span style={{width:20,height:20,borderRadius:5,background:(clubBrandKit&&clubBrandKit.primaryColor)||'#17458F',border:'1px solid rgba(0,0,0,.08)'}}/>
                <span style={{width:20,height:20,borderRadius:5,background:(clubBrandKit&&clubBrandKit.secondaryColor)||'#F7A81B',border:'1px solid rgba(0,0,0,.08)'}}/>
              </div>
              <div style={{flex:1,font:"500 12px 'Public Sans'",color:'#6B7790'}}>
                Club brand kit{clubBrandKit && clubBrandKit.toneWords ? ` — "${clubBrandKit.toneWords}"` : ''}
              </div>
              {/* Org-wide brand kit — Super Admin only (matches the header Palette icon
                  and the Firestore rule); a Campaign Admin sees it for reference only. */}
              {isSuperAdmin
                ? <button onClick={onOpenBrandKit} style={{border:'1px solid #D9E1EE',background:'#fff',color:'var(--b-primary)',borderRadius:7,padding:'6px 10px',font:"700 11px 'Public Sans'",cursor:'pointer',flex:'none'}}>Edit club brand kit</button>
                : <span style={{font:"600 11px 'Public Sans'",color:'#9AA6BC',flex:'none'}}>Only a Super Admin can edit this</span>}
            </div>

            <div style={{font:"700 11.5px 'Public Sans'",color:'#6B7790',marginBottom:8}}>Which branding leads for this campaign?</div>
            <div style={{display:'flex',gap:8,marginBottom:12}}>
              <button onClick={()=>setBrandPrimary('club')} style={{flex:1,textAlign:'left',border:'1.5px solid',borderColor:branding.primary==='club'?'var(--b-primary)':'#D9E1EE',background:branding.primary==='club'?'var(--b-wash)':'#fff',borderRadius:9,padding:'10px 12px',cursor:'pointer'}}>
                <div style={{font:"800 12.5px 'Public Sans'",color:branding.primary==='club'?'var(--b-primary)':'#1A2942'}}>Club brand leads</div>
                <div style={{font:"500 11px 'Public Sans'",color:'#9AA6BC',marginTop:2}}>Every post uses your club's logo and colours</div>
              </button>
              <button onClick={()=>setBrandPrimary('event')} style={{flex:1,textAlign:'left',border:'1.5px solid',borderColor:branding.primary==='event'?'var(--b-primary)':'#D9E1EE',background:branding.primary==='event'?'var(--b-wash)':'#fff',borderRadius:9,padding:'10px 12px',cursor:'pointer'}}>
                <div style={{font:"800 12.5px 'Public Sans'",color:branding.primary==='event'?'var(--b-primary)':'#1A2942'}}>This event has its own branding</div>
                <div style={{font:"500 11px 'Public Sans'",color:'#9AA6BC',marginTop:2}}>e.g. a named fun run with its own logo</div>
              </button>
            </div>

            {branding.primary==='event' && (
              <div style={{border:'1px solid #E5EAF2',borderRadius:10,padding:'12px',background:'#FAFBFE',marginBottom:12,display:'flex',flexDirection:'column',gap:10}}>
                <div style={{display:'flex',alignItems:'center',gap:12}}>
                  {branding.eventLogoUrl && <img src={branding.eventLogoUrl} alt="" style={{width:36,height:36,objectFit:'contain',border:'1px solid #E5EAF2',borderRadius:7,background:'#fff',flex:'none'}}/>}
                  <label style={{display:'inline-flex',alignItems:'center',gap:6,cursor:'pointer',background:'#F0F4FA',border:'1px solid #D5DEF0',borderRadius:7,padding:'7px 11px',font:"700 11px 'Public Sans'",color:'var(--b-primary)',flex:'none'}}>
                    <PaperclipIcon/>{eventLogoBusy?'Uploading…':branding.eventLogoName?'Replace event logo':'Upload event logo'}
                    <input type="file" accept="image/*" style={{display:'none'}} disabled={eventLogoBusy} onChange={e=>uploadEventLogo(e.target.files[0])}/>
                  </label>
                  {branding.eventLogoName && !eventLogoBusy && <span style={{font:"500 11.5px 'Public Sans'",color:'#5A6473'}}>{branding.eventLogoName}</span>}
                </div>
                <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12}}>
                  <label style={labelStyle}><span style={lblText}>Event primary colour</span>
                    <div style={{display:'flex',gap:8,alignItems:'center'}}>
                      <input type="color" value={branding.eventPrimaryColor||'#17458F'} onChange={e=>brandField('eventPrimaryColor',e)} style={{width:38,height:36,border:'1px solid #D9E1EE',borderRadius:7,padding:2,cursor:'pointer'}}/>
                      <input value={branding.eventPrimaryColor||''} onChange={e=>brandField('eventPrimaryColor',e)} placeholder="optional" style={rowInput}/>
                    </div>
                  </label>
                  <label style={labelStyle}><span style={lblText}>Event secondary colour</span>
                    <div style={{display:'flex',gap:8,alignItems:'center'}}>
                      <input type="color" value={branding.eventSecondaryColor||'#F7A81B'} onChange={e=>brandField('eventSecondaryColor',e)} style={{width:38,height:36,border:'1px solid #D9E1EE',borderRadius:7,padding:2,cursor:'pointer'}}/>
                      <input value={branding.eventSecondaryColor||''} onChange={e=>brandField('eventSecondaryColor',e)} placeholder="optional" style={rowInput}/>
                    </div>
                  </label>
                </div>
              </div>
            )}

            <label style={labelStyle}>
              <span style={lblText}>{branding.primary==='event' ? 'Where should the club brand still appear?' : 'Any branding notes for whoever designs graphics?'}</span>
              <textarea value={branding.usageNote||''} onChange={e=>brandField('usageNote',e)} rows={3}
                placeholder={branding.primary==='event'
                  ? "e.g. Event logo is primary on all graphics; club logo appears small in the footer of every post, and is the only logo shown on the launch post and sponsor thank-you posts."
                  : "e.g. Use the event hashtag alongside the club's standard tags."}
                style={{...inputStyle,resize:'vertical'}}/>
              <span style={{font:"500 11.5px/1.5 'Public Sans'",color:'#9AA6BC'}}>Whoever designs your graphics reads this — it keeps every post consistent without you repeating instructions post by post.</span>
            </label>
          </div>

          {[['beneficiaries','3 · Beneficiaries'],['sponsors','4 · Sponsors']].map(([list,title])=>(
            <div key={list}>
              <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:10}}>
                <span style={sectionHdr}>{title}</span>
                <button className="hov-outline" onClick={()=>addRow(list)} style={addBtn}><PlusIcon/>Add</button>
              </div>
              <div style={{display:'flex',flexDirection:'column',gap:10}}>
                {d[list].map(r=>{
                  const docKey=`${list}_${r.id}`;
                  return (
                    <div key={r.id} style={{border:'1px solid #E5EAF2',borderRadius:10,padding:'12px',background:'#FAFBFE'}}>
                      <div style={{display:'grid',gridTemplateColumns:'1fr 1fr 34px',gap:8,alignItems:'center',marginBottom:8}}>
                        <input value={r.name} onChange={e=>rowField(list,r.id,'name',e)} placeholder="Name" style={rowInput}/>
                        <input value={r.url}  onChange={e=>rowField(list,r.id,'url', e)} placeholder="https://…" style={{...rowInput,color:'var(--b-primary)'}}/>
                        <button className="hov-red" onClick={()=>rmRow(list,r.id)} style={rmBtn}><TrashIcon/></button>
                      </div>
                      <textarea value={r.about||''} onChange={e=>rowField(list,r.id,'about',e)} rows={2}
                        placeholder={`About this ${list==='beneficiaries'?'beneficiary':'sponsor'} — included as AI context when they are mentioned in a topic`}
                        style={{width:'100%',border:'1px solid #E1E8F2',borderRadius:8,padding:'8px 10px',font:"500 12px/1.5 'Public Sans'",color:'#1A2942',background:'#fff',outline:'none',resize:'vertical',boxSizing:'border-box'}}/>
                      <div style={{font:"500 11px/1.4 'Public Sans'",color:'#B0B8C9',marginTop:4}}>A specific sentence beats a generic one — "great local charity" gives the AI nothing to work with.</div>
                      <div style={{marginTop:6,display:'flex',alignItems:'center',gap:8,flexWrap:'wrap'}}>
                        {(r.url || r.docUrl) && (
                          <button onClick={()=>draftAbout(list,r)} disabled={!!draftBusy[`about_${list}_${r.id}`]}
                            title="Drafts from the name + link/doc you've provided — not fact-checked, review before saving"
                            style={{display:'inline-flex',alignItems:'center',gap:5,border:'1px solid #D5DEF0',background:'#F0F4FA',borderRadius:7,padding:'5px 10px',font:"700 11px 'Public Sans'",color:'var(--b-primary)',cursor:draftBusy[`about_${list}_${r.id}`]?'default':'pointer',opacity:draftBusy[`about_${list}_${r.id}`]?.6:1,flex:'none'}}>
                            ✨ {draftBusy[`about_${list}_${r.id}`]?'Drafting…':'Draft with AI'}
                          </button>
                        )}
                        <label style={{display:'inline-flex',alignItems:'center',gap:5,cursor:'pointer',background:'#F0F4FA',border:'1px solid #D5DEF0',borderRadius:7,padding:'5px 10px',font:"700 11px 'Public Sans'",color:'var(--b-primary)',flex:'none'}}>
                          <PaperclipIcon/>{docBusy[docKey]?'Uploading…':r.docName?'Replace':'Attach doc'}
                          <input type="file" accept=".pdf,.doc,.docx,.txt" style={{display:'none'}} disabled={!!docBusy[docKey]} onChange={e=>uploadDoc(list,r.id,e.target.files[0])}/>
                        </label>
                        {r.docName && !docBusy[docKey] && (
                          <span style={{display:'inline-flex',alignItems:'center',gap:5,font:"500 11.5px 'Public Sans'",color:'#5A6473'}}>
                            <a href={r.docUrl} target="_blank" rel="noreferrer" style={{color:'var(--b-primary)',textDecoration:'none'}}>{r.docName}</a>
                            <button onClick={()=>rmDoc(list,r.id)} style={{border:'none',background:'none',cursor:'pointer',color:'#C0473F',font:"800 14px 'Public Sans'",padding:0,lineHeight:1}}>×</button>
                          </span>
                        )}
                        {r.logoUrl && <img src={r.logoUrl} alt="" style={{width:26,height:26,objectFit:'contain',border:'1px solid #E5EAF2',borderRadius:6,background:'#fff',flex:'none'}}/>}
                        <label style={{display:'inline-flex',alignItems:'center',gap:5,cursor:'pointer',background:'#F0F4FA',border:'1px solid #D5DEF0',borderRadius:7,padding:'5px 10px',font:"700 11px 'Public Sans'",color:'var(--b-primary)',flex:'none'}}>
                          <PaperclipIcon/>{logoRowBusy[docKey]?'Uploading…':r.logoName?'Replace logo':'Upload logo'}
                          <input type="file" accept="image/*" style={{display:'none'}} disabled={!!logoRowBusy[docKey]} onChange={e=>uploadRowLogo(list,r.id,e.target.files[0])}/>
                        </label>
                        {r.logoName && !logoRowBusy[docKey] && (
                          <span style={{display:'inline-flex',alignItems:'center',gap:5,font:"500 11.5px 'Public Sans'",color:'#5A6473'}}>
                            {r.logoName}
                            <button onClick={()=>rmRowLogo(list,r.id)} style={{border:'none',background:'none',cursor:'pointer',color:'#C0473F',font:"800 14px 'Public Sans'",padding:0,lineHeight:1}}>×</button>
                          </span>
                        )}
                      </div>
                      {r.logoName && <div style={{font:"500 11px/1.4 'Public Sans'",color:'#B0B8C9',marginTop:4}}>Composited onto the AI-generated image (bottom-right) whenever a post is about this {list==='beneficiaries'?'beneficiary':'sponsor'} — the AI itself is never asked to draw the logo.</div>}
                    </div>
                  );
                })}
              </div>
            </div>
          ))}

          <div>
            <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:10}}>
              <span style={sectionHdr}>5 · Reference Documents</span>
              <button className="hov-outline" onClick={()=>addRow('referenceDocs')} style={addBtn}><PlusIcon/>Add</button>
            </div>
            <div style={{font:"500 12px 'Public Sans'",color:'#6B7790',marginBottom:10}}>Source material for AI generation — link a webpage or upload a doc, optionally tag it to a pillar. Pillars can cite specific documents in their Reference Questionnaire below. Websites go out of date — prefer an uploaded document, and date any link you rely on.</div>
            <div style={{display:'flex',flexDirection:'column',gap:10}}>
              {(d.referenceDocs||[]).map(r=>{
                const docKey = `referenceDocs_${r.id}`;
                const fresh  = docFreshness(r);
                return (
                  <div key={r.id} style={{border:'1px solid #E5EAF2',borderRadius:10,padding:'12px',background:'#FAFBFE'}}>
                    <div style={{display:'grid',gridTemplateColumns:'1fr 1fr 34px',gap:8,alignItems:'center',marginBottom:8}}>
                      <input value={r.name} onChange={e=>rowField('referenceDocs',r.id,'name',e)} placeholder="Document name" style={rowInput}/>
                      <input value={r.url}  onChange={e=>rowField('referenceDocs',r.id,'url', e)} placeholder="https://… (optional)" style={{...rowInput,color:'var(--b-primary)'}}/>
                      <button className="hov-red" onClick={()=>removeSourceDoc('referenceDocs',r.id)} style={rmBtn}><TrashIcon/></button>
                    </div>
                    <div style={{display:'grid',gridTemplateColumns:'200px 1fr',gap:8,alignItems:'start'}}>
                      <select value={r.pillarId||''} onChange={e=>rowField('referenceDocs',r.id,'pillarId',e)} style={{...rowInput,cursor:'pointer'}}>
                        <option value="">General — not pillar-specific</option>
                        {d.pillars.map(p=><option key={p.id} value={p.id}>{p.label}</option>)}
                      </select>
                      <textarea value={r.note||''} onChange={e=>rowField('referenceDocs',r.id,'note',e)} rows={1}
                        placeholder="Note — what's authoritative in this doc"
                        style={{border:'1px solid #E1E8F2',borderRadius:8,padding:'8px 10px',font:"500 12px/1.5 'Public Sans'",color:'#1A2942',background:'#fff',outline:'none',resize:'vertical',boxSizing:'border-box'}}/>
                    </div>
                    {r.url && !r.docUrl && (
                      <div style={{display:'flex',alignItems:'center',gap:8,marginTop:8}}>
                        <label style={{display:'flex',alignItems:'center',gap:6}}>
                          <span style={{font:"700 10.5px 'Public Sans'",color:'#9AA6BC'}}>Checked on</span>
                          <input type="date" value={r.verifiedDate||''} onChange={e=>rowField('referenceDocs',r.id,'verifiedDate',e)}
                            style={{border:'1px solid #D9E1EE',borderRadius:7,padding:'5px 8px',font:"600 11.5px 'Public Sans'",color:'#1A2942',outline:'none'}}/>
                        </label>
                        {fresh && (
                          <span style={{display:'inline-flex',alignItems:'center',gap:4,font:"700 10.5px 'Public Sans'",color:fresh.level==='ok'?'#15803D':'#B45309',background:fresh.level==='ok'?'#E3F5E9':'#FCEEDA',borderRadius:6,padding:'3px 8px'}}>
                            {fresh.level==='ok'?'✓':'⚠'} {fresh.text}
                          </span>
                        )}
                      </div>
                    )}
                    <div style={{marginTop:6,display:'flex',alignItems:'center',gap:8,flexWrap:'wrap'}}>
                      <label style={{display:'inline-flex',alignItems:'center',gap:5,cursor:'pointer',background:'#F0F4FA',border:'1px solid #D5DEF0',borderRadius:7,padding:'5px 10px',font:"700 11px 'Public Sans'",color:'var(--b-primary)',flex:'none'}}>
                        <PaperclipIcon/>{docBusy[docKey]?'Uploading…':r.docName?'Replace':'Attach doc'}
                        <input type="file" accept=".pdf,.doc,.docx,.txt" style={{display:'none'}} disabled={!!docBusy[docKey]} onChange={e=>uploadDoc('referenceDocs',r.id,e.target.files[0])}/>
                      </label>
                      {r.docName && !docBusy[docKey] && (
                        <span style={{display:'inline-flex',alignItems:'center',gap:5,font:"500 11.5px 'Public Sans'",color:'#5A6473'}}>
                          <a href={r.docUrl} target="_blank" rel="noreferrer" style={{color:'var(--b-primary)',textDecoration:'none'}}>{r.docName}</a>
                          <button onClick={()=>rmDoc('referenceDocs',r.id)} style={{border:'none',background:'none',cursor:'pointer',color:'#C0473F',font:"800 14px 'Public Sans'",padding:0,lineHeight:1}}>×</button>
                        </span>
                      )}
                    </div>
                  </div>
                );
              })}
              {(!d.referenceDocs || d.referenceDocs.length===0) && (
                <div style={{font:"500 12px 'Public Sans'",color:'#9AA6BC',padding:'8px 0'}}>No reference documents yet.</div>
              )}
            </div>
          </div>

          <div>
            <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:10}}>
              <span style={sectionHdr}>6 · Content Pillars</span>
              <button className="hov-outline" onClick={()=>addRow('pillars')} style={addBtn}><PlusIcon/>Add</button>
            </div>
            <div style={{font:"500 12px 'Public Sans'",color:'#6B7790',marginBottom:10}}>Each pillar can optionally carry a description, when-to-post timing, and a Reference Questionnaire that grounds AI generation in sourced facts.</div>
            <div style={{display:'flex',flexDirection:'column',gap:10}}>
              {d.pillars.map(r=>{
                const q      = r.questionnaire || {};
                const filled = qFilledCount(q);
                const isOpen = expandedPillars.has(r.id);
                return (
                  <div key={r.id} style={{border:'1px solid #E5EAF2',borderRadius:10,padding:'12px',background:'#FAFBFE'}}>
                    <div style={{display:'grid',gridTemplateColumns:'18px 1fr 34px',gap:10,alignItems:'center'}}>
                      <span style={{width:14,height:14,borderRadius:'50%',background:r.color,flex:'none'}}/>
                      <input value={r.label} onChange={e=>rowField('pillars',r.id,'label',e)} placeholder="Pillar name" style={{...rowInput,font:"600 12.5px 'Public Sans'"}}/>
                      <button className="hov-red" onClick={()=>rmRow('pillars',r.id)} style={rmBtn}><TrashIcon/></button>
                    </div>
                    <div style={{display:'flex',alignItems:'flex-start',gap:8,marginTop:8}}>
                      <textarea value={r.description||''} onChange={e=>rowField('pillars',r.id,'description',e)} placeholder="One-line description — what this pillar covers" rows={1}
                        style={{...rowInput,font:"500 12px/1.4 'Public Sans'",flex:1,resize:'vertical',minHeight:34,overflow:'hidden'}}/>
                      {(q.sourceDocIds||[]).length > 0 && (
                        <button onClick={()=>draftPillarDescription(r)} disabled={!!draftBusy[`pdesc_${r.id}`]}
                          title="Drafts from this pillar's linked source documents — not fact-checked, review before saving"
                          style={{display:'inline-flex',alignItems:'center',gap:5,border:'1px solid #D5DEF0',background:'#F0F4FA',borderRadius:7,padding:'8px 10px',font:"700 11px 'Public Sans'",color:'var(--b-primary)',cursor:draftBusy[`pdesc_${r.id}`]?'default':'pointer',opacity:draftBusy[`pdesc_${r.id}`]?.6:1,flex:'none',whiteSpace:'nowrap'}}>
                          ✨ {draftBusy[`pdesc_${r.id}`]?'Drafting…':'Draft with AI'}
                        </button>
                      )}
                    </div>
                    <div style={{display:'flex',alignItems:'center',gap:6,flexWrap:'wrap',marginTop:8}}>
                      <span style={{font:"700 10.5px 'Public Sans'",color:'#9AA6BC',marginRight:2}}>WHEN:</span>
                      {TIMING_TAGS.map(([tag,tlabel])=>{
                        const on = (r.timing||[]).includes(tag);
                        return (
                          <button key={tag} onClick={()=>togglePillarTiming(r.id,tag)}
                            style={{padding:'4px 10px',borderRadius:7,border:'1.5px solid',borderColor:on?r.color:'#D9E1EE',background:on?r.bg:'#F7F9FC',color:on?r.color:'#6B7790',font:"700 11px 'Public Sans'",cursor:'pointer'}}>
                            {tlabel}
                          </button>
                        );
                      })}
                    </div>
                    <button onClick={()=>togglePillarExpand(r.id)}
                      style={{marginTop:9,border:'none',background:'none',cursor:'pointer',color:'var(--b-primary)',font:"700 11.5px 'Public Sans'",padding:0,display:'inline-flex',alignItems:'center',gap:6}}>
                      {isOpen ? '▾' : '▸'} Reference Questionnaire <span style={{color:'#9AA6BC',fontWeight:500}}>— optional</span>
                      {filled>0 && <span style={{font:"800 10px 'Public Sans'",color:'#15803D',background:'#E3F5E9',borderRadius:999,padding:'2px 7px'}}>{filled}/{QUESTIONNAIRE_KEYS.length} filled</span>}
                    </button>
                    <div style={{font:"500 11.5px/1.5 'Public Sans'",color:'#9AA6BC',marginTop:4}}>Worth filling in if this pillar carries real numbers, names or values that must stay accurate (a prize amount, a beneficiary split). Skip it for pillars like "Volunteers" or "Stories" that don't need it.</div>
                    {isOpen && (
                      <div style={{marginTop:10,paddingTop:10,borderTop:'1px dashed #E1E8F2',display:'flex',flexDirection:'column',gap:8}}>
                        <div style={{paddingBottom:10,borderBottom:'1px dashed #E1E8F2'}}>
                          <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',flexWrap:'wrap',gap:8}}>
                            <span style={lblText}>Sources <span style={{fontWeight:500,color:'#9AA6BC'}}>— add URLs/docs, then generate A–G below with AI</span></span>
                            <button onClick={()=>draftQuestionnaire(r)} disabled={!(q.sourceDocIds||[]).length || !!draftBusy[`qgen_${r.id}`]}
                              title="Fills in A–G from the sources checked below — not fact-checked, review before saving"
                              style={{display:'inline-flex',alignItems:'center',gap:5,border:'1px solid #D5DEF0',background:(q.sourceDocIds||[]).length?'#F0F4FA':'#F4F5F8',borderRadius:7,padding:'7px 10px',font:"700 11px 'Public Sans'",color:(q.sourceDocIds||[]).length?'var(--b-primary)':'#B7C0D1',cursor:(q.sourceDocIds||[]).length&&!draftBusy[`qgen_${r.id}`]?'pointer':'default',opacity:draftBusy[`qgen_${r.id}`]?.6:1,flex:'none',whiteSpace:'nowrap'}}>
                              ✨ {draftBusy[`qgen_${r.id}`]?'Generating…':'Generate with AI'}
                            </button>
                          </div>
                          <div style={{display:'flex',flexDirection:'column',gap:5,marginTop:8}}>
                            {(d.moreInfoDocs||[]).length===0 && (d.referenceDocs||[]).length===0 && <span style={{font:"500 11.5px 'Public Sans'",color:'#9AA6BC'}}>No sources yet — add a URL or document below.</span>}
                            {[...(d.moreInfoDocs||[]).map(x=>({...x,_list:'moreInfoDocs'})), ...(d.referenceDocs||[]).map(x=>({...x,_list:'referenceDocs'}))].map(doc=>{
                              const checked = (q.sourceDocIds||[]).includes(doc.id);
                              return (
                                <div key={doc.id} style={{display:'flex',alignItems:'center',gap:7}}>
                                  <label style={{display:'flex',alignItems:'center',gap:7,cursor:'pointer',flex:1}}>
                                    <input type="checkbox" checked={checked} onChange={()=>toggleSourceDoc(r.id,doc.id)}/>
                                    <span style={{font:"500 12px 'Public Sans'",color:'#1A2942'}}>{doc.name||'Untitled document'}</span>
                                  </label>
                                  <button onClick={()=>removeSourceDoc(doc._list,doc.id)} title="Remove this document" style={{border:'none',background:'none',cursor:'pointer',color:'#C0473F',font:"800 14px 'Public Sans'",padding:0,lineHeight:1,flex:'none'}}>×</button>
                                </div>
                              );
                            })}
                          </div>
                          <div style={{display:'flex',alignItems:'center',gap:8,flexWrap:'wrap',marginTop:8}}>
                            <input value={pillarUrlDraft[r.id]||''} onChange={e=>setPillarUrlDraft(s=>({...s,[r.id]:e.target.value}))}
                              onKeyDown={e=>{ if(e.key==='Enter'){ e.preventDefault(); const url=(pillarUrlDraft[r.id]||'').trim(); if(!url) return; addPillarSourceDoc(r.id,{name:url,url}); setPillarUrlDraft(s=>({...s,[r.id]:''})); } }}
                              placeholder="https://… add a website" style={{...rowInput,flex:1,minWidth:180}}/>
                            <button onClick={()=>{ const url=(pillarUrlDraft[r.id]||'').trim(); if(!url) return; addPillarSourceDoc(r.id,{name:url,url}); setPillarUrlDraft(s=>({...s,[r.id]:''})); }}
                              style={{border:'1px solid #D5DEF0',background:'#F0F4FA',borderRadius:7,padding:'8px 10px',font:"700 11px 'Public Sans'",color:'var(--b-primary)',cursor:'pointer',flex:'none',whiteSpace:'nowrap'}}>+ Add URL</button>
                            <label style={{display:'inline-flex',alignItems:'center',gap:5,cursor:'pointer',background:'#F0F4FA',border:'1px solid #D5DEF0',borderRadius:7,padding:'8px 10px',font:"700 11px 'Public Sans'",color:'var(--b-primary)',flex:'none'}}>
                              <PaperclipIcon/>Attach doc
                              <input type="file" accept=".pdf,.doc,.docx,.txt" style={{display:'none'}} onChange={e=>{ const file=e.target.files[0]; if(!file) return; const newId=addPillarSourceDoc(r.id,{name:file.name}); uploadDoc('referenceDocs',newId,file); }}/>
                            </label>
                          </div>
                        </div>
                        <label style={labelStyle}><span style={lblText}>A · Facts &amp; figures <span style={{fontWeight:500,color:'#9AA6BC'}}>— with source</span></span>
                          <textarea value={q.facts||''} onChange={e=>qField(r.id,'facts',e)} rows={2}
                            placeholder="e.g. Entry fees: Adult $45, Child $30, Family $120 (Source: 2026 Event Summary Document §2)"
                            style={{...inputStyle,resize:'vertical'}}/></label>
                        <label style={labelStyle}><span style={lblText}>B · The hook</span>
                          <textarea value={q.hook||''} onChange={e=>qField(r.id,'hook',e)} rows={2}
                            placeholder="e.g. Early bird pricing ends soon - a simple, time-pressure angle"
                            style={{...inputStyle,resize:'vertical'}}/></label>
                        <label style={labelStyle}><span style={lblText}>C · Sub-entities to rotate <span style={{fontWeight:500,color:'#9AA6BC'}}>— one per line</span></span>
                          <textarea value={q.subEntities||''} onChange={e=>qField(r.id,'subEntities',e)} rows={3}
                            placeholder={"e.g. Local Food Bank\nYouth Mentoring Program\nCommunity Garden"}
                            style={{...inputStyle,resize:'vertical'}}/></label>
                        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:8}}>
                          <label style={labelStyle}><span style={lblText}>D · Call to action</span>
                            <input value={q.cta||''} onChange={e=>qField(r.id,'cta',e)} placeholder="e.g. Register now at yourevent.org.au" style={inputStyle}/></label>
                          <label style={labelStyle}><span style={lblText}>F · Deadline / trigger</span>
                            <input value={q.deadline||''} onChange={e=>qField(r.id,'deadline',e)} placeholder="e.g. Push hardest in the final 2 weeks before the event" style={inputStyle}/></label>
                        </div>
                        <label style={labelStyle}><span style={lblText}>E · Tone deviation</span>
                          <input value={q.toneNote||''} onChange={e=>qField(r.id,'toneNote',e)} placeholder="e.g. Playful and competitive — different from the campaign's usual warm tone" style={inputStyle}/></label>
                        <label style={labelStyle}><span style={lblText}>G · Off-limits</span>
                          <textarea value={q.avoid||''} onChange={e=>qField(r.id,'avoid',e)} rows={2}
                            placeholder="e.g. Don't state a specific dollar amount per beneficiary — the split isn't fixed"
                            style={{...inputStyle,resize:'vertical'}}/></label>
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          </div>

          <div>
            <div style={sectionHdr}>7 · Week Plan</div>
            <div style={{display:'flex',flexDirection:'column',gap:14}}>
              <div style={{display:'flex',gap:8,alignItems:'center'}}>
                <span style={{...lblText,width:120}}>Number of weeks</span>
                {stepper('numWeeks',1,16)}
              </div>
              <div>
                <div style={{...lblText,marginBottom:8}}>
                  Preferred posting days
                  <span style={{font:"600 11px 'Public Sans'",color:'#9AA6BC',marginLeft:8}}>— {prefDays.length*(d.postsPerDay||1)} post{prefDays.length*(d.postsPerDay||1)!==1?'s':''} per week</span>
                </div>
                <div style={{display:'flex',gap:6,flexWrap:'wrap'}}>
                  {DAY_NAMES.map((label,i) => {
                    const on = prefDays.includes(i);
                    return (
                      <button key={i} onClick={()=>toggleDay(i)} style={{padding:'8px 13px',borderRadius:9,border:'1.5px solid',borderColor:on?'var(--b-primary)':'#D9E1EE',background:on?'var(--b-wash)':'#F7F9FC',color:on?'var(--b-primary)':'#6B7790',font:"700 12.5px 'Public Sans'",cursor:'pointer',transition:'all .12s'}}>
                        {label}
                      </button>
                    );
                  })}
                </div>
                <div style={{display:'flex',gap:8,alignItems:'center',marginTop:10}}>
                  <span style={{...lblText,width:120}}>Posts per day</span>
                  {stepper('postsPerDay',1,3)}
                </div>
                <div style={{font:"500 11.5px 'Public Sans'",color:'#9AA6BC',marginTop:7}}>New posts will be created on these days. Existing posts keep their current dates unless you move them in the Calendar.</div>
              </div>
              <div style={{display:'flex',gap:8,alignItems:'center'}}>
                <span style={{...lblText,width:120}}>Default post time</span>
                <input type="time" value={d.defaultPostTime||'19:30'} onChange={e=>setDraft(dd=>({...dd,defaultPostTime:e.target.value}))}
                  style={{border:'1px solid #D9E1EE',borderRadius:8,padding:'7px 9px',font:"600 12.5px 'Public Sans'",color:'#1A2942',background:'#fff',outline:'none'}}/>
                <select value={d.timeZone||CCIntl.timezone()} onChange={e=>setDraft(dd=>({...dd,timeZone:e.target.value}))}
                  style={{border:'1px solid #D9E1EE',borderRadius:8,padding:'7px 9px',font:"600 12.5px 'Public Sans'",color:'#1A2942',background:'#fff',outline:'none'}}>
                  {CCIntl.allZones().map(z=><option key={z[0]} value={z[0]}>{z[1]} ({_tzAbbr(z[0])})</option>)}
                  {!CCIntl.allZones().some(z=>z[0]===(d.timeZone||CCIntl.timezone())) && <option value={d.timeZone}>{d.timeZone}</option>}
                </select>
              </div>
              <div style={{font:"500 11.5px 'Public Sans'",color:'#9AA6BC',marginLeft:128}}>Post times are in this time zone. Auto-publish waits until this time on each post's day, unless the post has its own time in Post Brief.</div>
            </div>
          </div>

          <div>
            <div style={sectionHdr}>8 · Content Exclusions</div>
            <div style={{font:"500 12px 'Public Sans'",color:'#6B7790',marginBottom:10}}>Phrases, angles or facts flagged as incorrect during topic generation. Sent with every generation request to guide the AI.</div>
            {d.exclusions && d.exclusions.length > 0 ? (
              <div style={{display:'flex',flexDirection:'column',gap:8}}>
                {d.exclusions.map(e=>(
                  <div key={e.id} style={{display:'flex',gap:10,alignItems:'flex-start',padding:'10px 12px',border:'1px solid #FEE2E2',borderRadius:9,background:'#FFF8F8'}}>
                    <div style={{flex:1,minWidth:0}}>
                      <div style={{font:"600 12.5px 'Public Sans'",color:'#1A2942',lineHeight:1.4}}>{e.text}</div>
                      {e.note && <div style={{font:"500 11.5px 'Public Sans'",color:'#C0473F',marginTop:3}}>{e.note}</div>}
                      {e.pillarId && <div style={{font:"500 11px 'Public Sans'",color:'#9AA6BC',marginTop:3}}>Pillar: {(d.pillars||[]).find(p=>p.id===e.pillarId)?.label||e.pillarId}</div>}
                    </div>
                    <button className="hov-red" onClick={()=>setDraft(d=>({...d,exclusions:d.exclusions.filter(x=>x.id!==e.id)}))} style={rmBtn}><TrashIcon/></button>
                  </div>
                ))}
              </div>
            ) : (
              <div style={{font:"500 12px 'Public Sans'",color:'#9AA6BC',padding:'8px 0'}}>No exclusions yet — use the Exclude button in Topic Suggestions to build this list over time.</div>
            )}
          </div>

        </div>

        <div style={{padding:'14px 22px',borderTop:'1px solid var(--b-bg)',display:'flex',justifyContent:'space-between',gap:10,background:'#FAFBFE'}}>
          <button className="hov-outline" onClick={onNewCampaign} style={{background:'#fff',color:'var(--b-primary)',border:'1px solid #B8CBEC',borderRadius:9,padding:'10px 16px',font:"800 13px 'Public Sans'",cursor:'pointer',display:'inline-flex',alignItems:'center',gap:6}}>
            <PlusIcon sz={13}/>New Campaign
          </button>
          <div style={{display:'flex',gap:10}}>
            <button className="hov-outline" onClick={onClose} style={{background:'#fff',color:'#6B7790',border:'1px solid #D9E1EE',borderRadius:9,padding:'10px 18px',font:"800 13px 'Public Sans'",cursor:'pointer'}}>Cancel</button>
            <button className="hov-blue" onClick={onSave} style={{background:'var(--b-primary)',color:'#fff',border:'none',borderRadius:9,padding:'10px 22px',font:"800 13px 'Public Sans'",cursor:'pointer'}}>Save & rebuild</button>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ── Admin Settings modal ─────────────────────────────────────────────────────
   Split out of Campaign Setup so day-to-day content work (branding, pillars,
   week plan…) isn't mixed in with technical integration settings and Team
   Roles — same Admin/Super-Admin gate as Setup (caps.setup), just decluttered.
   Shares the same draft object as SetupModal (both edit the one campaign
   config), so Save & rebuild behaves identically from either modal. ───────── */
/* ── Socials: connect Facebook by logging in, then pick the Page this campaign posts to ─────────────────
   The Page tokens stay on the server; nothing here is a Page ID, an Instagram ID or a webhook to paste. ── */
function SocialsPicker({d, setDraft}) {
  const [info, setInfo]   = React.useState(null);        // { enabled, canConnect, connections }
  const [err,  setErr]    = React.useState('');
  const [busy, setBusy]   = React.useState(false);
  const load = () => _api('GET', '/club/social/connections').then(setInfo).catch(e => setErr((e && e.message) || 'Could not load your connected Pages'));
  React.useEffect(() => { load(); }, []);
  const sectionHdr = {font:"800 11px 'Public Sans'",letterSpacing:'.08em',textTransform:'uppercase',color:'#8A94A8',marginBottom:8};
  const connect = async () => {
    setBusy(true); setErr('');
    try { const r = await _api('POST', '/club/social/connect'); window.location.assign(r.url); }
    catch (e) { setErr((e && e.message) || 'Could not start the Facebook login'); setBusy(false); }
  };
  const disconnect = async c => {
    if (!window.confirm('Disconnect ' + c.pageName + '? Posts for campaigns that use it will stop publishing until it is connected again.')) return;
    try { await _api('DELETE', '/club/social/connections/' + c.id); load(); } catch (e) { setErr((e && e.message) || 'Could not disconnect'); }
  };
  const choose = c => setDraft(dd => ({...dd, facebookPage: c.pageName, facebookPageId: c.pageId, facebookPageUrl: c.pageUrl || dd.facebookPageUrl || '', instagramAccountId: c.igId || ''}));
  const none = () => setDraft(dd => ({...dd, facebookPage: '', facebookPageId: '', facebookPageUrl: '', instagramAccountId: ''}));
  const conns = (info && info.connections) || [];
  const chosen = conns.find(c => c.pageId === d.facebookPageId);
  const btn = {border:'1px solid var(--b-primary)',background:'var(--b-primary)',color:'#fff',borderRadius:9,padding:'9px 16px',font:"800 12.5px 'Public Sans'",cursor:'pointer'};
  return (<>
    <div>
      <div style={sectionHdr}>Facebook and Instagram</div>
      {!info && !err && <div style={{font:"500 12.5px 'Public Sans'",color:'#9AA6BC'}}>Loading…</div>}
      {err && <div style={{font:"700 12px 'Public Sans'",color:'#B91C1C',marginBottom:8}}>{err}</div>}
      {info && !info.enabled && (
        <div style={{font:"500 12.5px/1.55 'Public Sans'",color:'#6B7790',background:'#F7F9FC',border:'1px solid #E5EAF2',borderRadius:10,padding:'12px 14px'}}>
          Connecting Facebook is being set up for Clubcraft. Until it is switched on, copy each caption and picture and use <b>Mark Posted</b> once it is up.
        </div>
      )}
      {info && info.enabled && (<>
        <div style={{font:"500 12.5px/1.55 'Public Sans'",color:'#6B7790',marginBottom:10}}>
          Log in to Facebook once and choose the Pages you manage. Their linked Instagram accounts come with them. Then pick the Page this campaign posts to.
        </div>
        <details style={{border:'1px solid #D9E1EE',background:'#F7F9FC',borderRadius:10,padding:'10px 13px',marginBottom:12}} open={conns.length === 0}>
          <summary style={{font:"800 12.5px 'Public Sans'",color:'var(--b-primary-deep)',cursor:'pointer'}}>How to set up Facebook and Instagram</summary>
          <div style={{font:"500 12.5px/1.6 'Public Sans'",color:'#4A566B',marginTop:8}}>
            <div style={{font:"800 12px 'Public Sans'",color:'var(--b-primary-deep)'}}>Before you click Connect</div>
            <ol style={{margin:'4px 0 10px',paddingLeft:20}}>
              <li>Your club needs a <b>Facebook Page</b> (not a personal profile). You must be an <b>admin</b> of that Page.</li>
              <li>For Instagram, the account must be a <b>Business or Creator</b> account. In the Instagram app: Settings, Account type and tools, Switch to professional account.</li>
              <li>Link Instagram to the Page: on Facebook, open the Page, Settings, <b>Linked accounts</b> (or Linked accounts in Meta Business Suite), then connect Instagram.</li>
            </ol>
            <div style={{font:"800 12px 'Public Sans'",color:'var(--b-primary-deep)'}}>Then</div>
            <ol style={{margin:'4px 0 10px',paddingLeft:20}}>
              <li>Click <b>Connect Facebook</b> below and log in as the Page admin.</li>
              <li>Choose <b>current Pages only</b>, then tick your Page and its Instagram account.</li>
              <li>Allow everything it asks for. Clubcraft can only post as the Page, never as you.</li>
              <li>Back here, choose the Page for this campaign and press <b>Save</b>.</li>
            </ol>
            <div style={{font:"800 12px 'Public Sans'",color:'var(--b-primary-deep)'}}>If something goes wrong</div>
            <ul style={{margin:'4px 0 0',paddingLeft:20}}>
              <li>Facebook says the app is not available or you lack access: Clubcraft's Facebook connection is still in testing, so ask Clubcraft support (ops@clubcraft.org) to add your Facebook account.</li>
              <li>No Instagram shown under the Page: the account is not Business or Creator, or is not linked to the Page.</li>
              <li>"Needs reconnecting" appears later: your Facebook password or Page access changed. Press Connect Facebook again.</li>
            </ul>
          </div>
        </details>
        {conns.length === 0 && <div style={{font:"600 12.5px 'Public Sans'",color:'#9AA6BC',marginBottom:10}}>No Pages connected yet.</div>}
        <div style={{display:'flex',flexDirection:'column',gap:8,marginBottom:12}}>
          {conns.map(c => (
            <label key={c.id} style={{display:'flex',gap:10,alignItems:'flex-start',border:'1px solid '+(d.facebookPageId===c.pageId?'var(--b-primary)':'#D9E1EE'),background:d.facebookPageId===c.pageId?'#F3F7FD':'#fff',borderRadius:10,padding:'10px 13px',cursor:'pointer'}}>
              <input type="radio" name="fbpage" checked={d.facebookPageId===c.pageId} onChange={()=>choose(c)} style={{marginTop:3}}/>
              <span style={{flex:1}}>
                <span style={{font:"800 13px 'Public Sans'",color:'var(--b-primary-deep)',display:'block'}}>{c.pageName}</span>
                <span style={{font:"500 11.5px 'Public Sans'",color:'#6B7790',display:'block'}}>{c.igName ? 'Instagram: @'+c.igName : 'No Instagram account linked to this Page'}</span>
                {c.status==='broken' && <span style={{font:"700 11.5px 'Public Sans'",color:'#B91C1C',display:'block',marginTop:2}}>Needs reconnecting: {c.error || 'Facebook asked for a new login'}. Use Connect Facebook again.</span>}
              </span>
              {info.canConnect && <button type="button" onClick={e=>{e.preventDefault();disconnect(c);}} style={{border:'1px solid #F0D6D6',background:'#FFF5F5',color:'#C0473F',borderRadius:7,padding:'4px 9px',font:"700 11px 'Public Sans'",cursor:'pointer'}}>Disconnect</button>}
            </label>
          ))}
          {d.facebookPageId && !chosen && (
            <div style={{font:"600 12px/1.5 'Public Sans'",color:'#B45309',background:'#FFF8EC',border:'1px solid #F3DDB0',borderRadius:10,padding:'10px 13px'}}>
              This campaign points at a Facebook Page ({d.facebookPage || d.facebookPageId}) that is not connected here, so it cannot publish. Connect it, or pick another Page.
            </div>
          )}
          {d.facebookPageId && <button type="button" onClick={none} style={{alignSelf:'flex-start',background:'none',border:'none',color:'#6B7790',font:"600 12px 'Public Sans'",cursor:'pointer',textDecoration:'underline',padding:0}}>Don't post to Facebook from this campaign</button>}
        </div>
        {info.canConnect
          ? <button type="button" onClick={connect} disabled={busy} style={{...btn,opacity:busy?0.6:1}}>{busy?'Opening Facebook…':(conns.length?'Connect another Page / Reconnect':'Connect Facebook')}</button>
          : <div style={{font:"500 12px 'Public Sans'",color:'#9AA6BC'}}>Only a club admin can connect Facebook.</div>}
        <div style={{font:"500 11.5px/1.5 'Public Sans'",color:'#9AA6BC',marginTop:8}}>Save to use the chosen Page for this campaign. Posts go out as the Page, using the logged-in admin's permission.</div>
      </>)}
    </div>
  </>);
}

function AdminSettingsModal({draft, setDraft, members, onInvite, onClose, onSave, section}) {
  const d = draft;
  const [inviteEmail, setInviteEmail] = React.useState('');
  const [inviteRole,  setInviteRole]  = React.useState('Read');

  const field   = (key,e) => setDraft(d=>({...d,[key]:e.target.value}));
  const setRole = (memberId, role) => setDraft(d=>({...d, memberRoles:{...d.memberRoles,[memberId]:role}}));

  const labelStyle = {display:'flex',flexDirection:'column',gap:5};
  const lblText    = {font:"700 11.5px 'Public Sans'",color:'#6B7790'};
  const inputStyle = {border:'1px solid #D9E1EE',borderRadius:8,padding:'9px 11px',font:"500 13px 'Public Sans'",color:'#1A2942',outline:'none',width:'100%'};
  const sectionHdr = {font:"800 11px 'Public Sans'",letterSpacing:'.05em',textTransform:'uppercase',color:'var(--b-primary)',marginBottom:10};

  return (
    <div className="modal-overlay">
      <div style={{width:'100%',maxWidth:560,background:'#fff',borderRadius:18,boxShadow:'0 24px 60px rgba(22,40,70,.35)',overflow:'hidden'}}>
        <div style={{padding:'18px 22px',borderTop:'3px solid var(--b-primary)',borderBottom:'1px solid var(--b-bg)',display:'flex',alignItems:'center',justifyContent:'space-between'}}>
          <div>
            <div style={{font:"800 18px 'Public Sans'",color:'var(--b-primary-deep)'}}>{section==='socials'?'Socials':'Team'}</div>
            <div style={{font:"500 12.5px 'Public Sans'",color:'#6B7790',marginTop:2}}>{section==='socials'?'The Facebook Page and Instagram account this campaign posts to. Admins only.':'Who works on this campaign, and what each person can do. Admins only.'}</div>
          </div>
          <button className="hov-outline" onClick={onClose} style={{width:34,height:34,display:'grid',placeItems:'center',border:'none',background:'#F1F4F9',borderRadius:9,cursor:'pointer',color:'#5A6473'}}><XIcon/></button>
        </div>

        <div style={{padding:'20px 22px',maxHeight:'70vh',overflowY:'auto',display:'flex',flexDirection:'column',gap:22}}>

          {section==='socials' && <SocialsPicker d={d} setDraft={setDraft}/>}

          {section!=='socials' && (          <div>
            <div style={sectionHdr}>Team Roles</div>
            <div style={{font:"500 12px 'Public Sans'",color:'#6B7790',marginBottom:10}}>Only people already on this campaign are listed here. To add someone, first give them a place on the club's plan in My club, then pick their level for this campaign below.</div>
            <div style={{display:'flex',flexDirection:'column',gap:10,marginBottom:14}}>
              {Object.keys(d.memberRoles||{}).length===0 && <div style={{font:"500 12.5px 'Public Sans'",color:'#9AA6BC'}}>Just you so far.</div>}
              {Object.keys(d.memberRoles||{}).map(uid=>{
                const role = d.memberRoles[uid]||'Read';
                const rc   = ROLE_COLOR[role]||ROLE_COLOR.Read;
                const m    = members.find(x=>x.id===uid);
                return (
                  <div key={uid} style={{display:'flex',alignItems:'center',gap:12}}>
                    <div style={{width:34,height:34,borderRadius:'50%',display:'grid',placeItems:'center',font:"800 11px 'Public Sans'",color:'#fff',background:m?m.avatarColor:'#8A94A8',flex:'none'}}>{m?m.initials:'?'}</div>
                    <span style={{flex:1,font:"600 13px 'Public Sans'",color:'#1A2942'}}>{m?m.name:uid}</span>
                    <select value={role} onChange={e=>setRole(uid,e.target.value)} style={{border:'1px solid #D9E1EE',borderRadius:8,padding:'6px 9px',font:"700 12px 'Public Sans'",color:rc.color,background:rc.bg,outline:'none',cursor:'pointer'}}>
                      {SD.ROLES.map(r=><option key={r} value={r} style={{background:'#fff',color:'#1A2942'}}>{r}</option>)}
                    </select>
                  </div>
                );
              })}
            </div>
            {(members||[]).filter(x=>!(d.memberRoles||{})[x.id]).length>0 && (
              <div style={{display:'flex',gap:8,alignItems:'flex-end',border:'1px dashed #D9E1EE',borderRadius:10,padding:'12px'}}>
                <label style={{...labelStyle,flex:1}}><span style={lblText}>Add a club member</span>
                  <select value={inviteEmail} onChange={e=>setInviteEmail(e.target.value)} style={inputStyle}>
                    <option value="">Choose a person…</option>
                    {members.filter(x=>!(d.memberRoles||{})[x.id]).map(x=><option key={x.id} value={x.id}>{x.name}</option>)}
                  </select>
                </label>
                <select value={inviteRole} onChange={e=>setInviteRole(e.target.value)} style={{border:'1px solid #D9E1EE',borderRadius:8,padding:'9px 10px',font:"700 12.5px 'Public Sans'",color:'#1A2942',outline:'none',cursor:'pointer'}}>
                  {SD.ROLES.map(r=><option key={r} value={r}>{r}</option>)}
                </select>
                <button onClick={()=>{ if(inviteEmail){ setRole(inviteEmail, inviteRole); setInviteEmail(''); } }} disabled={!inviteEmail} style={{background:'var(--b-primary)',color:'#fff',border:'none',borderRadius:8,padding:'9px 16px',font:"800 12.5px 'Public Sans'",cursor:'pointer',opacity:inviteEmail?1:0.5}}>Add</button>
              </div>
            )}
          </div>)}

        </div>

        <div style={{padding:'16px 22px',borderTop:'1px solid var(--b-bg)',display:'flex',justifyContent:'flex-end',gap:10}}>
          <button className="hov-outline" onClick={onClose} style={{background:'#fff',color:'#6B7790',border:'1px solid #D9E1EE',borderRadius:9,padding:'10px 18px',font:"800 13px 'Public Sans'",cursor:'pointer'}}>Cancel</button>
          <button className="hov-blue" onClick={onSave} style={{background:'var(--b-primary)',color:'#fff',border:'none',borderRadius:9,padding:'10px 22px',font:"800 13px 'Public Sans'",cursor:'pointer'}}>Save & rebuild</button>
        </div>
      </div>
    </div>
  );
}

/* ── Request Campaign modal ──────────────────────────────────────────────────
   Name only, per the approval flow — everything else (dates, pillars, roles)
   is filled in via Setup once a Super Admin approves it and the requester
   becomes Admin. ─────────────────────────────────────────────────────────── */
function RequestCampaignModal({onClose, onRequest}) {
  const [name, setName] = React.useState('');
  const [weeks, setWeeks] = React.useState(4);
  const [days, setDays]   = React.useState([1, 4]);
  const [perDay, setPerDay] = React.useState(1);
  const toggle = i => setDays(ds => ds.includes(i) ? (ds.length > 1 ? ds.filter(x => x !== i) : ds) : [...ds, i].sort((a, b) => a - b));
  const submit = () => { if (name.trim()) onRequest(name.trim(), { numWeeks: weeks, prefDays: days, postsPerDay: perDay }); };
  return (
    <div className="modal-overlay" style={{zIndex:60}}>
      <div style={{width:'100%',maxWidth:440,background:'#fff',borderRadius:16,boxShadow:'0 20px 50px rgba(22,40,70,.35)',overflow:'hidden',marginTop:80}}>
        <div style={{padding:'16px 20px',borderTop:'3px solid var(--b-accent)',borderBottom:'1px solid var(--b-bg)',display:'flex',alignItems:'center',justifyContent:'space-between'}}>
          <div style={{font:"800 16px 'Public Sans'",color:'var(--b-primary-deep)'}}>New campaign</div>
          <button onClick={onClose} style={{width:30,height:30,display:'grid',placeItems:'center',border:'none',background:'#F1F4F9',borderRadius:8,cursor:'pointer',color:'#5A6473'}}><XIcon sz={15}/></button>
        </div>
        <div style={{padding:'18px 20px',display:'flex',flexDirection:'column',gap:14}}>
          <label style={{display:'flex',flexDirection:'column',gap:5}}>
            <span style={{font:"700 11.5px 'Public Sans'",color:'#6B7790'}}>Event / campaign name</span>
            <input value={name} onChange={e=>setName(e.target.value)} onKeyDown={e=>e.key==='Enter'&&submit()} autoFocus placeholder="e.g. Annual Dinner 2026" style={{border:'1px solid #D9E1EE',borderRadius:8,padding:'9px 11px',font:"500 13px 'Public Sans'",color:'#1A2942',outline:'none'}}/>
          </label>
          <div style={{display:'flex',gap:8,alignItems:'center'}}>
            <span style={{font:"700 11.5px 'Public Sans'",color:'#6B7790',width:110}}>Number of weeks</span>
            <button onClick={()=>setWeeks(w=>Math.max(1,w-1))} style={{width:28,height:28,border:'1px solid #D9E1EE',background:'#fff',borderRadius:7,cursor:'pointer',font:"800 15px 'Public Sans'",color:'#1A2942'}}>-</button>
            <span style={{minWidth:24,textAlign:'center',font:"800 13px 'Public Sans'",color:'#1A2942'}}>{weeks}</span>
            <button onClick={()=>setWeeks(w=>Math.min(16,w+1))} style={{width:28,height:28,border:'1px solid #D9E1EE',background:'#fff',borderRadius:7,cursor:'pointer',font:"800 15px 'Public Sans'",color:'#1A2942'}}>+</button>
          </div>
          <div>
            <div style={{font:"700 11.5px 'Public Sans'",color:'#6B7790',marginBottom:6}}>Posting days <span style={{font:"600 11px 'Public Sans'",color:'#9AA6BC'}}>- {days.length*perDay} post{days.length*perDay!==1?'s':''} per week</span></div>
            <div style={{display:'flex',gap:6,flexWrap:'wrap'}}>
              {DAY_NAMES.map((label,i) => {
                const on = days.includes(i);
                return <button key={i} onClick={()=>toggle(i)} style={{padding:'7px 11px',borderRadius:9,border:'1.5px solid',borderColor:on?'var(--b-primary)':'#D9E1EE',background:on?'var(--b-wash)':'#F7F9FC',color:on?'var(--b-primary)':'#6B7790',font:"700 12px 'Public Sans'",cursor:'pointer'}}>{label}</button>;
              })}
            </div>
          </div>
          <div style={{display:'flex',gap:8,alignItems:'center'}}>
            <span style={{font:"700 11.5px 'Public Sans'",color:'#6B7790',width:110}}>Posts per day</span>
            <button onClick={()=>setPerDay(n=>Math.max(1,n-1))} style={{width:28,height:28,border:'1px solid #D9E1EE',background:'#fff',borderRadius:7,cursor:'pointer',font:"800 15px 'Public Sans'",color:'#1A2942'}}>-</button>
            <span style={{minWidth:24,textAlign:'center',font:"800 13px 'Public Sans'",color:'#1A2942'}}>{perDay}</span>
            <button onClick={()=>setPerDay(n=>Math.min(3,n+1))} style={{width:28,height:28,border:'1px solid #D9E1EE',background:'#fff',borderRadius:7,cursor:'pointer',font:"800 15px 'Public Sans'",color:'#1A2942'}}>+</button>
          </div>
          <div style={{font:"500 11.5px/1.5 'Public Sans'",color:'#9AA6BC'}}>A club admin's campaign starts straight away. Otherwise a club admin approves it first. Once it is live you are its Admin and can choose who else works on it.</div>
        </div>
        <div style={{padding:'12px 20px',borderTop:'1px solid var(--b-bg)',display:'flex',justifyContent:'flex-end',gap:10,background:'#FAFBFE'}}>
          <button onClick={onClose} style={{background:'#fff',color:'#6B7790',border:'1px solid #D9E1EE',borderRadius:9,padding:'9px 16px',font:"800 12.5px 'Public Sans'",cursor:'pointer'}}>Cancel</button>
          <button onClick={submit} disabled={!name.trim()} style={{background:'var(--b-primary)',color:'#fff',border:'none',borderRadius:9,padding:'9px 20px',font:"800 12.5px 'Public Sans'",cursor:'pointer',opacity:name.trim()?1:0.5}}>Create</button>
        </div>
      </div>
    </div>
  );
}

/* ── Approvals console (Super Admin only) ─────────────────────────────────────
   Two jobs: action pending campaign requests, and manage who the (max 3) Social
   Media Planner Super Admins are. Fully independent of Project Planner's own
   admin console — see infra/firestore.rules socialSuperAdmins. ────────────── */
function ApprovalsModal({state, actions, onClose}) {
  const [decliningId, setDecliningId] = React.useState(null);
  const [reason,       setReason]     = React.useState('');
  const [addUid,       setAddUid]     = React.useState('');

  const decline = id => { actions.declineCampaignRequest(id, reason.trim()); setDecliningId(null); setReason(''); };
  const admins  = state.socialSuperAdmins || [];
  const nameOf  = uid => (state.members.find(m=>m.id===uid)||{}).name || uid;

  const addAdmin = () => {
    if (!addUid || admins.includes(addUid) || admins.length>=3) return;
    actions.setSocialSuperAdmins([...admins, addUid]);
    setAddUid('');
  };
  const removeAdmin = uid => actions.setSocialSuperAdmins(admins.filter(x=>x!==uid));

  return (
    <div className="modal-overlay" style={{zIndex:60}}>
      <div style={{width:'100%',maxWidth:560,background:'#fff',borderRadius:16,boxShadow:'0 20px 50px rgba(22,40,70,.35)',overflow:'hidden'}}>
        <div style={{padding:'16px 20px',borderTop:'3px solid var(--b-accent)',borderBottom:'1px solid var(--b-bg)',display:'flex',alignItems:'center',justifyContent:'space-between'}}>
          <div style={{font:"800 16px 'Public Sans'",color:'var(--b-primary-deep)'}}>Social: campaigns waiting for approval</div>
          <button onClick={onClose} style={{width:30,height:30,display:'grid',placeItems:'center',border:'none',background:'#F1F4F9',borderRadius:8,cursor:'pointer',color:'#5A6473'}}><XIcon sz={15}/></button>
        </div>

        <div style={{padding:'18px 20px',maxHeight:'64vh',overflowY:'auto',display:'flex',flexDirection:'column',gap:22}}>
          <div>
            <div style={{font:"800 12px 'Public Sans'",color:'#6B7790',textTransform:'uppercase',letterSpacing:'.04em',marginBottom:10}}>Pending campaign requests</div>
            {state.pendingApprovals.length===0 && <div style={{font:"500 12.5px 'Public Sans'",color:'#9AA6BC'}}>Nothing waiting on you right now.</div>}
            <div style={{display:'flex',flexDirection:'column',gap:10}}>
              {state.pendingApprovals.map(c=>(
                <div key={c.id} style={{border:'1px solid #E5EAF2',borderRadius:10,padding:'12px 14px',background:'#FAFBFE'}}>
                  <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',gap:10}}>
                    <div>
                      <div style={{font:"800 13.5px 'Public Sans'",color:'#1A2942'}}>{c.config.eventName}</div>
                      <div style={{font:"500 11.5px 'Public Sans'",color:'#9AA6BC'}}>Requested by {c.requestedByName || c.requestedByEmail || nameOf(c.requestedBy)}</div>
                    </div>
                    <div style={{display:'flex',gap:8,flex:'none'}}>
                      <button onClick={()=>actions.approveCampaignRequest(c.id)} style={{background:'#15803D',color:'#fff',border:'none',borderRadius:8,padding:'7px 13px',font:"800 12px 'Public Sans'",cursor:'pointer'}}>Approve</button>
                      <button onClick={()=>setDecliningId(decliningId===c.id?null:c.id)} style={{background:'#fff',color:'#B45309',border:'1px solid #F0C48A',borderRadius:8,padding:'7px 13px',font:"800 12px 'Public Sans'",cursor:'pointer'}}>Decline</button>
                    </div>
                  </div>
                  {decliningId===c.id && (
                    <div style={{marginTop:10,display:'flex',gap:8}}>
                      <input value={reason} onChange={e=>setReason(e.target.value)} placeholder="Reason (sent to the requester)" style={{flex:1,border:'1px solid #D9E1EE',borderRadius:7,padding:'7px 10px',font:"500 12.5px 'Public Sans'",outline:'none'}}/>
                      <button onClick={()=>decline(c.id)} style={{background:'#B45309',color:'#fff',border:'none',borderRadius:7,padding:'7px 14px',font:"800 12px 'Public Sans'",cursor:'pointer'}}>Send</button>
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>

        </div>
      </div>
    </div>
  );
}

/* ── Pull in from Events ─────────────────────────────────────────────────────
   Lists the promotion steps of a finished Events plan; the social-looking ones start ticked. Importing adds them to this campaign
   as draft posts in the week their timing points to (store action importEventsPosts). */
const SOCIAL_CHANNEL = /facebook|instagram|linkedin|social|tiktok|twitter|youtube|\bx\b/i;
function EventsImportModal({campaign, onImport, onClose}) {
  const API = window.ClubcraftApi, club = window.CC_ACTIVE_CLUB;
  const [plans, setPlans] = React.useState(null);
  const [err, setErr] = React.useState('');
  const [planId, setPlanId] = React.useState('');
  const [rep, setRep] = React.useState(null);
  const [picked, setPicked] = React.useState({});
  React.useEffect(() => {
    API.call('GET', '/club/reports?module=Events', null, {club})
      .then(r => { const done = (r.reports||[]).filter(x => x.status==='done'); setPlans(done); if (done.length===1) choose(done[0].id); })
      .catch(e => { setErr(/access/i.test(e.message) ? 'You need access to Events to pull its plans in.' : e.message); setPlans([]); });
  }, []);
  const have = new Set((campaign.posts||[]).map(p => p.fromEvents).filter(Boolean));
  const choose = id => {
    setPlanId(id); setRep(null); setErr('');
    if (!id) return;
    API.call('GET', '/club/reports/'+id, null, {club}).then(r => {
      setRep(r);
      const pick = {};
      ((r.plan && r.plan.promotion) || []).forEach((p,i) => { pick[i] = SOCIAL_CHANNEL.test(p.channel||'') && !have.has('events:'+id+':'+i); });
      setPicked(pick);
    }).catch(e => setErr(e.message));
  };
  const items = rep && rep.plan ? (rep.plan.promotion||[]).map((p,i) => ({i, ...p})) : [];
  const chosen = items.filter(it => picked[it.i] && !have.has('events:'+planId+':'+it.i));
  const wk = it => { const d = window.CCSocialSeed.whenToDays(it.when); return d==null ? 'first week' : d>0 ? d+' day'+(d===1?'':'s')+' before' : d===0 ? 'event day' : (-d)+' days after'; };
  const go = () => { const r = onImport(planId, (rep.form||{}).event_date||'', chosen); onClose(r); };
  const btn = {border:'none',borderRadius:9,padding:'10px 20px',font:"800 13px 'Public Sans'",cursor:'pointer'};
  return (
    <div className="modal-overlay" style={{zIndex:1600}}>
      <div style={{width:'100%',maxWidth:640,background:'#fff',borderRadius:16,boxShadow:'0 20px 50px rgba(22,40,70,.35)',overflow:'hidden'}}>
        <div style={{padding:'16px 20px',borderTop:'3px solid var(--b-accent)',borderBottom:'1px solid var(--b-bg)',display:'flex',alignItems:'center',justifyContent:'space-between'}}>
          <div>
            <div style={{font:"800 16px 'Public Sans'",color:'var(--b-primary-deep)'}}>Pull in from Events</div>
            <div style={{font:"500 12.5px 'Public Sans'",color:'#6B7790',marginTop:2}}>Add an Events plan's promotion steps to {campaign.config.eventName} as draft posts.</div>
          </div>
          <button onClick={()=>onClose()} style={{width:30,height:30,display:'grid',placeItems:'center',border:'none',background:'#F1F4F9',borderRadius:8,cursor:'pointer',color:'#5A6473'}}><XIcon sz={15}/></button>
        </div>
        <div style={{padding:'16px 20px',maxHeight:'62vh',overflowY:'auto',display:'flex',flexDirection:'column',gap:12}}>
          {err && <div style={{font:"600 12.5px 'Public Sans'",color:'#B45309',background:'#FCEEDA',borderRadius:8,padding:'8px 12px'}}>{err}</div>}
          {plans===null && <div style={{font:"500 13px 'Public Sans'",color:'#9AA6BC'}}>Loading your Events plans…</div>}
          {plans && !plans.length && !err && <div style={{font:"500 13px 'Public Sans'",color:'#6B7790'}}>No finished Events plans yet. Make one in Events first.</div>}
          {plans && plans.length>1 && (
            <select value={planId} onChange={e=>choose(e.target.value)} style={{border:'1px solid #D9E1EE',borderRadius:8,padding:'9px 11px',font:"600 13px 'Public Sans'",color:'#1A2942'}}>
              <option value="">Choose an Events plan…</option>
              {plans.map(x => <option key={x.id} value={x.id}>{x.title}</option>)}
            </select>
          )}
          {rep && !items.length && <div style={{font:"500 13px 'Public Sans'",color:'#6B7790'}}>This plan has no promotion steps.</div>}
          {items.length>0 && (
            <div style={{display:'flex',flexDirection:'column',gap:6}}>
              {!(rep.form||{}).event_date && <div style={{font:"500 12px 'Public Sans'",color:'#6B7790'}}>This plan has no event date, so posts are placed by how many weeks before the end of the campaign they fall.</div>}
              {items.map(it => {
                const already = have.has('events:'+planId+':'+it.i);
                return (
                  <label key={it.i} style={{display:'flex',gap:10,alignItems:'flex-start',border:'1px solid #E5EAF2',borderRadius:10,padding:'9px 12px',background:already?'#F6F7FA':'#fff',opacity:already?.6:1,cursor:already?'default':'pointer'}}>
                    <input type="checkbox" disabled={already} checked={!!picked[it.i] && !already} onChange={e=>setPicked(pk=>({...pk,[it.i]:e.target.checked}))} style={{marginTop:3}}/>
                    <span style={{flex:1,minWidth:0}}>
                      <span style={{display:'block',font:"700 12.5px 'Public Sans'",color:'#1A2942'}}>{it.message}</span>
                      <span style={{display:'block',font:"500 11.5px 'Public Sans'",color:'#6B7790',marginTop:2}}>{it.channel||'No channel'} · {it.when||'No timing'} · {already?'already in this campaign':wk(it)}</span>
                    </span>
                  </label>
                );
              })}
            </div>
          )}
        </div>
        <div style={{padding:'12px 20px',borderTop:'1px solid var(--b-bg)',display:'flex',justifyContent:'flex-end',gap:10}}>
          <button onClick={()=>onClose()} style={{...btn,background:'#fff',color:'#6B7790',border:'1px solid #D9E1EE'}}>Cancel</button>
          <button onClick={go} disabled={!chosen.length} style={{...btn,background:'var(--b-primary)',color:'#fff',opacity:chosen.length?1:.5}}>Add {chosen.length||''} post{chosen.length===1?'':'s'}</button>
        </div>
      </div>
    </div>
  );
}

/* ── Import from Plan Social ─────────────────────────────────────────────────
   Reads a campaign file exported from the Plan Social app (format 'plansocial-campaign') and applies its setup to this campaign
   through Setup's own Save and rebuild, so weeks and default posts are built the usual way. Nothing is sent until Apply. */
function PlanSocialImportModal({campaign, onApply, onClose}) {
  const [file, setFile] = React.useState(null);
  const [data, setData] = React.useState(null);
  const [err, setErr] = React.useState('');
  const [setWeeks, setSetWeeks] = React.useState(true);
  const [content, setContent] = React.useState(true);
  const read = f => {
    setErr(''); setData(null); setFile(f);
    if (!f) return;
    const rd = new FileReader();
    rd.onload = () => {
      try {
        const j = JSON.parse(String(rd.result));
        if (j.format !== 'plansocial-campaign' || !j.campaign || !j.campaign.config) throw new Error('This is not a Plan Social campaign file.');
        setData(j.campaign);
      } catch (e) { setErr(e.message || 'Could not read that file.'); }
    };
    rd.readAsText(f);
  };
  const c = data && data.config;
  const rows = c ? [
    ['Event', c.eventName], ['Starts', c.campaignStart || 'not set'], ['Website', c.eventWebsite || 'not set'],
    ['Facebook page', c.facebookPage || c.facebookPageUrl || 'not set'], ['Instagram account', c.instagramAccountId ? 'set' : 'not set'],
    ['Posting days', (c.preferredDays||[]).map(d => DAY_NAMES[d]).join(', ') || 'not set'],
    ['Pillars', (c.pillars||[]).length], ['Beneficiaries', (c.beneficiaries||[]).length], ['Sponsors', (c.sponsors||[]).length],
    ['Reference documents', ((c.moreInfoDocs||[]).length + (c.referenceDocs||[]).length)], ['Weeks', (data.weeks||[]).length], ['Posts', (data.posts||[]).length]
  ] : [];
  const btn = {border:'none',borderRadius:9,padding:'10px 20px',font:"800 13px 'Public Sans'",cursor:'pointer'};
  return (
    <div className="modal-overlay" style={{zIndex:1600}}>
      <div style={{width:'100%',maxWidth:560,background:'#fff',borderRadius:16,boxShadow:'0 20px 50px rgba(22,40,70,.35)',overflow:'hidden'}}>
        <div style={{padding:'16px 20px',borderTop:'3px solid var(--b-accent)',borderBottom:'1px solid var(--b-bg)',display:'flex',alignItems:'center',justifyContent:'space-between'}}>
          <div>
            <div style={{font:"800 16px 'Public Sans'",color:'var(--b-primary-deep)'}}>Import from Plan Social</div>
            <div style={{font:"500 12.5px 'Public Sans'",color:'#6B7790',marginTop:2}}>Fill the setup of {campaign.config.eventName} from a Plan Social campaign file.</div>
          </div>
          <button onClick={onClose} style={{width:30,height:30,display:'grid',placeItems:'center',border:'none',background:'#F1F4F9',borderRadius:8,cursor:'pointer',color:'#5A6473'}}><XIcon sz={15}/></button>
        </div>
        <div style={{padding:'16px 20px',display:'flex',flexDirection:'column',gap:12}}>
          <input type="file" accept=".json,application/json" onChange={e=>read(e.target.files[0])} />
          {err && <div style={{font:"600 12.5px 'Public Sans'",color:'#B45309',background:'#FCEEDA',borderRadius:8,padding:'8px 12px'}}>{err}</div>}
          {c && (
            <>
              <div style={{border:'1px solid #E5EAF2',borderRadius:10,overflow:'hidden'}}>
                {rows.map(([k,v]) => (
                  <div key={k} style={{display:'flex',gap:12,padding:'7px 12px',borderBottom:'1px solid #F0F3F8',font:"500 12.5px 'Public Sans'"}}>
                    <span style={{width:150,color:'#6B7790',flex:'none'}}>{k}</span><span style={{color:'#1A2942',fontWeight:600,minWidth:0,overflowWrap:'anywhere'}}>{String(v)}</span>
                  </div>
                ))}
              </div>
              <label style={{display:'flex',gap:8,alignItems:'flex-start',font:"500 12.5px 'Public Sans'",color:'#1A2942'}}>
                <input type="checkbox" checked={setWeeks} onChange={e=>setSetWeeks(e.target.checked)} style={{marginTop:3}}/>
                <span>Set this campaign to {(data.weeks||[]).length || 'the same number of'} weeks. Missing weeks and the default posts for each posting day are added; posts you already have stay.</span>
              </label>
              <label style={{display:'flex',gap:8,alignItems:'flex-start',font:"500 12.5px 'Public Sans'",color:'#1A2942'}}>
                <input type="checkbox" checked={content} onChange={e=>setContent(e.target.checked)} style={{marginTop:3}}/>
                <span>Also bring over the {(data.weeks||[]).length} weeks and {(data.posts||[]).length} posts (topics, captions, dates, status). This replaces the weeks and posts this campaign has now.</span>
              </label>
              <div style={{font:"500 11.5px/1.5 'Public Sans'",color:'#9AA6BC'}}>This replaces the campaign's setup details (event, pages, pillars, sponsors, documents, sign-off, branding) with the file's. The AI and publishing links in the file are not carried over. Team roles are not changed.</div>
            </>
          )}
        </div>
        <div style={{padding:'12px 20px',borderTop:'1px solid var(--b-bg)',display:'flex',justifyContent:'flex-end',gap:10}}>
          <button onClick={onClose} style={{...btn,background:'#fff',color:'#6B7790',border:'1px solid #D9E1EE'}}>Cancel</button>
          <button onClick={()=>onApply(data, setWeeks, content)} disabled={!c} style={{...btn,background:'var(--b-primary)',color:'#fff',opacity:c?1:.5}}>Apply to this campaign</button>
        </div>
      </div>
    </div>
  );
}

/* ── Toast ───────────────────────────────────────────────────────────────── */
function Toast({msg}) {
  return (
    <div className="sp-toast">
      <span style={{width:7,height:7,borderRadius:'50%',background:'var(--b-accent)'}}/>
      {msg}
    </div>
  );
}

/* ── Sign-in screen (Firebase mode only) ───────────────────────────────── */
/* Layout mirrors Project Planner's `.signin`/`.signin-card` (app.jsx there) so
   the two sibling apps present the same branded gate: radial Rotary-blue
   background, white card with a kicker/H1/subtitle stack, real multi-colour
   Google button, divider, then the email-link fallback. */
function SignInScreen({signIn, sendEmailLink}) {
  const [email,   setEmail]   = React.useState('');
  const [sent,    setSent]    = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [busy,    setBusy]    = React.useState(false);

  const clubLabel = ((window.SOCIAL_FIREBASE||{}).clubId || '')
    .split('-').filter(Boolean).map(w => w[0].toUpperCase()+w.slice(1)).join(' ') || 'Social Media Planner';

  const handleGoogleSignIn = () => {
    if (busy) return;
    setBusy(true);
    Promise.resolve(signIn()).finally(() => setTimeout(() => setBusy(false), 4000));
  };
  const handleEmailSend = () => {
    if (!email.trim()) return;
    setSending(true);
    sendEmailLink(email.trim())
      .then(() => setSent(true))
      .catch(() => setSending(false));
  };

  /* Exact values pulled from Project Planner's live planner.css (--ink #16243A,
     --muted #5D6B80, --faint #8A97A8, --line-2 #D4DBE6) so the two sibling
     apps render pixel-identical gates, not just similar ones. */
  const inp = {width:'100%',boxSizing:'border-box',border:'1px solid #D4DBE6',borderRadius:9,padding:'9px 11px',font:"400 14px 'Public Sans'",outline:'none',color:'#16243A',textAlign:'center'};
  const secondaryBtn = {display:'inline-flex',alignItems:'center',justifyContent:'center',gap:7,background:'#fff',color:'#16243A',border:'1px solid #D4DBE6',borderRadius:9,padding:'9px 14px',font:"600 13.5px 'Public Sans'",cursor:'pointer',width:'100%'};

  return (
    <div style={{minHeight:'100vh',display:'flex',alignItems:'center',justifyContent:'center',padding:24,background:'radial-gradient(120% 120% at 50% 0%, #1b4f9c 0%, var(--b-primary) 42%, var(--b-primary-deep) 100%)'}}>
      <div style={{background:'#fff',borderRadius:20,padding:'38px 34px 30px',textAlign:'center',boxShadow:'0 30px 80px rgba(8,20,45,.4)',width:'100%',maxWidth:400,boxSizing:'border-box'}}>
        <div style={{marginBottom:18,display:'flex',justifyContent:'center'}}><RotaryLogo sz={64}/></div>
        <div style={{font:"800 11px 'Public Sans'",letterSpacing:'.16em',textTransform:'uppercase',color:'var(--b-primary)'}}>{clubLabel}</div>
        <div style={{font:"800 25px 'Public Sans'",letterSpacing:'-.02em',color:'#16243A',margin:'5px 0 10px'}}>Social Media Planner</div>
        <div style={{font:"400 14.5px 'Public Sans'",color:'#5D6B80',lineHeight:1.55,marginBottom:22}}>Sign in to access your club's campaigns.</div>

        <button onClick={handleGoogleSignIn} disabled={busy} style={{...secondaryBtn,gap:11,font:"700 15px 'Public Sans'",opacity:busy?0.7:1}}>
          <svg width="18" height="18" viewBox="0 0 48 48" aria-hidden="true"><path fill="#FFC107" d="M43.6 20.5h-1.9V20H24v8h11.3c-1.6 4.7-6.1 8-11.3 8-6.6 0-12-5.4-12-12s5.4-12 12-12c3.1 0 5.9 1.2 8 3.1l5.7-5.7C34.5 6.5 29.5 4.5 24 4.5 13.2 4.5 4.5 13.2 4.5 24S13.2 43.5 24 43.5 43.5 34.8 43.5 24c0-1.2-.1-2.3-.3-3.5z"/><path fill="#FF3D00" d="M6.3 14.7l6.6 4.8C14.7 15.1 19 12 24 12c3.1 0 5.9 1.2 8 3.1l5.7-5.7C34.5 6.5 29.5 4.5 24 4.5c-7.6 0-14.2 4.3-17.7 10.2z"/><path fill="#4CAF50" d="M24 43.5c5.4 0 10.3-2 14-5.3l-6.5-5.5C29.6 34.4 26.9 35.5 24 35.5c-5.2 0-9.6-3.3-11.3-7.9l-6.5 5C9.7 39.1 16.3 43.5 24 43.5z"/><path fill="#1976D2" d="M43.6 20.5H24v8h11.3c-.8 2.2-2.2 4.2-4.1 5.6l6.5 5.5c-.5.4 7-5.1 7-15.6 0-1.2-.1-2.3-.3-3.5z"/></svg>
          {busy ? 'Opening Google…' : 'Sign in with Google'}
        </button>

        <div style={{display:'flex',alignItems:'center',gap:12,margin:'18px 0 14px'}}>
          <div style={{flex:1,height:1,background:'#E2E8F0'}}/>
          <span style={{font:"600 11.5px 'Public Sans'",letterSpacing:'.04em',textTransform:'uppercase',color:'#8A97A8'}}>or use your email</span>
          <div style={{flex:1,height:1,background:'#E2E8F0'}}/>
        </div>

        {sent ? (
          <div style={{background:'#eaf3ec',border:'1px solid #cce6d4',borderRadius:11,padding:'14px 16px',display:'flex',flexDirection:'column',gap:5,textAlign:'left'}}>
            <b style={{font:"700 14px 'Public Sans'",color:'#1f7a44'}}>Check your inbox</b>
            <span style={{font:"500 13px 'Public Sans'",color:'#3a5a45',lineHeight:1.5}}>We've emailed a sign-in link to <b>{email}</b>. Open it on this device to finish signing in.</span>
          </div>
        ) : (
          <div style={{display:'flex',flexDirection:'column',gap:9}}>
            <input value={email} onChange={e=>setEmail(e.target.value)} onKeyDown={e=>e.key==='Enter'&&handleEmailSend()} placeholder="you@example.com" style={inp}/>
            <button onClick={handleEmailSend} disabled={sending || !email.trim()} style={{...secondaryBtn,opacity:(sending || !email.trim())?0.6:1}}>
              {sending ? 'Sending…' : 'Email me a sign-in link'}
            </button>
          </div>
        )}

        <div style={{marginTop:20,font:"400 12.5px 'Public Sans'",color:'#8A97A8',lineHeight:1.5}}>
          Club members sign in with their <b style={{color:'#5D6B80',fontWeight:700}}>club Google account</b>; campaign guests by invitation.
        </div>
      </div>
    </div>
  );
}

/* Loading/connecting gate — mirrors Project Planner's `Splash` (spinning
   Rotary mark + label on the app's own flat background), shown before the
   sign-in screen can even resolve whether there's a signed-in user. */
function Splash({label}) {
  return (
    <div style={{minHeight:'100vh',background:'var(--b-bg)',display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center',gap:18}}>
      <div style={{animation:'spin 1.1s linear infinite'}}><RotaryLogo sz={46}/></div>
      <div style={{font:"600 14px 'Public Sans'",color:'#5D6B80'}}>{label || 'Loading…'}</div>
    </div>
  );
}

/* ── Topic picker modal ──────────────────────────────────────────────────── */
function TopicPickerModal({suggestions, pillar, onPick, onExclude, onClose}) {
  const [excludeIdx,  setExcludeIdx]  = React.useState(null);
  const [excludeText, setExcludeText] = React.useState('');
  const [excludeNote, setExcludeNote] = React.useState('');
  /* Up to 2 selections — picking 2 lets the week's posts split across two
     distinct angles instead of every post sharing one topic string. */
  const [selected, setSelected] = React.useState([]);

  const startExclude = (i, s) => { setExcludeIdx(i); setExcludeText(s.topic); setExcludeNote(''); };
  const saveExclude  = () => {
    onExclude({ text: excludeText, note: excludeNote, pillarId: pillar ? pillar.id : null });
    setExcludeIdx(null);
  };
  const toggleSelect = i => setSelected(sel => sel.includes(i)
    ? sel.filter(x=>x!==i)
    : (sel.length >= 2 ? sel : [...sel, i]));

  return (
    <div style={{position:'fixed',inset:0,background:'rgba(17,27,50,.55)',zIndex:200,display:'flex',alignItems:'center',justifyContent:'center',padding:20}}>
      <div style={{background:'#fff',borderRadius:16,width:'100%',maxWidth:580,boxShadow:'0 8px 48px color-mix(in srgb, var(--b-primary) 18%, transparent)',overflow:'hidden'}}>
        <div style={{background:'linear-gradient(135deg,var(--b-primary),var(--b-primary-deep))',padding:'16px 20px',display:'flex',alignItems:'center',gap:10}}>
          <StarIcon sz={15} light/>
          <div style={{flex:1}}>
            <div style={{font:"800 14px 'Public Sans'",color:'#fff'}}>Topic & Angle Suggestions</div>
            {pillar && pillar.label && <div style={{font:"500 11.5px 'Public Sans'",color:'rgba(255,255,255,.72)',marginTop:2}}>Pillar: <b style={{color:'var(--b-accent)'}}>{pillar.label}</b></div>}
          </div>
          <button onClick={onClose} style={{background:'rgba(255,255,255,.15)',border:'none',color:'#fff',borderRadius:8,width:28,height:28,display:'grid',placeItems:'center',cursor:'pointer',font:"700 16px 'Public Sans'"}}>×</button>
        </div>
        <div style={{padding:'16px 20px 20px',display:'flex',flexDirection:'column',gap:10}}>
          <div style={{font:"500 12.5px 'Public Sans'",color:'#5A6473',marginBottom:2}}>Select 1 or <b>2</b> — picking 2 lets each post in the week take a different angle instead of all sounding the same. Use <b>Exclude</b> to flag anything that doesn't match your voice or facts — exclusions are saved and sent with future requests.</div>
          {suggestions.map((s, i) => {
            const isSel = selected.includes(i);
            const selPos = selected.indexOf(i);
            return (
            <div key={i} onClick={()=>excludeIdx!==i && toggleSelect(i)} style={{border:'1.5px solid',borderColor:excludeIdx===i?'#FECACA':(isSel?'var(--b-primary)':'#E1E8F2'),background:isSel?'#F3F7FC':'#fff',borderRadius:10,overflow:'hidden',transition:'border-color .15s,background .15s',cursor:excludeIdx===i?'default':'pointer'}}>
              <div style={{padding:'13px 15px',display:'flex',gap:10,alignItems:'flex-start'}}>
                <div style={{width:20,height:20,borderRadius:6,border:'1.5px solid '+(isSel?'var(--b-primary)':'#C7D1E2'),background:isSel?'var(--b-primary)':'#fff',display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0,marginTop:1,font:"800 11px 'Public Sans'",color:'#fff'}}>
                  {isSel ? (selected.length>1 ? selPos+1 : '✓') : ''}
                </div>
                <div style={{flex:1,minWidth:0}}>
                  <div style={{font:"600 13px 'Public Sans'",color:'#1A2942',lineHeight:1.45}}>{s.topic}</div>
                  {s.url && <div style={{font:"500 11px 'Public Sans'",color:'#8A94A8',marginTop:4,wordBreak:'break-all'}}>{s.url}</div>}
                </div>
                <div style={{display:'flex',gap:6,flexShrink:0}} onClick={e=>e.stopPropagation()}>
                  <button onClick={()=>excludeIdx===i ? setExcludeIdx(null) : startExclude(i,s)} style={{background:excludeIdx===i?'#FEE2E2':'#FFF5F5',color:'#C0473F',border:'1px solid #FECACA',borderRadius:8,padding:'8px 12px',font:"700 12px 'Public Sans'",cursor:'pointer'}}>
                    {excludeIdx===i ? 'Cancel' : 'Exclude'}
                  </button>
                </div>
              </div>
              {excludeIdx === i && (
                <div onClick={e=>e.stopPropagation()} style={{padding:'12px 15px',borderTop:'1px solid #FEE2E2',background:'#FFF8F8',display:'flex',flexDirection:'column',gap:8}}>
                  <div>
                    <div style={{font:"700 10.5px 'Public Sans'",letterSpacing:'.06em',textTransform:'uppercase',color:'#C0473F',marginBottom:5}}>Edit what to exclude</div>
                    <textarea value={excludeText} onChange={e=>setExcludeText(e.target.value)} rows={2} style={{width:'100%',border:'1px solid #FECACA',borderRadius:7,padding:'8px 10px',font:"500 12.5px 'Public Sans'",color:'#1A2942',outline:'none',resize:'vertical'}}/>
                  </div>
                  <div>
                    <div style={{font:"700 10.5px 'Public Sans'",letterSpacing:'.06em',textTransform:'uppercase',color:'#C0473F',marginBottom:5}}>Why is this wrong? <span style={{fontWeight:500,textTransform:'none',letterSpacing:0,color:'#9AA6BC'}}>— helps the AI avoid similar mistakes</span></div>
                    <textarea value={excludeNote} onChange={e=>setExcludeNote(e.target.value)} placeholder="e.g. We use KM not miles, and we check course conditions — we don't build the course" rows={2} style={{width:'100%',border:'1px solid #FECACA',borderRadius:7,padding:'8px 10px',font:"500 12.5px 'Public Sans'",color:'#1A2942',outline:'none',resize:'vertical'}}/>
                  </div>
                  <div style={{display:'flex',gap:8}}>
                    <button onClick={saveExclude} style={{background:'#C0473F',color:'#fff',border:'none',borderRadius:7,padding:'7px 14px',font:"700 12px 'Public Sans'",cursor:'pointer'}}>Save Exclusion</button>
                    <button onClick={()=>setExcludeIdx(null)} style={{background:'none',border:'1px solid #E1E8F2',borderRadius:7,padding:'7px 12px',font:"700 12px 'Public Sans'",color:'#6B7790',cursor:'pointer'}}>Cancel</button>
                  </div>
                </div>
              )}
            </div>
            );
          })}
          <div style={{display:'flex',alignItems:'center',justifyContent:'flex-end',gap:10,marginTop:4}}>
            <button onClick={onClose} style={{background:'none',border:'none',color:'#8A94A8',font:"500 13px 'Public Sans'",cursor:'pointer',padding:'4px 8px'}}>Close</button>
            <button onClick={()=>onPick(selected.map(i=>suggestions[i]))} disabled={!selected.length} style={{background:'var(--b-primary)',color:'#fff',border:'none',borderRadius:9,padding:'10px 18px',font:"700 13px 'Public Sans'",cursor:selected.length?'pointer':'default',opacity:selected.length?1:0.4}}>
              Use {selected.length===2?'2 selected':selected.length===1?'selected':''}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ── Root App ────────────────────────────────────────────────────────────── */
function App() {
  const { state, actions, mode, ready, user, authLoading, signIn, sendEmailLink, signOut } = window.useSocialStore();
  const toastTimer     = React.useRef(null);
  const clipTimer      = React.useRef(null);
  const justCreatedRef = React.useRef(false);

  const [setupDraft,    setSetupDraft]    = React.useState(null);
  const [setupView,     setSetupView]     = React.useState('campaign'); // 'campaign' | 'admin' — which modal setupDraft renders as
  const [brandKitDraft, setBrandKitDraft] = React.useState(null);
  const [showGuide,     setShowGuide]     = React.useState(false);
  const [showApprovals, setShowApprovals] = React.useState(false);
  const [newCampaign,   setNewCampaign]   = React.useState(false);
  const [topicPicker,   setTopicPicker]   = React.useState(null); // { weekId, suggestions, pillar }
  const [copiedId,      setCopiedId]      = React.useState(null);
  const [sendBackId,    setSendBackId]    = React.useState(null);
  const [noteDrafts,    setNoteDrafts]    = React.useState({});
  const [toast,         setToast]         = React.useState(null);
  const [pushConfirmId, setPushConfirmId] = React.useState(null);
  const [pushingId,     setPushingId]     = React.useState(null);
  const [approveConfirmId, setApproveConfirmId] = React.useState(null);
  const [approvingId,      setApprovingId]      = React.useState(null);
  const [postBusy,      setPostBusy]      = React.useState({});
  const [driveDest,     setDriveDest]     = React.useState({});
  const [showImageLib,  setShowImageLib]  = React.useState(false);
  const [showEventsImport, setShowEventsImport] = React.useState(false);
  const [showPsImport, setShowPsImport] = React.useState(false);

  /* ── current campaign or "all" ── */
  const isAllCampaigns = state.currentCampaignId === 'all';
  const selectedCampaign = isAllCampaigns ? null : state.campaigns.find(c => c.id === state.currentCampaignId);
  /* Selected a real, approved campaign that just isn't one of mine — the switcher
     lists everything in campaignIndex club-wide, but only members can open one.
     (A stale/unrecognised id that's in neither list falls back to the first
     accessible campaign below, same as the old always-fallback behaviour.) */
  const notAMember = !isAllCampaigns && !selectedCampaign && state.currentCampaignId
    && (state.campaignIndex||[]).some(c => c.id === state.currentCampaignId);
  const campaign = isAllCampaigns ? null : (selectedCampaign || (!notAMember ? state.campaigns[0] : null));

  /* Coming back from the Facebook login: say how it went and open Socials so a Page can be chosen. */
  const fbReturn = React.useRef((() => { try { const q = new URLSearchParams(window.location.search); return q.get('social-connect') ? { ok: q.get('social-connect') === 'ok', msg: q.get('msg') || '' } : null; } catch (e) { return null; } })());
  React.useEffect(() => {
    const r = fbReturn.current;
    if (!r || !campaign) return;
    fbReturn.current = null;
    try { const u = new URL(window.location.href); u.searchParams.delete('social-connect'); u.searchParams.delete('msg'); window.history.replaceState(null, '', u.pathname + (u.search || '') + u.hash); } catch (e) { /* leave the address as it is */ }
    flash(r.ok ? 'Facebook connected' + (r.msg ? ' (' + r.msg + ')' : '') + '. Pick the Page for this campaign, then Save.' : 'Facebook was not connected: ' + (r.msg || 'please try again'));
    if (r.ok) openAdminSettings('socials');
  }, [campaign && campaign.id]);

  /* Merged pillar list for all-campaigns mode (deduped by id) */
  const allPillars = React.useMemo(() => {
    const seen = new Map();
    state.campaigns.forEach(c => c.config.pillars.forEach(p => { if (!seen.has(p.id)) seen.set(p.id, p); }));
    return [...seen.values()];
  }, [state.campaigns]);

  /* Open Setup automatically after a new campaign is created */
  React.useEffect(() => {
    if (!justCreatedRef.current || !campaign) return;
    justCreatedRef.current = false;
    openSetup();
  }, [state.currentCampaignId]);

  /* Guards — must come after all hooks */
  if (mode === 'firebase' && authLoading) return <Splash label="Connecting…"/>;
  if (mode === 'firebase' && !user) return <SignInScreen signIn={signIn} sendEmailLink={sendEmailLink}/>;
  if (!ready) return <Splash label="Loading your campaigns…"/>;
  if (!state.campaigns.length || notAMember) {
    const me = state.members.find(m => m.id === state.currentUserId) || state.members[0];
    const notAMemberName = notAMember ? ((state.campaignIndex||[]).find(c=>c.id===state.currentCampaignId)||{}).name : null;
    return (
      <div className="sp-root" style={{background:'var(--b-bg)'}}>
        {/* Mini header so the user knows which club they're signed into */}
        <div style={{background:'linear-gradient(180deg,var(--b-primary),var(--b-primary-deep))',padding:'14px 24px',display:'flex',alignItems:'center',gap:12}}>
          <div style={{flex:1}}>
            <div style={{font:"800 15px 'Public Sans'",color:'#fff'}}>Social</div>
            {state.clubName && <div style={{font:"500 12px 'Public Sans'",color:'rgba(255,255,255,.72)'}}>{state.clubName}</div>}
          </div>
          {state.isSocialSuperAdmin && (
            <button onClick={()=>setShowApprovals(true)} style={{position:'relative',height:34,display:'inline-flex',alignItems:'center',gap:6,padding:'0 12px',border:'1px solid rgba(255,255,255,.22)',background:'rgba(255,255,255,.13)',borderRadius:9,cursor:'pointer',color:'#fff',font:"700 12px 'Public Sans'"}}>
              <ShieldIcon sz={13}/> Approvals{state.pendingApprovals.length>0 && <span style={{background:'var(--b-accent)',color:'#3A2C05',borderRadius:999,padding:'1px 6px',font:"800 10.5px 'Public Sans'"}}>{state.pendingApprovals.length}</span>}
            </button>
          )}
          {me && <div style={{display:'flex',alignItems:'center',gap:9}}>
            <div style={{width:34,height:34,borderRadius:'50%',display:'grid',placeItems:'center',font:"800 11px 'Public Sans'",color:'#fff',background:me.avatarColor}}>{me.initials}</div>
            <div style={{display:'flex',flexDirection:'column'}}>
              <div style={{font:"600 13px 'Public Sans'",color:'rgba(255,255,255,.9)'}}>{me.name}</div>
              {state.isSocialSuperAdmin && <div style={{font:"800 9.5px 'Public Sans'",color:'var(--b-accent)',letterSpacing:'.04em'}}>SUPER ADMIN</div>}
            </div>
          </div>}
          {signOut && <button onClick={signOut} style={{height:34,display:'inline-flex',alignItems:'center',padding:'0 12px',border:'1px solid rgba(255,255,255,.22)',background:'rgba(255,255,255,.13)',borderRadius:9,cursor:'pointer',color:'rgba(255,255,255,.85)',font:"600 12px 'Public Sans'"}}> Sign out</button>}
        </div>
        <div style={{display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center',minHeight:'70vh',gap:10,padding:'0 24px',textAlign:'center'}}>
          {notAMember ? (
            <>
              <div style={{font:"800 18px 'Public Sans'",color:'#B45309'}}>You are not a member of this Campaign</div>
              <div style={{font:"500 13.5px 'Public Sans'",color:'#5A6473',marginBottom:6,maxWidth:420}}>"{notAMemberName || 'This campaign'}" exists, but nobody's given you access yet — ask its Admin to invite you, or pick a campaign you belong to below.</div>
              {!!state.campaigns.length && (
                <select value="" onChange={e=>actions.patch({currentCampaignId:e.target.value})} style={{border:'1px solid #D9E1EE',borderRadius:8,padding:'9px 12px',font:"700 13px 'Public Sans'",color:'#1A2942',background:'#fff',outline:'none',marginBottom:10}}>
                  <option value="" disabled>Switch to a campaign you belong to…</option>
                  {state.campaigns.map(c=><option key={c.id} value={c.id}>{c.config.eventName}</option>)}
                </select>
              )}
            </>
          ) : (
            <>
              <div style={{font:"800 18px 'Public Sans'",color:'var(--b-primary)'}}>No campaigns yet</div>
              <div style={{font:"500 13.5px 'Public Sans'",color:'#5A6473',marginBottom:6}}>Create a campaign to get started.</div>
            </>
          )}
          {state.myPendingRequests.length>0 && (
            <div style={{font:"600 12.5px 'Public Sans'",color:'#B45309',background:'#FCEEDA',border:'1px solid rgba(180,83,9,.3)',borderRadius:8,padding:'8px 14px'}}>
              {state.myPendingRequests.map(c=>`"${c.config.eventName}" is waiting for a club admin to approve it`).join(' · ')}
            </div>
          )}
          {state.declinedForMe.length>0 && (
            <div style={{font:"600 12.5px 'Public Sans'",color:'#DC2626',background:'#FBE8E8',border:'1px solid rgba(220,38,38,.25)',borderRadius:8,padding:'8px 14px',maxWidth:480}}>
              {state.declinedForMe.map(c=><div key={c.id}>"{c.config.eventName}" wasn't approved{c.declineReason?`: ${c.declineReason}`:''}</div>)}
            </div>
          )}
          <button onClick={()=>setNewCampaign(true)} style={{marginTop:8,display:'inline-flex',alignItems:'center',gap:8,background:'var(--b-primary)',color:'#fff',border:'none',borderRadius:10,padding:'12px 24px',font:"700 14px 'Public Sans'",cursor:'pointer'}}>
            <PlusIcon sz={15}/> New campaign
          </button>
        </div>
        {newCampaign && (
          <RequestCampaignModal
            onClose={()=>setNewCampaign(false)}
            onRequest={(name, opts) => { actions.requestCampaign(name, null, opts); setNewCampaign(false); }}
          />
        )}
        {showApprovals && (
          <ApprovalsModal
            state={state} actions={actions}
            onClose={()=>setShowApprovals(false)}
          />
        )}
      </div>
    );
  }

  /* View object — tabs never see the multi-campaign split */
  const view = isAllCampaigns
    ? {
        ...state,
        config: {
          pillars: allPillars,
          campaignStart: state.campaigns.reduce((min,c) => !min||c.config.campaignStart<min?c.config.campaignStart:min, ''),
          webhookUrl:'', facebookPage:'', eventName:'All Campaigns', beneficiaries:[], sponsors:[],
        },
        weeks: state.campaigns.flatMap(c =>
          c.weeks.map(w => ({...w, _campaignId:c.id, _campaignStart:c.config.campaignStart, _eventName:c.config.eventName}))
        ),
        posts: state.campaigns.flatMap(c => c.posts).map(p=>_hydratePost(p, postBusy)),
      }
    : { ...state, config: campaign.config, weeks: campaign.weeks, posts: campaign.posts.map(p=>_hydratePost(p, postBusy)) };

  /* ── date helpers (week-start aware of _campaignStart tag) ── */
  const weekStart  = w => addDays(parseDate(w._campaignStart || (campaign && campaign.config.campaignStart) || '2026-01-01'), w.idx * 7);
  const weekNo     = w => isoWeek(weekStart(w));
  const dateRange  = w => { const s=weekStart(w); return `${fmtShort(s)} – ${fmtShort(addDays(s,6))}`; };
  const postDate   = (w,p) => addDays(weekStart(w), p.dayOffset);

  const pillarById = id => {
    if (isAllCampaigns) {
      for (const c of state.campaigns) {
        const p = c.config.pillars.find(p=>p.id===id);
        if (p) return p;
      }
      return {id:'',label:'',color:'#8A94A8',bg:'#EDF1F7'};
    }
    return campaign.config.pillars.find(p=>p.id===id) || campaign.config.pillars[0] || {id:'',label:'',color:'#8A94A8',bg:'#EDF1F7'};
  };

  const postsOf    = wid => view.posts.filter(p=>p.weekId===wid);
  const curMember  = () => state.members.find(m=>m.id===state.currentUserId) || state.members[0];
  const memberRole = () => isAllCampaigns ? 'Read' : ((campaign&&campaign.memberRoles||{})[state.currentUserId]||'Read');
  /* Super Admin gets full Admin-level capabilities on every campaign in the UI,
     regardless of whether they're personally in that campaign's memberRoles —
     matches the Firestore rules, which already grant isSocialSuperAdmin() a
     server-side bypass on campaign writes independent of memberRoles. Without
     this, a Super Admin who approves someone else's campaign request (which only
     grants Admin to the requester, not to the approver) would be locked out of
     that campaign's Setup/Guide UI despite having full write access underneath. */
  const caps       = () => (state.isSocialSuperAdmin && !isAllCampaigns) ? SD.CAPS.Admin : (SD.CAPS[memberRole()] || SD.CAPS.Read);

  const statusCells = wid => {
    const counts = {draft:0,needs:0,ready:0,posted:0};
    postsOf(wid).forEach(p => { counts[p.status]=(counts[p.status]||0)+1; });
    return ['posted','ready','needs','draft'].filter(k=>counts[k]>0).map(k=>({...SD.STATUS[k],n:counts[k]}));
  };

  /* ── flash ── */
  /* AI drafting: the old code called a webhook with fetch(); aiFetch keeps those call sites as they were but sends the same body to
     Clubcraft (POST /club/social/:id/ai, which charges credits and calls n8n server side), and hands back the same reply shape. */
  let lastAi = '';
  const aiFetch = (u, opts) => actions.ai(campaign.id, JSON.parse(opts.body))
    .then(res => ({ json: () => Promise.resolve(res) }))
    .catch(e => { lastAi = (e && e.message) || ''; throw e; });
  const aiFail = () => lastAi || 'Generation failed';
  const flash = msg => { setToast(msg); clearTimeout(toastTimer.current); toastTimer.current=setTimeout(()=>setToast(null),2400); };

  /* ── AI generation ── */
  const _ctxPayload = (pillarId) => {
    const cfg = campaign.config;
    const pil = pillarId ? pillarById(pillarId) : null;
    const q   = pil && pil.questionnaire;
    const bk  = state.clubBrandKit || {};
    const br  = cfg.branding || {};
    const moreInfoDocs = cfg.moreInfoDocs || [];
    return {
      clubName: state.clubName || '',
      campaignMoreInfo: cfg.moreInfo || '',
      campaignDocs:     moreInfoDocs.map(x=>({name:x.name||'', docUrl:x.docUrl||''})).filter(x=>x.docUrl),
      /* Campaign-specific closing/sign-off block (sponsor thanks, event CTA,
         hashtags) — distinct from the club Brand Kit's one-line signOff, since
         this is a richer default drafted per campaign in Setup §1. */
      campaignSignOff:  cfg.signOffMessage || '',
      /* Club-level voice (Brand Kit) — applies regardless of which logo/colours
         lead for this campaign, so it's sent on every generation request. */
      brandVoice: {
        toneWords:        bk.toneWords || '',
        standardHashtags: bk.standardHashtags || '',
        signOff:          bk.signOff || '',
        avoidWords:       bk.avoidWords || '',
      },
      /* Which logo/colours lead for this campaign, and the human-written note on
         where the other one still appears — read by whoever executes a media brief,
         not meant to steer the AI image prompt itself (that never renders logos/text). */
      branding: {
        primary:   br.primary || 'club',
        usageNote: br.usageNote || '',
      },
      beneficiaries: (cfg.beneficiaries||[]).filter(b=>b.name||b).map(b=>typeof b==='string'
        ? {name:b, url:'', about:'', docUrl:'', logoUrl:''}
        : {name:b.name||'', url:b.url||'', about:b.about||'', docUrl:b.docUrl||'', logoUrl:b.logoUrl||''}),
      sponsors: (cfg.sponsors||[]).filter(s=>s.name||s).map(s=>typeof s==='string'
        ? {name:s, url:'', about:'', docUrl:'', logoUrl:''}
        : {name:s.name||'', url:s.url||'', about:s.about||'', docUrl:s.docUrl||'', logoUrl:s.logoUrl||''}),
      /* Optional per-pillar reference context — populated when the pillar's
         Reference Questionnaire (Setup § 5) has been filled in. Named
         `pillarContext` (not `pillar`) because every call site already sets
         a top-level `pillar` field to the pillar's label string, and this
         is spread in after that — a same-key clash would silently overwrite
         the label with this object. */
      pillarContext: pil ? {
        label:         pil.label,
        description:   pil.description || '',
        timing:        pil.timing || [],
        questionnaire: q || null,
        sourceDocs: [...moreInfoDocs, ...(cfg.referenceDocs||[])]
          .filter(d => (q?.sourceDocIds||[]).includes(d.id))
          .map(d => ({name:d.name||'', url:d.url||'', docUrl:d.docUrl||'', stale:!!(docFreshness(d)&&docFreshness(d).level==='warn')})),
      } : null,
    };
  };

  /* Shared topic-suggestion fetch, used by both the interactive "Generate Week"
     button (shows a picker) and the silent auto-draft that runs after Save & rebuild. */
  const fetchWeekSuggestions = w => {
    const pillar = pillarById(w.pillarId);
    const _sf=(window.SOCIAL_FIREBASE||{});
    const url='ai';
    if (!url) {
      return new Promise(resolve => setTimeout(() => {
        resolve((SD.TOPICS[w.pillarId]||SD.TOPICS.p_event||[]).slice(0,3));
      },900));
    }
    const headers={'Content-Type':'application/json'};
    if (_sf.webhookSecret) headers['x-webhook-secret']=_sf.webhookSecret;
    return aiFetch(url, {
      method:'POST', headers,
      body: JSON.stringify({
        type:'week', pillar:pillar.label,
        campaignName:campaign.config.eventName,
        eventWebsite:campaign.config.eventWebsite||'',
        ..._ctxPayload(w.pillarId),
        existingTopic:w.topicAndAngle,
        count:3,
        exclusions:(campaign.config.exclusions||[])
          .filter(e=>!e.pillarId||e.pillarId===w.pillarId)
          .map(e=>e.text+(e.note?` — ${e.note}`:'')),
      }),
    })
    .then(r=>r.json())
    .then(data =>
      /* Support both { suggestions:[{topic,url}] } and legacy { topic, url } */
      Array.isArray(data.suggestions) && data.suggestions.length
        ? data.suggestions
        : (data.topic ? [{ topic:data.topic, url:data.url||'' }] : [])
    );
  };

  const generateWeek = id => {
    const c=caps(); if (!c.generate) return flash("Your role is Read-only for this campaign.");
    const w=campaign.weeks.find(x=>x.id===id); if (!w||w.generating) return;
    /* Weeks that already have a topic and/or drafted post captions get a
       confirm gate — generating fresh suggestions is only a silent, no-ask
       action when the week is still empty. */
    const weekHasData = !!(w.topicAndAngle && w.topicAndAngle.trim())
      || campaign.posts.some(p=>p.weekId===id && p.draftCaption && p.draftCaption.trim());
    if (weekHasData && !window.confirm('Week '+weekNo(w)+' already has a topic and/or drafted captions.\n\nGenerating new suggestions lets you pick a new topic — the current one (and any drafted captions built from it) will be overwritten. Continue?')) return;
    const pillar = pillarById(w.pillarId);
    actions.updateWeek(id,{generating:true});
    fetchWeekSuggestions(w)
      .then(suggestions => {
        actions.updateWeek(id,{generating:false});
        if (!suggestions.length) return flash('No suggestions came back. Please try again.');
        setTopicPicker({ weekId:id, suggestions, pillar });
      })
      .catch(()=>{
        actions.updateWeek(id,{generating:false});
        flash(aiFail());
      });
  };

  /* Shared topic-variance fetch — asks the AI for N distinct angle variants on
     one already-chosen topic (same subject, different hook/emphasis), rather
     than N brand-new topic ideas. Reuses the 'week' webhook route with a
     variantsOf flag so n8n needs no new route/nodes. */
  const fetchTopicVariants = (w, baseTopic, count) => {
    const pillar = pillarById(w.pillarId);
    const _sf=(window.SOCIAL_FIREBASE||{});
    const url='ai';
    if (!url) return new Promise(resolve => setTimeout(() => resolve([baseTopic]), 400));
    const headers={'Content-Type':'application/json'};
    if (_sf.webhookSecret) headers['x-webhook-secret']=_sf.webhookSecret;
    return aiFetch(url, {
      method:'POST', headers,
      body: JSON.stringify({
        type:'week', pillar:pillar.label,
        campaignName:campaign.config.eventName,
        eventWebsite:campaign.config.eventWebsite||'',
        ..._ctxPayload(w.pillarId),
        variantsOf:baseTopic, count:count||2,
        exclusions:(campaign.config.exclusions||[])
          .filter(e=>!e.pillarId||e.pillarId===w.pillarId)
          .map(e=>e.text+(e.note?` — ${e.note}`:'')),
      }),
    })
    .then(r=>r.json())
    .then(data => Array.isArray(data.suggestions) ? data.suggestions.map(s=>s.topic).filter(Boolean) : []);
  };

  /* Standalone "Generate" for a week's 2nd angle, exposed directly in Week
     Planner — the only other way to get a 2nd angle was the full "Generate
     Week" flow, which confirm-gates and overwrites the primary topic and any
     drafted captions. This touches topicAndAngle2 only, so it's safe to run
     any time a week's posts are all sharing one angle (the common case that
     makes Post Brief show two posts with an identical heading). */
  const generateSecondAngle = weekId => {
    const c=caps(); if (!c.generate) return flash("Your role is Read-only for this campaign.");
    const w = campaign.weeks.find(x=>x.id===weekId);
    if (!w || w.generating || !(w.topicAndAngle||'').trim()) return;
    actions.updateWeek(weekId, {generating:true});
    fetchTopicVariants(w, w.topicAndAngle, 2)
      .then(variants => {
        const variant = variants.find(v=>v && v!==w.topicAndAngle) || '';
        actions.updateWeek(weekId, {generating:false, topicAndAngle2:variant});
        flash(variant ? 'Second angle generated — posts in this week will now alternate between them' : 'Could not generate a distinct second angle — try again, or type one in directly');
      })
      .catch(()=>{
        actions.updateWeek(weekId, {generating:false});
        flash(aiFail());
      });
  };

  const handleTopicPick = (weekId, picked) => {
    if (!picked || !picked.length) return;
    const w = campaign.weeks.find(x=>x.id===weekId);
    if (picked.length >= 2) {
      actions.updateWeek(weekId, { topicAndAngle:picked[0].topic, referenceUrl:picked[0].url||'', topicAndAngle2:picked[1].topic });
      setTopicPicker(null);
      flash('2 angles applied — posts in this week will alternate between them');
      return;
    }
    /* Single pick — derive a second angle so posts don't all read the same,
       per the user's ask: "if only 1 is marked, 2 clear variances are made." */
    actions.updateWeek(weekId, { topicAndAngle:picked[0].topic, referenceUrl:picked[0].url||'', topicAndAngle2:'', generating:true });
    setTopicPicker(null);
    fetchTopicVariants(w, picked[0].topic, 2)
      .then(variants => {
        const variant = variants.find(v=>v && v!==picked[0].topic) || '';
        actions.updateWeek(weekId, { generating:false, topicAndAngle2: variant });
        flash(variant ? 'Topic applied — a second angle was generated for variety' : 'Topic applied — could not generate a distinct second angle, all posts will share one angle');
      })
      .catch(()=>{
        actions.updateWeek(weekId, { generating:false });
        flash('Topic applied — could not generate a second angle, all posts will share one angle');
      });
  };

  const handleExclude = ({ text, note, pillarId }) => {
    const excl = { id:'exc_'+Math.random().toString(36).slice(2,8), text, note, pillarId, createdAt: new Date().toISOString() };
    actions.addExclusion(campaign.id, excl);
    flash('Exclusion saved — included in all future generation requests');
  };

  const generatePost = id => {
    const c=caps(); if (!c.generate) return flash("Your role is Read-only for this campaign.");
    const p=campaign.posts.find(x=>x.id===id); if (!p||p.generating) return;
    const w=campaign.weeks.find(x=>x.id===p.weekId);
    actions.updatePost(id,{generating:true});
    const isRegen=p.status==='needs';
    /* Alternate between the week's two angles (if set) by each post's day
       position, and tell the AI which sibling angle to write differently
       from — otherwise every post in the week gets the same topicAndAngle
       string and no signal that other posts exist, so they read alike. */
    const weekPosts = w ? campaign.posts.filter(x=>x.weekId===w.id) : [];
    /* This post's 1-based position within its week, ordered by day like postAngle()
       does — feeds postIndex/postCount in the payload so the AI knows which of the
       week's posts it's writing. Was referenced but never defined (ReferenceError
       thrown before fetch → per-post "Generate caption" silently did nothing). */
    const postIdx = weekPosts.slice().sort((a,b)=>(a.dayOffset||0)-(b.dayOffset||0)).findIndex(x=>x.id===id);
    const hasAlt = !!(w && w.topicAndAngle2 && w.topicAndAngle2.trim());
    const angle = w ? postAngle(w, weekPosts, id) : '';
    const otherAngle = hasAlt ? (angle===w.topicAndAngle2 ? w.topicAndAngle : w.topicAndAngle2) : '';
    /* Actual drafted openings of this post's siblings — otherAngle above only
       differentiates topic/subject when a week has a manually-set second
       angle, which most weeks don't. Without real sibling text, same-angle
       posts have no signal beyond "vary the opening line" and the model
       reliably converges on the same formulaic hook. Passing the sibling
       captions themselves lets the AI avoid repeating the same wording. */
    const siblingCaptions = weekPosts.filter(x=>x.id!==id && (x.draftCaption||'').trim()).map(x=>x.draftCaption.trim());
    /* The start of the latest captions in the other weeks, so a new post does not repeat the same facts and phrases followers have already seen. */
    const weekIdx = new Map(campaign.weeks.map(x=>[x.id, x.idx]));
    const earlierPosts = campaign.posts
      .filter(x=>x.id!==id && (!w || x.weekId!==w.id) && (x.draftCaption||'').trim())
      .sort((a,b)=>((weekIdx.get(a.weekId)||0)-(weekIdx.get(b.weekId)||0)) || ((a.dayOffset||0)-(b.dayOffset||0)))
      .slice(-6).map(x=>x.draftCaption.trim().slice(0,320));
    const _sf2=(window.SOCIAL_FIREBASE||{});
    const url='ai';
    if (url) {
      const headers={'Content-Type':'application/json'};
      if (_sf2.webhookSecret) headers['x-webhook-secret']=_sf2.webhookSecret;
      aiFetch(url, {
        method:'POST', headers,
        body: JSON.stringify({
          type:'post', pillar:pillarById(w?w.pillarId:'').label,
          topicAndAngle:angle,
          postIndex:postIdx>=0?postIdx+1:1, postCount:weekPosts.length||1,
          otherAngleInWeek:otherAngle,
          siblingCaptions:siblingCaptions,
          earlierPosts:earlierPosts,
          campaignName:campaign.config.eventName,
          facebookPage:campaign.config.facebookPage,
          ..._ctxPayload(w?w.pillarId:''),
          existingCaption:p.draftCaption,
          reviewerNotes:p.reviewerNotes,
          isRegenerate:isRegen,
          exclusions:(campaign.config.exclusions||[])
            .filter(e=>!e.pillarId||e.pillarId===(w?w.pillarId:''))
            .map(e=>e.text+(e.note?` — ${e.note}`:'')),
        }),
      })
      .then(r=>r.json())
      .then(data=>{
        actions.updatePost(id,{generating:false,draftCaption:data.caption||'',mediaBrief:data.mediaBrief||'',status:isRegen?'draft':p.status,updatedBy:(curMember()||{}).name||''});
        flash(isRegen?'Caption re-generated from your notes':'Draft caption generated');
      })
      .catch(()=>{
        actions.updatePost(id,{generating:false});
        flash(aiFail());
      });
    } else {
      setTimeout(()=>{
        const g=SD.GEN[w?w.pillarId:'']||SD.GEN.p_event;
        const caption=(isRegen&&SD.GEN2[w?w.pillarId:''])?SD.GEN2[w.pillarId]:g.caption;
        actions.updatePost(id,{generating:false,draftCaption:caption,mediaBrief:g.brief,status:isRegen?'draft':p.status,updatedBy:(curMember()||{}).name||''});
        flash(isRegen?'Caption re-generated from your notes':'Draft caption generated (demo)');
      },1400);
    }
  };

  const _setBusy = (id, flags) => setPostBusy(prev => ({...prev, [id]: {...(prev[id]||{}), ...flags}}));

  const driveDestFor = id => driveDest[id] || 'campaign';

  const generateMediaBrief = id => {
    const c=caps(); if (!c.generate) return flash("Your role is Read-only for this campaign.");
    const p=campaign.posts.find(x=>x.id===id); if (!p||(postBusy[id]||{}).generatingBrief) return;
    const w=campaign.weeks.find(x=>x.id===p.weekId);
    _setBusy(id,{generatingBrief:true});
    const _sf2=(window.SOCIAL_FIREBASE||{});
    const url='ai';
    const styleLabel=(IMAGE_STYLES.find(s=>s.id===(p.imageStyle||'none'))||{label:'Original'}).label;
    if (url) {
      const headers={'Content-Type':'application/json'};
      if (_sf2.webhookSecret) headers['x-webhook-secret']=_sf2.webhookSecret;
      aiFetch(url,{
        method:'POST',headers,
        body:JSON.stringify({type:'mediaBrief',pillar:pillarById(w?w.pillarId:'').label,topicAndAngle:w?w.topicAndAngle:'',campaignName:campaign.config.eventName,..._ctxPayload(w?w.pillarId:''),draftCaption:p.draftCaption,imageStyle:p.imageStyle||'none',imageStyleLabel:styleLabel}),
      })
      .then(r=>r.json())
      .then(data=>{_setBusy(id,{generatingBrief:false});actions.updatePost(id,{mediaBrief:data.mediaBrief||''});flash('Media brief regenerated');})
      .catch(()=>{_setBusy(id,{generatingBrief:false});flash(lastAi || 'Media brief regeneration failed');});
    } else {
      setTimeout(()=>{
        _setBusy(id,{generatingBrief:false});
        actions.updatePost(id,{mediaBrief:`${styleLabel} style photo for "${w?w.topicAndAngle:'post'}" — vibrant, engaging, suitable for Facebook.`});
        flash('Media brief regenerated (demo)');
      },900);
    }
  };

  /* A picture for a post: Gemini (through Clubcraft, which charges credits) or the member's own file. Either way it is shrunk to
     1200 by 630 here, stored by the server and the post's image address is set. */
  const generateImage = async id => {
    const c=caps(); if (!c.generate) return flash("Your role is Read-only for this campaign.");
    const p=campaign.posts.find(x=>x.id===id); if (!p||(postBusy[id]||{}).generatingImage) return;
    if (!(p.mediaBrief||'').trim()) return flash('Write a media brief for this post first, then generate the image.');
    const w=campaign.weeks.find(x=>x.id===p.weekId);
    const styleLabel=(IMAGE_STYLES.find(s=>s.id===(p.imageStyle||'none'))||{label:'Original'}).label;
    _setBusy(id,{generatingImage:true});
    try {
      const ctx=_ctxPayload(w?w.pillarId:'');
      const res=await actions.ai(campaign.id,{type:'generateImage',mediaBrief:p.mediaBrief,imageStyle:p.imageStyle||'none',imageStyleLabel:styleLabel,campaignName:campaign.config.eventName,
        beneficiaries:ctx.beneficiaries,sponsors:ctx.sponsors,pillarContext:ctx.pillarContext?{description:ctx.pillarContext.description,questionnaire:ctx.pillarContext.questionnaire?{hook:ctx.pillarContext.questionnaire.hook}:null}:null,topicAndAngle:w?w.topicAndAngle:''});
      if (!res||!res.imageBase64) throw new Error('No image data in response');
      const byteStr=atob(res.imageBase64);
      const arr=new Uint8Array(byteStr.length);
      for (let i=0;i<byteStr.length;i++) arr[i]=byteStr.charCodeAt(i);
      const blob=await _resizeForFacebook(new Blob([arr],{type:res.mime||'image/jpeg'}));
      const filename=`${(campaign.config.eventName||'post').replace(/[^a-z0-9]/gi,'-')}_${id}.jpg`;
      const stored=await _storeImage(blob,{campaignId:campaign.id,postId:id,filename,kind:'post'});
      _setBusy(id,{generatingImage:false});
      actions.updatePost(id,{generatedImageUrl:stored.url,mediaFileLink:stored.url});
      flash('Image generated and saved');
    } catch(err) {
      console.error('generateImage error:',err);
      _setBusy(id,{generatingImage:false});
      flash(_imgError(err,'Image generation failed. Please try again.'));
    }
  };

  const handleImageUpload = async (id,file) => {
    if (!file) return;
    if (!caps().edit) return flash("Your role is Read-only for this campaign.");
    _setBusy(id,{uploadingImage:true});
    try {
      const filename=(file.name||`upload_${id}.jpg`).replace(/\.[^.]+$/,'.jpg');
      const blob=await _resizeForFacebook(new Blob([file],{type:file.type||'image/jpeg'}));
      const stored=await _storeImage(blob,{campaignId:campaign.id,postId:id,filename,kind:'post'});
      _setBusy(id,{uploadingImage:false});
      actions.updatePost(id,{generatedImageUrl:stored.url,mediaFileLink:stored.url});
      flash('Image uploaded');
    } catch(err) {
      console.error('Upload error:',err);
      _setBusy(id,{uploadingImage:false});
      flash(_imgError(err,'Image upload failed'));
    }
  };

  const advance = (e,id) => {
    e.stopPropagation();
    const c=caps(); const p=view.posts.find(x=>x.id===id); if (!p) return;
    if (p.status==='posted') return flash('This post is in Post History — use the Send Back button there to recall it for editing.');
    // Draft → Needs Edit → Ready to Post → Needs Edit (toggles back; Posted only via Ready to Post page)
    const nxt = p.status==='draft' ? 'needs' : p.status==='needs' ? 'ready' : 'needs';
    const needApprove = nxt==='ready';
    if (needApprove?!c.approve:!c.edit) return flash(`Your role can't move a post to ${SD.STATUS[nxt].label}.`);
    // Leaving 'ready' for edits must never leave a stale auto-publish approval armed.
    actions.updatePost(id,{status:nxt,updatedBy:(curMember()||{}).name||'', ...(p.status==='ready'&&nxt==='needs' ? {autoPublishApprovedAt:null} : {})});
  };

  /* Admin is the sole final posting authority — Action can still trigger
     Publish / Mark Posted, but for anyone short of Admin (Super Admin
     included, via the caps bypass) the click becomes a pendingAction request
     instead of executing immediately. An Admin's own click on a pending post
     both confirms the request and executes it in one step. */
  const isAdminAuthority = () => memberRole()==='Admin' || state.isSocialSuperAdmin;

  const requestPendingAction = (id, type, label) => {
    actions.updatePost(id, {pendingAction:{type, byUid:state.currentUserId, byName:(curMember()||{}).name||''}});
    setPushConfirmId(null);
    flash(`Sent to your Admin to confirm ${label}.`);
  };

  const declinePendingAction = id => {
    if (!isAdminAuthority()) return;
    actions.updatePost(id, {pendingAction:null});
    flash('Request declined');
  };

  const publishPost = async id => {
    if (!campaign) return;
    if (!caps().approve) return flash("Your role can't publish posts.");
    if (!isAdminAuthority()) return requestPendingAction(id, 'publish', 'publishing this post');
    const p = view.posts.find(x => x.id === id);
    const w = p && view.weeks.find(x => x.id === p.weekId);
    if (!p || !w) return;
    const plats = postPlatforms(p, campaign.config);
    if (!plats.facebook && !plats.instagram) { setPushConfirmId(null); return flash('Select at least one platform to publish to.'); }
    if (!campaign.config.facebookPageId) { setPushConfirmId(null); return flash('Connect this campaign to a Facebook Page first (Campaign menu, Socials).'); }
    setPushingId(id);
    setPushConfirmId(null);
    try {
      const data = await _api('POST', '/club/social/' + campaign.id + '/posts/' + id + '/publish');
      actions.refresh(campaign.id);
      if (data.status === 'published') flash('Published' + (plats.instagram ? ' to Facebook and Instagram' : ' to Facebook'));
      else if (data.status === 'partial') flash('Partly published. Check each platform on the card.');
      else flash((data.results && Object.values(data.results).find(r=>r&&r.error)?.error) || 'Publish failed');
    } catch (e) {
      flash((e && e.message) || 'Publish failed');
    } finally {
      setPushingId(null);
    }
  };

  /* Deliberate second gate before the cron will fire this post: 'ready' alone is
     not enough. Only an Admin's explicit approval (direct, or confirming a
     pendingAction request) arms auto-publish for both Facebook and Instagram. */
  const approveForAutoPublish = async id => {
    if (!campaign) return;
    if (!caps().approve) return flash("Your role can't approve posts for auto-publish.");
    if (!campaign.config.facebookPageId) { setApproveConfirmId(null); return flash('Connect this campaign to a Facebook Page first (Campaign menu, Socials).'); }
    if (!isAdminAuthority()) return requestPendingAction(id, 'approveForAutoPublish', 'approving this post for auto-publish');
    const p = view.posts.find(x => x.id === id);
    const plats = p && postPlatforms(p, campaign.config);
    if (!plats || (!plats.facebook && !plats.instagram)) { setApproveConfirmId(null); return flash('Select at least one platform before approving.'); }
    /* The image must actually load before the cron is armed; a dead link would fail at publish time. */
    const imgUrl = p.generatedImageUrl || '';
    if (plats.instagram && !imgUrl) { setApproveConfirmId(null); return flash('Instagram needs an image. Add one before approving.'); }
    if (imgUrl && !(await _checkImageUrl(imgUrl))) { setApproveConfirmId(null); return flash('The image on this post does not load. Replace the image, then approve again.'); }
    actions.updatePost(id, { autoPublishApprovedAt: new Date().toISOString(), pendingAction: null });
    setApproveConfirmId(null);
    flash('Approved for auto-publish');
  };

  /* Admin-only, immediate, no pendingAction round-trip — undoing an armed
     auto-publish is itself a safety action; it shouldn't need a second approval. */
  const revokeAutoPublishApproval = id => {
    if (!isAdminAuthority()) return flash('Only an Admin can revoke auto-publish approval.');
    actions.updatePost(id, { autoPublishApprovedAt: null });
    flash('Auto-publish approval revoked');
  };

  const copyCaption = (id,text) => {
    try { navigator.clipboard&&navigator.clipboard.writeText(text); } catch(e){}
    setCopiedId(id); clearTimeout(clipTimer.current); clipTimer.current=setTimeout(()=>setCopiedId(null),1700);
  };

  /* via: 'manual' (the Posted button — "I already posted this myself"),
     'instant' (the Instant Publish button actually fired it), or
     'auto' (the auto-publish cron fired it) — surfaced in Post History
     so it's clear how each post actually went out. */
  const markPosted = (id, via='manual') => {
    if (!caps().approve) return flash("Your role can't mark posts as Posted.");
    if (!isAdminAuthority()) return requestPendingAction(id, 'posted', 'marking this post Posted');
    actions.updatePost(id,{status:'posted',postedVia:via,postedAt:new Date().toISOString(),updatedBy:(curMember()||{}).name||'',pendingAction:null,autoPublishApprovedAt:null});
    flash('Marked as Posted');
  };

  const confirmSendBack = id => {
    if (!caps().edit) return flash("Your role can't send posts back.");
    const note=(noteDrafts[id]||'').trim();
    actions.updatePost(id,{status:'needs',reviewerNotes:note||'Sent back for edits.',updatedBy:(curMember()||{}).name||'',autoPublishApprovedAt:null});
    setSendBackId(null); setNoteDrafts(d=>({...d,[id]:''}));
    flash('Sent back to Needs Edit');
  };

  /* Multi-reviewer sign-off — any Write/Action/Admin member can mark a post
     "recommended" with an optional note. Purely informational: it never gates
     the Admin-only posting actions, it just surfaces who's reviewed a post. */
  const setSignOff = (post, on, note) => {
    const uid = state.currentUserId;
    const mb  = curMember();
    const existing = (post.signOffs||[]).filter(x=>x.uid!==uid);
    const next = on ? [...existing, {uid, name:(mb||{}).name||'', note:(note||'').trim(), ts:Date.now()}] : existing;
    actions.updatePost(post.id, {signOffs: next});
  };

  /* ── calendar drag-and-drop ── */
  const movePostToDate = (campaignId, postId, targetDate) => {
    const c = state.campaigns.find(x=>x.id===campaignId);
    if (!c||!c.weeks.length) return;
    const camStart  = parseDate(c.config.campaignStart);
    const totalDays = Math.round((targetDate.getTime()-camStart.getTime())/86400000);
    if (totalDays<0||totalDays>=c.weeks.length*7) return;
    const weekIdx = Math.floor(totalDays/7);
    const dayOff  = totalDays%7;
    const week    = c.weeks.find(w=>w.idx===weekIdx);
    if (!week) return;
    actions.movePost(campaignId,postId,week.id,dayOff);
    flash('Post rescheduled');
  };

  /* ── setup ── (setupDraft is shared by both SetupModal and AdminSettingsModal —
     they edit the same campaign config, just show a different subset of it) */
  const buildSetupDraft = () => {
    if (!campaign) return null;
    const cfg = campaign.config;
    return {
      clubName:      state.clubName,
      eventName:     cfg.eventName,
      eventWebsite:  cfg.eventWebsite || '',
      facebookPage:    cfg.facebookPage,
      facebookPageId:  cfg.facebookPageId  || '',
      facebookPageUrl: cfg.facebookPageUrl || '',
      facebookPushUrl: cfg.facebookPushUrl || '',
      instagramAccountId: cfg.instagramAccountId || '',
      campaignStart:   cfg.campaignStart,
      webhookUrl:      cfg.webhookUrl,
      preferredDays: cfg.preferredDays&&cfg.preferredDays.length ? cfg.preferredDays : [1,4],
      postsPerDay:   cfg.postsPerDay||1,
      defaultPostTime: cfg.defaultPostTime || '19:30',
      timeZone: cfg.timeZone || CCIntl.timezone(),
      beneficiaries: cfg.beneficiaries.map(x=>({...x})),
      sponsors:      cfg.sponsors.map(x=>({...x})),
      referenceDocs: (cfg.referenceDocs||[]).map(x=>({...x})),
      pillars:       cfg.pillars.map(x=>({...x, timing:[...(x.timing||[])], questionnaire:{...blankQuestionnaire(), ...(x.questionnaire||{})}})),
      numWeeks:      campaign.weeks.length||6,
      memberRoles:   {...(campaign.memberRoles||{})},
      exclusions:    (cfg.exclusions||[]).map(x=>({...x})),
      moreInfo:        cfg.moreInfo        || '',
      moreInfoDocs:    (cfg.moreInfoDocs&&cfg.moreInfoDocs.length) ? cfg.moreInfoDocs.map(x=>({...x}))
        : (cfg.moreInfoDocUrl ? [{id:'mi'+Math.random().toString(36).slice(2,7), name:cfg.moreInfoDocName||'', docUrl:cfg.moreInfoDocUrl, docName:cfg.moreInfoDocName||''}] : []),
      signOffMessage:  cfg.signOffMessage || defaultSignOffMessage(cfg, state.clubBrandKit),
      branding:        {...blankBranding(), ...(cfg.branding||{})},
    };
  };
  const openSetup = () => { const dr = buildSetupDraft(); if (dr) { setSetupView('campaign'); setSetupDraft(dr); } };
  const openAdminSettings = view => { const dr = buildSetupDraft(); if (dr) { setSetupView(view); setSetupDraft(dr); } };

  const applyPlanSocial = async (data, setWeeks, content) => {
    const base = buildSetupDraft();
    if (!base || !data) return;
    const c = data.config || {}, has = k => c[k] !== undefined && c[k] !== null;
    const draft = {...base};
    ['eventName','eventWebsite','facebookPage','facebookPageId','facebookPageUrl','instagramAccountId','campaignStart','moreInfo','signOffMessage','defaultPostTime','timeZone'].forEach(k => { if (has(k)) draft[k] = c[k]; });
    if (has('preferredDays') && c.preferredDays.length) draft.preferredDays = c.preferredDays;
    ['beneficiaries','sponsors','referenceDocs','exclusions','moreInfoDocs'].forEach(k => { if (Array.isArray(c[k])) draft[k] = c[k].map(x => typeof x === 'string' ? {name:x} : {...x}); });
    if (Array.isArray(c.pillars) && c.pillars.length) draft.pillars = c.pillars.map(x => ({...x, timing:[...(x.timing||[])], questionnaire:{...blankQuestionnaire(), ...(x.questionnaire||{})}}));
    if (c.branding) draft.branding = {...blankBranding(), ...c.branding};
    if (setWeeks && (data.weeks||[]).length) draft.numWeeks = Math.min(16, data.weeks.length);
    setShowPsImport(false);
    await actions.saveSetup(draft);
    if (content && Array.isArray(data.weeks) && data.weeks.length) await actions.replaceContent(data.weeks, data.posts || []);
    flash(content ? 'Setup, weeks and posts imported from Plan Social' : 'Setup imported from Plan Social');
  };
  const saveSetup = () => {
    actions.saveSetup(setupDraft);
    setSetupDraft(null);
    flash('Campaign saved — planner updated');
  };

  /* ── club brand kit ── */
  const openBrandKit = () => setBrandKitDraft({...blankBrandKit(), ...(state.clubBrandKit||{})});
  const saveBrandKit = () => {
    actions.saveBrandKit(brandKitDraft);
    setBrandKitDraft(null);
    flash('Brand kit saved');
  };

  const c  = caps();
  const mb = curMember();
  const mr = memberRole();
  const isAdmin = isAdminAuthority();
  const pendingConfirmCount = campaign ? campaign.posts.filter(p=>p.pendingAction).length : 0;
  const calCampaigns = isAllCampaigns ? state.campaigns : (campaign ? [campaign] : []);

  return (
    <div className="sp-root sp-layout" style={{background:'var(--b-bg)'}}>
      <AppHeader
        state={state} actions={actions}
        campaign={campaign} member={mb} memberRole={mr} caps={c}
        onSetup={openSetup} onEventsImport={()=>setShowEventsImport(true)} onPlanSocialImport={()=>setShowPsImport(true)} onTeam={()=>openAdminSettings('team')} onSocials={()=>openAdminSettings('socials')} onDeleteCampaign={()=>{ if(!campaign) return; if (window.confirm('Delete "'+campaign.config.eventName+'"? Its weeks, posts and stored pictures are removed and this cannot be undone.')) actions.deleteCampaign(campaign.id); }} onBrandKit={openBrandKit} onGuide={()=>setShowGuide(true)} onShowImages={()=>setShowImageLib(true)}
        onNewCampaign={()=>setNewCampaign(true)} onApprovals={()=>setShowApprovals(true)}
        isAllCampaigns={isAllCampaigns} mode={mode} onSignOut={signOut}
        pendingConfirmCount={isAdmin ? pendingConfirmCount : 0}
      />
      <div className="cc-appmain">
      <main style={{maxWidth:1240,width:'100%',margin:'0 auto',padding:'26px 24px 64px'}}>
        {window.CCRoomNote && <window.CCRoomNote app="Social" style={{marginTop:0,marginBottom:18,maxWidth:'none'}}/>}
        {state.tab==='planner'  && <WeekPlannerTab state={view} actions={actions} caps={c} pillarById={pillarById} weekNo={weekNo} dateRange={dateRange} statusCells={statusCells} generateWeek={generateWeek} generateSecondAngle={generateSecondAngle}/>}
        {state.tab==='posts'    && <PostBriefTab   state={view} actions={actions} caps={c} pillarById={pillarById} weekNo={weekNo} dateRange={dateRange} postDate={postDate} postsOf={postsOf} statusCells={statusCells} generatePost={generatePost} advance={advance} generateMediaBrief={generateMediaBrief} generateImage={generateImage} handleImageUpload={handleImageUpload} setSignOff={setSignOff} driveDestFor={driveDestFor} setDriveDest={setDriveDest} movePostToDate={movePostToDate}/>}
        {state.tab==='review'   && <ReadyToPostTab state={view} actions={actions} caps={c} weekNo={weekNo} postDate={postDate} pillarById={pillarById} copyCaption={copyCaption} copiedId={copiedId} markPosted={markPosted} sendBackId={sendBackId} setSendBackId={setSendBackId} noteDrafts={noteDrafts} setNoteDrafts={setNoteDrafts} confirmSendBack={confirmSendBack} pushConfirmId={pushConfirmId} setPushConfirmId={setPushConfirmId} onPublish={publishPost} pushingId={pushingId} setSignOff={setSignOff} isAdmin={isAdmin} declinePendingAction={declinePendingAction} approveConfirmId={approveConfirmId} setApproveConfirmId={setApproveConfirmId} onApproveForAutoPublish={approveForAutoPublish} approvingId={approvingId} onRevokeAutoPublishApproval={revokeAutoPublishApproval}/>}
        {state.tab==='history'  && <PostHistoryTab  state={view} caps={c} weekNo={weekNo} postDate={postDate} pillarById={pillarById} copyCaption={copyCaption} copiedId={copiedId} sendBackId={sendBackId} setSendBackId={setSendBackId} noteDrafts={noteDrafts} setNoteDrafts={setNoteDrafts} confirmSendBack={confirmSendBack}/>}
        {state.tab==='calendar' && <CalendarView    onSetup={openSetup} campaigns={calCampaigns} showAllCampaigns={isAllCampaigns} caps={c} movePostToDate={movePostToDate} pillarById={pillarById}/>}
      </main>
      </div>
      {setupDraft && setupView==='campaign' && (
        <SetupModal
          draft={setupDraft} setDraft={setSetupDraft}
          clubBrandKit={state.clubBrandKit}
          onOpenBrandKit={openBrandKit}
          onOpenGuide={()=>setShowGuide(true)}
          clubId={(window.SOCIAL_FIREBASE||{}).clubId}
          campaignId={state.currentCampaignId}
          isSuperAdmin={state.isSocialSuperAdmin}
          callAI={body=>actions.ai(campaign.id, body)}
          onClose={()=>setSetupDraft(null)}
          onSave={saveSetup}
          onNewCampaign={()=>setNewCampaign(true)}
        />
      )}
      {setupDraft && (setupView==='team' || setupView==='socials') && (
        <AdminSettingsModal section={setupView}
          draft={setupDraft} setDraft={setSetupDraft}
          members={state.members}
          onInvite={(email,role)=>actions.inviteToCampaign(state.currentCampaignId, email, role)}
          onClose={()=>setSetupDraft(null)}
          onSave={saveSetup}
        />
      )}
      {brandKitDraft && (
        <BrandKitModal
          draft={brandKitDraft} setDraft={setBrandKitDraft}
          clubId={(window.SOCIAL_FIREBASE||{}).clubId}
          onClose={()=>setBrandKitDraft(null)}
          onSave={saveBrandKit}
        />
      )}
      {showGuide && campaign && (
        <SetupGuideModal
          config={campaign.config}
          clubBrandKit={state.clubBrandKit}
          onClose={()=>setShowGuide(false)}
        />
      )}
      {newCampaign && (
        <RequestCampaignModal
          onClose={()=>setNewCampaign(false)}
          onRequest={(name, opts) => { actions.requestCampaign(name, null, opts); setNewCampaign(false); }}
        />
      )}
      {showApprovals && (
        <ApprovalsModal
          state={state} actions={actions}
          onClose={()=>setShowApprovals(false)}
        />
      )}
      {topicPicker && (
        <TopicPickerModal
          suggestions={topicPicker.suggestions}
          pillar={topicPicker.pillar}
          onPick={s => handleTopicPick(topicPicker.weekId, s)}
          onExclude={handleExclude}
          onClose={()=>setTopicPicker(null)}
        />
      )}
      {showImageLib && (
        <ImageLibraryModal
          clubId={(window.SOCIAL_FIREBASE||{}).clubId}
          campaigns={state.campaigns}
          settings={state.clubImageStorage}
          canManage={false}
          onSaveSettings={()=>{}}
          onClose={()=>setShowImageLib(false)}
        />
      )}
      {showEventsImport && campaign && (
        <EventsImportModal campaign={campaign}
          onImport={(rid, date, items)=>actions.importEventsPosts(rid, date, items)}
          onClose={r=>{ setShowEventsImport(false); if (r && r.added) flash(r.added+' post'+(r.added===1?'':'s')+' added as drafts'+(r.skipped?' ('+r.skipped+' already in)':'')); }}/>
      )}
      {showPsImport && campaign && <PlanSocialImportModal campaign={campaign} onApply={applyPlanSocial} onClose={()=>setShowPsImport(false)}/>}
      {toast && <Toast msg={toast}/>}
    </div>
  );
}

window.CCSocial = App;
})();
