/* screen-brand-actions.jsx — Brand-side action modals so the brand flow
   ────────────────────────────────────────────────────────────────────
   mirrors the creator flow and runs end-to-end as one demo loop.

   Modals:
     1. ReviewApplicationModal  → opened from any application row · full pitch
        view + Approve / Reject / Shortlist. Optimistically updates the row.
     2. RequestRevisionsModal   → annotated feedback composer for a deliverable.
        Sends issues to the creator's revision flow.
     3. ReviewDeliverableModal  → preview submitted video + Approve & pay $720
        or Request revisions (opens the modal above).
     4. NudgeCreatorsModal      → pick which late creators to nudge + message.
     5. ExtendDeadlineModal     → pick a new date, push out the milestone.

   Exposes:
     <BrandActionsHost />        provider
     useBrandActions()           hook with:
       openReviewApplication(a, onUpdate?)
       openReviewDeliverable(d)
       openNudgeCreators()
       openExtendDeadline()
       toast(msg, kind?)
*/
/* global React, Modal, Toast, Avatar, Pill, Icon, CFAvatar */

// ── 1. Review Application modal ────────────────────────────────────
function ReviewApplicationModal({ open, onClose, applicant, onUpdate, onToast }) {
  if (!applicant) return null;
  const a = applicant;

  const decide = (decision) => {
    onUpdate?.(a.id, decision);
    const msg = decision === 'accepted'
      ? `${a.name} booked · contract drafted · payment held in escrow`
      : decision === 'shortlisted'
      ? `${a.name} added to shortlist · they'll get a 15-min sync invite`
      : `${a.name} declined · feedback sent privately`;
    onToast(msg, decision === 'rejected' ? 'info' : 'success');
    onClose();
  };

  // Mock references — same look as creator's submitted refs
  const refs = [
    { g: 'linear-gradient(135deg, #79FEE7, #009CFF)', views: '1.2M', er: '8.4%' },
    { g: 'linear-gradient(135deg, #FFC3D6, #FF6FA3)', views: '820K', er: '7.1%' },
  ];

  return (
    <Modal open={open} onClose={onClose} width={720}
      title="Review application"
      subtitle={`${a.name} · applied to Acne Spot Cream · Launch`}>

      {/* Header strip */}
      <div className="row items-center gap-14" style={{
        padding: 16, borderRadius: 14, marginBottom: 16,
        background: 'linear-gradient(135deg, rgba(0,156,255,0.06), rgba(121,254,231,0.06))',
        border: '1px solid rgba(0,156,255,0.18)'
      }}>
        <Avatar name={a.name} size={52} />
        <div className="flex-1">
          <div className="row items-center gap-8">
            <span className="bold" style={{ fontSize: 15 }}>{a.name}</span>
            {a.rebookCount > 0 && <Pill variant="lav">{a.rebookCount}× rebook</Pill>}
            {a.status === 'accepted' && <Pill variant="mint">Booked</Pill>}
            {a.status === 'rejected' && <Pill variant="pink">Rejected</Pill>}
          </div>
          <div className="muted" style={{ fontSize: 11.5, marginTop: 2 }}>
            {a.platform === 'tiktok' ? 'TikTok' : a.platform === 'instagram' ? 'Instagram' : 'YouTube'} · {a.handle} · {a.followers} followers · ER {a.er}%
          </div>
          <div className="row gap-6 mt-2">
            <Pill variant="cyan">Skincare · HCM 18–24F</Pill>
            <Pill variant="mint">Bot &lt; 4%</Pill>
            <Pill variant="ink">Verified ID</Pill>
          </div>
        </div>
        <div className="text-right">
          <div className="cap-label" style={{ fontSize: 9 }}>AI match</div>
          <div className="font-display bold tabular" style={{
            fontSize: 36, letterSpacing: '-0.02em',
            color: a.match >= 80 ? 'var(--mint-deep)' : a.match >= 65 ? 'var(--ink)' : 'var(--pink-hot)'
          }}>{a.match}%</div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 14 }}>
        <div>
          {/* Pitch */}
          <div className="cap-label mb-2">Their pitch</div>
          <div style={{ padding: 14, background: 'var(--bg-soft)', borderRadius: 10, fontSize: 13, lineHeight: 1.55, marginBottom: 14 }}>
            "{a.note}"
          </div>

          {/* Deliverable */}
          <div className="cap-label mb-2">Proposed bundle</div>
          <div style={{ padding: 12, background: 'white', border: '1px solid var(--line)', borderRadius: 10, marginBottom: 14 }}>
            <div className="row items-center gap-8 mb-2">
              <Pill variant="ink" icon={a.platform === 'tiktok' ? Icon.tiktok : a.platform === 'instagram' ? Icon.instagram : Icon.youtube}>{a.platform === 'tiktok' ? 'TikTok' : a.platform === 'instagram' ? 'Instagram' : 'YouTube'}</Pill>
              <span className="bold" style={{ fontSize: 13 }}>1 hero video · 30s</span>
              <span className="muted" style={{ fontSize: 11 }}>delivers May 22</span>
            </div>
            <div className="row items-center gap-8">
              <Pill variant="ink">Follow-up 15s</Pill>
              <span className="muted" style={{ fontSize: 11 }}>delivers Jun 04</span>
            </div>
          </div>

          {/* References */}
          <div className="cap-label mb-2">Reference posts · 2 attached</div>
          <div className="row gap-8">
            {refs.map((r, i) => (
              <div key={i} style={{
                width: 80, height: 110, borderRadius: 10, background: r.g, position: 'relative', overflow: 'hidden'
              }}>
                <div style={{
                  position: 'absolute', inset: 0, display: 'grid', placeItems: 'center',
                  color: 'white', fontSize: 22
                }}>▶</div>
                <div style={{
                  position: 'absolute', bottom: 0, left: 0, right: 0, padding: '6px 6px 4px',
                  background: 'linear-gradient(transparent, rgba(0,0,0,0.55))',
                  color: 'white', fontSize: 9, fontWeight: 800
                }}>{r.views} · {r.er}</div>
              </div>
            ))}
          </div>
        </div>

        <div>
          {/* Rate */}
          <div className="card-elevated mb-3" style={{ padding: 14, background: 'rgba(31,214,180,0.06)', border: '1px solid rgba(31,214,180,0.25)' }}>
            <div className="cap-label" style={{ fontSize: 9 }}>Asking rate</div>
            <div className="font-display tabular" style={{ fontSize: 32, fontWeight: 700, letterSpacing: '-0.02em', lineHeight: 1, marginTop: 4 }}>${a.rate.toLocaleString()}</div>
            <div className="muted mt-1" style={{ fontSize: 11 }}>
              Within brand band $1.2K – $4.5K ✓
            </div>
          </div>

          {/* AI breakdown */}
          <div className="cap-label mb-2">Why {a.match}% match</div>
          {[
            ['Audience overlap', 96, 'var(--mint-deep)'],
            ['Category match', 94, 'var(--cyan)'],
            ['ER vs threshold', 88, 'var(--indigo)'],
            ['Past performance', a.match, 'var(--pink-hot)'],
          ].map(([l, v, c], i) => (
            <div key={i} style={{ marginBottom: 8 }}>
              <div className="row items-center justify-between" style={{ fontSize: 11.5, fontWeight: 600 }}>
                <span>{l}</span><span className="tabular bold">{v}%</span>
              </div>
              <div style={{ height: 5, borderRadius: 999, background: 'var(--bg-soft)', overflow: 'hidden', marginTop: 3 }}>
                <div style={{ height: '100%', width: v + '%', background: c, borderRadius: 999 }} />
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Action footer */}
      <div className="row items-center gap-8 mt-6" style={{ paddingTop: 16, borderTop: '1px solid var(--line)' }}>
        <button className="btn btn-ghost btn-sm" onClick={onClose}>Close</button>
        <button className="btn btn-ghost btn-sm">Message creator</button>
        <div style={{ flex: 1 }} />
        {a.status === 'pending' && (
          <>
            <button className="btn btn-ghost btn-sm" onClick={() => decide('rejected')}
              style={{ color: 'var(--pink-hot)' }}>Reject</button>
            <button className="btn btn-ghost btn-sm" onClick={() => decide('shortlisted')}>Shortlist for sync</button>
            <button className="btn btn-primary btn-sm" onClick={() => decide('accepted')}>
              {Icon.check} Approve · book ${a.rate.toLocaleString()}
            </button>
          </>
        )}
        {a.status === 'accepted' && (
          <button className="btn btn-primary btn-sm">Open project →</button>
        )}
        {a.status === 'rejected' && (
          <button className="btn btn-ghost btn-sm">Re-open application</button>
        )}
      </div>
    </Modal>
  );
}

// ── 2. Request revisions composer ───────────────────────────────────
function RequestRevisionsModal({ open, onClose, onToast }) {
  const [issues, setIssues] = React.useState([
    { ts: '0:04', title: 'Add #ad disclosure overlay', body: 'Required on-screen in the first 3 seconds.', sev: 'required' },
  ]);
  const [note, setNote] = React.useState('Love the energy! Three small things before we ship.');

  React.useEffect(() => { if (!open) { setIssues([{ ts: '0:04', title: 'Add #ad disclosure overlay', body: 'Required on-screen in the first 3 seconds.', sev: 'required' }]); setNote('Love the energy! Three small things before we ship.'); } }, [open]);

  const addIssue = () => setIssues(s => [...s, { ts: '0:' + String(10 + s.length * 6).padStart(2, '0'), title: '', body: '', sev: 'required' }]);
  const remove = (i) => setIssues(s => s.filter((_, j) => j !== i));
  const update = (i, k, v) => setIssues(s => s.map((it, j) => j === i ? { ...it, [k]: v } : it));

  const send = () => {
    const valid = issues.filter(i => i.title.trim());
    onToast(`${valid.length} revision request${valid.length !== 1 ? 's' : ''} sent to Linh Châu`, 'info');
    onClose();
  };

  return (
    <Modal open={open} onClose={onClose} width={620}
      title="Request revisions"
      subtitle="Each issue gets a timestamp so the creator can fix what you flagged exactly"
      footer={
        <div className="row gap-8">
          <button onClick={onClose} className="btn btn-ghost btn-sm">Cancel</button>
          <button onClick={send} className="btn btn-primary btn-sm" disabled={!issues.some(i => i.title.trim())}
            style={{ opacity: issues.some(i => i.title.trim()) ? 1 : 0.4 }}>
            Send {issues.filter(i => i.title.trim()).length} request{issues.filter(i => i.title.trim()).length !== 1 ? 's' : ''}
          </button>
        </div>
      }>
      <label className="cap-label mb-2">Note to creator</label>
      <textarea className="input" rows="2" value={note} onChange={e => setNote(e.target.value)} style={{ resize: 'vertical', fontFamily: 'inherit' }} />

      <div className="row items-center justify-between mt-4 mb-2">
        <label className="cap-label">Annotated issues</label>
        <button onClick={addIssue} className="btn btn-ghost btn-sm">{Icon.plus} Add issue</button>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {issues.map((it, i) => (
          <div key={i} style={{ padding: 12, background: 'var(--bg-soft)', borderRadius: 12 }}>
            <div className="row items-center gap-8 mb-2">
              <input value={it.ts} onChange={e => update(i, 'ts', e.target.value)} placeholder="0:04"
                style={{ width: 60, padding: '4px 8px', borderRadius: 6, border: '1px solid var(--line)', fontSize: 12, fontFamily: 'inherit', fontWeight: 700, textAlign: 'center' }} />
              <input value={it.title} onChange={e => update(i, 'title', e.target.value)} placeholder="What needs to change"
                style={{ flex: 1, padding: '6px 10px', borderRadius: 6, border: '1px solid var(--line)', fontSize: 12.5, fontFamily: 'inherit', fontWeight: 600 }} />
              <select value={it.sev} onChange={e => update(i, 'sev', e.target.value)} style={{ padding: '4px 8px', borderRadius: 6, border: '1px solid var(--line)', fontSize: 11, fontFamily: 'inherit', fontWeight: 700 }}>
                <option value="required">Required</option>
                <option value="nice">Nice-to-have</option>
              </select>
              <button onClick={() => remove(i)} style={{ width: 26, height: 26, borderRadius: 6, background: 'white', border: '1px solid var(--line)', color: 'var(--ink-soft)', cursor: 'pointer' }}>×</button>
            </div>
            <textarea value={it.body} onChange={e => update(i, 'body', e.target.value)} placeholder="Brief, specific instructions for the creator"
              rows="2"
              style={{ width: '100%', padding: '8px 10px', borderRadius: 6, border: '1px solid var(--line)', fontSize: 12, fontFamily: 'inherit', resize: 'vertical', lineHeight: 1.5 }} />
          </div>
        ))}
      </div>
    </Modal>
  );
}

// ── 3. Review Deliverable modal ─────────────────────────────────────
function ReviewDeliverableModal({ open, onClose, deliverable, onRequestRevisions, onToast }) {
  if (!deliverable) return null;
  const d = deliverable;

  const approve = () => {
    onToast(`Approved · $${d.pay} released to ${d.creator}`, 'success');
    onClose();
  };

  return (
    <Modal open={open} onClose={onClose} width={760}
      title={`Review · ${d.title}`}
      subtitle={`Submitted by ${d.creator} · ${d.when}`}>

      <div style={{ display: 'grid', gridTemplateColumns: '260px 1fr', gap: 16 }}>
        {/* Video preview */}
        <div>
          <div style={{
            position: 'relative', aspectRatio: '9/16', borderRadius: 12, overflow: 'hidden',
            background: 'linear-gradient(135deg, #79FEE7, #009CFF)'
          }}>
            <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', color: 'white', fontSize: 48, cursor: 'pointer' }}>▶</div>
            <div style={{ position: 'absolute', top: 8, left: 8, right: 8, color: 'white' }}>
              <div className="row items-center gap-6">
                <div style={{ width: 24, height: 24, borderRadius: 999, background: 'white', color: 'var(--cyan-dark)', display: 'grid', placeItems: 'center', fontWeight: 800, fontSize: 11 }}>L</div>
                <div style={{ fontSize: 11, fontWeight: 700 }}>@linhchau</div>
              </div>
            </div>
            <div style={{ position: 'absolute', bottom: 8, left: 8, right: 8, color: 'white', fontSize: 9, fontWeight: 700, textShadow: '0 1px 3px rgba(0,0,0,0.4)' }}>
              0:00 / {d.length}
            </div>
          </div>

          {/* Scrubber */}
          <div style={{ marginTop: 10, height: 4, borderRadius: 999, background: 'var(--bg-soft)' }}>
            <div style={{ width: '32%', height: '100%', background: 'var(--cyan)', borderRadius: 999 }} />
          </div>

          <div className="row gap-6 mt-3" style={{ flexWrap: 'wrap' }}>
            <Pill variant="ink">{d.length}</Pill>
            <Pill variant="ink">{d.size}</Pill>
            <Pill variant="cyan">9:16 vertical</Pill>
          </div>
        </div>

        <div>
          {/* Compliance auto-check */}
          <div className="cap-label mb-2">Compliance auto-check</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 14 }}>
            {[
              ['#ad disclosure in caption', true],
              ['#ad disclosure on-screen (first 3s)', false],
              ['@coolmate.vn tag present', true],
              ['No medical claims detected', true],
              ['No filter detected', false],
            ].map(([l, ok], i) => (
              <div key={i} className="row items-center gap-8" style={{ fontSize: 12.5 }}>
                <span style={{
                  width: 18, height: 18, borderRadius: 999, display: 'grid', placeItems: 'center',
                  background: ok ? 'var(--mint-deep)' : 'rgba(255,111,163,0.18)',
                  color: ok ? 'white' : 'var(--pink-hot)',
                  fontWeight: 800, fontSize: 11
                }}>{ok ? '✓' : '!'}</span>
                <span style={{ color: ok ? 'var(--ink)' : 'var(--ink-soft)' }}>{l}</span>
                {!ok && <span style={{ marginLeft: 'auto', fontSize: 11, fontWeight: 700, color: 'var(--pink-hot)' }}>Flag for revision</span>}
              </div>
            ))}
          </div>

          {/* Caption */}
          <div className="cap-label mb-2">Caption</div>
          <div style={{ padding: 12, background: 'var(--bg-soft)', borderRadius: 10, fontSize: 12.5, lineHeight: 1.5, whiteSpace: 'pre-wrap', marginBottom: 14 }}>
            POV: when ur niacinamide finally hits ✨{'\n\n'}Full routine in comments. Wearing the new @coolmate.vn Vit-C — review hits next week 🍊{'\n\n'}#ad #skincare #vitaminc
          </div>

          {/* Approval block */}
          <div className="cap-label mb-2">Pays on approval</div>
          <div className="row items-center gap-12" style={{ padding: 14, borderRadius: 12, background: 'rgba(31,214,180,0.08)', border: '1px solid rgba(31,214,180,0.3)' }}>
            <div className="font-display tabular bold" style={{ fontSize: 26 }}>${d.pay}</div>
            <div className="flex-1">
              <div className="bold" style={{ fontSize: 12.5 }}>Will release to {d.creator} on approval</div>
              <div className="muted" style={{ fontSize: 11 }}>Held in escrow · arrives in their wallet within minutes</div>
            </div>
          </div>
        </div>
      </div>

      {/* Action footer */}
      <div className="row items-center gap-8 mt-6" style={{ paddingTop: 16, borderTop: '1px solid var(--line)' }}>
        <button onClick={onClose} className="btn btn-ghost btn-sm">Close</button>
        <button onClick={() => { onClose(); onRequestRevisions(); }} className="btn btn-ghost btn-sm" style={{ color: 'var(--pink-hot)' }}>
          ↺ Request revisions
        </button>
        <div style={{ flex: 1 }} />
        <button onClick={approve} className="btn btn-primary btn-sm">{Icon.check} Approve &amp; pay ${d.pay}</button>
      </div>
    </Modal>
  );
}

// ── 4. Nudge creators modal ─────────────────────────────────────────
function NudgeCreatorsModal({ open, onClose, onToast }) {
  const LATE = [
    { id: 'l1', name: 'Hà Giang', handle: '@hagiang', missed: 'D1 draft', due: 'May 18 · 2 days late' },
    { id: 'l2', name: 'Diệu Linh', handle: '@dieulinh.skin', missed: 'D1 draft', due: 'May 18 · 2 days late' },
  ];
  const [picked, setPicked] = React.useState(['l1', 'l2']);
  const [msg, setMsg] = React.useState('Hey! Quick check — when can we expect the first draft? Let us know if you need a deadline extension.');

  const send = () => {
    onToast(`Nudge sent to ${picked.length} creator${picked.length !== 1 ? 's' : ''}`, 'info');
    onClose();
  };

  return (
    <Modal open={open} onClose={onClose} width={520}
      title="Nudge late creators"
      subtitle="They'll get a polite ping in-app + email · no public flag"
      footer={
        <div className="row gap-8">
          <button onClick={onClose} className="btn btn-ghost btn-sm">Cancel</button>
          <button onClick={send} className="btn btn-primary btn-sm" disabled={picked.length === 0}
            style={{ opacity: picked.length === 0 ? 0.4 : 1 }}>Send nudge</button>
        </div>
      }>
      <div className="cap-label mb-2">Who to nudge</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 14 }}>
        {LATE.map(p => {
          const isPicked = picked.includes(p.id);
          return (
            <label key={p.id} className="row items-center gap-12" style={{
              padding: 12, borderRadius: 10, cursor: 'pointer',
              background: isPicked ? 'rgba(0,156,255,0.06)' : 'var(--bg-soft)',
              border: '2px solid ' + (isPicked ? 'var(--cyan)' : 'transparent')
            }}>
              <input type="checkbox" checked={isPicked} onChange={() => setPicked(s => isPicked ? s.filter(x => x !== p.id) : [...s, p.id])} />
              <Avatar name={p.name} size={32} />
              <div className="flex-1">
                <div className="bold" style={{ fontSize: 13 }}>{p.name}</div>
                <div className="muted" style={{ fontSize: 11 }}>{p.handle} · missed {p.missed}</div>
              </div>
              <Pill variant="pink">{p.due}</Pill>
            </label>
          );
        })}
      </div>

      <div className="cap-label mb-2">Message</div>
      <textarea className="input" rows="3" value={msg} onChange={e => setMsg(e.target.value)} style={{ resize: 'vertical', fontFamily: 'inherit' }} />
    </Modal>
  );
}

// ── 5. Extend deadline modal ────────────────────────────────────────
function ExtendDeadlineModal({ open, onClose, onToast }) {
  const [days, setDays] = React.useState(3);
  const [reason, setReason] = React.useState('Extending so Hà & Linh can deliver quality drafts.');

  return (
    <Modal open={open} onClose={onClose} width={460}
      title="Extend draft deadline"
      subtitle="Push the milestone for everyone in this campaign"
      footer={
        <div className="row gap-8">
          <button onClick={onClose} className="btn btn-ghost btn-sm">Cancel</button>
          <button onClick={() => { onToast(`Deadline pushed by ${days} day${days !== 1 ? 's' : ''} · all 6 creators notified`, 'info'); onClose(); }} className="btn btn-primary btn-sm">Push deadline</button>
        </div>
      }>
      <div className="cap-label mb-2">Current deadline</div>
      <div className="row items-center gap-12 mb-4" style={{ padding: 12, background: 'rgba(255,111,163,0.08)', borderRadius: 10, border: '1px solid rgba(255,111,163,0.2)' }}>
        <div style={{ fontSize: 22 }}>📅</div>
        <div>
          <div className="bold">May 18, 2026 · drafts due</div>
          <div className="muted" style={{ fontSize: 11 }}>2 days overdue · 2 of 6 creators late</div>
        </div>
      </div>

      <div className="cap-label mb-2">Push by</div>
      <div className="row gap-6 mb-3">
        {[1, 2, 3, 5, 7].map(d => (
          <button key={d} onClick={() => setDays(d)} style={{
            flex: 1, padding: 12, borderRadius: 10, border: 0, cursor: 'pointer', fontFamily: 'inherit',
            background: days === d ? 'var(--ink)' : 'var(--bg-soft)',
            color: days === d ? 'white' : 'var(--ink)', fontWeight: 700
          }}>
            <div className="font-display bold tabular" style={{ fontSize: 18 }}>+{d}</div>
            <div style={{ fontSize: 10, opacity: 0.8 }}>day{d !== 1 ? 's' : ''}</div>
          </button>
        ))}
      </div>
      <div className="row items-center gap-12 mb-4" style={{ padding: 12, background: 'rgba(31,214,180,0.08)', borderRadius: 10 }}>
        <div style={{ fontSize: 22 }}>✓</div>
        <div>
          <div className="bold">New deadline · May {18 + days}, 2026</div>
          <div className="muted" style={{ fontSize: 11 }}>All 6 creators will get an updated milestone</div>
        </div>
      </div>

      <div className="cap-label mb-2">Reason (sent to creators)</div>
      <textarea className="input" rows="2" value={reason} onChange={e => setReason(e.target.value)} style={{ resize: 'vertical', fontFamily: 'inherit' }} />
    </Modal>
  );
}

// ── Host + hook ────────────────────────────────────────────────────
const BrandActionsCtx = React.createContext(null);

function BrandActionsHost({ children }) {
  const [app,    setApp]    = React.useState(null);
  const [appCb,  setAppCb]  = React.useState(() => () => {});
  const [deliv,  setDeliv]  = React.useState(null);
  const [reqRev, setReqRev] = React.useState(false);
  const [nudge,  setNudge]  = React.useState(false);
  const [extend, setExtend] = React.useState(false);
  const [toast,  setToast]  = React.useState(null);

  const showToast = React.useCallback((message, kind = 'success', action) => {
    setToast({ message, kind, action });
  }, []);

  const api = React.useMemo(() => ({
    openReviewApplication: (a, onUpdate) => { setAppCb(() => onUpdate || (() => {})); setApp(a); },
    openReviewDeliverable: (d) => setDeliv(d),
    openRequestRevisions:  () => setReqRev(true),
    openNudgeCreators:     () => setNudge(true),
    openExtendDeadline:    () => setExtend(true),
    toast: showToast,
  }), [showToast]);

  return (
    <BrandActionsCtx.Provider value={api}>
      {children}
      <ReviewApplicationModal open={!!app}  onClose={() => setApp(null)}  applicant={app}    onUpdate={appCb} onToast={showToast} />
      <ReviewDeliverableModal open={!!deliv} onClose={() => setDeliv(null)} deliverable={deliv}
        onRequestRevisions={() => setReqRev(true)} onToast={showToast} />
      <RequestRevisionsModal  open={reqRev} onClose={() => setReqRev(false)} onToast={showToast} />
      <NudgeCreatorsModal     open={nudge}  onClose={() => setNudge(false)}  onToast={showToast} />
      <ExtendDeadlineModal    open={extend} onClose={() => setExtend(false)} onToast={showToast} />
      <Toast open={!!toast} onClose={() => setToast(null)} kind={toast?.kind} message={toast?.message} action={toast?.action} />
    </BrandActionsCtx.Provider>
  );
}

function useBrandActions() {
  return React.useContext(BrandActionsCtx) || {
    openReviewApplication: () => {}, openReviewDeliverable: () => {},
    openRequestRevisions: () => {}, openNudgeCreators: () => {}, openExtendDeadline: () => {},
    toast: () => {}
  };
}

Object.assign(window, { BrandActionsHost, useBrandActions });
